Handle DW_TAG_variant_part and DW_TAG_variant
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89 #include "rust-lang.h"
90
91 /* When == 1, print basic high level tracing messages.
92    When > 1, be more verbose.
93    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
94 static unsigned int dwarf_read_debug = 0;
95
96 /* When non-zero, dump DIEs after they are read in.  */
97 static unsigned int dwarf_die_debug = 0;
98
99 /* When non-zero, dump line number entries as they are read in.  */
100 static unsigned int dwarf_line_debug = 0;
101
102 /* When non-zero, cross-check physname against demangler.  */
103 static int check_physname = 0;
104
105 /* When non-zero, do not reject deprecated .gdb_index sections.  */
106 static int use_deprecated_index_sections = 0;
107
108 static const struct objfile_data *dwarf2_objfile_data_key;
109
110 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
111
112 static int dwarf2_locexpr_index;
113 static int dwarf2_loclist_index;
114 static int dwarf2_locexpr_block_index;
115 static int dwarf2_loclist_block_index;
116
117 /* A descriptor for dwarf sections.
118
119    S.ASECTION, SIZE are typically initialized when the objfile is first
120    scanned.  BUFFER, READIN are filled in later when the section is read.
121    If the section contained compressed data then SIZE is updated to record
122    the uncompressed size of the section.
123
124    DWP file format V2 introduces a wrinkle that is easiest to handle by
125    creating the concept of virtual sections contained within a real section.
126    In DWP V2 the sections of the input DWO files are concatenated together
127    into one section, but section offsets are kept relative to the original
128    input section.
129    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
130    the real section this "virtual" section is contained in, and BUFFER,SIZE
131    describe the virtual section.  */
132
133 struct dwarf2_section_info
134 {
135   union
136   {
137     /* If this is a real section, the bfd section.  */
138     asection *section;
139     /* If this is a virtual section, pointer to the containing ("real")
140        section.  */
141     struct dwarf2_section_info *containing_section;
142   } s;
143   /* Pointer to section data, only valid if readin.  */
144   const gdb_byte *buffer;
145   /* The size of the section, real or virtual.  */
146   bfd_size_type size;
147   /* If this is a virtual section, the offset in the real section.
148      Only valid if is_virtual.  */
149   bfd_size_type virtual_offset;
150   /* True if we have tried to read this section.  */
151   char readin;
152   /* True if this is a virtual section, False otherwise.
153      This specifies which of s.section and s.containing_section to use.  */
154   char is_virtual;
155 };
156
157 typedef struct dwarf2_section_info dwarf2_section_info_def;
158 DEF_VEC_O (dwarf2_section_info_def);
159
160 /* All offsets in the index are of this type.  It must be
161    architecture-independent.  */
162 typedef uint32_t offset_type;
163
164 DEF_VEC_I (offset_type);
165
166 /* Ensure only legit values are used.  */
167 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
168   do { \
169     gdb_assert ((unsigned int) (value) <= 1); \
170     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
171   } while (0)
172
173 /* Ensure only legit values are used.  */
174 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
175   do { \
176     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
177                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
178     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
179   } while (0)
180
181 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
182 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
183   do { \
184     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
185     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
186   } while (0)
187
188 #if WORDS_BIGENDIAN
189
190 /* Convert VALUE between big- and little-endian.  */
191
192 static offset_type
193 byte_swap (offset_type value)
194 {
195   offset_type result;
196
197   result = (value & 0xff) << 24;
198   result |= (value & 0xff00) << 8;
199   result |= (value & 0xff0000) >> 8;
200   result |= (value & 0xff000000) >> 24;
201   return result;
202 }
203
204 #define MAYBE_SWAP(V)  byte_swap (V)
205
206 #else
207 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
208 #endif /* WORDS_BIGENDIAN */
209
210 /* An index into a (C++) symbol name component in a symbol name as
211    recorded in the mapped_index's symbol table.  For each C++ symbol
212    in the symbol table, we record one entry for the start of each
213    component in the symbol in a table of name components, and then
214    sort the table, in order to be able to binary search symbol names,
215    ignoring leading namespaces, both completion and regular look up.
216    For example, for symbol "A::B::C", we'll have an entry that points
217    to "A::B::C", another that points to "B::C", and another for "C".
218    Note that function symbols in GDB index have no parameter
219    information, just the function/method names.  You can convert a
220    name_component to a "const char *" using the
221    'mapped_index::symbol_name_at(offset_type)' method.  */
222
223 struct name_component
224 {
225   /* Offset in the symbol name where the component starts.  Stored as
226      a (32-bit) offset instead of a pointer to save memory and improve
227      locality on 64-bit architectures.  */
228   offset_type name_offset;
229
230   /* The symbol's index in the symbol and constant pool tables of a
231      mapped_index.  */
232   offset_type idx;
233 };
234
235 /* Base class containing bits shared by both .gdb_index and
236    .debug_name indexes.  */
237
238 struct mapped_index_base
239 {
240   /* The name_component table (a sorted vector).  See name_component's
241      description above.  */
242   std::vector<name_component> name_components;
243
244   /* How NAME_COMPONENTS is sorted.  */
245   enum case_sensitivity name_components_casing;
246
247   /* Return the number of names in the symbol table.  */
248   virtual size_t symbol_name_count () const = 0;
249
250   /* Get the name of the symbol at IDX in the symbol table.  */
251   virtual const char *symbol_name_at (offset_type idx) const = 0;
252
253   /* Return whether the name at IDX in the symbol table should be
254      ignored.  */
255   virtual bool symbol_name_slot_invalid (offset_type idx) const
256   {
257     return false;
258   }
259
260   /* Build the symbol name component sorted vector, if we haven't
261      yet.  */
262   void build_name_components ();
263
264   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
265      possible matches for LN_NO_PARAMS in the name component
266      vector.  */
267   std::pair<std::vector<name_component>::const_iterator,
268             std::vector<name_component>::const_iterator>
269     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
270
271   /* Prevent deleting/destroying via a base class pointer.  */
272 protected:
273   ~mapped_index_base() = default;
274 };
275
276 /* A description of the mapped index.  The file format is described in
277    a comment by the code that writes the index.  */
278 struct mapped_index final : public mapped_index_base
279 {
280   /* A slot/bucket in the symbol table hash.  */
281   struct symbol_table_slot
282   {
283     const offset_type name;
284     const offset_type vec;
285   };
286
287   /* Index data format version.  */
288   int version;
289
290   /* The total length of the buffer.  */
291   off_t total_size;
292
293   /* The address table data.  */
294   gdb::array_view<const gdb_byte> address_table;
295
296   /* The symbol table, implemented as a hash table.  */
297   gdb::array_view<symbol_table_slot> symbol_table;
298
299   /* A pointer to the constant pool.  */
300   const char *constant_pool;
301
302   bool symbol_name_slot_invalid (offset_type idx) const override
303   {
304     const auto &bucket = this->symbol_table[idx];
305     return bucket.name == 0 && bucket.vec;
306   }
307
308   /* Convenience method to get at the name of the symbol at IDX in the
309      symbol table.  */
310   const char *symbol_name_at (offset_type idx) const override
311   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
312
313   size_t symbol_name_count () const override
314   { return this->symbol_table.size (); }
315 };
316
317 /* A description of the mapped .debug_names.
318    Uninitialized map has CU_COUNT 0.  */
319 struct mapped_debug_names final : public mapped_index_base
320 {
321   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
322   : dwarf2_per_objfile (dwarf2_per_objfile_)
323   {}
324
325   struct dwarf2_per_objfile *dwarf2_per_objfile;
326   bfd_endian dwarf5_byte_order;
327   bool dwarf5_is_dwarf64;
328   bool augmentation_is_gdb;
329   uint8_t offset_size;
330   uint32_t cu_count = 0;
331   uint32_t tu_count, bucket_count, name_count;
332   const gdb_byte *cu_table_reordered, *tu_table_reordered;
333   const uint32_t *bucket_table_reordered, *hash_table_reordered;
334   const gdb_byte *name_table_string_offs_reordered;
335   const gdb_byte *name_table_entry_offs_reordered;
336   const gdb_byte *entry_pool;
337
338   struct index_val
339   {
340     ULONGEST dwarf_tag;
341     struct attr
342     {
343       /* Attribute name DW_IDX_*.  */
344       ULONGEST dw_idx;
345
346       /* Attribute form DW_FORM_*.  */
347       ULONGEST form;
348
349       /* Value if FORM is DW_FORM_implicit_const.  */
350       LONGEST implicit_const;
351     };
352     std::vector<attr> attr_vec;
353   };
354
355   std::unordered_map<ULONGEST, index_val> abbrev_map;
356
357   const char *namei_to_name (uint32_t namei) const;
358
359   /* Implementation of the mapped_index_base virtual interface, for
360      the name_components cache.  */
361
362   const char *symbol_name_at (offset_type idx) const override
363   { return namei_to_name (idx); }
364
365   size_t symbol_name_count () const override
366   { return this->name_count; }
367 };
368
369 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
370 DEF_VEC_P (dwarf2_per_cu_ptr);
371
372 struct tu_stats
373 {
374   int nr_uniq_abbrev_tables;
375   int nr_symtabs;
376   int nr_symtab_sharers;
377   int nr_stmt_less_type_units;
378   int nr_all_type_units_reallocs;
379 };
380
381 /* Collection of data recorded per objfile.
382    This hangs off of dwarf2_objfile_data_key.  */
383
384 struct dwarf2_per_objfile : public allocate_on_obstack
385 {
386   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
387      dwarf2 section names, or is NULL if the standard ELF names are
388      used.  */
389   dwarf2_per_objfile (struct objfile *objfile,
390                       const dwarf2_debug_sections *names);
391
392   ~dwarf2_per_objfile ();
393
394   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
395
396   /* Free all cached compilation units.  */
397   void free_cached_comp_units ();
398 private:
399   /* This function is mapped across the sections and remembers the
400      offset and size of each of the debugging sections we are
401      interested in.  */
402   void locate_sections (bfd *abfd, asection *sectp,
403                         const dwarf2_debug_sections &names);
404
405 public:
406   dwarf2_section_info info {};
407   dwarf2_section_info abbrev {};
408   dwarf2_section_info line {};
409   dwarf2_section_info loc {};
410   dwarf2_section_info loclists {};
411   dwarf2_section_info macinfo {};
412   dwarf2_section_info macro {};
413   dwarf2_section_info str {};
414   dwarf2_section_info line_str {};
415   dwarf2_section_info ranges {};
416   dwarf2_section_info rnglists {};
417   dwarf2_section_info addr {};
418   dwarf2_section_info frame {};
419   dwarf2_section_info eh_frame {};
420   dwarf2_section_info gdb_index {};
421   dwarf2_section_info debug_names {};
422   dwarf2_section_info debug_aranges {};
423
424   VEC (dwarf2_section_info_def) *types = NULL;
425
426   /* Back link.  */
427   struct objfile *objfile = NULL;
428
429   /* Table of all the compilation units.  This is used to locate
430      the target compilation unit of a particular reference.  */
431   struct dwarf2_per_cu_data **all_comp_units = NULL;
432
433   /* The number of compilation units in ALL_COMP_UNITS.  */
434   int n_comp_units = 0;
435
436   /* The number of .debug_types-related CUs.  */
437   int n_type_units = 0;
438
439   /* The number of elements allocated in all_type_units.
440      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
441   int n_allocated_type_units = 0;
442
443   /* The .debug_types-related CUs (TUs).
444      This is stored in malloc space because we may realloc it.  */
445   struct signatured_type **all_type_units = NULL;
446
447   /* Table of struct type_unit_group objects.
448      The hash key is the DW_AT_stmt_list value.  */
449   htab_t type_unit_groups {};
450
451   /* A table mapping .debug_types signatures to its signatured_type entry.
452      This is NULL if the .debug_types section hasn't been read in yet.  */
453   htab_t signatured_types {};
454
455   /* Type unit statistics, to see how well the scaling improvements
456      are doing.  */
457   struct tu_stats tu_stats {};
458
459   /* A chain of compilation units that are currently read in, so that
460      they can be freed later.  */
461   dwarf2_per_cu_data *read_in_chain = NULL;
462
463   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
464      This is NULL if the table hasn't been allocated yet.  */
465   htab_t dwo_files {};
466
467   /* True if we've checked for whether there is a DWP file.  */
468   bool dwp_checked = false;
469
470   /* The DWP file if there is one, or NULL.  */
471   struct dwp_file *dwp_file = NULL;
472
473   /* The shared '.dwz' file, if one exists.  This is used when the
474      original data was compressed using 'dwz -m'.  */
475   struct dwz_file *dwz_file = NULL;
476
477   /* A flag indicating whether this objfile has a section loaded at a
478      VMA of 0.  */
479   bool has_section_at_zero = false;
480
481   /* True if we are using the mapped index,
482      or we are faking it for OBJF_READNOW's sake.  */
483   bool using_index = false;
484
485   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
486   mapped_index *index_table = NULL;
487
488   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
489   std::unique_ptr<mapped_debug_names> debug_names_table;
490
491   /* When using index_table, this keeps track of all quick_file_names entries.
492      TUs typically share line table entries with a CU, so we maintain a
493      separate table of all line table entries to support the sharing.
494      Note that while there can be way more TUs than CUs, we've already
495      sorted all the TUs into "type unit groups", grouped by their
496      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
497      CU and its associated TU group if there is one.  */
498   htab_t quick_file_names_table {};
499
500   /* Set during partial symbol reading, to prevent queueing of full
501      symbols.  */
502   bool reading_partial_symbols = false;
503
504   /* Table mapping type DIEs to their struct type *.
505      This is NULL if not allocated yet.
506      The mapping is done via (CU/TU + DIE offset) -> type.  */
507   htab_t die_type_hash {};
508
509   /* The CUs we recently read.  */
510   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
511
512   /* Table containing line_header indexed by offset and offset_in_dwz.  */
513   htab_t line_header_hash {};
514
515   /* Table containing all filenames.  This is an optional because the
516      table is lazily constructed on first access.  */
517   gdb::optional<filename_seen_cache> filenames_cache;
518 };
519
520 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
521
522 struct dwarf2_per_objfile *
523 get_dwarf2_per_objfile (struct objfile *objfile)
524 {
525   return ((struct dwarf2_per_objfile *)
526           objfile_data (objfile, dwarf2_objfile_data_key));
527 }
528
529 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
530
531 void
532 set_dwarf2_per_objfile (struct objfile *objfile,
533                         struct dwarf2_per_objfile *dwarf2_per_objfile)
534 {
535   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
536   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
537 }
538
539 /* Default names of the debugging sections.  */
540
541 /* Note that if the debugging section has been compressed, it might
542    have a name like .zdebug_info.  */
543
544 static const struct dwarf2_debug_sections dwarf2_elf_names =
545 {
546   { ".debug_info", ".zdebug_info" },
547   { ".debug_abbrev", ".zdebug_abbrev" },
548   { ".debug_line", ".zdebug_line" },
549   { ".debug_loc", ".zdebug_loc" },
550   { ".debug_loclists", ".zdebug_loclists" },
551   { ".debug_macinfo", ".zdebug_macinfo" },
552   { ".debug_macro", ".zdebug_macro" },
553   { ".debug_str", ".zdebug_str" },
554   { ".debug_line_str", ".zdebug_line_str" },
555   { ".debug_ranges", ".zdebug_ranges" },
556   { ".debug_rnglists", ".zdebug_rnglists" },
557   { ".debug_types", ".zdebug_types" },
558   { ".debug_addr", ".zdebug_addr" },
559   { ".debug_frame", ".zdebug_frame" },
560   { ".eh_frame", NULL },
561   { ".gdb_index", ".zgdb_index" },
562   { ".debug_names", ".zdebug_names" },
563   { ".debug_aranges", ".zdebug_aranges" },
564   23
565 };
566
567 /* List of DWO/DWP sections.  */
568
569 static const struct dwop_section_names
570 {
571   struct dwarf2_section_names abbrev_dwo;
572   struct dwarf2_section_names info_dwo;
573   struct dwarf2_section_names line_dwo;
574   struct dwarf2_section_names loc_dwo;
575   struct dwarf2_section_names loclists_dwo;
576   struct dwarf2_section_names macinfo_dwo;
577   struct dwarf2_section_names macro_dwo;
578   struct dwarf2_section_names str_dwo;
579   struct dwarf2_section_names str_offsets_dwo;
580   struct dwarf2_section_names types_dwo;
581   struct dwarf2_section_names cu_index;
582   struct dwarf2_section_names tu_index;
583 }
584 dwop_section_names =
585 {
586   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
587   { ".debug_info.dwo", ".zdebug_info.dwo" },
588   { ".debug_line.dwo", ".zdebug_line.dwo" },
589   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
590   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
591   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
592   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
593   { ".debug_str.dwo", ".zdebug_str.dwo" },
594   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
595   { ".debug_types.dwo", ".zdebug_types.dwo" },
596   { ".debug_cu_index", ".zdebug_cu_index" },
597   { ".debug_tu_index", ".zdebug_tu_index" },
598 };
599
600 /* local data types */
601
602 /* The data in a compilation unit header, after target2host
603    translation, looks like this.  */
604 struct comp_unit_head
605 {
606   unsigned int length;
607   short version;
608   unsigned char addr_size;
609   unsigned char signed_addr_p;
610   sect_offset abbrev_sect_off;
611
612   /* Size of file offsets; either 4 or 8.  */
613   unsigned int offset_size;
614
615   /* Size of the length field; either 4 or 12.  */
616   unsigned int initial_length_size;
617
618   enum dwarf_unit_type unit_type;
619
620   /* Offset to the first byte of this compilation unit header in the
621      .debug_info section, for resolving relative reference dies.  */
622   sect_offset sect_off;
623
624   /* Offset to first die in this cu from the start of the cu.
625      This will be the first byte following the compilation unit header.  */
626   cu_offset first_die_cu_offset;
627
628   /* 64-bit signature of this type unit - it is valid only for
629      UNIT_TYPE DW_UT_type.  */
630   ULONGEST signature;
631
632   /* For types, offset in the type's DIE of the type defined by this TU.  */
633   cu_offset type_cu_offset_in_tu;
634 };
635
636 /* Type used for delaying computation of method physnames.
637    See comments for compute_delayed_physnames.  */
638 struct delayed_method_info
639 {
640   /* The type to which the method is attached, i.e., its parent class.  */
641   struct type *type;
642
643   /* The index of the method in the type's function fieldlists.  */
644   int fnfield_index;
645
646   /* The index of the method in the fieldlist.  */
647   int index;
648
649   /* The name of the DIE.  */
650   const char *name;
651
652   /*  The DIE associated with this method.  */
653   struct die_info *die;
654 };
655
656 /* Internal state when decoding a particular compilation unit.  */
657 struct dwarf2_cu
658 {
659   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
660   ~dwarf2_cu ();
661
662   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
663
664   /* The header of the compilation unit.  */
665   struct comp_unit_head header {};
666
667   /* Base address of this compilation unit.  */
668   CORE_ADDR base_address = 0;
669
670   /* Non-zero if base_address has been set.  */
671   int base_known = 0;
672
673   /* The language we are debugging.  */
674   enum language language = language_unknown;
675   const struct language_defn *language_defn = nullptr;
676
677   const char *producer = nullptr;
678
679   /* The generic symbol table building routines have separate lists for
680      file scope symbols and all all other scopes (local scopes).  So
681      we need to select the right one to pass to add_symbol_to_list().
682      We do it by keeping a pointer to the correct list in list_in_scope.
683
684      FIXME: The original dwarf code just treated the file scope as the
685      first local scope, and all other local scopes as nested local
686      scopes, and worked fine.  Check to see if we really need to
687      distinguish these in buildsym.c.  */
688   struct pending **list_in_scope = nullptr;
689
690   /* Hash table holding all the loaded partial DIEs
691      with partial_die->offset.SECT_OFF as hash.  */
692   htab_t partial_dies = nullptr;
693
694   /* Storage for things with the same lifetime as this read-in compilation
695      unit, including partial DIEs.  */
696   auto_obstack comp_unit_obstack;
697
698   /* When multiple dwarf2_cu structures are living in memory, this field
699      chains them all together, so that they can be released efficiently.
700      We will probably also want a generation counter so that most-recently-used
701      compilation units are cached...  */
702   struct dwarf2_per_cu_data *read_in_chain = nullptr;
703
704   /* Backlink to our per_cu entry.  */
705   struct dwarf2_per_cu_data *per_cu;
706
707   /* How many compilation units ago was this CU last referenced?  */
708   int last_used = 0;
709
710   /* A hash table of DIE cu_offset for following references with
711      die_info->offset.sect_off as hash.  */
712   htab_t die_hash = nullptr;
713
714   /* Full DIEs if read in.  */
715   struct die_info *dies = nullptr;
716
717   /* A set of pointers to dwarf2_per_cu_data objects for compilation
718      units referenced by this one.  Only set during full symbol processing;
719      partial symbol tables do not have dependencies.  */
720   htab_t dependencies = nullptr;
721
722   /* Header data from the line table, during full symbol processing.  */
723   struct line_header *line_header = nullptr;
724   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
725      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
726      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
727      to the line header as long as this DIE is being processed.  See
728      process_die_scope.  */
729   die_info *line_header_die_owner = nullptr;
730
731   /* A list of methods which need to have physnames computed
732      after all type information has been read.  */
733   std::vector<delayed_method_info> method_list;
734
735   /* To be copied to symtab->call_site_htab.  */
736   htab_t call_site_htab = nullptr;
737
738   /* Non-NULL if this CU came from a DWO file.
739      There is an invariant here that is important to remember:
740      Except for attributes copied from the top level DIE in the "main"
741      (or "stub") file in preparation for reading the DWO file
742      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
743      Either there isn't a DWO file (in which case this is NULL and the point
744      is moot), or there is and either we're not going to read it (in which
745      case this is NULL) or there is and we are reading it (in which case this
746      is non-NULL).  */
747   struct dwo_unit *dwo_unit = nullptr;
748
749   /* The DW_AT_addr_base attribute if present, zero otherwise
750      (zero is a valid value though).
751      Note this value comes from the Fission stub CU/TU's DIE.  */
752   ULONGEST addr_base = 0;
753
754   /* The DW_AT_ranges_base attribute if present, zero otherwise
755      (zero is a valid value though).
756      Note this value comes from the Fission stub CU/TU's DIE.
757      Also note that the value is zero in the non-DWO case so this value can
758      be used without needing to know whether DWO files are in use or not.
759      N.B. This does not apply to DW_AT_ranges appearing in
760      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
761      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
762      DW_AT_ranges_base *would* have to be applied, and we'd have to care
763      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
764   ULONGEST ranges_base = 0;
765
766   /* When reading debug info generated by older versions of rustc, we
767      have to rewrite some union types to be struct types with a
768      variant part.  This rewriting must be done after the CU is fully
769      read in, because otherwise at the point of rewriting some struct
770      type might not have been fully processed.  So, we keep a list of
771      all such types here and process them after expansion.  */
772   std::vector<struct type *> rust_unions;
773
774   /* Mark used when releasing cached dies.  */
775   unsigned int mark : 1;
776
777   /* This CU references .debug_loc.  See the symtab->locations_valid field.
778      This test is imperfect as there may exist optimized debug code not using
779      any location list and still facing inlining issues if handled as
780      unoptimized code.  For a future better test see GCC PR other/32998.  */
781   unsigned int has_loclist : 1;
782
783   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
784      if all the producer_is_* fields are valid.  This information is cached
785      because profiling CU expansion showed excessive time spent in
786      producer_is_gxx_lt_4_6.  */
787   unsigned int checked_producer : 1;
788   unsigned int producer_is_gxx_lt_4_6 : 1;
789   unsigned int producer_is_gcc_lt_4_3 : 1;
790   unsigned int producer_is_icc_lt_14 : 1;
791
792   /* When set, the file that we're processing is known to have
793      debugging info for C++ namespaces.  GCC 3.3.x did not produce
794      this information, but later versions do.  */
795
796   unsigned int processing_has_namespace_info : 1;
797
798   struct partial_die_info *find_partial_die (sect_offset sect_off);
799 };
800
801 /* Persistent data held for a compilation unit, even when not
802    processing it.  We put a pointer to this structure in the
803    read_symtab_private field of the psymtab.  */
804
805 struct dwarf2_per_cu_data
806 {
807   /* The start offset and length of this compilation unit.
808      NOTE: Unlike comp_unit_head.length, this length includes
809      initial_length_size.
810      If the DIE refers to a DWO file, this is always of the original die,
811      not the DWO file.  */
812   sect_offset sect_off;
813   unsigned int length;
814
815   /* DWARF standard version this data has been read from (such as 4 or 5).  */
816   short dwarf_version;
817
818   /* Flag indicating this compilation unit will be read in before
819      any of the current compilation units are processed.  */
820   unsigned int queued : 1;
821
822   /* This flag will be set when reading partial DIEs if we need to load
823      absolutely all DIEs for this compilation unit, instead of just the ones
824      we think are interesting.  It gets set if we look for a DIE in the
825      hash table and don't find it.  */
826   unsigned int load_all_dies : 1;
827
828   /* Non-zero if this CU is from .debug_types.
829      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
830      this is non-zero.  */
831   unsigned int is_debug_types : 1;
832
833   /* Non-zero if this CU is from the .dwz file.  */
834   unsigned int is_dwz : 1;
835
836   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
837      This flag is only valid if is_debug_types is true.
838      We can't read a CU directly from a DWO file: There are required
839      attributes in the stub.  */
840   unsigned int reading_dwo_directly : 1;
841
842   /* Non-zero if the TU has been read.
843      This is used to assist the "Stay in DWO Optimization" for Fission:
844      When reading a DWO, it's faster to read TUs from the DWO instead of
845      fetching them from random other DWOs (due to comdat folding).
846      If the TU has already been read, the optimization is unnecessary
847      (and unwise - we don't want to change where gdb thinks the TU lives
848      "midflight").
849      This flag is only valid if is_debug_types is true.  */
850   unsigned int tu_read : 1;
851
852   /* The section this CU/TU lives in.
853      If the DIE refers to a DWO file, this is always the original die,
854      not the DWO file.  */
855   struct dwarf2_section_info *section;
856
857   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
858      of the CU cache it gets reset to NULL again.  This is left as NULL for
859      dummy CUs (a CU header, but nothing else).  */
860   struct dwarf2_cu *cu;
861
862   /* The corresponding dwarf2_per_objfile.  */
863   struct dwarf2_per_objfile *dwarf2_per_objfile;
864
865   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
866      is active.  Otherwise, the 'psymtab' field is active.  */
867   union
868   {
869     /* The partial symbol table associated with this compilation unit,
870        or NULL for unread partial units.  */
871     struct partial_symtab *psymtab;
872
873     /* Data needed by the "quick" functions.  */
874     struct dwarf2_per_cu_quick_data *quick;
875   } v;
876
877   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
878      while reading psymtabs, used to compute the psymtab dependencies,
879      and then cleared.  Then it is filled in again while reading full
880      symbols, and only deleted when the objfile is destroyed.
881
882      This is also used to work around a difference between the way gold
883      generates .gdb_index version <=7 and the way gdb does.  Arguably this
884      is a gold bug.  For symbols coming from TUs, gold records in the index
885      the CU that includes the TU instead of the TU itself.  This breaks
886      dw2_lookup_symbol: It assumes that if the index says symbol X lives
887      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
888      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
889      we need to look in TU Z to find X.  Fortunately, this is akin to
890      DW_TAG_imported_unit, so we just use the same mechanism: For
891      .gdb_index version <=7 this also records the TUs that the CU referred
892      to.  Concurrently with this change gdb was modified to emit version 8
893      indices so we only pay a price for gold generated indices.
894      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
895   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
896 };
897
898 /* Entry in the signatured_types hash table.  */
899
900 struct signatured_type
901 {
902   /* The "per_cu" object of this type.
903      This struct is used iff per_cu.is_debug_types.
904      N.B.: This is the first member so that it's easy to convert pointers
905      between them.  */
906   struct dwarf2_per_cu_data per_cu;
907
908   /* The type's signature.  */
909   ULONGEST signature;
910
911   /* Offset in the TU of the type's DIE, as read from the TU header.
912      If this TU is a DWO stub and the definition lives in a DWO file
913      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
914   cu_offset type_offset_in_tu;
915
916   /* Offset in the section of the type's DIE.
917      If the definition lives in a DWO file, this is the offset in the
918      .debug_types.dwo section.
919      The value is zero until the actual value is known.
920      Zero is otherwise not a valid section offset.  */
921   sect_offset type_offset_in_section;
922
923   /* Type units are grouped by their DW_AT_stmt_list entry so that they
924      can share them.  This points to the containing symtab.  */
925   struct type_unit_group *type_unit_group;
926
927   /* The type.
928      The first time we encounter this type we fully read it in and install it
929      in the symbol tables.  Subsequent times we only need the type.  */
930   struct type *type;
931
932   /* Containing DWO unit.
933      This field is valid iff per_cu.reading_dwo_directly.  */
934   struct dwo_unit *dwo_unit;
935 };
936
937 typedef struct signatured_type *sig_type_ptr;
938 DEF_VEC_P (sig_type_ptr);
939
940 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
941    This includes type_unit_group and quick_file_names.  */
942
943 struct stmt_list_hash
944 {
945   /* The DWO unit this table is from or NULL if there is none.  */
946   struct dwo_unit *dwo_unit;
947
948   /* Offset in .debug_line or .debug_line.dwo.  */
949   sect_offset line_sect_off;
950 };
951
952 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
953    an object of this type.  */
954
955 struct type_unit_group
956 {
957   /* dwarf2read.c's main "handle" on a TU symtab.
958      To simplify things we create an artificial CU that "includes" all the
959      type units using this stmt_list so that the rest of the code still has
960      a "per_cu" handle on the symtab.
961      This PER_CU is recognized by having no section.  */
962 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
963   struct dwarf2_per_cu_data per_cu;
964
965   /* The TUs that share this DW_AT_stmt_list entry.
966      This is added to while parsing type units to build partial symtabs,
967      and is deleted afterwards and not used again.  */
968   VEC (sig_type_ptr) *tus;
969
970   /* The compunit symtab.
971      Type units in a group needn't all be defined in the same source file,
972      so we create an essentially anonymous symtab as the compunit symtab.  */
973   struct compunit_symtab *compunit_symtab;
974
975   /* The data used to construct the hash key.  */
976   struct stmt_list_hash hash;
977
978   /* The number of symtabs from the line header.
979      The value here must match line_header.num_file_names.  */
980   unsigned int num_symtabs;
981
982   /* The symbol tables for this TU (obtained from the files listed in
983      DW_AT_stmt_list).
984      WARNING: The order of entries here must match the order of entries
985      in the line header.  After the first TU using this type_unit_group, the
986      line header for the subsequent TUs is recreated from this.  This is done
987      because we need to use the same symtabs for each TU using the same
988      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
989      there's no guarantee the line header doesn't have duplicate entries.  */
990   struct symtab **symtabs;
991 };
992
993 /* These sections are what may appear in a (real or virtual) DWO file.  */
994
995 struct dwo_sections
996 {
997   struct dwarf2_section_info abbrev;
998   struct dwarf2_section_info line;
999   struct dwarf2_section_info loc;
1000   struct dwarf2_section_info loclists;
1001   struct dwarf2_section_info macinfo;
1002   struct dwarf2_section_info macro;
1003   struct dwarf2_section_info str;
1004   struct dwarf2_section_info str_offsets;
1005   /* In the case of a virtual DWO file, these two are unused.  */
1006   struct dwarf2_section_info info;
1007   VEC (dwarf2_section_info_def) *types;
1008 };
1009
1010 /* CUs/TUs in DWP/DWO files.  */
1011
1012 struct dwo_unit
1013 {
1014   /* Backlink to the containing struct dwo_file.  */
1015   struct dwo_file *dwo_file;
1016
1017   /* The "id" that distinguishes this CU/TU.
1018      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1019      Since signatures came first, we stick with it for consistency.  */
1020   ULONGEST signature;
1021
1022   /* The section this CU/TU lives in, in the DWO file.  */
1023   struct dwarf2_section_info *section;
1024
1025   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1026   sect_offset sect_off;
1027   unsigned int length;
1028
1029   /* For types, offset in the type's DIE of the type defined by this TU.  */
1030   cu_offset type_offset_in_tu;
1031 };
1032
1033 /* include/dwarf2.h defines the DWP section codes.
1034    It defines a max value but it doesn't define a min value, which we
1035    use for error checking, so provide one.  */
1036
1037 enum dwp_v2_section_ids
1038 {
1039   DW_SECT_MIN = 1
1040 };
1041
1042 /* Data for one DWO file.
1043
1044    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1045    appears in a DWP file).  DWP files don't really have DWO files per se -
1046    comdat folding of types "loses" the DWO file they came from, and from
1047    a high level view DWP files appear to contain a mass of random types.
1048    However, to maintain consistency with the non-DWP case we pretend DWP
1049    files contain virtual DWO files, and we assign each TU with one virtual
1050    DWO file (generally based on the line and abbrev section offsets -
1051    a heuristic that seems to work in practice).  */
1052
1053 struct dwo_file
1054 {
1055   /* The DW_AT_GNU_dwo_name attribute.
1056      For virtual DWO files the name is constructed from the section offsets
1057      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1058      from related CU+TUs.  */
1059   const char *dwo_name;
1060
1061   /* The DW_AT_comp_dir attribute.  */
1062   const char *comp_dir;
1063
1064   /* The bfd, when the file is open.  Otherwise this is NULL.
1065      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1066   bfd *dbfd;
1067
1068   /* The sections that make up this DWO file.
1069      Remember that for virtual DWO files in DWP V2, these are virtual
1070      sections (for lack of a better name).  */
1071   struct dwo_sections sections;
1072
1073   /* The CUs in the file.
1074      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1075      an extension to handle LLVM's Link Time Optimization output (where
1076      multiple source files may be compiled into a single object/dwo pair). */
1077   htab_t cus;
1078
1079   /* Table of TUs in the file.
1080      Each element is a struct dwo_unit.  */
1081   htab_t tus;
1082 };
1083
1084 /* These sections are what may appear in a DWP file.  */
1085
1086 struct dwp_sections
1087 {
1088   /* These are used by both DWP version 1 and 2.  */
1089   struct dwarf2_section_info str;
1090   struct dwarf2_section_info cu_index;
1091   struct dwarf2_section_info tu_index;
1092
1093   /* These are only used by DWP version 2 files.
1094      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1095      sections are referenced by section number, and are not recorded here.
1096      In DWP version 2 there is at most one copy of all these sections, each
1097      section being (effectively) comprised of the concatenation of all of the
1098      individual sections that exist in the version 1 format.
1099      To keep the code simple we treat each of these concatenated pieces as a
1100      section itself (a virtual section?).  */
1101   struct dwarf2_section_info abbrev;
1102   struct dwarf2_section_info info;
1103   struct dwarf2_section_info line;
1104   struct dwarf2_section_info loc;
1105   struct dwarf2_section_info macinfo;
1106   struct dwarf2_section_info macro;
1107   struct dwarf2_section_info str_offsets;
1108   struct dwarf2_section_info types;
1109 };
1110
1111 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1112    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1113
1114 struct virtual_v1_dwo_sections
1115 {
1116   struct dwarf2_section_info abbrev;
1117   struct dwarf2_section_info line;
1118   struct dwarf2_section_info loc;
1119   struct dwarf2_section_info macinfo;
1120   struct dwarf2_section_info macro;
1121   struct dwarf2_section_info str_offsets;
1122   /* Each DWP hash table entry records one CU or one TU.
1123      That is recorded here, and copied to dwo_unit.section.  */
1124   struct dwarf2_section_info info_or_types;
1125 };
1126
1127 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1128    In version 2, the sections of the DWO files are concatenated together
1129    and stored in one section of that name.  Thus each ELF section contains
1130    several "virtual" sections.  */
1131
1132 struct virtual_v2_dwo_sections
1133 {
1134   bfd_size_type abbrev_offset;
1135   bfd_size_type abbrev_size;
1136
1137   bfd_size_type line_offset;
1138   bfd_size_type line_size;
1139
1140   bfd_size_type loc_offset;
1141   bfd_size_type loc_size;
1142
1143   bfd_size_type macinfo_offset;
1144   bfd_size_type macinfo_size;
1145
1146   bfd_size_type macro_offset;
1147   bfd_size_type macro_size;
1148
1149   bfd_size_type str_offsets_offset;
1150   bfd_size_type str_offsets_size;
1151
1152   /* Each DWP hash table entry records one CU or one TU.
1153      That is recorded here, and copied to dwo_unit.section.  */
1154   bfd_size_type info_or_types_offset;
1155   bfd_size_type info_or_types_size;
1156 };
1157
1158 /* Contents of DWP hash tables.  */
1159
1160 struct dwp_hash_table
1161 {
1162   uint32_t version, nr_columns;
1163   uint32_t nr_units, nr_slots;
1164   const gdb_byte *hash_table, *unit_table;
1165   union
1166   {
1167     struct
1168     {
1169       const gdb_byte *indices;
1170     } v1;
1171     struct
1172     {
1173       /* This is indexed by column number and gives the id of the section
1174          in that column.  */
1175 #define MAX_NR_V2_DWO_SECTIONS \
1176   (1 /* .debug_info or .debug_types */ \
1177    + 1 /* .debug_abbrev */ \
1178    + 1 /* .debug_line */ \
1179    + 1 /* .debug_loc */ \
1180    + 1 /* .debug_str_offsets */ \
1181    + 1 /* .debug_macro or .debug_macinfo */)
1182       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1183       const gdb_byte *offsets;
1184       const gdb_byte *sizes;
1185     } v2;
1186   } section_pool;
1187 };
1188
1189 /* Data for one DWP file.  */
1190
1191 struct dwp_file
1192 {
1193   /* Name of the file.  */
1194   const char *name;
1195
1196   /* File format version.  */
1197   int version;
1198
1199   /* The bfd.  */
1200   bfd *dbfd;
1201
1202   /* Section info for this file.  */
1203   struct dwp_sections sections;
1204
1205   /* Table of CUs in the file.  */
1206   const struct dwp_hash_table *cus;
1207
1208   /* Table of TUs in the file.  */
1209   const struct dwp_hash_table *tus;
1210
1211   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1212   htab_t loaded_cus;
1213   htab_t loaded_tus;
1214
1215   /* Table to map ELF section numbers to their sections.
1216      This is only needed for the DWP V1 file format.  */
1217   unsigned int num_sections;
1218   asection **elf_sections;
1219 };
1220
1221 /* This represents a '.dwz' file.  */
1222
1223 struct dwz_file
1224 {
1225   /* A dwz file can only contain a few sections.  */
1226   struct dwarf2_section_info abbrev;
1227   struct dwarf2_section_info info;
1228   struct dwarf2_section_info str;
1229   struct dwarf2_section_info line;
1230   struct dwarf2_section_info macro;
1231   struct dwarf2_section_info gdb_index;
1232   struct dwarf2_section_info debug_names;
1233
1234   /* The dwz's BFD.  */
1235   bfd *dwz_bfd;
1236 };
1237
1238 /* Struct used to pass misc. parameters to read_die_and_children, et
1239    al.  which are used for both .debug_info and .debug_types dies.
1240    All parameters here are unchanging for the life of the call.  This
1241    struct exists to abstract away the constant parameters of die reading.  */
1242
1243 struct die_reader_specs
1244 {
1245   /* The bfd of die_section.  */
1246   bfd* abfd;
1247
1248   /* The CU of the DIE we are parsing.  */
1249   struct dwarf2_cu *cu;
1250
1251   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1252   struct dwo_file *dwo_file;
1253
1254   /* The section the die comes from.
1255      This is either .debug_info or .debug_types, or the .dwo variants.  */
1256   struct dwarf2_section_info *die_section;
1257
1258   /* die_section->buffer.  */
1259   const gdb_byte *buffer;
1260
1261   /* The end of the buffer.  */
1262   const gdb_byte *buffer_end;
1263
1264   /* The value of the DW_AT_comp_dir attribute.  */
1265   const char *comp_dir;
1266
1267   /* The abbreviation table to use when reading the DIEs.  */
1268   struct abbrev_table *abbrev_table;
1269 };
1270
1271 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1272 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1273                                       const gdb_byte *info_ptr,
1274                                       struct die_info *comp_unit_die,
1275                                       int has_children,
1276                                       void *data);
1277
1278 /* A 1-based directory index.  This is a strong typedef to prevent
1279    accidentally using a directory index as a 0-based index into an
1280    array/vector.  */
1281 enum class dir_index : unsigned int {};
1282
1283 /* Likewise, a 1-based file name index.  */
1284 enum class file_name_index : unsigned int {};
1285
1286 struct file_entry
1287 {
1288   file_entry () = default;
1289
1290   file_entry (const char *name_, dir_index d_index_,
1291               unsigned int mod_time_, unsigned int length_)
1292     : name (name_),
1293       d_index (d_index_),
1294       mod_time (mod_time_),
1295       length (length_)
1296   {}
1297
1298   /* Return the include directory at D_INDEX stored in LH.  Returns
1299      NULL if D_INDEX is out of bounds.  */
1300   const char *include_dir (const line_header *lh) const;
1301
1302   /* The file name.  Note this is an observing pointer.  The memory is
1303      owned by debug_line_buffer.  */
1304   const char *name {};
1305
1306   /* The directory index (1-based).  */
1307   dir_index d_index {};
1308
1309   unsigned int mod_time {};
1310
1311   unsigned int length {};
1312
1313   /* True if referenced by the Line Number Program.  */
1314   bool included_p {};
1315
1316   /* The associated symbol table, if any.  */
1317   struct symtab *symtab {};
1318 };
1319
1320 /* The line number information for a compilation unit (found in the
1321    .debug_line section) begins with a "statement program header",
1322    which contains the following information.  */
1323 struct line_header
1324 {
1325   line_header ()
1326     : offset_in_dwz {}
1327   {}
1328
1329   /* Add an entry to the include directory table.  */
1330   void add_include_dir (const char *include_dir);
1331
1332   /* Add an entry to the file name table.  */
1333   void add_file_name (const char *name, dir_index d_index,
1334                       unsigned int mod_time, unsigned int length);
1335
1336   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1337      is out of bounds.  */
1338   const char *include_dir_at (dir_index index) const
1339   {
1340     /* Convert directory index number (1-based) to vector index
1341        (0-based).  */
1342     size_t vec_index = to_underlying (index) - 1;
1343
1344     if (vec_index >= include_dirs.size ())
1345       return NULL;
1346     return include_dirs[vec_index];
1347   }
1348
1349   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1350      is out of bounds.  */
1351   file_entry *file_name_at (file_name_index index)
1352   {
1353     /* Convert file name index number (1-based) to vector index
1354        (0-based).  */
1355     size_t vec_index = to_underlying (index) - 1;
1356
1357     if (vec_index >= file_names.size ())
1358       return NULL;
1359     return &file_names[vec_index];
1360   }
1361
1362   /* Const version of the above.  */
1363   const file_entry *file_name_at (unsigned int index) const
1364   {
1365     if (index >= file_names.size ())
1366       return NULL;
1367     return &file_names[index];
1368   }
1369
1370   /* Offset of line number information in .debug_line section.  */
1371   sect_offset sect_off {};
1372
1373   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1374   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1375
1376   unsigned int total_length {};
1377   unsigned short version {};
1378   unsigned int header_length {};
1379   unsigned char minimum_instruction_length {};
1380   unsigned char maximum_ops_per_instruction {};
1381   unsigned char default_is_stmt {};
1382   int line_base {};
1383   unsigned char line_range {};
1384   unsigned char opcode_base {};
1385
1386   /* standard_opcode_lengths[i] is the number of operands for the
1387      standard opcode whose value is i.  This means that
1388      standard_opcode_lengths[0] is unused, and the last meaningful
1389      element is standard_opcode_lengths[opcode_base - 1].  */
1390   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1391
1392   /* The include_directories table.  Note these are observing
1393      pointers.  The memory is owned by debug_line_buffer.  */
1394   std::vector<const char *> include_dirs;
1395
1396   /* The file_names table.  */
1397   std::vector<file_entry> file_names;
1398
1399   /* The start and end of the statement program following this
1400      header.  These point into dwarf2_per_objfile->line_buffer.  */
1401   const gdb_byte *statement_program_start {}, *statement_program_end {};
1402 };
1403
1404 typedef std::unique_ptr<line_header> line_header_up;
1405
1406 const char *
1407 file_entry::include_dir (const line_header *lh) const
1408 {
1409   return lh->include_dir_at (d_index);
1410 }
1411
1412 /* When we construct a partial symbol table entry we only
1413    need this much information.  */
1414 struct partial_die_info : public allocate_on_obstack
1415   {
1416     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1417
1418     /* Disable assign but still keep copy ctor, which is needed
1419        load_partial_dies.   */
1420     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1421
1422     /* Adjust the partial die before generating a symbol for it.  This
1423        function may set the is_external flag or change the DIE's
1424        name.  */
1425     void fixup (struct dwarf2_cu *cu);
1426
1427     /* Read a minimal amount of information into the minimal die
1428        structure.  */
1429     const gdb_byte *read (const struct die_reader_specs *reader,
1430                           const struct abbrev_info &abbrev,
1431                           const gdb_byte *info_ptr);
1432
1433     /* Offset of this DIE.  */
1434     const sect_offset sect_off;
1435
1436     /* DWARF-2 tag for this DIE.  */
1437     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1438
1439     /* Assorted flags describing the data found in this DIE.  */
1440     const unsigned int has_children : 1;
1441
1442     unsigned int is_external : 1;
1443     unsigned int is_declaration : 1;
1444     unsigned int has_type : 1;
1445     unsigned int has_specification : 1;
1446     unsigned int has_pc_info : 1;
1447     unsigned int may_be_inlined : 1;
1448
1449     /* This DIE has been marked DW_AT_main_subprogram.  */
1450     unsigned int main_subprogram : 1;
1451
1452     /* Flag set if the SCOPE field of this structure has been
1453        computed.  */
1454     unsigned int scope_set : 1;
1455
1456     /* Flag set if the DIE has a byte_size attribute.  */
1457     unsigned int has_byte_size : 1;
1458
1459     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1460     unsigned int has_const_value : 1;
1461
1462     /* Flag set if any of the DIE's children are template arguments.  */
1463     unsigned int has_template_arguments : 1;
1464
1465     /* Flag set if fixup has been called on this die.  */
1466     unsigned int fixup_called : 1;
1467
1468     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1469     unsigned int is_dwz : 1;
1470
1471     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1472     unsigned int spec_is_dwz : 1;
1473
1474     /* The name of this DIE.  Normally the value of DW_AT_name, but
1475        sometimes a default name for unnamed DIEs.  */
1476     const char *name = nullptr;
1477
1478     /* The linkage name, if present.  */
1479     const char *linkage_name = nullptr;
1480
1481     /* The scope to prepend to our children.  This is generally
1482        allocated on the comp_unit_obstack, so will disappear
1483        when this compilation unit leaves the cache.  */
1484     const char *scope = nullptr;
1485
1486     /* Some data associated with the partial DIE.  The tag determines
1487        which field is live.  */
1488     union
1489     {
1490       /* The location description associated with this DIE, if any.  */
1491       struct dwarf_block *locdesc;
1492       /* The offset of an import, for DW_TAG_imported_unit.  */
1493       sect_offset sect_off;
1494     } d {};
1495
1496     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1497     CORE_ADDR lowpc = 0;
1498     CORE_ADDR highpc = 0;
1499
1500     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1501        DW_AT_sibling, if any.  */
1502     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1503        could return DW_AT_sibling values to its caller load_partial_dies.  */
1504     const gdb_byte *sibling = nullptr;
1505
1506     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1507        DW_AT_specification (or DW_AT_abstract_origin or
1508        DW_AT_extension).  */
1509     sect_offset spec_offset {};
1510
1511     /* Pointers to this DIE's parent, first child, and next sibling,
1512        if any.  */
1513     struct partial_die_info *die_parent = nullptr;
1514     struct partial_die_info *die_child = nullptr;
1515     struct partial_die_info *die_sibling = nullptr;
1516
1517     friend struct partial_die_info *
1518     dwarf2_cu::find_partial_die (sect_offset sect_off);
1519
1520   private:
1521     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1522     partial_die_info (sect_offset sect_off)
1523       : partial_die_info (sect_off, DW_TAG_padding, 0)
1524     {
1525     }
1526
1527     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1528                       int has_children_)
1529       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1530     {
1531       is_external = 0;
1532       is_declaration = 0;
1533       has_type = 0;
1534       has_specification = 0;
1535       has_pc_info = 0;
1536       may_be_inlined = 0;
1537       main_subprogram = 0;
1538       scope_set = 0;
1539       has_byte_size = 0;
1540       has_const_value = 0;
1541       has_template_arguments = 0;
1542       fixup_called = 0;
1543       is_dwz = 0;
1544       spec_is_dwz = 0;
1545     }
1546   };
1547
1548 /* This data structure holds the information of an abbrev.  */
1549 struct abbrev_info
1550   {
1551     unsigned int number;        /* number identifying abbrev */
1552     enum dwarf_tag tag;         /* dwarf tag */
1553     unsigned short has_children;                /* boolean */
1554     unsigned short num_attrs;   /* number of attributes */
1555     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1556     struct abbrev_info *next;   /* next in chain */
1557   };
1558
1559 struct attr_abbrev
1560   {
1561     ENUM_BITFIELD(dwarf_attribute) name : 16;
1562     ENUM_BITFIELD(dwarf_form) form : 16;
1563
1564     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1565     LONGEST implicit_const;
1566   };
1567
1568 /* Size of abbrev_table.abbrev_hash_table.  */
1569 #define ABBREV_HASH_SIZE 121
1570
1571 /* Top level data structure to contain an abbreviation table.  */
1572
1573 struct abbrev_table
1574 {
1575   explicit abbrev_table (sect_offset off)
1576     : sect_off (off)
1577   {
1578     m_abbrevs =
1579       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1580     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1581   }
1582
1583   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1584
1585   /* Allocate space for a struct abbrev_info object in
1586      ABBREV_TABLE.  */
1587   struct abbrev_info *alloc_abbrev ();
1588
1589   /* Add an abbreviation to the table.  */
1590   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1591
1592   /* Look up an abbrev in the table.
1593      Returns NULL if the abbrev is not found.  */
1594
1595   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1596
1597
1598   /* Where the abbrev table came from.
1599      This is used as a sanity check when the table is used.  */
1600   const sect_offset sect_off;
1601
1602   /* Storage for the abbrev table.  */
1603   auto_obstack abbrev_obstack;
1604
1605 private:
1606
1607   /* Hash table of abbrevs.
1608      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1609      It could be statically allocated, but the previous code didn't so we
1610      don't either.  */
1611   struct abbrev_info **m_abbrevs;
1612 };
1613
1614 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1615
1616 /* Attributes have a name and a value.  */
1617 struct attribute
1618   {
1619     ENUM_BITFIELD(dwarf_attribute) name : 16;
1620     ENUM_BITFIELD(dwarf_form) form : 15;
1621
1622     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1623        field should be in u.str (existing only for DW_STRING) but it is kept
1624        here for better struct attribute alignment.  */
1625     unsigned int string_is_canonical : 1;
1626
1627     union
1628       {
1629         const char *str;
1630         struct dwarf_block *blk;
1631         ULONGEST unsnd;
1632         LONGEST snd;
1633         CORE_ADDR addr;
1634         ULONGEST signature;
1635       }
1636     u;
1637   };
1638
1639 /* This data structure holds a complete die structure.  */
1640 struct die_info
1641   {
1642     /* DWARF-2 tag for this DIE.  */
1643     ENUM_BITFIELD(dwarf_tag) tag : 16;
1644
1645     /* Number of attributes */
1646     unsigned char num_attrs;
1647
1648     /* True if we're presently building the full type name for the
1649        type derived from this DIE.  */
1650     unsigned char building_fullname : 1;
1651
1652     /* True if this die is in process.  PR 16581.  */
1653     unsigned char in_process : 1;
1654
1655     /* Abbrev number */
1656     unsigned int abbrev;
1657
1658     /* Offset in .debug_info or .debug_types section.  */
1659     sect_offset sect_off;
1660
1661     /* The dies in a compilation unit form an n-ary tree.  PARENT
1662        points to this die's parent; CHILD points to the first child of
1663        this node; and all the children of a given node are chained
1664        together via their SIBLING fields.  */
1665     struct die_info *child;     /* Its first child, if any.  */
1666     struct die_info *sibling;   /* Its next sibling, if any.  */
1667     struct die_info *parent;    /* Its parent, if any.  */
1668
1669     /* An array of attributes, with NUM_ATTRS elements.  There may be
1670        zero, but it's not common and zero-sized arrays are not
1671        sufficiently portable C.  */
1672     struct attribute attrs[1];
1673   };
1674
1675 /* Get at parts of an attribute structure.  */
1676
1677 #define DW_STRING(attr)    ((attr)->u.str)
1678 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1679 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1680 #define DW_BLOCK(attr)     ((attr)->u.blk)
1681 #define DW_SND(attr)       ((attr)->u.snd)
1682 #define DW_ADDR(attr)      ((attr)->u.addr)
1683 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1684
1685 /* Blocks are a bunch of untyped bytes.  */
1686 struct dwarf_block
1687   {
1688     size_t size;
1689
1690     /* Valid only if SIZE is not zero.  */
1691     const gdb_byte *data;
1692   };
1693
1694 #ifndef ATTR_ALLOC_CHUNK
1695 #define ATTR_ALLOC_CHUNK 4
1696 #endif
1697
1698 /* Allocate fields for structs, unions and enums in this size.  */
1699 #ifndef DW_FIELD_ALLOC_CHUNK
1700 #define DW_FIELD_ALLOC_CHUNK 4
1701 #endif
1702
1703 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1704    but this would require a corresponding change in unpack_field_as_long
1705    and friends.  */
1706 static int bits_per_byte = 8;
1707
1708 /* When reading a variant or variant part, we track a bit more
1709    information about the field, and store it in an object of this
1710    type.  */
1711
1712 struct variant_field
1713 {
1714   /* If we see a DW_TAG_variant, then this will be the discriminant
1715      value.  */
1716   ULONGEST discriminant_value;
1717   /* If we see a DW_TAG_variant, then this will be set if this is the
1718      default branch.  */
1719   bool default_branch;
1720   /* While reading a DW_TAG_variant_part, this will be set if this
1721      field is the discriminant.  */
1722   bool is_discriminant;
1723 };
1724
1725 struct nextfield
1726 {
1727   struct nextfield *next;
1728   int accessibility;
1729   int virtuality;
1730   /* Extra information to describe a variant or variant part.  */
1731   struct variant_field variant;
1732   struct field field;
1733 };
1734
1735 struct nextfnfield
1736 {
1737   struct nextfnfield *next;
1738   struct fn_field fnfield;
1739 };
1740
1741 struct fnfieldlist
1742 {
1743   const char *name;
1744   int length;
1745   struct nextfnfield *head;
1746 };
1747
1748 struct decl_field_list
1749 {
1750   struct decl_field field;
1751   struct decl_field_list *next;
1752 };
1753
1754 /* The routines that read and process dies for a C struct or C++ class
1755    pass lists of data member fields and lists of member function fields
1756    in an instance of a field_info structure, as defined below.  */
1757 struct field_info
1758   {
1759     /* List of data member and baseclasses fields.  */
1760     struct nextfield *fields, *baseclasses;
1761
1762     /* Number of fields (including baseclasses).  */
1763     int nfields;
1764
1765     /* Number of baseclasses.  */
1766     int nbaseclasses;
1767
1768     /* Set if the accesibility of one of the fields is not public.  */
1769     int non_public_fields;
1770
1771     /* Member function fieldlist array, contains name of possibly overloaded
1772        member function, number of overloaded member functions and a pointer
1773        to the head of the member function field chain.  */
1774     struct fnfieldlist *fnfieldlists;
1775
1776     /* Number of entries in the fnfieldlists array.  */
1777     int nfnfields;
1778
1779     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1780        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1781     struct decl_field_list *typedef_field_list;
1782     unsigned typedef_field_list_count;
1783
1784     /* Nested types defined by this class and the number of elements in this
1785        list.  */
1786     struct decl_field_list *nested_types_list;
1787     unsigned nested_types_list_count;
1788   };
1789
1790 /* One item on the queue of compilation units to read in full symbols
1791    for.  */
1792 struct dwarf2_queue_item
1793 {
1794   struct dwarf2_per_cu_data *per_cu;
1795   enum language pretend_language;
1796   struct dwarf2_queue_item *next;
1797 };
1798
1799 /* The current queue.  */
1800 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1801
1802 /* Loaded secondary compilation units are kept in memory until they
1803    have not been referenced for the processing of this many
1804    compilation units.  Set this to zero to disable caching.  Cache
1805    sizes of up to at least twenty will improve startup time for
1806    typical inter-CU-reference binaries, at an obvious memory cost.  */
1807 static int dwarf_max_cache_age = 5;
1808 static void
1809 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1810                           struct cmd_list_element *c, const char *value)
1811 {
1812   fprintf_filtered (file, _("The upper bound on the age of cached "
1813                             "DWARF compilation units is %s.\n"),
1814                     value);
1815 }
1816 \f
1817 /* local function prototypes */
1818
1819 static const char *get_section_name (const struct dwarf2_section_info *);
1820
1821 static const char *get_section_file_name (const struct dwarf2_section_info *);
1822
1823 static void dwarf2_find_base_address (struct die_info *die,
1824                                       struct dwarf2_cu *cu);
1825
1826 static struct partial_symtab *create_partial_symtab
1827   (struct dwarf2_per_cu_data *per_cu, const char *name);
1828
1829 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1830                                         const gdb_byte *info_ptr,
1831                                         struct die_info *type_unit_die,
1832                                         int has_children, void *data);
1833
1834 static void dwarf2_build_psymtabs_hard
1835   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1836
1837 static void scan_partial_symbols (struct partial_die_info *,
1838                                   CORE_ADDR *, CORE_ADDR *,
1839                                   int, struct dwarf2_cu *);
1840
1841 static void add_partial_symbol (struct partial_die_info *,
1842                                 struct dwarf2_cu *);
1843
1844 static void add_partial_namespace (struct partial_die_info *pdi,
1845                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1846                                    int set_addrmap, struct dwarf2_cu *cu);
1847
1848 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1849                                 CORE_ADDR *highpc, int set_addrmap,
1850                                 struct dwarf2_cu *cu);
1851
1852 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1853                                      struct dwarf2_cu *cu);
1854
1855 static void add_partial_subprogram (struct partial_die_info *pdi,
1856                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1857                                     int need_pc, struct dwarf2_cu *cu);
1858
1859 static void dwarf2_read_symtab (struct partial_symtab *,
1860                                 struct objfile *);
1861
1862 static void psymtab_to_symtab_1 (struct partial_symtab *);
1863
1864 static abbrev_table_up abbrev_table_read_table
1865   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1866    sect_offset);
1867
1868 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1869
1870 static struct partial_die_info *load_partial_dies
1871   (const struct die_reader_specs *, const gdb_byte *, int);
1872
1873 static struct partial_die_info *find_partial_die (sect_offset, int,
1874                                                   struct dwarf2_cu *);
1875
1876 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1877                                        struct attribute *, struct attr_abbrev *,
1878                                        const gdb_byte *);
1879
1880 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1881
1882 static int read_1_signed_byte (bfd *, const gdb_byte *);
1883
1884 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1885
1886 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1887
1888 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1889
1890 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1891                                unsigned int *);
1892
1893 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1894
1895 static LONGEST read_checked_initial_length_and_offset
1896   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1897    unsigned int *, unsigned int *);
1898
1899 static LONGEST read_offset (bfd *, const gdb_byte *,
1900                             const struct comp_unit_head *,
1901                             unsigned int *);
1902
1903 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1904
1905 static sect_offset read_abbrev_offset
1906   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1907    struct dwarf2_section_info *, sect_offset);
1908
1909 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1910
1911 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1912
1913 static const char *read_indirect_string
1914   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1915    const struct comp_unit_head *, unsigned int *);
1916
1917 static const char *read_indirect_line_string
1918   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1919    const struct comp_unit_head *, unsigned int *);
1920
1921 static const char *read_indirect_string_at_offset
1922   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1923    LONGEST str_offset);
1924
1925 static const char *read_indirect_string_from_dwz
1926   (struct objfile *objfile, struct dwz_file *, LONGEST);
1927
1928 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1929
1930 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1931                                               const gdb_byte *,
1932                                               unsigned int *);
1933
1934 static const char *read_str_index (const struct die_reader_specs *reader,
1935                                    ULONGEST str_index);
1936
1937 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1938
1939 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1940                                       struct dwarf2_cu *);
1941
1942 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1943                                                 unsigned int);
1944
1945 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1946                                        struct dwarf2_cu *cu);
1947
1948 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1949                                struct dwarf2_cu *cu);
1950
1951 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1952
1953 static struct die_info *die_specification (struct die_info *die,
1954                                            struct dwarf2_cu **);
1955
1956 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1957                                                 struct dwarf2_cu *cu);
1958
1959 static void dwarf_decode_lines (struct line_header *, const char *,
1960                                 struct dwarf2_cu *, struct partial_symtab *,
1961                                 CORE_ADDR, int decode_mapping);
1962
1963 static void dwarf2_start_subfile (const char *, const char *);
1964
1965 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1966                                                     const char *, const char *,
1967                                                     CORE_ADDR);
1968
1969 static struct symbol *new_symbol (struct die_info *, struct type *,
1970                                   struct dwarf2_cu *, struct symbol * = NULL);
1971
1972 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1973                                 struct dwarf2_cu *);
1974
1975 static void dwarf2_const_value_attr (const struct attribute *attr,
1976                                      struct type *type,
1977                                      const char *name,
1978                                      struct obstack *obstack,
1979                                      struct dwarf2_cu *cu, LONGEST *value,
1980                                      const gdb_byte **bytes,
1981                                      struct dwarf2_locexpr_baton **baton);
1982
1983 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1984
1985 static int need_gnat_info (struct dwarf2_cu *);
1986
1987 static struct type *die_descriptive_type (struct die_info *,
1988                                           struct dwarf2_cu *);
1989
1990 static void set_descriptive_type (struct type *, struct die_info *,
1991                                   struct dwarf2_cu *);
1992
1993 static struct type *die_containing_type (struct die_info *,
1994                                          struct dwarf2_cu *);
1995
1996 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1997                                      struct dwarf2_cu *);
1998
1999 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
2000
2001 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
2002
2003 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
2004
2005 static char *typename_concat (struct obstack *obs, const char *prefix,
2006                               const char *suffix, int physname,
2007                               struct dwarf2_cu *cu);
2008
2009 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
2010
2011 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
2012
2013 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
2014
2015 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
2016
2017 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
2018
2019 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
2020
2021 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
2022                                struct dwarf2_cu *, struct partial_symtab *);
2023
2024 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
2025    values.  Keep the items ordered with increasing constraints compliance.  */
2026 enum pc_bounds_kind
2027 {
2028   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
2029   PC_BOUNDS_NOT_PRESENT,
2030
2031   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
2032      were present but they do not form a valid range of PC addresses.  */
2033   PC_BOUNDS_INVALID,
2034
2035   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
2036   PC_BOUNDS_RANGES,
2037
2038   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
2039   PC_BOUNDS_HIGH_LOW,
2040 };
2041
2042 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
2043                                                  CORE_ADDR *, CORE_ADDR *,
2044                                                  struct dwarf2_cu *,
2045                                                  struct partial_symtab *);
2046
2047 static void get_scope_pc_bounds (struct die_info *,
2048                                  CORE_ADDR *, CORE_ADDR *,
2049                                  struct dwarf2_cu *);
2050
2051 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
2052                                         CORE_ADDR, struct dwarf2_cu *);
2053
2054 static void dwarf2_add_field (struct field_info *, struct die_info *,
2055                               struct dwarf2_cu *);
2056
2057 static void dwarf2_attach_fields_to_type (struct field_info *,
2058                                           struct type *, struct dwarf2_cu *);
2059
2060 static void dwarf2_add_member_fn (struct field_info *,
2061                                   struct die_info *, struct type *,
2062                                   struct dwarf2_cu *);
2063
2064 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
2065                                              struct type *,
2066                                              struct dwarf2_cu *);
2067
2068 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
2069
2070 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2071
2072 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2073
2074 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2075
2076 static struct using_direct **using_directives (enum language);
2077
2078 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2079
2080 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2081
2082 static struct type *read_module_type (struct die_info *die,
2083                                       struct dwarf2_cu *cu);
2084
2085 static const char *namespace_name (struct die_info *die,
2086                                    int *is_anonymous, struct dwarf2_cu *);
2087
2088 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2089
2090 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2091
2092 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2093                                                        struct dwarf2_cu *);
2094
2095 static struct die_info *read_die_and_siblings_1
2096   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2097    struct die_info *);
2098
2099 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2100                                                const gdb_byte *info_ptr,
2101                                                const gdb_byte **new_info_ptr,
2102                                                struct die_info *parent);
2103
2104 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2105                                         struct die_info **, const gdb_byte *,
2106                                         int *, int);
2107
2108 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2109                                       struct die_info **, const gdb_byte *,
2110                                       int *);
2111
2112 static void process_die (struct die_info *, struct dwarf2_cu *);
2113
2114 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2115                                              struct obstack *);
2116
2117 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2118
2119 static const char *dwarf2_full_name (const char *name,
2120                                      struct die_info *die,
2121                                      struct dwarf2_cu *cu);
2122
2123 static const char *dwarf2_physname (const char *name, struct die_info *die,
2124                                     struct dwarf2_cu *cu);
2125
2126 static struct die_info *dwarf2_extension (struct die_info *die,
2127                                           struct dwarf2_cu **);
2128
2129 static const char *dwarf_tag_name (unsigned int);
2130
2131 static const char *dwarf_attr_name (unsigned int);
2132
2133 static const char *dwarf_form_name (unsigned int);
2134
2135 static const char *dwarf_bool_name (unsigned int);
2136
2137 static const char *dwarf_type_encoding_name (unsigned int);
2138
2139 static struct die_info *sibling_die (struct die_info *);
2140
2141 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2142
2143 static void dump_die_for_error (struct die_info *);
2144
2145 static void dump_die_1 (struct ui_file *, int level, int max_level,
2146                         struct die_info *);
2147
2148 /*static*/ void dump_die (struct die_info *, int max_level);
2149
2150 static void store_in_ref_table (struct die_info *,
2151                                 struct dwarf2_cu *);
2152
2153 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2154
2155 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2156
2157 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2158                                                const struct attribute *,
2159                                                struct dwarf2_cu **);
2160
2161 static struct die_info *follow_die_ref (struct die_info *,
2162                                         const struct attribute *,
2163                                         struct dwarf2_cu **);
2164
2165 static struct die_info *follow_die_sig (struct die_info *,
2166                                         const struct attribute *,
2167                                         struct dwarf2_cu **);
2168
2169 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2170                                          struct dwarf2_cu *);
2171
2172 static struct type *get_DW_AT_signature_type (struct die_info *,
2173                                               const struct attribute *,
2174                                               struct dwarf2_cu *);
2175
2176 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2177
2178 static void read_signatured_type (struct signatured_type *);
2179
2180 static int attr_to_dynamic_prop (const struct attribute *attr,
2181                                  struct die_info *die, struct dwarf2_cu *cu,
2182                                  struct dynamic_prop *prop);
2183
2184 /* memory allocation interface */
2185
2186 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2187
2188 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2189
2190 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2191
2192 static int attr_form_is_block (const struct attribute *);
2193
2194 static int attr_form_is_section_offset (const struct attribute *);
2195
2196 static int attr_form_is_constant (const struct attribute *);
2197
2198 static int attr_form_is_ref (const struct attribute *);
2199
2200 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2201                                    struct dwarf2_loclist_baton *baton,
2202                                    const struct attribute *attr);
2203
2204 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2205                                          struct symbol *sym,
2206                                          struct dwarf2_cu *cu,
2207                                          int is_block);
2208
2209 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2210                                      const gdb_byte *info_ptr,
2211                                      struct abbrev_info *abbrev);
2212
2213 static hashval_t partial_die_hash (const void *item);
2214
2215 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2216
2217 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2218   (sect_offset sect_off, unsigned int offset_in_dwz,
2219    struct dwarf2_per_objfile *dwarf2_per_objfile);
2220
2221 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2222                                    struct die_info *comp_unit_die,
2223                                    enum language pretend_language);
2224
2225 static void free_cached_comp_units (void *);
2226
2227 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2228
2229 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2230
2231 static struct type *set_die_type (struct die_info *, struct type *,
2232                                   struct dwarf2_cu *);
2233
2234 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2235
2236 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2237
2238 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2239                                  enum language);
2240
2241 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2242                                     enum language);
2243
2244 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2245                                     enum language);
2246
2247 static void dwarf2_add_dependence (struct dwarf2_cu *,
2248                                    struct dwarf2_per_cu_data *);
2249
2250 static void dwarf2_mark (struct dwarf2_cu *);
2251
2252 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2253
2254 static struct type *get_die_type_at_offset (sect_offset,
2255                                             struct dwarf2_per_cu_data *);
2256
2257 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2258
2259 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2260                              enum language pretend_language);
2261
2262 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2263
2264 /* Class, the destructor of which frees all allocated queue entries.  This
2265    will only have work to do if an error was thrown while processing the
2266    dwarf.  If no error was thrown then the queue entries should have all
2267    been processed, and freed, as we went along.  */
2268
2269 class dwarf2_queue_guard
2270 {
2271 public:
2272   dwarf2_queue_guard () = default;
2273
2274   /* Free any entries remaining on the queue.  There should only be
2275      entries left if we hit an error while processing the dwarf.  */
2276   ~dwarf2_queue_guard ()
2277   {
2278     struct dwarf2_queue_item *item, *last;
2279
2280     item = dwarf2_queue;
2281     while (item)
2282       {
2283         /* Anything still marked queued is likely to be in an
2284            inconsistent state, so discard it.  */
2285         if (item->per_cu->queued)
2286           {
2287             if (item->per_cu->cu != NULL)
2288               free_one_cached_comp_unit (item->per_cu);
2289             item->per_cu->queued = 0;
2290           }
2291
2292         last = item;
2293         item = item->next;
2294         xfree (last);
2295       }
2296
2297     dwarf2_queue = dwarf2_queue_tail = NULL;
2298   }
2299 };
2300
2301 /* The return type of find_file_and_directory.  Note, the enclosed
2302    string pointers are only valid while this object is valid.  */
2303
2304 struct file_and_directory
2305 {
2306   /* The filename.  This is never NULL.  */
2307   const char *name;
2308
2309   /* The compilation directory.  NULL if not known.  If we needed to
2310      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2311      points directly to the DW_AT_comp_dir string attribute owned by
2312      the obstack that owns the DIE.  */
2313   const char *comp_dir;
2314
2315   /* If we needed to build a new string for comp_dir, this is what
2316      owns the storage.  */
2317   std::string comp_dir_storage;
2318 };
2319
2320 static file_and_directory find_file_and_directory (struct die_info *die,
2321                                                    struct dwarf2_cu *cu);
2322
2323 static char *file_full_name (int file, struct line_header *lh,
2324                              const char *comp_dir);
2325
2326 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2327 enum class rcuh_kind { COMPILE, TYPE };
2328
2329 static const gdb_byte *read_and_check_comp_unit_head
2330   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2331    struct comp_unit_head *header,
2332    struct dwarf2_section_info *section,
2333    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2334    rcuh_kind section_kind);
2335
2336 static void init_cutu_and_read_dies
2337   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2338    int use_existing_cu, int keep,
2339    die_reader_func_ftype *die_reader_func, void *data);
2340
2341 static void init_cutu_and_read_dies_simple
2342   (struct dwarf2_per_cu_data *this_cu,
2343    die_reader_func_ftype *die_reader_func, void *data);
2344
2345 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2346
2347 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2348
2349 static struct dwo_unit *lookup_dwo_unit_in_dwp
2350   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2351    struct dwp_file *dwp_file, const char *comp_dir,
2352    ULONGEST signature, int is_debug_types);
2353
2354 static struct dwp_file *get_dwp_file
2355   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2356
2357 static struct dwo_unit *lookup_dwo_comp_unit
2358   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2359
2360 static struct dwo_unit *lookup_dwo_type_unit
2361   (struct signatured_type *, const char *, const char *);
2362
2363 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2364
2365 static void free_dwo_file_cleanup (void *);
2366
2367 struct free_dwo_file_cleanup_data
2368 {
2369   struct dwo_file *dwo_file;
2370   struct dwarf2_per_objfile *dwarf2_per_objfile;
2371 };
2372
2373 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2374
2375 static void check_producer (struct dwarf2_cu *cu);
2376
2377 static void free_line_header_voidp (void *arg);
2378 \f
2379 /* Various complaints about symbol reading that don't abort the process.  */
2380
2381 static void
2382 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2383 {
2384   complaint (&symfile_complaints,
2385              _("statement list doesn't fit in .debug_line section"));
2386 }
2387
2388 static void
2389 dwarf2_debug_line_missing_file_complaint (void)
2390 {
2391   complaint (&symfile_complaints,
2392              _(".debug_line section has line data without a file"));
2393 }
2394
2395 static void
2396 dwarf2_debug_line_missing_end_sequence_complaint (void)
2397 {
2398   complaint (&symfile_complaints,
2399              _(".debug_line section has line "
2400                "program sequence without an end"));
2401 }
2402
2403 static void
2404 dwarf2_complex_location_expr_complaint (void)
2405 {
2406   complaint (&symfile_complaints, _("location expression too complex"));
2407 }
2408
2409 static void
2410 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2411                                               int arg3)
2412 {
2413   complaint (&symfile_complaints,
2414              _("const value length mismatch for '%s', got %d, expected %d"),
2415              arg1, arg2, arg3);
2416 }
2417
2418 static void
2419 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2420 {
2421   complaint (&symfile_complaints,
2422              _("debug info runs off end of %s section"
2423                " [in module %s]"),
2424              get_section_name (section),
2425              get_section_file_name (section));
2426 }
2427
2428 static void
2429 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2430 {
2431   complaint (&symfile_complaints,
2432              _("macro debug info contains a "
2433                "malformed macro definition:\n`%s'"),
2434              arg1);
2435 }
2436
2437 static void
2438 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2439 {
2440   complaint (&symfile_complaints,
2441              _("invalid attribute class or form for '%s' in '%s'"),
2442              arg1, arg2);
2443 }
2444
2445 /* Hash function for line_header_hash.  */
2446
2447 static hashval_t
2448 line_header_hash (const struct line_header *ofs)
2449 {
2450   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2451 }
2452
2453 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2454
2455 static hashval_t
2456 line_header_hash_voidp (const void *item)
2457 {
2458   const struct line_header *ofs = (const struct line_header *) item;
2459
2460   return line_header_hash (ofs);
2461 }
2462
2463 /* Equality function for line_header_hash.  */
2464
2465 static int
2466 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2467 {
2468   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2469   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2470
2471   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2472           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2473 }
2474
2475 \f
2476
2477 /* Read the given attribute value as an address, taking the attribute's
2478    form into account.  */
2479
2480 static CORE_ADDR
2481 attr_value_as_address (struct attribute *attr)
2482 {
2483   CORE_ADDR addr;
2484
2485   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2486     {
2487       /* Aside from a few clearly defined exceptions, attributes that
2488          contain an address must always be in DW_FORM_addr form.
2489          Unfortunately, some compilers happen to be violating this
2490          requirement by encoding addresses using other forms, such
2491          as DW_FORM_data4 for example.  For those broken compilers,
2492          we try to do our best, without any guarantee of success,
2493          to interpret the address correctly.  It would also be nice
2494          to generate a complaint, but that would require us to maintain
2495          a list of legitimate cases where a non-address form is allowed,
2496          as well as update callers to pass in at least the CU's DWARF
2497          version.  This is more overhead than what we're willing to
2498          expand for a pretty rare case.  */
2499       addr = DW_UNSND (attr);
2500     }
2501   else
2502     addr = DW_ADDR (attr);
2503
2504   return addr;
2505 }
2506
2507 /* The suffix for an index file.  */
2508 #define INDEX4_SUFFIX ".gdb-index"
2509 #define INDEX5_SUFFIX ".debug_names"
2510 #define DEBUG_STR_SUFFIX ".debug_str"
2511
2512 /* See declaration.  */
2513
2514 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2515                                         const dwarf2_debug_sections *names)
2516   : objfile (objfile_)
2517 {
2518   if (names == NULL)
2519     names = &dwarf2_elf_names;
2520
2521   bfd *obfd = objfile->obfd;
2522
2523   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2524     locate_sections (obfd, sec, *names);
2525 }
2526
2527 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2528
2529 dwarf2_per_objfile::~dwarf2_per_objfile ()
2530 {
2531   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2532   free_cached_comp_units ();
2533
2534   if (quick_file_names_table)
2535     htab_delete (quick_file_names_table);
2536
2537   if (line_header_hash)
2538     htab_delete (line_header_hash);
2539
2540   for (int ix = 0; ix < n_comp_units; ++ix)
2541    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2542
2543   for (int ix = 0; ix < n_type_units; ++ix)
2544     VEC_free (dwarf2_per_cu_ptr,
2545               all_type_units[ix]->per_cu.imported_symtabs);
2546   xfree (all_type_units);
2547
2548   VEC_free (dwarf2_section_info_def, types);
2549
2550   if (dwo_files != NULL)
2551     free_dwo_files (dwo_files, objfile);
2552   if (dwp_file != NULL)
2553     gdb_bfd_unref (dwp_file->dbfd);
2554
2555   if (dwz_file != NULL && dwz_file->dwz_bfd)
2556     gdb_bfd_unref (dwz_file->dwz_bfd);
2557
2558   if (index_table != NULL)
2559     index_table->~mapped_index ();
2560
2561   /* Everything else should be on the objfile obstack.  */
2562 }
2563
2564 /* See declaration.  */
2565
2566 void
2567 dwarf2_per_objfile::free_cached_comp_units ()
2568 {
2569   dwarf2_per_cu_data *per_cu = read_in_chain;
2570   dwarf2_per_cu_data **last_chain = &read_in_chain;
2571   while (per_cu != NULL)
2572     {
2573       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2574
2575       delete per_cu->cu;
2576       *last_chain = next_cu;
2577       per_cu = next_cu;
2578     }
2579 }
2580
2581 /* Try to locate the sections we need for DWARF 2 debugging
2582    information and return true if we have enough to do something.
2583    NAMES points to the dwarf2 section names, or is NULL if the standard
2584    ELF names are used.  */
2585
2586 int
2587 dwarf2_has_info (struct objfile *objfile,
2588                  const struct dwarf2_debug_sections *names)
2589 {
2590   if (objfile->flags & OBJF_READNEVER)
2591     return 0;
2592
2593   struct dwarf2_per_objfile *dwarf2_per_objfile
2594     = get_dwarf2_per_objfile (objfile);
2595
2596   if (dwarf2_per_objfile == NULL)
2597     {
2598       /* Initialize per-objfile state.  */
2599       dwarf2_per_objfile
2600         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2601                                                                      names);
2602       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2603     }
2604   return (!dwarf2_per_objfile->info.is_virtual
2605           && dwarf2_per_objfile->info.s.section != NULL
2606           && !dwarf2_per_objfile->abbrev.is_virtual
2607           && dwarf2_per_objfile->abbrev.s.section != NULL);
2608 }
2609
2610 /* Return the containing section of virtual section SECTION.  */
2611
2612 static struct dwarf2_section_info *
2613 get_containing_section (const struct dwarf2_section_info *section)
2614 {
2615   gdb_assert (section->is_virtual);
2616   return section->s.containing_section;
2617 }
2618
2619 /* Return the bfd owner of SECTION.  */
2620
2621 static struct bfd *
2622 get_section_bfd_owner (const struct dwarf2_section_info *section)
2623 {
2624   if (section->is_virtual)
2625     {
2626       section = get_containing_section (section);
2627       gdb_assert (!section->is_virtual);
2628     }
2629   return section->s.section->owner;
2630 }
2631
2632 /* Return the bfd section of SECTION.
2633    Returns NULL if the section is not present.  */
2634
2635 static asection *
2636 get_section_bfd_section (const struct dwarf2_section_info *section)
2637 {
2638   if (section->is_virtual)
2639     {
2640       section = get_containing_section (section);
2641       gdb_assert (!section->is_virtual);
2642     }
2643   return section->s.section;
2644 }
2645
2646 /* Return the name of SECTION.  */
2647
2648 static const char *
2649 get_section_name (const struct dwarf2_section_info *section)
2650 {
2651   asection *sectp = get_section_bfd_section (section);
2652
2653   gdb_assert (sectp != NULL);
2654   return bfd_section_name (get_section_bfd_owner (section), sectp);
2655 }
2656
2657 /* Return the name of the file SECTION is in.  */
2658
2659 static const char *
2660 get_section_file_name (const struct dwarf2_section_info *section)
2661 {
2662   bfd *abfd = get_section_bfd_owner (section);
2663
2664   return bfd_get_filename (abfd);
2665 }
2666
2667 /* Return the id of SECTION.
2668    Returns 0 if SECTION doesn't exist.  */
2669
2670 static int
2671 get_section_id (const struct dwarf2_section_info *section)
2672 {
2673   asection *sectp = get_section_bfd_section (section);
2674
2675   if (sectp == NULL)
2676     return 0;
2677   return sectp->id;
2678 }
2679
2680 /* Return the flags of SECTION.
2681    SECTION (or containing section if this is a virtual section) must exist.  */
2682
2683 static int
2684 get_section_flags (const struct dwarf2_section_info *section)
2685 {
2686   asection *sectp = get_section_bfd_section (section);
2687
2688   gdb_assert (sectp != NULL);
2689   return bfd_get_section_flags (sectp->owner, sectp);
2690 }
2691
2692 /* When loading sections, we look either for uncompressed section or for
2693    compressed section names.  */
2694
2695 static int
2696 section_is_p (const char *section_name,
2697               const struct dwarf2_section_names *names)
2698 {
2699   if (names->normal != NULL
2700       && strcmp (section_name, names->normal) == 0)
2701     return 1;
2702   if (names->compressed != NULL
2703       && strcmp (section_name, names->compressed) == 0)
2704     return 1;
2705   return 0;
2706 }
2707
2708 /* See declaration.  */
2709
2710 void
2711 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2712                                      const dwarf2_debug_sections &names)
2713 {
2714   flagword aflag = bfd_get_section_flags (abfd, sectp);
2715
2716   if ((aflag & SEC_HAS_CONTENTS) == 0)
2717     {
2718     }
2719   else if (section_is_p (sectp->name, &names.info))
2720     {
2721       this->info.s.section = sectp;
2722       this->info.size = bfd_get_section_size (sectp);
2723     }
2724   else if (section_is_p (sectp->name, &names.abbrev))
2725     {
2726       this->abbrev.s.section = sectp;
2727       this->abbrev.size = bfd_get_section_size (sectp);
2728     }
2729   else if (section_is_p (sectp->name, &names.line))
2730     {
2731       this->line.s.section = sectp;
2732       this->line.size = bfd_get_section_size (sectp);
2733     }
2734   else if (section_is_p (sectp->name, &names.loc))
2735     {
2736       this->loc.s.section = sectp;
2737       this->loc.size = bfd_get_section_size (sectp);
2738     }
2739   else if (section_is_p (sectp->name, &names.loclists))
2740     {
2741       this->loclists.s.section = sectp;
2742       this->loclists.size = bfd_get_section_size (sectp);
2743     }
2744   else if (section_is_p (sectp->name, &names.macinfo))
2745     {
2746       this->macinfo.s.section = sectp;
2747       this->macinfo.size = bfd_get_section_size (sectp);
2748     }
2749   else if (section_is_p (sectp->name, &names.macro))
2750     {
2751       this->macro.s.section = sectp;
2752       this->macro.size = bfd_get_section_size (sectp);
2753     }
2754   else if (section_is_p (sectp->name, &names.str))
2755     {
2756       this->str.s.section = sectp;
2757       this->str.size = bfd_get_section_size (sectp);
2758     }
2759   else if (section_is_p (sectp->name, &names.line_str))
2760     {
2761       this->line_str.s.section = sectp;
2762       this->line_str.size = bfd_get_section_size (sectp);
2763     }
2764   else if (section_is_p (sectp->name, &names.addr))
2765     {
2766       this->addr.s.section = sectp;
2767       this->addr.size = bfd_get_section_size (sectp);
2768     }
2769   else if (section_is_p (sectp->name, &names.frame))
2770     {
2771       this->frame.s.section = sectp;
2772       this->frame.size = bfd_get_section_size (sectp);
2773     }
2774   else if (section_is_p (sectp->name, &names.eh_frame))
2775     {
2776       this->eh_frame.s.section = sectp;
2777       this->eh_frame.size = bfd_get_section_size (sectp);
2778     }
2779   else if (section_is_p (sectp->name, &names.ranges))
2780     {
2781       this->ranges.s.section = sectp;
2782       this->ranges.size = bfd_get_section_size (sectp);
2783     }
2784   else if (section_is_p (sectp->name, &names.rnglists))
2785     {
2786       this->rnglists.s.section = sectp;
2787       this->rnglists.size = bfd_get_section_size (sectp);
2788     }
2789   else if (section_is_p (sectp->name, &names.types))
2790     {
2791       struct dwarf2_section_info type_section;
2792
2793       memset (&type_section, 0, sizeof (type_section));
2794       type_section.s.section = sectp;
2795       type_section.size = bfd_get_section_size (sectp);
2796
2797       VEC_safe_push (dwarf2_section_info_def, this->types,
2798                      &type_section);
2799     }
2800   else if (section_is_p (sectp->name, &names.gdb_index))
2801     {
2802       this->gdb_index.s.section = sectp;
2803       this->gdb_index.size = bfd_get_section_size (sectp);
2804     }
2805   else if (section_is_p (sectp->name, &names.debug_names))
2806     {
2807       this->debug_names.s.section = sectp;
2808       this->debug_names.size = bfd_get_section_size (sectp);
2809     }
2810   else if (section_is_p (sectp->name, &names.debug_aranges))
2811     {
2812       this->debug_aranges.s.section = sectp;
2813       this->debug_aranges.size = bfd_get_section_size (sectp);
2814     }
2815
2816   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2817       && bfd_section_vma (abfd, sectp) == 0)
2818     this->has_section_at_zero = true;
2819 }
2820
2821 /* A helper function that decides whether a section is empty,
2822    or not present.  */
2823
2824 static int
2825 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2826 {
2827   if (section->is_virtual)
2828     return section->size == 0;
2829   return section->s.section == NULL || section->size == 0;
2830 }
2831
2832 /* Read the contents of the section INFO.
2833    OBJFILE is the main object file, but not necessarily the file where
2834    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2835    of the DWO file.
2836    If the section is compressed, uncompress it before returning.  */
2837
2838 static void
2839 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2840 {
2841   asection *sectp;
2842   bfd *abfd;
2843   gdb_byte *buf, *retbuf;
2844
2845   if (info->readin)
2846     return;
2847   info->buffer = NULL;
2848   info->readin = 1;
2849
2850   if (dwarf2_section_empty_p (info))
2851     return;
2852
2853   sectp = get_section_bfd_section (info);
2854
2855   /* If this is a virtual section we need to read in the real one first.  */
2856   if (info->is_virtual)
2857     {
2858       struct dwarf2_section_info *containing_section =
2859         get_containing_section (info);
2860
2861       gdb_assert (sectp != NULL);
2862       if ((sectp->flags & SEC_RELOC) != 0)
2863         {
2864           error (_("Dwarf Error: DWP format V2 with relocations is not"
2865                    " supported in section %s [in module %s]"),
2866                  get_section_name (info), get_section_file_name (info));
2867         }
2868       dwarf2_read_section (objfile, containing_section);
2869       /* Other code should have already caught virtual sections that don't
2870          fit.  */
2871       gdb_assert (info->virtual_offset + info->size
2872                   <= containing_section->size);
2873       /* If the real section is empty or there was a problem reading the
2874          section we shouldn't get here.  */
2875       gdb_assert (containing_section->buffer != NULL);
2876       info->buffer = containing_section->buffer + info->virtual_offset;
2877       return;
2878     }
2879
2880   /* If the section has relocations, we must read it ourselves.
2881      Otherwise we attach it to the BFD.  */
2882   if ((sectp->flags & SEC_RELOC) == 0)
2883     {
2884       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2885       return;
2886     }
2887
2888   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2889   info->buffer = buf;
2890
2891   /* When debugging .o files, we may need to apply relocations; see
2892      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2893      We never compress sections in .o files, so we only need to
2894      try this when the section is not compressed.  */
2895   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2896   if (retbuf != NULL)
2897     {
2898       info->buffer = retbuf;
2899       return;
2900     }
2901
2902   abfd = get_section_bfd_owner (info);
2903   gdb_assert (abfd != NULL);
2904
2905   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2906       || bfd_bread (buf, info->size, abfd) != info->size)
2907     {
2908       error (_("Dwarf Error: Can't read DWARF data"
2909                " in section %s [in module %s]"),
2910              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2911     }
2912 }
2913
2914 /* A helper function that returns the size of a section in a safe way.
2915    If you are positive that the section has been read before using the
2916    size, then it is safe to refer to the dwarf2_section_info object's
2917    "size" field directly.  In other cases, you must call this
2918    function, because for compressed sections the size field is not set
2919    correctly until the section has been read.  */
2920
2921 static bfd_size_type
2922 dwarf2_section_size (struct objfile *objfile,
2923                      struct dwarf2_section_info *info)
2924 {
2925   if (!info->readin)
2926     dwarf2_read_section (objfile, info);
2927   return info->size;
2928 }
2929
2930 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2931    SECTION_NAME.  */
2932
2933 void
2934 dwarf2_get_section_info (struct objfile *objfile,
2935                          enum dwarf2_section_enum sect,
2936                          asection **sectp, const gdb_byte **bufp,
2937                          bfd_size_type *sizep)
2938 {
2939   struct dwarf2_per_objfile *data
2940     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2941                                                   dwarf2_objfile_data_key);
2942   struct dwarf2_section_info *info;
2943
2944   /* We may see an objfile without any DWARF, in which case we just
2945      return nothing.  */
2946   if (data == NULL)
2947     {
2948       *sectp = NULL;
2949       *bufp = NULL;
2950       *sizep = 0;
2951       return;
2952     }
2953   switch (sect)
2954     {
2955     case DWARF2_DEBUG_FRAME:
2956       info = &data->frame;
2957       break;
2958     case DWARF2_EH_FRAME:
2959       info = &data->eh_frame;
2960       break;
2961     default:
2962       gdb_assert_not_reached ("unexpected section");
2963     }
2964
2965   dwarf2_read_section (objfile, info);
2966
2967   *sectp = get_section_bfd_section (info);
2968   *bufp = info->buffer;
2969   *sizep = info->size;
2970 }
2971
2972 /* A helper function to find the sections for a .dwz file.  */
2973
2974 static void
2975 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2976 {
2977   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2978
2979   /* Note that we only support the standard ELF names, because .dwz
2980      is ELF-only (at the time of writing).  */
2981   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2982     {
2983       dwz_file->abbrev.s.section = sectp;
2984       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2985     }
2986   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2987     {
2988       dwz_file->info.s.section = sectp;
2989       dwz_file->info.size = bfd_get_section_size (sectp);
2990     }
2991   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2992     {
2993       dwz_file->str.s.section = sectp;
2994       dwz_file->str.size = bfd_get_section_size (sectp);
2995     }
2996   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2997     {
2998       dwz_file->line.s.section = sectp;
2999       dwz_file->line.size = bfd_get_section_size (sectp);
3000     }
3001   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
3002     {
3003       dwz_file->macro.s.section = sectp;
3004       dwz_file->macro.size = bfd_get_section_size (sectp);
3005     }
3006   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
3007     {
3008       dwz_file->gdb_index.s.section = sectp;
3009       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
3010     }
3011   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
3012     {
3013       dwz_file->debug_names.s.section = sectp;
3014       dwz_file->debug_names.size = bfd_get_section_size (sectp);
3015     }
3016 }
3017
3018 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
3019    there is no .gnu_debugaltlink section in the file.  Error if there
3020    is such a section but the file cannot be found.  */
3021
3022 static struct dwz_file *
3023 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
3024 {
3025   const char *filename;
3026   struct dwz_file *result;
3027   bfd_size_type buildid_len_arg;
3028   size_t buildid_len;
3029   bfd_byte *buildid;
3030
3031   if (dwarf2_per_objfile->dwz_file != NULL)
3032     return dwarf2_per_objfile->dwz_file;
3033
3034   bfd_set_error (bfd_error_no_error);
3035   gdb::unique_xmalloc_ptr<char> data
3036     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
3037                                   &buildid_len_arg, &buildid));
3038   if (data == NULL)
3039     {
3040       if (bfd_get_error () == bfd_error_no_error)
3041         return NULL;
3042       error (_("could not read '.gnu_debugaltlink' section: %s"),
3043              bfd_errmsg (bfd_get_error ()));
3044     }
3045
3046   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
3047
3048   buildid_len = (size_t) buildid_len_arg;
3049
3050   filename = data.get ();
3051
3052   std::string abs_storage;
3053   if (!IS_ABSOLUTE_PATH (filename))
3054     {
3055       gdb::unique_xmalloc_ptr<char> abs
3056         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
3057
3058       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
3059       filename = abs_storage.c_str ();
3060     }
3061
3062   /* First try the file name given in the section.  If that doesn't
3063      work, try to use the build-id instead.  */
3064   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
3065   if (dwz_bfd != NULL)
3066     {
3067       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
3068         dwz_bfd.release ();
3069     }
3070
3071   if (dwz_bfd == NULL)
3072     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
3073
3074   if (dwz_bfd == NULL)
3075     error (_("could not find '.gnu_debugaltlink' file for %s"),
3076            objfile_name (dwarf2_per_objfile->objfile));
3077
3078   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
3079                            struct dwz_file);
3080   result->dwz_bfd = dwz_bfd.release ();
3081
3082   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
3083
3084   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
3085   dwarf2_per_objfile->dwz_file = result;
3086   return result;
3087 }
3088 \f
3089 /* DWARF quick_symbols_functions support.  */
3090
3091 /* TUs can share .debug_line entries, and there can be a lot more TUs than
3092    unique line tables, so we maintain a separate table of all .debug_line
3093    derived entries to support the sharing.
3094    All the quick functions need is the list of file names.  We discard the
3095    line_header when we're done and don't need to record it here.  */
3096 struct quick_file_names
3097 {
3098   /* The data used to construct the hash key.  */
3099   struct stmt_list_hash hash;
3100
3101   /* The number of entries in file_names, real_names.  */
3102   unsigned int num_file_names;
3103
3104   /* The file names from the line table, after being run through
3105      file_full_name.  */
3106   const char **file_names;
3107
3108   /* The file names from the line table after being run through
3109      gdb_realpath.  These are computed lazily.  */
3110   const char **real_names;
3111 };
3112
3113 /* When using the index (and thus not using psymtabs), each CU has an
3114    object of this type.  This is used to hold information needed by
3115    the various "quick" methods.  */
3116 struct dwarf2_per_cu_quick_data
3117 {
3118   /* The file table.  This can be NULL if there was no file table
3119      or it's currently not read in.
3120      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3121   struct quick_file_names *file_names;
3122
3123   /* The corresponding symbol table.  This is NULL if symbols for this
3124      CU have not yet been read.  */
3125   struct compunit_symtab *compunit_symtab;
3126
3127   /* A temporary mark bit used when iterating over all CUs in
3128      expand_symtabs_matching.  */
3129   unsigned int mark : 1;
3130
3131   /* True if we've tried to read the file table and found there isn't one.
3132      There will be no point in trying to read it again next time.  */
3133   unsigned int no_file_data : 1;
3134 };
3135
3136 /* Utility hash function for a stmt_list_hash.  */
3137
3138 static hashval_t
3139 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3140 {
3141   hashval_t v = 0;
3142
3143   if (stmt_list_hash->dwo_unit != NULL)
3144     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3145   v += to_underlying (stmt_list_hash->line_sect_off);
3146   return v;
3147 }
3148
3149 /* Utility equality function for a stmt_list_hash.  */
3150
3151 static int
3152 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3153                     const struct stmt_list_hash *rhs)
3154 {
3155   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3156     return 0;
3157   if (lhs->dwo_unit != NULL
3158       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3159     return 0;
3160
3161   return lhs->line_sect_off == rhs->line_sect_off;
3162 }
3163
3164 /* Hash function for a quick_file_names.  */
3165
3166 static hashval_t
3167 hash_file_name_entry (const void *e)
3168 {
3169   const struct quick_file_names *file_data
3170     = (const struct quick_file_names *) e;
3171
3172   return hash_stmt_list_entry (&file_data->hash);
3173 }
3174
3175 /* Equality function for a quick_file_names.  */
3176
3177 static int
3178 eq_file_name_entry (const void *a, const void *b)
3179 {
3180   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3181   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3182
3183   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3184 }
3185
3186 /* Delete function for a quick_file_names.  */
3187
3188 static void
3189 delete_file_name_entry (void *e)
3190 {
3191   struct quick_file_names *file_data = (struct quick_file_names *) e;
3192   int i;
3193
3194   for (i = 0; i < file_data->num_file_names; ++i)
3195     {
3196       xfree ((void*) file_data->file_names[i]);
3197       if (file_data->real_names)
3198         xfree ((void*) file_data->real_names[i]);
3199     }
3200
3201   /* The space for the struct itself lives on objfile_obstack,
3202      so we don't free it here.  */
3203 }
3204
3205 /* Create a quick_file_names hash table.  */
3206
3207 static htab_t
3208 create_quick_file_names_table (unsigned int nr_initial_entries)
3209 {
3210   return htab_create_alloc (nr_initial_entries,
3211                             hash_file_name_entry, eq_file_name_entry,
3212                             delete_file_name_entry, xcalloc, xfree);
3213 }
3214
3215 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3216    have to be created afterwards.  You should call age_cached_comp_units after
3217    processing PER_CU->CU.  dw2_setup must have been already called.  */
3218
3219 static void
3220 load_cu (struct dwarf2_per_cu_data *per_cu)
3221 {
3222   if (per_cu->is_debug_types)
3223     load_full_type_unit (per_cu);
3224   else
3225     load_full_comp_unit (per_cu, language_minimal);
3226
3227   if (per_cu->cu == NULL)
3228     return;  /* Dummy CU.  */
3229
3230   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3231 }
3232
3233 /* Read in the symbols for PER_CU.  */
3234
3235 static void
3236 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3237 {
3238   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3239
3240   /* Skip type_unit_groups, reading the type units they contain
3241      is handled elsewhere.  */
3242   if (IS_TYPE_UNIT_GROUP (per_cu))
3243     return;
3244
3245   /* The destructor of dwarf2_queue_guard frees any entries left on
3246      the queue.  After this point we're guaranteed to leave this function
3247      with the dwarf queue empty.  */
3248   dwarf2_queue_guard q_guard;
3249
3250   if (dwarf2_per_objfile->using_index
3251       ? per_cu->v.quick->compunit_symtab == NULL
3252       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3253     {
3254       queue_comp_unit (per_cu, language_minimal);
3255       load_cu (per_cu);
3256
3257       /* If we just loaded a CU from a DWO, and we're working with an index
3258          that may badly handle TUs, load all the TUs in that DWO as well.
3259          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3260       if (!per_cu->is_debug_types
3261           && per_cu->cu != NULL
3262           && per_cu->cu->dwo_unit != NULL
3263           && dwarf2_per_objfile->index_table != NULL
3264           && dwarf2_per_objfile->index_table->version <= 7
3265           /* DWP files aren't supported yet.  */
3266           && get_dwp_file (dwarf2_per_objfile) == NULL)
3267         queue_and_load_all_dwo_tus (per_cu);
3268     }
3269
3270   process_queue (dwarf2_per_objfile);
3271
3272   /* Age the cache, releasing compilation units that have not
3273      been used recently.  */
3274   age_cached_comp_units (dwarf2_per_objfile);
3275 }
3276
3277 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3278    the objfile from which this CU came.  Returns the resulting symbol
3279    table.  */
3280
3281 static struct compunit_symtab *
3282 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3283 {
3284   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3285
3286   gdb_assert (dwarf2_per_objfile->using_index);
3287   if (!per_cu->v.quick->compunit_symtab)
3288     {
3289       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3290                                               dwarf2_per_objfile);
3291       scoped_restore decrementer = increment_reading_symtab ();
3292       dw2_do_instantiate_symtab (per_cu);
3293       process_cu_includes (dwarf2_per_objfile);
3294       do_cleanups (back_to);
3295     }
3296
3297   return per_cu->v.quick->compunit_symtab;
3298 }
3299
3300 /* Return the CU/TU given its index.
3301
3302    This is intended for loops like:
3303
3304    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3305                     + dwarf2_per_objfile->n_type_units); ++i)
3306      {
3307        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3308
3309        ...;
3310      }
3311 */
3312
3313 static struct dwarf2_per_cu_data *
3314 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3315               int index)
3316 {
3317   if (index >= dwarf2_per_objfile->n_comp_units)
3318     {
3319       index -= dwarf2_per_objfile->n_comp_units;
3320       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3321       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3322     }
3323
3324   return dwarf2_per_objfile->all_comp_units[index];
3325 }
3326
3327 /* Return the CU given its index.
3328    This differs from dw2_get_cutu in that it's for when you know INDEX
3329    refers to a CU.  */
3330
3331 static struct dwarf2_per_cu_data *
3332 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3333 {
3334   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3335
3336   return dwarf2_per_objfile->all_comp_units[index];
3337 }
3338
3339 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3340    objfile_obstack, and constructed with the specified field
3341    values.  */
3342
3343 static dwarf2_per_cu_data *
3344 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3345                           struct dwarf2_section_info *section,
3346                           int is_dwz,
3347                           sect_offset sect_off, ULONGEST length)
3348 {
3349   struct objfile *objfile = dwarf2_per_objfile->objfile;
3350   dwarf2_per_cu_data *the_cu
3351     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3352                      struct dwarf2_per_cu_data);
3353   the_cu->sect_off = sect_off;
3354   the_cu->length = length;
3355   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3356   the_cu->section = section;
3357   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3358                                    struct dwarf2_per_cu_quick_data);
3359   the_cu->is_dwz = is_dwz;
3360   return the_cu;
3361 }
3362
3363 /* A helper for create_cus_from_index that handles a given list of
3364    CUs.  */
3365
3366 static void
3367 create_cus_from_index_list (struct objfile *objfile,
3368                             const gdb_byte *cu_list, offset_type n_elements,
3369                             struct dwarf2_section_info *section,
3370                             int is_dwz,
3371                             int base_offset)
3372 {
3373   offset_type i;
3374   struct dwarf2_per_objfile *dwarf2_per_objfile
3375     = get_dwarf2_per_objfile (objfile);
3376
3377   for (i = 0; i < n_elements; i += 2)
3378     {
3379       gdb_static_assert (sizeof (ULONGEST) >= 8);
3380
3381       sect_offset sect_off
3382         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3383       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3384       cu_list += 2 * 8;
3385
3386       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3387         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3388                                      sect_off, length);
3389     }
3390 }
3391
3392 /* Read the CU list from the mapped index, and use it to create all
3393    the CU objects for this objfile.  */
3394
3395 static void
3396 create_cus_from_index (struct objfile *objfile,
3397                        const gdb_byte *cu_list, offset_type cu_list_elements,
3398                        const gdb_byte *dwz_list, offset_type dwz_elements)
3399 {
3400   struct dwz_file *dwz;
3401   struct dwarf2_per_objfile *dwarf2_per_objfile
3402     = get_dwarf2_per_objfile (objfile);
3403
3404   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3405   dwarf2_per_objfile->all_comp_units =
3406     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3407                dwarf2_per_objfile->n_comp_units);
3408
3409   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3410                               &dwarf2_per_objfile->info, 0, 0);
3411
3412   if (dwz_elements == 0)
3413     return;
3414
3415   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3416   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3417                               cu_list_elements / 2);
3418 }
3419
3420 /* Create the signatured type hash table from the index.  */
3421
3422 static void
3423 create_signatured_type_table_from_index (struct objfile *objfile,
3424                                          struct dwarf2_section_info *section,
3425                                          const gdb_byte *bytes,
3426                                          offset_type elements)
3427 {
3428   offset_type i;
3429   htab_t sig_types_hash;
3430   struct dwarf2_per_objfile *dwarf2_per_objfile
3431     = get_dwarf2_per_objfile (objfile);
3432
3433   dwarf2_per_objfile->n_type_units
3434     = dwarf2_per_objfile->n_allocated_type_units
3435     = elements / 3;
3436   dwarf2_per_objfile->all_type_units =
3437     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3438
3439   sig_types_hash = allocate_signatured_type_table (objfile);
3440
3441   for (i = 0; i < elements; i += 3)
3442     {
3443       struct signatured_type *sig_type;
3444       ULONGEST signature;
3445       void **slot;
3446       cu_offset type_offset_in_tu;
3447
3448       gdb_static_assert (sizeof (ULONGEST) >= 8);
3449       sect_offset sect_off
3450         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3451       type_offset_in_tu
3452         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3453                                                 BFD_ENDIAN_LITTLE);
3454       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3455       bytes += 3 * 8;
3456
3457       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3458                                  struct signatured_type);
3459       sig_type->signature = signature;
3460       sig_type->type_offset_in_tu = type_offset_in_tu;
3461       sig_type->per_cu.is_debug_types = 1;
3462       sig_type->per_cu.section = section;
3463       sig_type->per_cu.sect_off = sect_off;
3464       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3465       sig_type->per_cu.v.quick
3466         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3467                           struct dwarf2_per_cu_quick_data);
3468
3469       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3470       *slot = sig_type;
3471
3472       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3473     }
3474
3475   dwarf2_per_objfile->signatured_types = sig_types_hash;
3476 }
3477
3478 /* Create the signatured type hash table from .debug_names.  */
3479
3480 static void
3481 create_signatured_type_table_from_debug_names
3482   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3483    const mapped_debug_names &map,
3484    struct dwarf2_section_info *section,
3485    struct dwarf2_section_info *abbrev_section)
3486 {
3487   struct objfile *objfile = dwarf2_per_objfile->objfile;
3488
3489   dwarf2_read_section (objfile, section);
3490   dwarf2_read_section (objfile, abbrev_section);
3491
3492   dwarf2_per_objfile->n_type_units
3493     = dwarf2_per_objfile->n_allocated_type_units
3494     = map.tu_count;
3495   dwarf2_per_objfile->all_type_units
3496     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3497
3498   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3499
3500   for (uint32_t i = 0; i < map.tu_count; ++i)
3501     {
3502       struct signatured_type *sig_type;
3503       ULONGEST signature;
3504       void **slot;
3505       cu_offset type_offset_in_tu;
3506
3507       sect_offset sect_off
3508         = (sect_offset) (extract_unsigned_integer
3509                          (map.tu_table_reordered + i * map.offset_size,
3510                           map.offset_size,
3511                           map.dwarf5_byte_order));
3512
3513       comp_unit_head cu_header;
3514       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3515                                      abbrev_section,
3516                                      section->buffer + to_underlying (sect_off),
3517                                      rcuh_kind::TYPE);
3518
3519       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3520                                  struct signatured_type);
3521       sig_type->signature = cu_header.signature;
3522       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3523       sig_type->per_cu.is_debug_types = 1;
3524       sig_type->per_cu.section = section;
3525       sig_type->per_cu.sect_off = sect_off;
3526       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3527       sig_type->per_cu.v.quick
3528         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3529                           struct dwarf2_per_cu_quick_data);
3530
3531       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3532       *slot = sig_type;
3533
3534       dwarf2_per_objfile->all_type_units[i] = sig_type;
3535     }
3536
3537   dwarf2_per_objfile->signatured_types = sig_types_hash;
3538 }
3539
3540 /* Read the address map data from the mapped index, and use it to
3541    populate the objfile's psymtabs_addrmap.  */
3542
3543 static void
3544 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3545                            struct mapped_index *index)
3546 {
3547   struct objfile *objfile = dwarf2_per_objfile->objfile;
3548   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3549   const gdb_byte *iter, *end;
3550   struct addrmap *mutable_map;
3551   CORE_ADDR baseaddr;
3552
3553   auto_obstack temp_obstack;
3554
3555   mutable_map = addrmap_create_mutable (&temp_obstack);
3556
3557   iter = index->address_table.data ();
3558   end = iter + index->address_table.size ();
3559
3560   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3561
3562   while (iter < end)
3563     {
3564       ULONGEST hi, lo, cu_index;
3565       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3566       iter += 8;
3567       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3568       iter += 8;
3569       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3570       iter += 4;
3571
3572       if (lo > hi)
3573         {
3574           complaint (&symfile_complaints,
3575                      _(".gdb_index address table has invalid range (%s - %s)"),
3576                      hex_string (lo), hex_string (hi));
3577           continue;
3578         }
3579
3580       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3581         {
3582           complaint (&symfile_complaints,
3583                      _(".gdb_index address table has invalid CU number %u"),
3584                      (unsigned) cu_index);
3585           continue;
3586         }
3587
3588       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3589       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3590       addrmap_set_empty (mutable_map, lo, hi - 1,
3591                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3592     }
3593
3594   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3595                                                     &objfile->objfile_obstack);
3596 }
3597
3598 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3599    populate the objfile's psymtabs_addrmap.  */
3600
3601 static void
3602 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3603                              struct dwarf2_section_info *section)
3604 {
3605   struct objfile *objfile = dwarf2_per_objfile->objfile;
3606   bfd *abfd = objfile->obfd;
3607   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3608   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3609                                        SECT_OFF_TEXT (objfile));
3610
3611   auto_obstack temp_obstack;
3612   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3613
3614   std::unordered_map<sect_offset,
3615                      dwarf2_per_cu_data *,
3616                      gdb::hash_enum<sect_offset>>
3617     debug_info_offset_to_per_cu;
3618   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3619     {
3620       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3621       const auto insertpair
3622         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3623       if (!insertpair.second)
3624         {
3625           warning (_("Section .debug_aranges in %s has duplicate "
3626                      "debug_info_offset %s, ignoring .debug_aranges."),
3627                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3628           return;
3629         }
3630     }
3631
3632   dwarf2_read_section (objfile, section);
3633
3634   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3635
3636   const gdb_byte *addr = section->buffer;
3637
3638   while (addr < section->buffer + section->size)
3639     {
3640       const gdb_byte *const entry_addr = addr;
3641       unsigned int bytes_read;
3642
3643       const LONGEST entry_length = read_initial_length (abfd, addr,
3644                                                         &bytes_read);
3645       addr += bytes_read;
3646
3647       const gdb_byte *const entry_end = addr + entry_length;
3648       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3649       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3650       if (addr + entry_length > section->buffer + section->size)
3651         {
3652           warning (_("Section .debug_aranges in %s entry at offset %zu "
3653                      "length %s exceeds section length %s, "
3654                      "ignoring .debug_aranges."),
3655                    objfile_name (objfile), entry_addr - section->buffer,
3656                    plongest (bytes_read + entry_length),
3657                    pulongest (section->size));
3658           return;
3659         }
3660
3661       /* The version number.  */
3662       const uint16_t version = read_2_bytes (abfd, addr);
3663       addr += 2;
3664       if (version != 2)
3665         {
3666           warning (_("Section .debug_aranges in %s entry at offset %zu "
3667                      "has unsupported version %d, ignoring .debug_aranges."),
3668                    objfile_name (objfile), entry_addr - section->buffer,
3669                    version);
3670           return;
3671         }
3672
3673       const uint64_t debug_info_offset
3674         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3675       addr += offset_size;
3676       const auto per_cu_it
3677         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3678       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3679         {
3680           warning (_("Section .debug_aranges in %s entry at offset %zu "
3681                      "debug_info_offset %s does not exists, "
3682                      "ignoring .debug_aranges."),
3683                    objfile_name (objfile), entry_addr - section->buffer,
3684                    pulongest (debug_info_offset));
3685           return;
3686         }
3687       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3688
3689       const uint8_t address_size = *addr++;
3690       if (address_size < 1 || address_size > 8)
3691         {
3692           warning (_("Section .debug_aranges in %s entry at offset %zu "
3693                      "address_size %u is invalid, ignoring .debug_aranges."),
3694                    objfile_name (objfile), entry_addr - section->buffer,
3695                    address_size);
3696           return;
3697         }
3698
3699       const uint8_t segment_selector_size = *addr++;
3700       if (segment_selector_size != 0)
3701         {
3702           warning (_("Section .debug_aranges in %s entry at offset %zu "
3703                      "segment_selector_size %u is not supported, "
3704                      "ignoring .debug_aranges."),
3705                    objfile_name (objfile), entry_addr - section->buffer,
3706                    segment_selector_size);
3707           return;
3708         }
3709
3710       /* Must pad to an alignment boundary that is twice the address
3711          size.  It is undocumented by the DWARF standard but GCC does
3712          use it.  */
3713       for (size_t padding = ((-(addr - section->buffer))
3714                              & (2 * address_size - 1));
3715            padding > 0; padding--)
3716         if (*addr++ != 0)
3717           {
3718             warning (_("Section .debug_aranges in %s entry at offset %zu "
3719                        "padding is not zero, ignoring .debug_aranges."),
3720                      objfile_name (objfile), entry_addr - section->buffer);
3721             return;
3722           }
3723
3724       for (;;)
3725         {
3726           if (addr + 2 * address_size > entry_end)
3727             {
3728               warning (_("Section .debug_aranges in %s entry at offset %zu "
3729                          "address list is not properly terminated, "
3730                          "ignoring .debug_aranges."),
3731                        objfile_name (objfile), entry_addr - section->buffer);
3732               return;
3733             }
3734           ULONGEST start = extract_unsigned_integer (addr, address_size,
3735                                                      dwarf5_byte_order);
3736           addr += address_size;
3737           ULONGEST length = extract_unsigned_integer (addr, address_size,
3738                                                       dwarf5_byte_order);
3739           addr += address_size;
3740           if (start == 0 && length == 0)
3741             break;
3742           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3743             {
3744               /* Symbol was eliminated due to a COMDAT group.  */
3745               continue;
3746             }
3747           ULONGEST end = start + length;
3748           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3749           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3750           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3751         }
3752     }
3753
3754   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3755                                                     &objfile->objfile_obstack);
3756 }
3757
3758 /* The hash function for strings in the mapped index.  This is the same as
3759    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3760    implementation.  This is necessary because the hash function is tied to the
3761    format of the mapped index file.  The hash values do not have to match with
3762    SYMBOL_HASH_NEXT.
3763    
3764    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3765
3766 static hashval_t
3767 mapped_index_string_hash (int index_version, const void *p)
3768 {
3769   const unsigned char *str = (const unsigned char *) p;
3770   hashval_t r = 0;
3771   unsigned char c;
3772
3773   while ((c = *str++) != 0)
3774     {
3775       if (index_version >= 5)
3776         c = tolower (c);
3777       r = r * 67 + c - 113;
3778     }
3779
3780   return r;
3781 }
3782
3783 /* Find a slot in the mapped index INDEX for the object named NAME.
3784    If NAME is found, set *VEC_OUT to point to the CU vector in the
3785    constant pool and return true.  If NAME cannot be found, return
3786    false.  */
3787
3788 static bool
3789 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3790                           offset_type **vec_out)
3791 {
3792   offset_type hash;
3793   offset_type slot, step;
3794   int (*cmp) (const char *, const char *);
3795
3796   gdb::unique_xmalloc_ptr<char> without_params;
3797   if (current_language->la_language == language_cplus
3798       || current_language->la_language == language_fortran
3799       || current_language->la_language == language_d)
3800     {
3801       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3802          not contain any.  */
3803
3804       if (strchr (name, '(') != NULL)
3805         {
3806           without_params = cp_remove_params (name);
3807
3808           if (without_params != NULL)
3809             name = without_params.get ();
3810         }
3811     }
3812
3813   /* Index version 4 did not support case insensitive searches.  But the
3814      indices for case insensitive languages are built in lowercase, therefore
3815      simulate our NAME being searched is also lowercased.  */
3816   hash = mapped_index_string_hash ((index->version == 4
3817                                     && case_sensitivity == case_sensitive_off
3818                                     ? 5 : index->version),
3819                                    name);
3820
3821   slot = hash & (index->symbol_table.size () - 1);
3822   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3823   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3824
3825   for (;;)
3826     {
3827       const char *str;
3828
3829       const auto &bucket = index->symbol_table[slot];
3830       if (bucket.name == 0 && bucket.vec == 0)
3831         return false;
3832
3833       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3834       if (!cmp (name, str))
3835         {
3836           *vec_out = (offset_type *) (index->constant_pool
3837                                       + MAYBE_SWAP (bucket.vec));
3838           return true;
3839         }
3840
3841       slot = (slot + step) & (index->symbol_table.size () - 1);
3842     }
3843 }
3844
3845 /* A helper function that reads the .gdb_index from SECTION and fills
3846    in MAP.  FILENAME is the name of the file containing the section;
3847    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3848    ok to use deprecated sections.
3849
3850    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3851    out parameters that are filled in with information about the CU and
3852    TU lists in the section.
3853
3854    Returns 1 if all went well, 0 otherwise.  */
3855
3856 static int
3857 read_index_from_section (struct objfile *objfile,
3858                          const char *filename,
3859                          int deprecated_ok,
3860                          struct dwarf2_section_info *section,
3861                          struct mapped_index *map,
3862                          const gdb_byte **cu_list,
3863                          offset_type *cu_list_elements,
3864                          const gdb_byte **types_list,
3865                          offset_type *types_list_elements)
3866 {
3867   const gdb_byte *addr;
3868   offset_type version;
3869   offset_type *metadata;
3870   int i;
3871
3872   if (dwarf2_section_empty_p (section))
3873     return 0;
3874
3875   /* Older elfutils strip versions could keep the section in the main
3876      executable while splitting it for the separate debug info file.  */
3877   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3878     return 0;
3879
3880   dwarf2_read_section (objfile, section);
3881
3882   addr = section->buffer;
3883   /* Version check.  */
3884   version = MAYBE_SWAP (*(offset_type *) addr);
3885   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3886      causes the index to behave very poorly for certain requests.  Version 3
3887      contained incomplete addrmap.  So, it seems better to just ignore such
3888      indices.  */
3889   if (version < 4)
3890     {
3891       static int warning_printed = 0;
3892       if (!warning_printed)
3893         {
3894           warning (_("Skipping obsolete .gdb_index section in %s."),
3895                    filename);
3896           warning_printed = 1;
3897         }
3898       return 0;
3899     }
3900   /* Index version 4 uses a different hash function than index version
3901      5 and later.
3902
3903      Versions earlier than 6 did not emit psymbols for inlined
3904      functions.  Using these files will cause GDB not to be able to
3905      set breakpoints on inlined functions by name, so we ignore these
3906      indices unless the user has done
3907      "set use-deprecated-index-sections on".  */
3908   if (version < 6 && !deprecated_ok)
3909     {
3910       static int warning_printed = 0;
3911       if (!warning_printed)
3912         {
3913           warning (_("\
3914 Skipping deprecated .gdb_index section in %s.\n\
3915 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3916 to use the section anyway."),
3917                    filename);
3918           warning_printed = 1;
3919         }
3920       return 0;
3921     }
3922   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3923      of the TU (for symbols coming from TUs),
3924      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3925      Plus gold-generated indices can have duplicate entries for global symbols,
3926      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3927      These are just performance bugs, and we can't distinguish gdb-generated
3928      indices from gold-generated ones, so issue no warning here.  */
3929
3930   /* Indexes with higher version than the one supported by GDB may be no
3931      longer backward compatible.  */
3932   if (version > 8)
3933     return 0;
3934
3935   map->version = version;
3936   map->total_size = section->size;
3937
3938   metadata = (offset_type *) (addr + sizeof (offset_type));
3939
3940   i = 0;
3941   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3942   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3943                        / 8);
3944   ++i;
3945
3946   *types_list = addr + MAYBE_SWAP (metadata[i]);
3947   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3948                            - MAYBE_SWAP (metadata[i]))
3949                           / 8);
3950   ++i;
3951
3952   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3953   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3954   map->address_table
3955     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3956   ++i;
3957
3958   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3959   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3960   map->symbol_table
3961     = gdb::array_view<mapped_index::symbol_table_slot>
3962        ((mapped_index::symbol_table_slot *) symbol_table,
3963         (mapped_index::symbol_table_slot *) symbol_table_end);
3964
3965   ++i;
3966   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3967
3968   return 1;
3969 }
3970
3971 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3972    elements of all the CUs and return 1.  Otherwise, return 0.  */
3973
3974 static int
3975 dwarf2_read_index (struct objfile *objfile)
3976 {
3977   struct mapped_index local_map, *map;
3978   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3979   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3980   struct dwz_file *dwz;
3981   struct dwarf2_per_objfile *dwarf2_per_objfile
3982     = get_dwarf2_per_objfile (objfile);
3983
3984   if (!read_index_from_section (objfile, objfile_name (objfile),
3985                                 use_deprecated_index_sections,
3986                                 &dwarf2_per_objfile->gdb_index, &local_map,
3987                                 &cu_list, &cu_list_elements,
3988                                 &types_list, &types_list_elements))
3989     return 0;
3990
3991   /* Don't use the index if it's empty.  */
3992   if (local_map.symbol_table.empty ())
3993     return 0;
3994
3995   /* If there is a .dwz file, read it so we can get its CU list as
3996      well.  */
3997   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3998   if (dwz != NULL)
3999     {
4000       struct mapped_index dwz_map;
4001       const gdb_byte *dwz_types_ignore;
4002       offset_type dwz_types_elements_ignore;
4003
4004       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
4005                                     1,
4006                                     &dwz->gdb_index, &dwz_map,
4007                                     &dwz_list, &dwz_list_elements,
4008                                     &dwz_types_ignore,
4009                                     &dwz_types_elements_ignore))
4010         {
4011           warning (_("could not read '.gdb_index' section from %s; skipping"),
4012                    bfd_get_filename (dwz->dwz_bfd));
4013           return 0;
4014         }
4015     }
4016
4017   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
4018                          dwz_list_elements);
4019
4020   if (types_list_elements)
4021     {
4022       struct dwarf2_section_info *section;
4023
4024       /* We can only handle a single .debug_types when we have an
4025          index.  */
4026       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
4027         return 0;
4028
4029       section = VEC_index (dwarf2_section_info_def,
4030                            dwarf2_per_objfile->types, 0);
4031
4032       create_signatured_type_table_from_index (objfile, section, types_list,
4033                                                types_list_elements);
4034     }
4035
4036   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
4037
4038   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
4039   map = new (map) mapped_index ();
4040   *map = local_map;
4041
4042   dwarf2_per_objfile->index_table = map;
4043   dwarf2_per_objfile->using_index = 1;
4044   dwarf2_per_objfile->quick_file_names_table =
4045     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4046
4047   return 1;
4048 }
4049
4050 /* die_reader_func for dw2_get_file_names.  */
4051
4052 static void
4053 dw2_get_file_names_reader (const struct die_reader_specs *reader,
4054                            const gdb_byte *info_ptr,
4055                            struct die_info *comp_unit_die,
4056                            int has_children,
4057                            void *data)
4058 {
4059   struct dwarf2_cu *cu = reader->cu;
4060   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
4061   struct dwarf2_per_objfile *dwarf2_per_objfile
4062     = cu->per_cu->dwarf2_per_objfile;
4063   struct objfile *objfile = dwarf2_per_objfile->objfile;
4064   struct dwarf2_per_cu_data *lh_cu;
4065   struct attribute *attr;
4066   int i;
4067   void **slot;
4068   struct quick_file_names *qfn;
4069
4070   gdb_assert (! this_cu->is_debug_types);
4071
4072   /* Our callers never want to match partial units -- instead they
4073      will match the enclosing full CU.  */
4074   if (comp_unit_die->tag == DW_TAG_partial_unit)
4075     {
4076       this_cu->v.quick->no_file_data = 1;
4077       return;
4078     }
4079
4080   lh_cu = this_cu;
4081   slot = NULL;
4082
4083   line_header_up lh;
4084   sect_offset line_offset {};
4085
4086   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4087   if (attr)
4088     {
4089       struct quick_file_names find_entry;
4090
4091       line_offset = (sect_offset) DW_UNSND (attr);
4092
4093       /* We may have already read in this line header (TU line header sharing).
4094          If we have we're done.  */
4095       find_entry.hash.dwo_unit = cu->dwo_unit;
4096       find_entry.hash.line_sect_off = line_offset;
4097       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
4098                              &find_entry, INSERT);
4099       if (*slot != NULL)
4100         {
4101           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
4102           return;
4103         }
4104
4105       lh = dwarf_decode_line_header (line_offset, cu);
4106     }
4107   if (lh == NULL)
4108     {
4109       lh_cu->v.quick->no_file_data = 1;
4110       return;
4111     }
4112
4113   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4114   qfn->hash.dwo_unit = cu->dwo_unit;
4115   qfn->hash.line_sect_off = line_offset;
4116   gdb_assert (slot != NULL);
4117   *slot = qfn;
4118
4119   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4120
4121   qfn->num_file_names = lh->file_names.size ();
4122   qfn->file_names =
4123     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4124   for (i = 0; i < lh->file_names.size (); ++i)
4125     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4126   qfn->real_names = NULL;
4127
4128   lh_cu->v.quick->file_names = qfn;
4129 }
4130
4131 /* A helper for the "quick" functions which attempts to read the line
4132    table for THIS_CU.  */
4133
4134 static struct quick_file_names *
4135 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4136 {
4137   /* This should never be called for TUs.  */
4138   gdb_assert (! this_cu->is_debug_types);
4139   /* Nor type unit groups.  */
4140   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4141
4142   if (this_cu->v.quick->file_names != NULL)
4143     return this_cu->v.quick->file_names;
4144   /* If we know there is no line data, no point in looking again.  */
4145   if (this_cu->v.quick->no_file_data)
4146     return NULL;
4147
4148   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4149
4150   if (this_cu->v.quick->no_file_data)
4151     return NULL;
4152   return this_cu->v.quick->file_names;
4153 }
4154
4155 /* A helper for the "quick" functions which computes and caches the
4156    real path for a given file name from the line table.  */
4157
4158 static const char *
4159 dw2_get_real_path (struct objfile *objfile,
4160                    struct quick_file_names *qfn, int index)
4161 {
4162   if (qfn->real_names == NULL)
4163     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4164                                       qfn->num_file_names, const char *);
4165
4166   if (qfn->real_names[index] == NULL)
4167     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4168
4169   return qfn->real_names[index];
4170 }
4171
4172 static struct symtab *
4173 dw2_find_last_source_symtab (struct objfile *objfile)
4174 {
4175   struct dwarf2_per_objfile *dwarf2_per_objfile
4176     = get_dwarf2_per_objfile (objfile);
4177   int index = dwarf2_per_objfile->n_comp_units - 1;
4178   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4179   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4180
4181   if (cust == NULL)
4182     return NULL;
4183
4184   return compunit_primary_filetab (cust);
4185 }
4186
4187 /* Traversal function for dw2_forget_cached_source_info.  */
4188
4189 static int
4190 dw2_free_cached_file_names (void **slot, void *info)
4191 {
4192   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4193
4194   if (file_data->real_names)
4195     {
4196       int i;
4197
4198       for (i = 0; i < file_data->num_file_names; ++i)
4199         {
4200           xfree ((void*) file_data->real_names[i]);
4201           file_data->real_names[i] = NULL;
4202         }
4203     }
4204
4205   return 1;
4206 }
4207
4208 static void
4209 dw2_forget_cached_source_info (struct objfile *objfile)
4210 {
4211   struct dwarf2_per_objfile *dwarf2_per_objfile
4212     = get_dwarf2_per_objfile (objfile);
4213
4214   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4215                           dw2_free_cached_file_names, NULL);
4216 }
4217
4218 /* Helper function for dw2_map_symtabs_matching_filename that expands
4219    the symtabs and calls the iterator.  */
4220
4221 static int
4222 dw2_map_expand_apply (struct objfile *objfile,
4223                       struct dwarf2_per_cu_data *per_cu,
4224                       const char *name, const char *real_path,
4225                       gdb::function_view<bool (symtab *)> callback)
4226 {
4227   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4228
4229   /* Don't visit already-expanded CUs.  */
4230   if (per_cu->v.quick->compunit_symtab)
4231     return 0;
4232
4233   /* This may expand more than one symtab, and we want to iterate over
4234      all of them.  */
4235   dw2_instantiate_symtab (per_cu);
4236
4237   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4238                                     last_made, callback);
4239 }
4240
4241 /* Implementation of the map_symtabs_matching_filename method.  */
4242
4243 static bool
4244 dw2_map_symtabs_matching_filename
4245   (struct objfile *objfile, const char *name, const char *real_path,
4246    gdb::function_view<bool (symtab *)> callback)
4247 {
4248   int i;
4249   const char *name_basename = lbasename (name);
4250   struct dwarf2_per_objfile *dwarf2_per_objfile
4251     = get_dwarf2_per_objfile (objfile);
4252
4253   /* The rule is CUs specify all the files, including those used by
4254      any TU, so there's no need to scan TUs here.  */
4255
4256   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4257     {
4258       int j;
4259       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4260       struct quick_file_names *file_data;
4261
4262       /* We only need to look at symtabs not already expanded.  */
4263       if (per_cu->v.quick->compunit_symtab)
4264         continue;
4265
4266       file_data = dw2_get_file_names (per_cu);
4267       if (file_data == NULL)
4268         continue;
4269
4270       for (j = 0; j < file_data->num_file_names; ++j)
4271         {
4272           const char *this_name = file_data->file_names[j];
4273           const char *this_real_name;
4274
4275           if (compare_filenames_for_search (this_name, name))
4276             {
4277               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4278                                         callback))
4279                 return true;
4280               continue;
4281             }
4282
4283           /* Before we invoke realpath, which can get expensive when many
4284              files are involved, do a quick comparison of the basenames.  */
4285           if (! basenames_may_differ
4286               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4287             continue;
4288
4289           this_real_name = dw2_get_real_path (objfile, file_data, j);
4290           if (compare_filenames_for_search (this_real_name, name))
4291             {
4292               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4293                                         callback))
4294                 return true;
4295               continue;
4296             }
4297
4298           if (real_path != NULL)
4299             {
4300               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4301               gdb_assert (IS_ABSOLUTE_PATH (name));
4302               if (this_real_name != NULL
4303                   && FILENAME_CMP (real_path, this_real_name) == 0)
4304                 {
4305                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4306                                             callback))
4307                     return true;
4308                   continue;
4309                 }
4310             }
4311         }
4312     }
4313
4314   return false;
4315 }
4316
4317 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4318
4319 struct dw2_symtab_iterator
4320 {
4321   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4322   struct dwarf2_per_objfile *dwarf2_per_objfile;
4323   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4324   int want_specific_block;
4325   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4326      Unused if !WANT_SPECIFIC_BLOCK.  */
4327   int block_index;
4328   /* The kind of symbol we're looking for.  */
4329   domain_enum domain;
4330   /* The list of CUs from the index entry of the symbol,
4331      or NULL if not found.  */
4332   offset_type *vec;
4333   /* The next element in VEC to look at.  */
4334   int next;
4335   /* The number of elements in VEC, or zero if there is no match.  */
4336   int length;
4337   /* Have we seen a global version of the symbol?
4338      If so we can ignore all further global instances.
4339      This is to work around gold/15646, inefficient gold-generated
4340      indices.  */
4341   int global_seen;
4342 };
4343
4344 /* Initialize the index symtab iterator ITER.
4345    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4346    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4347
4348 static void
4349 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4350                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4351                       int want_specific_block,
4352                       int block_index,
4353                       domain_enum domain,
4354                       const char *name)
4355 {
4356   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4357   iter->want_specific_block = want_specific_block;
4358   iter->block_index = block_index;
4359   iter->domain = domain;
4360   iter->next = 0;
4361   iter->global_seen = 0;
4362
4363   mapped_index *index = dwarf2_per_objfile->index_table;
4364
4365   /* index is NULL if OBJF_READNOW.  */
4366   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4367     iter->length = MAYBE_SWAP (*iter->vec);
4368   else
4369     {
4370       iter->vec = NULL;
4371       iter->length = 0;
4372     }
4373 }
4374
4375 /* Return the next matching CU or NULL if there are no more.  */
4376
4377 static struct dwarf2_per_cu_data *
4378 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4379 {
4380   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4381
4382   for ( ; iter->next < iter->length; ++iter->next)
4383     {
4384       offset_type cu_index_and_attrs =
4385         MAYBE_SWAP (iter->vec[iter->next + 1]);
4386       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4387       struct dwarf2_per_cu_data *per_cu;
4388       int want_static = iter->block_index != GLOBAL_BLOCK;
4389       /* This value is only valid for index versions >= 7.  */
4390       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4391       gdb_index_symbol_kind symbol_kind =
4392         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4393       /* Only check the symbol attributes if they're present.
4394          Indices prior to version 7 don't record them,
4395          and indices >= 7 may elide them for certain symbols
4396          (gold does this).  */
4397       int attrs_valid =
4398         (dwarf2_per_objfile->index_table->version >= 7
4399          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4400
4401       /* Don't crash on bad data.  */
4402       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4403                        + dwarf2_per_objfile->n_type_units))
4404         {
4405           complaint (&symfile_complaints,
4406                      _(".gdb_index entry has bad CU index"
4407                        " [in module %s]"),
4408                      objfile_name (dwarf2_per_objfile->objfile));
4409           continue;
4410         }
4411
4412       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4413
4414       /* Skip if already read in.  */
4415       if (per_cu->v.quick->compunit_symtab)
4416         continue;
4417
4418       /* Check static vs global.  */
4419       if (attrs_valid)
4420         {
4421           if (iter->want_specific_block
4422               && want_static != is_static)
4423             continue;
4424           /* Work around gold/15646.  */
4425           if (!is_static && iter->global_seen)
4426             continue;
4427           if (!is_static)
4428             iter->global_seen = 1;
4429         }
4430
4431       /* Only check the symbol's kind if it has one.  */
4432       if (attrs_valid)
4433         {
4434           switch (iter->domain)
4435             {
4436             case VAR_DOMAIN:
4437               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4438                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4439                   /* Some types are also in VAR_DOMAIN.  */
4440                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4441                 continue;
4442               break;
4443             case STRUCT_DOMAIN:
4444               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4445                 continue;
4446               break;
4447             case LABEL_DOMAIN:
4448               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4449                 continue;
4450               break;
4451             default:
4452               break;
4453             }
4454         }
4455
4456       ++iter->next;
4457       return per_cu;
4458     }
4459
4460   return NULL;
4461 }
4462
4463 static struct compunit_symtab *
4464 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4465                    const char *name, domain_enum domain)
4466 {
4467   struct compunit_symtab *stab_best = NULL;
4468   struct dwarf2_per_objfile *dwarf2_per_objfile
4469     = get_dwarf2_per_objfile (objfile);
4470
4471   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4472
4473   struct dw2_symtab_iterator iter;
4474   struct dwarf2_per_cu_data *per_cu;
4475
4476   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4477
4478   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4479     {
4480       struct symbol *sym, *with_opaque = NULL;
4481       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4482       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4483       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4484
4485       sym = block_find_symbol (block, name, domain,
4486                                block_find_non_opaque_type_preferred,
4487                                &with_opaque);
4488
4489       /* Some caution must be observed with overloaded functions
4490          and methods, since the index will not contain any overload
4491          information (but NAME might contain it).  */
4492
4493       if (sym != NULL
4494           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4495         return stab;
4496       if (with_opaque != NULL
4497           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4498         stab_best = stab;
4499
4500       /* Keep looking through other CUs.  */
4501     }
4502
4503   return stab_best;
4504 }
4505
4506 static void
4507 dw2_print_stats (struct objfile *objfile)
4508 {
4509   struct dwarf2_per_objfile *dwarf2_per_objfile
4510     = get_dwarf2_per_objfile (objfile);
4511   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4512   int count = 0;
4513
4514   for (int i = 0; i < total; ++i)
4515     {
4516       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4517
4518       if (!per_cu->v.quick->compunit_symtab)
4519         ++count;
4520     }
4521   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4522   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4523 }
4524
4525 /* This dumps minimal information about the index.
4526    It is called via "mt print objfiles".
4527    One use is to verify .gdb_index has been loaded by the
4528    gdb.dwarf2/gdb-index.exp testcase.  */
4529
4530 static void
4531 dw2_dump (struct objfile *objfile)
4532 {
4533   struct dwarf2_per_objfile *dwarf2_per_objfile
4534     = get_dwarf2_per_objfile (objfile);
4535
4536   gdb_assert (dwarf2_per_objfile->using_index);
4537   printf_filtered (".gdb_index:");
4538   if (dwarf2_per_objfile->index_table != NULL)
4539     {
4540       printf_filtered (" version %d\n",
4541                        dwarf2_per_objfile->index_table->version);
4542     }
4543   else
4544     printf_filtered (" faked for \"readnow\"\n");
4545   printf_filtered ("\n");
4546 }
4547
4548 static void
4549 dw2_relocate (struct objfile *objfile,
4550               const struct section_offsets *new_offsets,
4551               const struct section_offsets *delta)
4552 {
4553   /* There's nothing to relocate here.  */
4554 }
4555
4556 static void
4557 dw2_expand_symtabs_for_function (struct objfile *objfile,
4558                                  const char *func_name)
4559 {
4560   struct dwarf2_per_objfile *dwarf2_per_objfile
4561     = get_dwarf2_per_objfile (objfile);
4562
4563   struct dw2_symtab_iterator iter;
4564   struct dwarf2_per_cu_data *per_cu;
4565
4566   /* Note: It doesn't matter what we pass for block_index here.  */
4567   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4568                         func_name);
4569
4570   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4571     dw2_instantiate_symtab (per_cu);
4572
4573 }
4574
4575 static void
4576 dw2_expand_all_symtabs (struct objfile *objfile)
4577 {
4578   struct dwarf2_per_objfile *dwarf2_per_objfile
4579     = get_dwarf2_per_objfile (objfile);
4580   int total_units = (dwarf2_per_objfile->n_comp_units
4581                      + dwarf2_per_objfile->n_type_units);
4582
4583   for (int i = 0; i < total_units; ++i)
4584     {
4585       struct dwarf2_per_cu_data *per_cu
4586         = dw2_get_cutu (dwarf2_per_objfile, i);
4587
4588       dw2_instantiate_symtab (per_cu);
4589     }
4590 }
4591
4592 static void
4593 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4594                                   const char *fullname)
4595 {
4596   struct dwarf2_per_objfile *dwarf2_per_objfile
4597     = get_dwarf2_per_objfile (objfile);
4598
4599   /* We don't need to consider type units here.
4600      This is only called for examining code, e.g. expand_line_sal.
4601      There can be an order of magnitude (or more) more type units
4602      than comp units, and we avoid them if we can.  */
4603
4604   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4605     {
4606       int j;
4607       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4608       struct quick_file_names *file_data;
4609
4610       /* We only need to look at symtabs not already expanded.  */
4611       if (per_cu->v.quick->compunit_symtab)
4612         continue;
4613
4614       file_data = dw2_get_file_names (per_cu);
4615       if (file_data == NULL)
4616         continue;
4617
4618       for (j = 0; j < file_data->num_file_names; ++j)
4619         {
4620           const char *this_fullname = file_data->file_names[j];
4621
4622           if (filename_cmp (this_fullname, fullname) == 0)
4623             {
4624               dw2_instantiate_symtab (per_cu);
4625               break;
4626             }
4627         }
4628     }
4629 }
4630
4631 static void
4632 dw2_map_matching_symbols (struct objfile *objfile,
4633                           const char * name, domain_enum domain,
4634                           int global,
4635                           int (*callback) (struct block *,
4636                                            struct symbol *, void *),
4637                           void *data, symbol_name_match_type match,
4638                           symbol_compare_ftype *ordered_compare)
4639 {
4640   /* Currently unimplemented; used for Ada.  The function can be called if the
4641      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4642      does not look for non-Ada symbols this function should just return.  */
4643 }
4644
4645 /* Symbol name matcher for .gdb_index names.
4646
4647    Symbol names in .gdb_index have a few particularities:
4648
4649    - There's no indication of which is the language of each symbol.
4650
4651      Since each language has its own symbol name matching algorithm,
4652      and we don't know which language is the right one, we must match
4653      each symbol against all languages.  This would be a potential
4654      performance problem if it were not mitigated by the
4655      mapped_index::name_components lookup table, which significantly
4656      reduces the number of times we need to call into this matcher,
4657      making it a non-issue.
4658
4659    - Symbol names in the index have no overload (parameter)
4660      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4661      appear as "foo" in the index, for example.
4662
4663      This means that the lookup names passed to the symbol name
4664      matcher functions must have no parameter information either
4665      because (e.g.) symbol search name "foo" does not match
4666      lookup-name "foo(int)" [while swapping search name for lookup
4667      name would match].
4668 */
4669 class gdb_index_symbol_name_matcher
4670 {
4671 public:
4672   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4673   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4674
4675   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4676      Returns true if any matcher matches.  */
4677   bool matches (const char *symbol_name);
4678
4679 private:
4680   /* A reference to the lookup name we're matching against.  */
4681   const lookup_name_info &m_lookup_name;
4682
4683   /* A vector holding all the different symbol name matchers, for all
4684      languages.  */
4685   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4686 };
4687
4688 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4689   (const lookup_name_info &lookup_name)
4690     : m_lookup_name (lookup_name)
4691 {
4692   /* Prepare the vector of comparison functions upfront, to avoid
4693      doing the same work for each symbol.  Care is taken to avoid
4694      matching with the same matcher more than once if/when multiple
4695      languages use the same matcher function.  */
4696   auto &matchers = m_symbol_name_matcher_funcs;
4697   matchers.reserve (nr_languages);
4698
4699   matchers.push_back (default_symbol_name_matcher);
4700
4701   for (int i = 0; i < nr_languages; i++)
4702     {
4703       const language_defn *lang = language_def ((enum language) i);
4704       symbol_name_matcher_ftype *name_matcher
4705         = get_symbol_name_matcher (lang, m_lookup_name);
4706
4707       /* Don't insert the same comparison routine more than once.
4708          Note that we do this linear walk instead of a seemingly
4709          cheaper sorted insert, or use a std::set or something like
4710          that, because relative order of function addresses is not
4711          stable.  This is not a problem in practice because the number
4712          of supported languages is low, and the cost here is tiny
4713          compared to the number of searches we'll do afterwards using
4714          this object.  */
4715       if (name_matcher != default_symbol_name_matcher
4716           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4717               == matchers.end ()))
4718         matchers.push_back (name_matcher);
4719     }
4720 }
4721
4722 bool
4723 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4724 {
4725   for (auto matches_name : m_symbol_name_matcher_funcs)
4726     if (matches_name (symbol_name, m_lookup_name, NULL))
4727       return true;
4728
4729   return false;
4730 }
4731
4732 /* Starting from a search name, return the string that finds the upper
4733    bound of all strings that start with SEARCH_NAME in a sorted name
4734    list.  Returns the empty string to indicate that the upper bound is
4735    the end of the list.  */
4736
4737 static std::string
4738 make_sort_after_prefix_name (const char *search_name)
4739 {
4740   /* When looking to complete "func", we find the upper bound of all
4741      symbols that start with "func" by looking for where we'd insert
4742      the closest string that would follow "func" in lexicographical
4743      order.  Usually, that's "func"-with-last-character-incremented,
4744      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4745      will be UTF-8 multi-byte sequences, but we can't be certain.
4746      Especially mind the 0xff character, which is a valid character in
4747      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4748      rule out compilers allowing it in identifiers.  Note that
4749      conveniently, strcmp/strcasecmp are specified to compare
4750      characters interpreted as unsigned char.  So what we do is treat
4751      the whole string as a base 256 number composed of a sequence of
4752      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4753      to 0, and carries 1 to the following more-significant position.
4754      If the very first character in SEARCH_NAME ends up incremented
4755      and carries/overflows, then the upper bound is the end of the
4756      list.  The string after the empty string is also the empty
4757      string.
4758
4759      Some examples of this operation:
4760
4761        SEARCH_NAME  => "+1" RESULT
4762
4763        "abc"              => "abd"
4764        "ab\xff"           => "ac"
4765        "\xff" "a" "\xff"  => "\xff" "b"
4766        "\xff"             => ""
4767        "\xff\xff"         => ""
4768        ""                 => ""
4769
4770      Then, with these symbols for example:
4771
4772       func
4773       func1
4774       fund
4775
4776      completing "func" looks for symbols between "func" and
4777      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4778      which finds "func" and "func1", but not "fund".
4779
4780      And with:
4781
4782       funcÿ     (Latin1 'ÿ' [0xff])
4783       funcÿ1
4784       fund
4785
4786      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4787      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4788
4789      And with:
4790
4791       ÿÿ        (Latin1 'ÿ' [0xff])
4792       ÿÿ1
4793
4794      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4795      the end of the list.
4796   */
4797   std::string after = search_name;
4798   while (!after.empty () && (unsigned char) after.back () == 0xff)
4799     after.pop_back ();
4800   if (!after.empty ())
4801     after.back () = (unsigned char) after.back () + 1;
4802   return after;
4803 }
4804
4805 /* See declaration.  */
4806
4807 std::pair<std::vector<name_component>::const_iterator,
4808           std::vector<name_component>::const_iterator>
4809 mapped_index_base::find_name_components_bounds
4810   (const lookup_name_info &lookup_name_without_params) const
4811 {
4812   auto *name_cmp
4813     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4814
4815   const char *cplus
4816     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4817
4818   /* Comparison function object for lower_bound that matches against a
4819      given symbol name.  */
4820   auto lookup_compare_lower = [&] (const name_component &elem,
4821                                    const char *name)
4822     {
4823       const char *elem_qualified = this->symbol_name_at (elem.idx);
4824       const char *elem_name = elem_qualified + elem.name_offset;
4825       return name_cmp (elem_name, name) < 0;
4826     };
4827
4828   /* Comparison function object for upper_bound that matches against a
4829      given symbol name.  */
4830   auto lookup_compare_upper = [&] (const char *name,
4831                                    const name_component &elem)
4832     {
4833       const char *elem_qualified = this->symbol_name_at (elem.idx);
4834       const char *elem_name = elem_qualified + elem.name_offset;
4835       return name_cmp (name, elem_name) < 0;
4836     };
4837
4838   auto begin = this->name_components.begin ();
4839   auto end = this->name_components.end ();
4840
4841   /* Find the lower bound.  */
4842   auto lower = [&] ()
4843     {
4844       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4845         return begin;
4846       else
4847         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4848     } ();
4849
4850   /* Find the upper bound.  */
4851   auto upper = [&] ()
4852     {
4853       if (lookup_name_without_params.completion_mode ())
4854         {
4855           /* In completion mode, we want UPPER to point past all
4856              symbols names that have the same prefix.  I.e., with
4857              these symbols, and completing "func":
4858
4859               function        << lower bound
4860               function1
4861               other_function  << upper bound
4862
4863              We find the upper bound by looking for the insertion
4864              point of "func"-with-last-character-incremented,
4865              i.e. "fund".  */
4866           std::string after = make_sort_after_prefix_name (cplus);
4867           if (after.empty ())
4868             return end;
4869           return std::lower_bound (lower, end, after.c_str (),
4870                                    lookup_compare_lower);
4871         }
4872       else
4873         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4874     } ();
4875
4876   return {lower, upper};
4877 }
4878
4879 /* See declaration.  */
4880
4881 void
4882 mapped_index_base::build_name_components ()
4883 {
4884   if (!this->name_components.empty ())
4885     return;
4886
4887   this->name_components_casing = case_sensitivity;
4888   auto *name_cmp
4889     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4890
4891   /* The code below only knows how to break apart components of C++
4892      symbol names (and other languages that use '::' as
4893      namespace/module separator).  If we add support for wild matching
4894      to some language that uses some other operator (E.g., Ada, Go and
4895      D use '.'), then we'll need to try splitting the symbol name
4896      according to that language too.  Note that Ada does support wild
4897      matching, but doesn't currently support .gdb_index.  */
4898   auto count = this->symbol_name_count ();
4899   for (offset_type idx = 0; idx < count; idx++)
4900     {
4901       if (this->symbol_name_slot_invalid (idx))
4902         continue;
4903
4904       const char *name = this->symbol_name_at (idx);
4905
4906       /* Add each name component to the name component table.  */
4907       unsigned int previous_len = 0;
4908       for (unsigned int current_len = cp_find_first_component (name);
4909            name[current_len] != '\0';
4910            current_len += cp_find_first_component (name + current_len))
4911         {
4912           gdb_assert (name[current_len] == ':');
4913           this->name_components.push_back ({previous_len, idx});
4914           /* Skip the '::'.  */
4915           current_len += 2;
4916           previous_len = current_len;
4917         }
4918       this->name_components.push_back ({previous_len, idx});
4919     }
4920
4921   /* Sort name_components elements by name.  */
4922   auto name_comp_compare = [&] (const name_component &left,
4923                                 const name_component &right)
4924     {
4925       const char *left_qualified = this->symbol_name_at (left.idx);
4926       const char *right_qualified = this->symbol_name_at (right.idx);
4927
4928       const char *left_name = left_qualified + left.name_offset;
4929       const char *right_name = right_qualified + right.name_offset;
4930
4931       return name_cmp (left_name, right_name) < 0;
4932     };
4933
4934   std::sort (this->name_components.begin (),
4935              this->name_components.end (),
4936              name_comp_compare);
4937 }
4938
4939 /* Helper for dw2_expand_symtabs_matching that works with a
4940    mapped_index_base instead of the containing objfile.  This is split
4941    to a separate function in order to be able to unit test the
4942    name_components matching using a mock mapped_index_base.  For each
4943    symbol name that matches, calls MATCH_CALLBACK, passing it the
4944    symbol's index in the mapped_index_base symbol table.  */
4945
4946 static void
4947 dw2_expand_symtabs_matching_symbol
4948   (mapped_index_base &index,
4949    const lookup_name_info &lookup_name_in,
4950    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4951    enum search_domain kind,
4952    gdb::function_view<void (offset_type)> match_callback)
4953 {
4954   lookup_name_info lookup_name_without_params
4955     = lookup_name_in.make_ignore_params ();
4956   gdb_index_symbol_name_matcher lookup_name_matcher
4957     (lookup_name_without_params);
4958
4959   /* Build the symbol name component sorted vector, if we haven't
4960      yet.  */
4961   index.build_name_components ();
4962
4963   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4964
4965   /* Now for each symbol name in range, check to see if we have a name
4966      match, and if so, call the MATCH_CALLBACK callback.  */
4967
4968   /* The same symbol may appear more than once in the range though.
4969      E.g., if we're looking for symbols that complete "w", and we have
4970      a symbol named "w1::w2", we'll find the two name components for
4971      that same symbol in the range.  To be sure we only call the
4972      callback once per symbol, we first collect the symbol name
4973      indexes that matched in a temporary vector and ignore
4974      duplicates.  */
4975   std::vector<offset_type> matches;
4976   matches.reserve (std::distance (bounds.first, bounds.second));
4977
4978   for (; bounds.first != bounds.second; ++bounds.first)
4979     {
4980       const char *qualified = index.symbol_name_at (bounds.first->idx);
4981
4982       if (!lookup_name_matcher.matches (qualified)
4983           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4984         continue;
4985
4986       matches.push_back (bounds.first->idx);
4987     }
4988
4989   std::sort (matches.begin (), matches.end ());
4990
4991   /* Finally call the callback, once per match.  */
4992   ULONGEST prev = -1;
4993   for (offset_type idx : matches)
4994     {
4995       if (prev != idx)
4996         {
4997           match_callback (idx);
4998           prev = idx;
4999         }
5000     }
5001
5002   /* Above we use a type wider than idx's for 'prev', since 0 and
5003      (offset_type)-1 are both possible values.  */
5004   static_assert (sizeof (prev) > sizeof (offset_type), "");
5005 }
5006
5007 #if GDB_SELF_TEST
5008
5009 namespace selftests { namespace dw2_expand_symtabs_matching {
5010
5011 /* A mock .gdb_index/.debug_names-like name index table, enough to
5012    exercise dw2_expand_symtabs_matching_symbol, which works with the
5013    mapped_index_base interface.  Builds an index from the symbol list
5014    passed as parameter to the constructor.  */
5015 class mock_mapped_index : public mapped_index_base
5016 {
5017 public:
5018   mock_mapped_index (gdb::array_view<const char *> symbols)
5019     : m_symbol_table (symbols)
5020   {}
5021
5022   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
5023
5024   /* Return the number of names in the symbol table.  */
5025   virtual size_t symbol_name_count () const
5026   {
5027     return m_symbol_table.size ();
5028   }
5029
5030   /* Get the name of the symbol at IDX in the symbol table.  */
5031   virtual const char *symbol_name_at (offset_type idx) const
5032   {
5033     return m_symbol_table[idx];
5034   }
5035
5036 private:
5037   gdb::array_view<const char *> m_symbol_table;
5038 };
5039
5040 /* Convenience function that converts a NULL pointer to a "<null>"
5041    string, to pass to print routines.  */
5042
5043 static const char *
5044 string_or_null (const char *str)
5045 {
5046   return str != NULL ? str : "<null>";
5047 }
5048
5049 /* Check if a lookup_name_info built from
5050    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
5051    index.  EXPECTED_LIST is the list of expected matches, in expected
5052    matching order.  If no match expected, then an empty list is
5053    specified.  Returns true on success.  On failure prints a warning
5054    indicating the file:line that failed, and returns false.  */
5055
5056 static bool
5057 check_match (const char *file, int line,
5058              mock_mapped_index &mock_index,
5059              const char *name, symbol_name_match_type match_type,
5060              bool completion_mode,
5061              std::initializer_list<const char *> expected_list)
5062 {
5063   lookup_name_info lookup_name (name, match_type, completion_mode);
5064
5065   bool matched = true;
5066
5067   auto mismatch = [&] (const char *expected_str,
5068                        const char *got)
5069   {
5070     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
5071                "expected=\"%s\", got=\"%s\"\n"),
5072              file, line,
5073              (match_type == symbol_name_match_type::FULL
5074               ? "FULL" : "WILD"),
5075              name, string_or_null (expected_str), string_or_null (got));
5076     matched = false;
5077   };
5078
5079   auto expected_it = expected_list.begin ();
5080   auto expected_end = expected_list.end ();
5081
5082   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
5083                                       NULL, ALL_DOMAIN,
5084                                       [&] (offset_type idx)
5085   {
5086     const char *matched_name = mock_index.symbol_name_at (idx);
5087     const char *expected_str
5088       = expected_it == expected_end ? NULL : *expected_it++;
5089
5090     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
5091       mismatch (expected_str, matched_name);
5092   });
5093
5094   const char *expected_str
5095   = expected_it == expected_end ? NULL : *expected_it++;
5096   if (expected_str != NULL)
5097     mismatch (expected_str, NULL);
5098
5099   return matched;
5100 }
5101
5102 /* The symbols added to the mock mapped_index for testing (in
5103    canonical form).  */
5104 static const char *test_symbols[] = {
5105   "function",
5106   "std::bar",
5107   "std::zfunction",
5108   "std::zfunction2",
5109   "w1::w2",
5110   "ns::foo<char*>",
5111   "ns::foo<int>",
5112   "ns::foo<long>",
5113   "ns2::tmpl<int>::foo2",
5114   "(anonymous namespace)::A::B::C",
5115
5116   /* These are used to check that the increment-last-char in the
5117      matching algorithm for completion doesn't match "t1_fund" when
5118      completing "t1_func".  */
5119   "t1_func",
5120   "t1_func1",
5121   "t1_fund",
5122   "t1_fund1",
5123
5124   /* A UTF-8 name with multi-byte sequences to make sure that
5125      cp-name-parser understands this as a single identifier ("função"
5126      is "function" in PT).  */
5127   u8"u8função",
5128
5129   /* \377 (0xff) is Latin1 'ÿ'.  */
5130   "yfunc\377",
5131
5132   /* \377 (0xff) is Latin1 'ÿ'.  */
5133   "\377",
5134   "\377\377123",
5135
5136   /* A name with all sorts of complications.  Starts with "z" to make
5137      it easier for the completion tests below.  */
5138 #define Z_SYM_NAME \
5139   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5140     "::tuple<(anonymous namespace)::ui*, " \
5141     "std::default_delete<(anonymous namespace)::ui>, void>"
5142
5143   Z_SYM_NAME
5144 };
5145
5146 /* Returns true if the mapped_index_base::find_name_component_bounds
5147    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5148    in completion mode.  */
5149
5150 static bool
5151 check_find_bounds_finds (mapped_index_base &index,
5152                          const char *search_name,
5153                          gdb::array_view<const char *> expected_syms)
5154 {
5155   lookup_name_info lookup_name (search_name,
5156                                 symbol_name_match_type::FULL, true);
5157
5158   auto bounds = index.find_name_components_bounds (lookup_name);
5159
5160   size_t distance = std::distance (bounds.first, bounds.second);
5161   if (distance != expected_syms.size ())
5162     return false;
5163
5164   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5165     {
5166       auto nc_elem = bounds.first + exp_elem;
5167       const char *qualified = index.symbol_name_at (nc_elem->idx);
5168       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5169         return false;
5170     }
5171
5172   return true;
5173 }
5174
5175 /* Test the lower-level mapped_index::find_name_component_bounds
5176    method.  */
5177
5178 static void
5179 test_mapped_index_find_name_component_bounds ()
5180 {
5181   mock_mapped_index mock_index (test_symbols);
5182
5183   mock_index.build_name_components ();
5184
5185   /* Test the lower-level mapped_index::find_name_component_bounds
5186      method in completion mode.  */
5187   {
5188     static const char *expected_syms[] = {
5189       "t1_func",
5190       "t1_func1",
5191     };
5192
5193     SELF_CHECK (check_find_bounds_finds (mock_index,
5194                                          "t1_func", expected_syms));
5195   }
5196
5197   /* Check that the increment-last-char in the name matching algorithm
5198      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5199   {
5200     static const char *expected_syms1[] = {
5201       "\377",
5202       "\377\377123",
5203     };
5204     SELF_CHECK (check_find_bounds_finds (mock_index,
5205                                          "\377", expected_syms1));
5206
5207     static const char *expected_syms2[] = {
5208       "\377\377123",
5209     };
5210     SELF_CHECK (check_find_bounds_finds (mock_index,
5211                                          "\377\377", expected_syms2));
5212   }
5213 }
5214
5215 /* Test dw2_expand_symtabs_matching_symbol.  */
5216
5217 static void
5218 test_dw2_expand_symtabs_matching_symbol ()
5219 {
5220   mock_mapped_index mock_index (test_symbols);
5221
5222   /* We let all tests run until the end even if some fails, for debug
5223      convenience.  */
5224   bool any_mismatch = false;
5225
5226   /* Create the expected symbols list (an initializer_list).  Needed
5227      because lists have commas, and we need to pass them to CHECK,
5228      which is a macro.  */
5229 #define EXPECT(...) { __VA_ARGS__ }
5230
5231   /* Wrapper for check_match that passes down the current
5232      __FILE__/__LINE__.  */
5233 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5234   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5235                                 mock_index,                             \
5236                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5237                                 EXPECTED_LIST)
5238
5239   /* Identity checks.  */
5240   for (const char *sym : test_symbols)
5241     {
5242       /* Should be able to match all existing symbols.  */
5243       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5244                    EXPECT (sym));
5245
5246       /* Should be able to match all existing symbols with
5247          parameters.  */
5248       std::string with_params = std::string (sym) + "(int)";
5249       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5250                    EXPECT (sym));
5251
5252       /* Should be able to match all existing symbols with
5253          parameters and qualifiers.  */
5254       with_params = std::string (sym) + " ( int ) const";
5255       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5256                    EXPECT (sym));
5257
5258       /* This should really find sym, but cp-name-parser.y doesn't
5259          know about lvalue/rvalue qualifiers yet.  */
5260       with_params = std::string (sym) + " ( int ) &&";
5261       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5262                    {});
5263     }
5264
5265   /* Check that the name matching algorithm for completion doesn't get
5266      confused with Latin1 'ÿ' / 0xff.  */
5267   {
5268     static const char str[] = "\377";
5269     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5270                  EXPECT ("\377", "\377\377123"));
5271   }
5272
5273   /* Check that the increment-last-char in the matching algorithm for
5274      completion doesn't match "t1_fund" when completing "t1_func".  */
5275   {
5276     static const char str[] = "t1_func";
5277     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5278                  EXPECT ("t1_func", "t1_func1"));
5279   }
5280
5281   /* Check that completion mode works at each prefix of the expected
5282      symbol name.  */
5283   {
5284     static const char str[] = "function(int)";
5285     size_t len = strlen (str);
5286     std::string lookup;
5287
5288     for (size_t i = 1; i < len; i++)
5289       {
5290         lookup.assign (str, i);
5291         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5292                      EXPECT ("function"));
5293       }
5294   }
5295
5296   /* While "w" is a prefix of both components, the match function
5297      should still only be called once.  */
5298   {
5299     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5300                  EXPECT ("w1::w2"));
5301     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5302                  EXPECT ("w1::w2"));
5303   }
5304
5305   /* Same, with a "complicated" symbol.  */
5306   {
5307     static const char str[] = Z_SYM_NAME;
5308     size_t len = strlen (str);
5309     std::string lookup;
5310
5311     for (size_t i = 1; i < len; i++)
5312       {
5313         lookup.assign (str, i);
5314         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5315                      EXPECT (Z_SYM_NAME));
5316       }
5317   }
5318
5319   /* In FULL mode, an incomplete symbol doesn't match.  */
5320   {
5321     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5322                  {});
5323   }
5324
5325   /* A complete symbol with parameters matches any overload, since the
5326      index has no overload info.  */
5327   {
5328     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5329                  EXPECT ("std::zfunction", "std::zfunction2"));
5330     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5331                  EXPECT ("std::zfunction", "std::zfunction2"));
5332     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5333                  EXPECT ("std::zfunction", "std::zfunction2"));
5334   }
5335
5336   /* Check that whitespace is ignored appropriately.  A symbol with a
5337      template argument list. */
5338   {
5339     static const char expected[] = "ns::foo<int>";
5340     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5341                  EXPECT (expected));
5342     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5343                  EXPECT (expected));
5344   }
5345
5346   /* Check that whitespace is ignored appropriately.  A symbol with a
5347      template argument list that includes a pointer.  */
5348   {
5349     static const char expected[] = "ns::foo<char*>";
5350     /* Try both completion and non-completion modes.  */
5351     static const bool completion_mode[2] = {false, true};
5352     for (size_t i = 0; i < 2; i++)
5353       {
5354         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5355                      completion_mode[i], EXPECT (expected));
5356         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5357                      completion_mode[i], EXPECT (expected));
5358
5359         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5360                      completion_mode[i], EXPECT (expected));
5361         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5362                      completion_mode[i], EXPECT (expected));
5363       }
5364   }
5365
5366   {
5367     /* Check method qualifiers are ignored.  */
5368     static const char expected[] = "ns::foo<char*>";
5369     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5370                  symbol_name_match_type::FULL, true, EXPECT (expected));
5371     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5372                  symbol_name_match_type::FULL, true, EXPECT (expected));
5373     CHECK_MATCH ("foo < char * >  ( int ) const",
5374                  symbol_name_match_type::WILD, true, EXPECT (expected));
5375     CHECK_MATCH ("foo < char * >  ( int ) &&",
5376                  symbol_name_match_type::WILD, true, EXPECT (expected));
5377   }
5378
5379   /* Test lookup names that don't match anything.  */
5380   {
5381     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5382                  {});
5383
5384     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5385                  {});
5386   }
5387
5388   /* Some wild matching tests, exercising "(anonymous namespace)",
5389      which should not be confused with a parameter list.  */
5390   {
5391     static const char *syms[] = {
5392       "A::B::C",
5393       "B::C",
5394       "C",
5395       "A :: B :: C ( int )",
5396       "B :: C ( int )",
5397       "C ( int )",
5398     };
5399
5400     for (const char *s : syms)
5401       {
5402         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5403                      EXPECT ("(anonymous namespace)::A::B::C"));
5404       }
5405   }
5406
5407   {
5408     static const char expected[] = "ns2::tmpl<int>::foo2";
5409     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5410                  EXPECT (expected));
5411     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5412                  EXPECT (expected));
5413   }
5414
5415   SELF_CHECK (!any_mismatch);
5416
5417 #undef EXPECT
5418 #undef CHECK_MATCH
5419 }
5420
5421 static void
5422 run_test ()
5423 {
5424   test_mapped_index_find_name_component_bounds ();
5425   test_dw2_expand_symtabs_matching_symbol ();
5426 }
5427
5428 }} // namespace selftests::dw2_expand_symtabs_matching
5429
5430 #endif /* GDB_SELF_TEST */
5431
5432 /* If FILE_MATCHER is NULL or if PER_CU has
5433    dwarf2_per_cu_quick_data::MARK set (see
5434    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5435    EXPANSION_NOTIFY on it.  */
5436
5437 static void
5438 dw2_expand_symtabs_matching_one
5439   (struct dwarf2_per_cu_data *per_cu,
5440    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5441    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5442 {
5443   if (file_matcher == NULL || per_cu->v.quick->mark)
5444     {
5445       bool symtab_was_null
5446         = (per_cu->v.quick->compunit_symtab == NULL);
5447
5448       dw2_instantiate_symtab (per_cu);
5449
5450       if (expansion_notify != NULL
5451           && symtab_was_null
5452           && per_cu->v.quick->compunit_symtab != NULL)
5453         expansion_notify (per_cu->v.quick->compunit_symtab);
5454     }
5455 }
5456
5457 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5458    matched, to expand corresponding CUs that were marked.  IDX is the
5459    index of the symbol name that matched.  */
5460
5461 static void
5462 dw2_expand_marked_cus
5463   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5464    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5465    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5466    search_domain kind)
5467 {
5468   offset_type *vec, vec_len, vec_idx;
5469   bool global_seen = false;
5470   mapped_index &index = *dwarf2_per_objfile->index_table;
5471
5472   vec = (offset_type *) (index.constant_pool
5473                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5474   vec_len = MAYBE_SWAP (vec[0]);
5475   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5476     {
5477       struct dwarf2_per_cu_data *per_cu;
5478       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5479       /* This value is only valid for index versions >= 7.  */
5480       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5481       gdb_index_symbol_kind symbol_kind =
5482         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5483       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5484       /* Only check the symbol attributes if they're present.
5485          Indices prior to version 7 don't record them,
5486          and indices >= 7 may elide them for certain symbols
5487          (gold does this).  */
5488       int attrs_valid =
5489         (index.version >= 7
5490          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5491
5492       /* Work around gold/15646.  */
5493       if (attrs_valid)
5494         {
5495           if (!is_static && global_seen)
5496             continue;
5497           if (!is_static)
5498             global_seen = true;
5499         }
5500
5501       /* Only check the symbol's kind if it has one.  */
5502       if (attrs_valid)
5503         {
5504           switch (kind)
5505             {
5506             case VARIABLES_DOMAIN:
5507               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5508                 continue;
5509               break;
5510             case FUNCTIONS_DOMAIN:
5511               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5512                 continue;
5513               break;
5514             case TYPES_DOMAIN:
5515               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5516                 continue;
5517               break;
5518             default:
5519               break;
5520             }
5521         }
5522
5523       /* Don't crash on bad data.  */
5524       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5525                        + dwarf2_per_objfile->n_type_units))
5526         {
5527           complaint (&symfile_complaints,
5528                      _(".gdb_index entry has bad CU index"
5529                        " [in module %s]"),
5530                        objfile_name (dwarf2_per_objfile->objfile));
5531           continue;
5532         }
5533
5534       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5535       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5536                                        expansion_notify);
5537     }
5538 }
5539
5540 /* If FILE_MATCHER is non-NULL, set all the
5541    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5542    that match FILE_MATCHER.  */
5543
5544 static void
5545 dw_expand_symtabs_matching_file_matcher
5546   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5547    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5548 {
5549   if (file_matcher == NULL)
5550     return;
5551
5552   objfile *const objfile = dwarf2_per_objfile->objfile;
5553
5554   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5555                                             htab_eq_pointer,
5556                                             NULL, xcalloc, xfree));
5557   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5558                                                 htab_eq_pointer,
5559                                                 NULL, xcalloc, xfree));
5560
5561   /* The rule is CUs specify all the files, including those used by
5562      any TU, so there's no need to scan TUs here.  */
5563
5564   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5565     {
5566       int j;
5567       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5568       struct quick_file_names *file_data;
5569       void **slot;
5570
5571       QUIT;
5572
5573       per_cu->v.quick->mark = 0;
5574
5575       /* We only need to look at symtabs not already expanded.  */
5576       if (per_cu->v.quick->compunit_symtab)
5577         continue;
5578
5579       file_data = dw2_get_file_names (per_cu);
5580       if (file_data == NULL)
5581         continue;
5582
5583       if (htab_find (visited_not_found.get (), file_data) != NULL)
5584         continue;
5585       else if (htab_find (visited_found.get (), file_data) != NULL)
5586         {
5587           per_cu->v.quick->mark = 1;
5588           continue;
5589         }
5590
5591       for (j = 0; j < file_data->num_file_names; ++j)
5592         {
5593           const char *this_real_name;
5594
5595           if (file_matcher (file_data->file_names[j], false))
5596             {
5597               per_cu->v.quick->mark = 1;
5598               break;
5599             }
5600
5601           /* Before we invoke realpath, which can get expensive when many
5602              files are involved, do a quick comparison of the basenames.  */
5603           if (!basenames_may_differ
5604               && !file_matcher (lbasename (file_data->file_names[j]),
5605                                 true))
5606             continue;
5607
5608           this_real_name = dw2_get_real_path (objfile, file_data, j);
5609           if (file_matcher (this_real_name, false))
5610             {
5611               per_cu->v.quick->mark = 1;
5612               break;
5613             }
5614         }
5615
5616       slot = htab_find_slot (per_cu->v.quick->mark
5617                              ? visited_found.get ()
5618                              : visited_not_found.get (),
5619                              file_data, INSERT);
5620       *slot = file_data;
5621     }
5622 }
5623
5624 static void
5625 dw2_expand_symtabs_matching
5626   (struct objfile *objfile,
5627    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5628    const lookup_name_info &lookup_name,
5629    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5630    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5631    enum search_domain kind)
5632 {
5633   struct dwarf2_per_objfile *dwarf2_per_objfile
5634     = get_dwarf2_per_objfile (objfile);
5635
5636   /* index_table is NULL if OBJF_READNOW.  */
5637   if (!dwarf2_per_objfile->index_table)
5638     return;
5639
5640   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5641
5642   mapped_index &index = *dwarf2_per_objfile->index_table;
5643
5644   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5645                                       symbol_matcher,
5646                                       kind, [&] (offset_type idx)
5647     {
5648       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5649                              expansion_notify, kind);
5650     });
5651 }
5652
5653 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5654    symtab.  */
5655
5656 static struct compunit_symtab *
5657 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5658                                           CORE_ADDR pc)
5659 {
5660   int i;
5661
5662   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5663       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5664     return cust;
5665
5666   if (cust->includes == NULL)
5667     return NULL;
5668
5669   for (i = 0; cust->includes[i]; ++i)
5670     {
5671       struct compunit_symtab *s = cust->includes[i];
5672
5673       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5674       if (s != NULL)
5675         return s;
5676     }
5677
5678   return NULL;
5679 }
5680
5681 static struct compunit_symtab *
5682 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5683                                   struct bound_minimal_symbol msymbol,
5684                                   CORE_ADDR pc,
5685                                   struct obj_section *section,
5686                                   int warn_if_readin)
5687 {
5688   struct dwarf2_per_cu_data *data;
5689   struct compunit_symtab *result;
5690
5691   if (!objfile->psymtabs_addrmap)
5692     return NULL;
5693
5694   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5695                                                      pc);
5696   if (!data)
5697     return NULL;
5698
5699   if (warn_if_readin && data->v.quick->compunit_symtab)
5700     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5701              paddress (get_objfile_arch (objfile), pc));
5702
5703   result
5704     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5705                                                 pc);
5706   gdb_assert (result != NULL);
5707   return result;
5708 }
5709
5710 static void
5711 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5712                           void *data, int need_fullname)
5713 {
5714   struct dwarf2_per_objfile *dwarf2_per_objfile
5715     = get_dwarf2_per_objfile (objfile);
5716
5717   if (!dwarf2_per_objfile->filenames_cache)
5718     {
5719       dwarf2_per_objfile->filenames_cache.emplace ();
5720
5721       htab_up visited (htab_create_alloc (10,
5722                                           htab_hash_pointer, htab_eq_pointer,
5723                                           NULL, xcalloc, xfree));
5724
5725       /* The rule is CUs specify all the files, including those used
5726          by any TU, so there's no need to scan TUs here.  We can
5727          ignore file names coming from already-expanded CUs.  */
5728
5729       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5730         {
5731           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5732
5733           if (per_cu->v.quick->compunit_symtab)
5734             {
5735               void **slot = htab_find_slot (visited.get (),
5736                                             per_cu->v.quick->file_names,
5737                                             INSERT);
5738
5739               *slot = per_cu->v.quick->file_names;
5740             }
5741         }
5742
5743       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5744         {
5745           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5746           struct quick_file_names *file_data;
5747           void **slot;
5748
5749           /* We only need to look at symtabs not already expanded.  */
5750           if (per_cu->v.quick->compunit_symtab)
5751             continue;
5752
5753           file_data = dw2_get_file_names (per_cu);
5754           if (file_data == NULL)
5755             continue;
5756
5757           slot = htab_find_slot (visited.get (), file_data, INSERT);
5758           if (*slot)
5759             {
5760               /* Already visited.  */
5761               continue;
5762             }
5763           *slot = file_data;
5764
5765           for (int j = 0; j < file_data->num_file_names; ++j)
5766             {
5767               const char *filename = file_data->file_names[j];
5768               dwarf2_per_objfile->filenames_cache->seen (filename);
5769             }
5770         }
5771     }
5772
5773   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5774     {
5775       gdb::unique_xmalloc_ptr<char> this_real_name;
5776
5777       if (need_fullname)
5778         this_real_name = gdb_realpath (filename);
5779       (*fun) (filename, this_real_name.get (), data);
5780     });
5781 }
5782
5783 static int
5784 dw2_has_symbols (struct objfile *objfile)
5785 {
5786   return 1;
5787 }
5788
5789 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5790 {
5791   dw2_has_symbols,
5792   dw2_find_last_source_symtab,
5793   dw2_forget_cached_source_info,
5794   dw2_map_symtabs_matching_filename,
5795   dw2_lookup_symbol,
5796   dw2_print_stats,
5797   dw2_dump,
5798   dw2_relocate,
5799   dw2_expand_symtabs_for_function,
5800   dw2_expand_all_symtabs,
5801   dw2_expand_symtabs_with_fullname,
5802   dw2_map_matching_symbols,
5803   dw2_expand_symtabs_matching,
5804   dw2_find_pc_sect_compunit_symtab,
5805   NULL,
5806   dw2_map_symbol_filenames
5807 };
5808
5809 /* DWARF-5 debug_names reader.  */
5810
5811 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5812 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5813
5814 /* A helper function that reads the .debug_names section in SECTION
5815    and fills in MAP.  FILENAME is the name of the file containing the
5816    section; it is used for error reporting.
5817
5818    Returns true if all went well, false otherwise.  */
5819
5820 static bool
5821 read_debug_names_from_section (struct objfile *objfile,
5822                                const char *filename,
5823                                struct dwarf2_section_info *section,
5824                                mapped_debug_names &map)
5825 {
5826   if (dwarf2_section_empty_p (section))
5827     return false;
5828
5829   /* Older elfutils strip versions could keep the section in the main
5830      executable while splitting it for the separate debug info file.  */
5831   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5832     return false;
5833
5834   dwarf2_read_section (objfile, section);
5835
5836   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5837
5838   const gdb_byte *addr = section->buffer;
5839
5840   bfd *const abfd = get_section_bfd_owner (section);
5841
5842   unsigned int bytes_read;
5843   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5844   addr += bytes_read;
5845
5846   map.dwarf5_is_dwarf64 = bytes_read != 4;
5847   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5848   if (bytes_read + length != section->size)
5849     {
5850       /* There may be multiple per-CU indices.  */
5851       warning (_("Section .debug_names in %s length %s does not match "
5852                  "section length %s, ignoring .debug_names."),
5853                filename, plongest (bytes_read + length),
5854                pulongest (section->size));
5855       return false;
5856     }
5857
5858   /* The version number.  */
5859   uint16_t version = read_2_bytes (abfd, addr);
5860   addr += 2;
5861   if (version != 5)
5862     {
5863       warning (_("Section .debug_names in %s has unsupported version %d, "
5864                  "ignoring .debug_names."),
5865                filename, version);
5866       return false;
5867     }
5868
5869   /* Padding.  */
5870   uint16_t padding = read_2_bytes (abfd, addr);
5871   addr += 2;
5872   if (padding != 0)
5873     {
5874       warning (_("Section .debug_names in %s has unsupported padding %d, "
5875                  "ignoring .debug_names."),
5876                filename, padding);
5877       return false;
5878     }
5879
5880   /* comp_unit_count - The number of CUs in the CU list.  */
5881   map.cu_count = read_4_bytes (abfd, addr);
5882   addr += 4;
5883
5884   /* local_type_unit_count - The number of TUs in the local TU
5885      list.  */
5886   map.tu_count = read_4_bytes (abfd, addr);
5887   addr += 4;
5888
5889   /* foreign_type_unit_count - The number of TUs in the foreign TU
5890      list.  */
5891   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5892   addr += 4;
5893   if (foreign_tu_count != 0)
5894     {
5895       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5896                  "ignoring .debug_names."),
5897                filename, static_cast<unsigned long> (foreign_tu_count));
5898       return false;
5899     }
5900
5901   /* bucket_count - The number of hash buckets in the hash lookup
5902      table.  */
5903   map.bucket_count = read_4_bytes (abfd, addr);
5904   addr += 4;
5905
5906   /* name_count - The number of unique names in the index.  */
5907   map.name_count = read_4_bytes (abfd, addr);
5908   addr += 4;
5909
5910   /* abbrev_table_size - The size in bytes of the abbreviations
5911      table.  */
5912   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5913   addr += 4;
5914
5915   /* augmentation_string_size - The size in bytes of the augmentation
5916      string.  This value is rounded up to a multiple of 4.  */
5917   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5918   addr += 4;
5919   map.augmentation_is_gdb = ((augmentation_string_size
5920                               == sizeof (dwarf5_augmentation))
5921                              && memcmp (addr, dwarf5_augmentation,
5922                                         sizeof (dwarf5_augmentation)) == 0);
5923   augmentation_string_size += (-augmentation_string_size) & 3;
5924   addr += augmentation_string_size;
5925
5926   /* List of CUs */
5927   map.cu_table_reordered = addr;
5928   addr += map.cu_count * map.offset_size;
5929
5930   /* List of Local TUs */
5931   map.tu_table_reordered = addr;
5932   addr += map.tu_count * map.offset_size;
5933
5934   /* Hash Lookup Table */
5935   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5936   addr += map.bucket_count * 4;
5937   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5938   addr += map.name_count * 4;
5939
5940   /* Name Table */
5941   map.name_table_string_offs_reordered = addr;
5942   addr += map.name_count * map.offset_size;
5943   map.name_table_entry_offs_reordered = addr;
5944   addr += map.name_count * map.offset_size;
5945
5946   const gdb_byte *abbrev_table_start = addr;
5947   for (;;)
5948     {
5949       unsigned int bytes_read;
5950       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5951       addr += bytes_read;
5952       if (index_num == 0)
5953         break;
5954
5955       const auto insertpair
5956         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5957       if (!insertpair.second)
5958         {
5959           warning (_("Section .debug_names in %s has duplicate index %s, "
5960                      "ignoring .debug_names."),
5961                    filename, pulongest (index_num));
5962           return false;
5963         }
5964       mapped_debug_names::index_val &indexval = insertpair.first->second;
5965       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5966       addr += bytes_read;
5967
5968       for (;;)
5969         {
5970           mapped_debug_names::index_val::attr attr;
5971           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5972           addr += bytes_read;
5973           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5974           addr += bytes_read;
5975           if (attr.form == DW_FORM_implicit_const)
5976             {
5977               attr.implicit_const = read_signed_leb128 (abfd, addr,
5978                                                         &bytes_read);
5979               addr += bytes_read;
5980             }
5981           if (attr.dw_idx == 0 && attr.form == 0)
5982             break;
5983           indexval.attr_vec.push_back (std::move (attr));
5984         }
5985     }
5986   if (addr != abbrev_table_start + abbrev_table_size)
5987     {
5988       warning (_("Section .debug_names in %s has abbreviation_table "
5989                  "of size %zu vs. written as %u, ignoring .debug_names."),
5990                filename, addr - abbrev_table_start, abbrev_table_size);
5991       return false;
5992     }
5993   map.entry_pool = addr;
5994
5995   return true;
5996 }
5997
5998 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5999    list.  */
6000
6001 static void
6002 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
6003                                   const mapped_debug_names &map,
6004                                   dwarf2_section_info &section,
6005                                   bool is_dwz, int base_offset)
6006 {
6007   sect_offset sect_off_prev;
6008   for (uint32_t i = 0; i <= map.cu_count; ++i)
6009     {
6010       sect_offset sect_off_next;
6011       if (i < map.cu_count)
6012         {
6013           sect_off_next
6014             = (sect_offset) (extract_unsigned_integer
6015                              (map.cu_table_reordered + i * map.offset_size,
6016                               map.offset_size,
6017                               map.dwarf5_byte_order));
6018         }
6019       else
6020         sect_off_next = (sect_offset) section.size;
6021       if (i >= 1)
6022         {
6023           const ULONGEST length = sect_off_next - sect_off_prev;
6024           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
6025             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
6026                                          sect_off_prev, length);
6027         }
6028       sect_off_prev = sect_off_next;
6029     }
6030 }
6031
6032 /* Read the CU list from the mapped index, and use it to create all
6033    the CU objects for this dwarf2_per_objfile.  */
6034
6035 static void
6036 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
6037                              const mapped_debug_names &map,
6038                              const mapped_debug_names &dwz_map)
6039 {
6040   struct objfile *objfile = dwarf2_per_objfile->objfile;
6041
6042   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
6043   dwarf2_per_objfile->all_comp_units
6044     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
6045                  dwarf2_per_objfile->n_comp_units);
6046
6047   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
6048                                     dwarf2_per_objfile->info,
6049                                     false /* is_dwz */,
6050                                     0 /* base_offset */);
6051
6052   if (dwz_map.cu_count == 0)
6053     return;
6054
6055   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6056   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
6057                                     true /* is_dwz */,
6058                                     map.cu_count /* base_offset */);
6059 }
6060
6061 /* Read .debug_names.  If everything went ok, initialize the "quick"
6062    elements of all the CUs and return true.  Otherwise, return false.  */
6063
6064 static bool
6065 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
6066 {
6067   mapped_debug_names local_map (dwarf2_per_objfile);
6068   mapped_debug_names dwz_map (dwarf2_per_objfile);
6069   struct objfile *objfile = dwarf2_per_objfile->objfile;
6070
6071   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
6072                                       &dwarf2_per_objfile->debug_names,
6073                                       local_map))
6074     return false;
6075
6076   /* Don't use the index if it's empty.  */
6077   if (local_map.name_count == 0)
6078     return false;
6079
6080   /* If there is a .dwz file, read it so we can get its CU list as
6081      well.  */
6082   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6083   if (dwz != NULL)
6084     {
6085       if (!read_debug_names_from_section (objfile,
6086                                           bfd_get_filename (dwz->dwz_bfd),
6087                                           &dwz->debug_names, dwz_map))
6088         {
6089           warning (_("could not read '.debug_names' section from %s; skipping"),
6090                    bfd_get_filename (dwz->dwz_bfd));
6091           return false;
6092         }
6093     }
6094
6095   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
6096
6097   if (local_map.tu_count != 0)
6098     {
6099       /* We can only handle a single .debug_types when we have an
6100          index.  */
6101       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
6102         return false;
6103
6104       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6105                                                 dwarf2_per_objfile->types, 0);
6106
6107       create_signatured_type_table_from_debug_names
6108         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6109     }
6110
6111   create_addrmap_from_aranges (dwarf2_per_objfile,
6112                                &dwarf2_per_objfile->debug_aranges);
6113
6114   dwarf2_per_objfile->debug_names_table.reset
6115     (new mapped_debug_names (dwarf2_per_objfile));
6116   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6117   dwarf2_per_objfile->using_index = 1;
6118   dwarf2_per_objfile->quick_file_names_table =
6119     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6120
6121   return true;
6122 }
6123
6124 /* Symbol name hashing function as specified by DWARF-5.  */
6125
6126 static uint32_t
6127 dwarf5_djb_hash (const char *str_)
6128 {
6129   const unsigned char *str = (const unsigned char *) str_;
6130
6131   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6132      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6133
6134   uint32_t hash = 5381;
6135   while (int c = *str++)
6136     hash = hash * 33 + tolower (c);
6137   return hash;
6138 }
6139
6140 /* Type used to manage iterating over all CUs looking for a symbol for
6141    .debug_names.  */
6142
6143 class dw2_debug_names_iterator
6144 {
6145 public:
6146   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6147      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6148   dw2_debug_names_iterator (const mapped_debug_names &map,
6149                             bool want_specific_block,
6150                             block_enum block_index, domain_enum domain,
6151                             const char *name)
6152     : m_map (map), m_want_specific_block (want_specific_block),
6153       m_block_index (block_index), m_domain (domain),
6154       m_addr (find_vec_in_debug_names (map, name))
6155   {}
6156
6157   dw2_debug_names_iterator (const mapped_debug_names &map,
6158                             search_domain search, uint32_t namei)
6159     : m_map (map),
6160       m_search (search),
6161       m_addr (find_vec_in_debug_names (map, namei))
6162   {}
6163
6164   /* Return the next matching CU or NULL if there are no more.  */
6165   dwarf2_per_cu_data *next ();
6166
6167 private:
6168   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6169                                                   const char *name);
6170   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6171                                                   uint32_t namei);
6172
6173   /* The internalized form of .debug_names.  */
6174   const mapped_debug_names &m_map;
6175
6176   /* If true, only look for symbols that match BLOCK_INDEX.  */
6177   const bool m_want_specific_block = false;
6178
6179   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6180      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6181      value.  */
6182   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6183
6184   /* The kind of symbol we're looking for.  */
6185   const domain_enum m_domain = UNDEF_DOMAIN;
6186   const search_domain m_search = ALL_DOMAIN;
6187
6188   /* The list of CUs from the index entry of the symbol, or NULL if
6189      not found.  */
6190   const gdb_byte *m_addr;
6191 };
6192
6193 const char *
6194 mapped_debug_names::namei_to_name (uint32_t namei) const
6195 {
6196   const ULONGEST namei_string_offs
6197     = extract_unsigned_integer ((name_table_string_offs_reordered
6198                                  + namei * offset_size),
6199                                 offset_size,
6200                                 dwarf5_byte_order);
6201   return read_indirect_string_at_offset
6202     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6203 }
6204
6205 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6206    found, return pointer to its pool data.  If NAME cannot be found,
6207    return NULL.  */
6208
6209 const gdb_byte *
6210 dw2_debug_names_iterator::find_vec_in_debug_names
6211   (const mapped_debug_names &map, const char *name)
6212 {
6213   int (*cmp) (const char *, const char *);
6214
6215   if (current_language->la_language == language_cplus
6216       || current_language->la_language == language_fortran
6217       || current_language->la_language == language_d)
6218     {
6219       /* NAME is already canonical.  Drop any qualifiers as
6220          .debug_names does not contain any.  */
6221
6222       if (strchr (name, '(') != NULL)
6223         {
6224           gdb::unique_xmalloc_ptr<char> without_params
6225             = cp_remove_params (name);
6226
6227           if (without_params != NULL)
6228             {
6229               name = without_params.get();
6230             }
6231         }
6232     }
6233
6234   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6235
6236   const uint32_t full_hash = dwarf5_djb_hash (name);
6237   uint32_t namei
6238     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6239                                 (map.bucket_table_reordered
6240                                  + (full_hash % map.bucket_count)), 4,
6241                                 map.dwarf5_byte_order);
6242   if (namei == 0)
6243     return NULL;
6244   --namei;
6245   if (namei >= map.name_count)
6246     {
6247       complaint (&symfile_complaints,
6248                  _("Wrong .debug_names with name index %u but name_count=%u "
6249                    "[in module %s]"),
6250                  namei, map.name_count,
6251                  objfile_name (map.dwarf2_per_objfile->objfile));
6252       return NULL;
6253     }
6254
6255   for (;;)
6256     {
6257       const uint32_t namei_full_hash
6258         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6259                                     (map.hash_table_reordered + namei), 4,
6260                                     map.dwarf5_byte_order);
6261       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6262         return NULL;
6263
6264       if (full_hash == namei_full_hash)
6265         {
6266           const char *const namei_string = map.namei_to_name (namei);
6267
6268 #if 0 /* An expensive sanity check.  */
6269           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6270             {
6271               complaint (&symfile_complaints,
6272                          _("Wrong .debug_names hash for string at index %u "
6273                            "[in module %s]"),
6274                          namei, objfile_name (dwarf2_per_objfile->objfile));
6275               return NULL;
6276             }
6277 #endif
6278
6279           if (cmp (namei_string, name) == 0)
6280             {
6281               const ULONGEST namei_entry_offs
6282                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6283                                              + namei * map.offset_size),
6284                                             map.offset_size, map.dwarf5_byte_order);
6285               return map.entry_pool + namei_entry_offs;
6286             }
6287         }
6288
6289       ++namei;
6290       if (namei >= map.name_count)
6291         return NULL;
6292     }
6293 }
6294
6295 const gdb_byte *
6296 dw2_debug_names_iterator::find_vec_in_debug_names
6297   (const mapped_debug_names &map, uint32_t namei)
6298 {
6299   if (namei >= map.name_count)
6300     {
6301       complaint (&symfile_complaints,
6302                  _("Wrong .debug_names with name index %u but name_count=%u "
6303                    "[in module %s]"),
6304                  namei, map.name_count,
6305                  objfile_name (map.dwarf2_per_objfile->objfile));
6306       return NULL;
6307     }
6308
6309   const ULONGEST namei_entry_offs
6310     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6311                                  + namei * map.offset_size),
6312                                 map.offset_size, map.dwarf5_byte_order);
6313   return map.entry_pool + namei_entry_offs;
6314 }
6315
6316 /* See dw2_debug_names_iterator.  */
6317
6318 dwarf2_per_cu_data *
6319 dw2_debug_names_iterator::next ()
6320 {
6321   if (m_addr == NULL)
6322     return NULL;
6323
6324   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6325   struct objfile *objfile = dwarf2_per_objfile->objfile;
6326   bfd *const abfd = objfile->obfd;
6327
6328  again:
6329
6330   unsigned int bytes_read;
6331   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6332   m_addr += bytes_read;
6333   if (abbrev == 0)
6334     return NULL;
6335
6336   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6337   if (indexval_it == m_map.abbrev_map.cend ())
6338     {
6339       complaint (&symfile_complaints,
6340                  _("Wrong .debug_names undefined abbrev code %s "
6341                    "[in module %s]"),
6342                  pulongest (abbrev), objfile_name (objfile));
6343       return NULL;
6344     }
6345   const mapped_debug_names::index_val &indexval = indexval_it->second;
6346   bool have_is_static = false;
6347   bool is_static;
6348   dwarf2_per_cu_data *per_cu = NULL;
6349   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6350     {
6351       ULONGEST ull;
6352       switch (attr.form)
6353         {
6354         case DW_FORM_implicit_const:
6355           ull = attr.implicit_const;
6356           break;
6357         case DW_FORM_flag_present:
6358           ull = 1;
6359           break;
6360         case DW_FORM_udata:
6361           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6362           m_addr += bytes_read;
6363           break;
6364         default:
6365           complaint (&symfile_complaints,
6366                      _("Unsupported .debug_names form %s [in module %s]"),
6367                      dwarf_form_name (attr.form),
6368                      objfile_name (objfile));
6369           return NULL;
6370         }
6371       switch (attr.dw_idx)
6372         {
6373         case DW_IDX_compile_unit:
6374           /* Don't crash on bad data.  */
6375           if (ull >= dwarf2_per_objfile->n_comp_units)
6376             {
6377               complaint (&symfile_complaints,
6378                          _(".debug_names entry has bad CU index %s"
6379                            " [in module %s]"),
6380                          pulongest (ull),
6381                          objfile_name (dwarf2_per_objfile->objfile));
6382               continue;
6383             }
6384           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6385           break;
6386         case DW_IDX_type_unit:
6387           /* Don't crash on bad data.  */
6388           if (ull >= dwarf2_per_objfile->n_type_units)
6389             {
6390               complaint (&symfile_complaints,
6391                          _(".debug_names entry has bad TU index %s"
6392                            " [in module %s]"),
6393                          pulongest (ull),
6394                          objfile_name (dwarf2_per_objfile->objfile));
6395               continue;
6396             }
6397           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6398                                  dwarf2_per_objfile->n_comp_units + ull);
6399           break;
6400         case DW_IDX_GNU_internal:
6401           if (!m_map.augmentation_is_gdb)
6402             break;
6403           have_is_static = true;
6404           is_static = true;
6405           break;
6406         case DW_IDX_GNU_external:
6407           if (!m_map.augmentation_is_gdb)
6408             break;
6409           have_is_static = true;
6410           is_static = false;
6411           break;
6412         }
6413     }
6414
6415   /* Skip if already read in.  */
6416   if (per_cu->v.quick->compunit_symtab)
6417     goto again;
6418
6419   /* Check static vs global.  */
6420   if (have_is_static)
6421     {
6422       const bool want_static = m_block_index != GLOBAL_BLOCK;
6423       if (m_want_specific_block && want_static != is_static)
6424         goto again;
6425     }
6426
6427   /* Match dw2_symtab_iter_next, symbol_kind
6428      and debug_names::psymbol_tag.  */
6429   switch (m_domain)
6430     {
6431     case VAR_DOMAIN:
6432       switch (indexval.dwarf_tag)
6433         {
6434         case DW_TAG_variable:
6435         case DW_TAG_subprogram:
6436         /* Some types are also in VAR_DOMAIN.  */
6437         case DW_TAG_typedef:
6438         case DW_TAG_structure_type:
6439           break;
6440         default:
6441           goto again;
6442         }
6443       break;
6444     case STRUCT_DOMAIN:
6445       switch (indexval.dwarf_tag)
6446         {
6447         case DW_TAG_typedef:
6448         case DW_TAG_structure_type:
6449           break;
6450         default:
6451           goto again;
6452         }
6453       break;
6454     case LABEL_DOMAIN:
6455       switch (indexval.dwarf_tag)
6456         {
6457         case 0:
6458         case DW_TAG_variable:
6459           break;
6460         default:
6461           goto again;
6462         }
6463       break;
6464     default:
6465       break;
6466     }
6467
6468   /* Match dw2_expand_symtabs_matching, symbol_kind and
6469      debug_names::psymbol_tag.  */
6470   switch (m_search)
6471     {
6472     case VARIABLES_DOMAIN:
6473       switch (indexval.dwarf_tag)
6474         {
6475         case DW_TAG_variable:
6476           break;
6477         default:
6478           goto again;
6479         }
6480       break;
6481     case FUNCTIONS_DOMAIN:
6482       switch (indexval.dwarf_tag)
6483         {
6484         case DW_TAG_subprogram:
6485           break;
6486         default:
6487           goto again;
6488         }
6489       break;
6490     case TYPES_DOMAIN:
6491       switch (indexval.dwarf_tag)
6492         {
6493         case DW_TAG_typedef:
6494         case DW_TAG_structure_type:
6495           break;
6496         default:
6497           goto again;
6498         }
6499       break;
6500     default:
6501       break;
6502     }
6503
6504   return per_cu;
6505 }
6506
6507 static struct compunit_symtab *
6508 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6509                                const char *name, domain_enum domain)
6510 {
6511   const block_enum block_index = static_cast<block_enum> (block_index_int);
6512   struct dwarf2_per_objfile *dwarf2_per_objfile
6513     = get_dwarf2_per_objfile (objfile);
6514
6515   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6516   if (!mapp)
6517     {
6518       /* index is NULL if OBJF_READNOW.  */
6519       return NULL;
6520     }
6521   const auto &map = *mapp;
6522
6523   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6524                                  block_index, domain, name);
6525
6526   struct compunit_symtab *stab_best = NULL;
6527   struct dwarf2_per_cu_data *per_cu;
6528   while ((per_cu = iter.next ()) != NULL)
6529     {
6530       struct symbol *sym, *with_opaque = NULL;
6531       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6532       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6533       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6534
6535       sym = block_find_symbol (block, name, domain,
6536                                block_find_non_opaque_type_preferred,
6537                                &with_opaque);
6538
6539       /* Some caution must be observed with overloaded functions and
6540          methods, since the index will not contain any overload
6541          information (but NAME might contain it).  */
6542
6543       if (sym != NULL
6544           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6545         return stab;
6546       if (with_opaque != NULL
6547           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6548         stab_best = stab;
6549
6550       /* Keep looking through other CUs.  */
6551     }
6552
6553   return stab_best;
6554 }
6555
6556 /* This dumps minimal information about .debug_names.  It is called
6557    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6558    uses this to verify that .debug_names has been loaded.  */
6559
6560 static void
6561 dw2_debug_names_dump (struct objfile *objfile)
6562 {
6563   struct dwarf2_per_objfile *dwarf2_per_objfile
6564     = get_dwarf2_per_objfile (objfile);
6565
6566   gdb_assert (dwarf2_per_objfile->using_index);
6567   printf_filtered (".debug_names:");
6568   if (dwarf2_per_objfile->debug_names_table)
6569     printf_filtered (" exists\n");
6570   else
6571     printf_filtered (" faked for \"readnow\"\n");
6572   printf_filtered ("\n");
6573 }
6574
6575 static void
6576 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6577                                              const char *func_name)
6578 {
6579   struct dwarf2_per_objfile *dwarf2_per_objfile
6580     = get_dwarf2_per_objfile (objfile);
6581
6582   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6583   if (dwarf2_per_objfile->debug_names_table)
6584     {
6585       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6586
6587       /* Note: It doesn't matter what we pass for block_index here.  */
6588       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6589                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6590
6591       struct dwarf2_per_cu_data *per_cu;
6592       while ((per_cu = iter.next ()) != NULL)
6593         dw2_instantiate_symtab (per_cu);
6594     }
6595 }
6596
6597 static void
6598 dw2_debug_names_expand_symtabs_matching
6599   (struct objfile *objfile,
6600    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6601    const lookup_name_info &lookup_name,
6602    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6603    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6604    enum search_domain kind)
6605 {
6606   struct dwarf2_per_objfile *dwarf2_per_objfile
6607     = get_dwarf2_per_objfile (objfile);
6608
6609   /* debug_names_table is NULL if OBJF_READNOW.  */
6610   if (!dwarf2_per_objfile->debug_names_table)
6611     return;
6612
6613   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6614
6615   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6616
6617   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6618                                       symbol_matcher,
6619                                       kind, [&] (offset_type namei)
6620     {
6621       /* The name was matched, now expand corresponding CUs that were
6622          marked.  */
6623       dw2_debug_names_iterator iter (map, kind, namei);
6624
6625       struct dwarf2_per_cu_data *per_cu;
6626       while ((per_cu = iter.next ()) != NULL)
6627         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6628                                          expansion_notify);
6629     });
6630 }
6631
6632 const struct quick_symbol_functions dwarf2_debug_names_functions =
6633 {
6634   dw2_has_symbols,
6635   dw2_find_last_source_symtab,
6636   dw2_forget_cached_source_info,
6637   dw2_map_symtabs_matching_filename,
6638   dw2_debug_names_lookup_symbol,
6639   dw2_print_stats,
6640   dw2_debug_names_dump,
6641   dw2_relocate,
6642   dw2_debug_names_expand_symtabs_for_function,
6643   dw2_expand_all_symtabs,
6644   dw2_expand_symtabs_with_fullname,
6645   dw2_map_matching_symbols,
6646   dw2_debug_names_expand_symtabs_matching,
6647   dw2_find_pc_sect_compunit_symtab,
6648   NULL,
6649   dw2_map_symbol_filenames
6650 };
6651
6652 /* See symfile.h.  */
6653
6654 bool
6655 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6656 {
6657   struct dwarf2_per_objfile *dwarf2_per_objfile
6658     = get_dwarf2_per_objfile (objfile);
6659
6660   /* If we're about to read full symbols, don't bother with the
6661      indices.  In this case we also don't care if some other debug
6662      format is making psymtabs, because they are all about to be
6663      expanded anyway.  */
6664   if ((objfile->flags & OBJF_READNOW))
6665     {
6666       int i;
6667
6668       dwarf2_per_objfile->using_index = 1;
6669       create_all_comp_units (dwarf2_per_objfile);
6670       create_all_type_units (dwarf2_per_objfile);
6671       dwarf2_per_objfile->quick_file_names_table =
6672         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6673
6674       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6675                        + dwarf2_per_objfile->n_type_units); ++i)
6676         {
6677           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6678
6679           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6680                                             struct dwarf2_per_cu_quick_data);
6681         }
6682
6683       /* Return 1 so that gdb sees the "quick" functions.  However,
6684          these functions will be no-ops because we will have expanded
6685          all symtabs.  */
6686       *index_kind = dw_index_kind::GDB_INDEX;
6687       return true;
6688     }
6689
6690   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6691     {
6692       *index_kind = dw_index_kind::DEBUG_NAMES;
6693       return true;
6694     }
6695
6696   if (dwarf2_read_index (objfile))
6697     {
6698       *index_kind = dw_index_kind::GDB_INDEX;
6699       return true;
6700     }
6701
6702   return false;
6703 }
6704
6705 \f
6706
6707 /* Build a partial symbol table.  */
6708
6709 void
6710 dwarf2_build_psymtabs (struct objfile *objfile)
6711 {
6712   struct dwarf2_per_objfile *dwarf2_per_objfile
6713     = get_dwarf2_per_objfile (objfile);
6714
6715   if (objfile->global_psymbols.capacity () == 0
6716       && objfile->static_psymbols.capacity () == 0)
6717     init_psymbol_list (objfile, 1024);
6718
6719   TRY
6720     {
6721       /* This isn't really ideal: all the data we allocate on the
6722          objfile's obstack is still uselessly kept around.  However,
6723          freeing it seems unsafe.  */
6724       psymtab_discarder psymtabs (objfile);
6725       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6726       psymtabs.keep ();
6727     }
6728   CATCH (except, RETURN_MASK_ERROR)
6729     {
6730       exception_print (gdb_stderr, except);
6731     }
6732   END_CATCH
6733 }
6734
6735 /* Return the total length of the CU described by HEADER.  */
6736
6737 static unsigned int
6738 get_cu_length (const struct comp_unit_head *header)
6739 {
6740   return header->initial_length_size + header->length;
6741 }
6742
6743 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6744
6745 static inline bool
6746 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6747 {
6748   sect_offset bottom = cu_header->sect_off;
6749   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6750
6751   return sect_off >= bottom && sect_off < top;
6752 }
6753
6754 /* Find the base address of the compilation unit for range lists and
6755    location lists.  It will normally be specified by DW_AT_low_pc.
6756    In DWARF-3 draft 4, the base address could be overridden by
6757    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6758    compilation units with discontinuous ranges.  */
6759
6760 static void
6761 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6762 {
6763   struct attribute *attr;
6764
6765   cu->base_known = 0;
6766   cu->base_address = 0;
6767
6768   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6769   if (attr)
6770     {
6771       cu->base_address = attr_value_as_address (attr);
6772       cu->base_known = 1;
6773     }
6774   else
6775     {
6776       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6777       if (attr)
6778         {
6779           cu->base_address = attr_value_as_address (attr);
6780           cu->base_known = 1;
6781         }
6782     }
6783 }
6784
6785 /* Read in the comp unit header information from the debug_info at info_ptr.
6786    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6787    NOTE: This leaves members offset, first_die_offset to be filled in
6788    by the caller.  */
6789
6790 static const gdb_byte *
6791 read_comp_unit_head (struct comp_unit_head *cu_header,
6792                      const gdb_byte *info_ptr,
6793                      struct dwarf2_section_info *section,
6794                      rcuh_kind section_kind)
6795 {
6796   int signed_addr;
6797   unsigned int bytes_read;
6798   const char *filename = get_section_file_name (section);
6799   bfd *abfd = get_section_bfd_owner (section);
6800
6801   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6802   cu_header->initial_length_size = bytes_read;
6803   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6804   info_ptr += bytes_read;
6805   cu_header->version = read_2_bytes (abfd, info_ptr);
6806   info_ptr += 2;
6807   if (cu_header->version < 5)
6808     switch (section_kind)
6809       {
6810       case rcuh_kind::COMPILE:
6811         cu_header->unit_type = DW_UT_compile;
6812         break;
6813       case rcuh_kind::TYPE:
6814         cu_header->unit_type = DW_UT_type;
6815         break;
6816       default:
6817         internal_error (__FILE__, __LINE__,
6818                         _("read_comp_unit_head: invalid section_kind"));
6819       }
6820   else
6821     {
6822       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6823                                                  (read_1_byte (abfd, info_ptr));
6824       info_ptr += 1;
6825       switch (cu_header->unit_type)
6826         {
6827         case DW_UT_compile:
6828           if (section_kind != rcuh_kind::COMPILE)
6829             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6830                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6831                    filename);
6832           break;
6833         case DW_UT_type:
6834           section_kind = rcuh_kind::TYPE;
6835           break;
6836         default:
6837           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6838                  "(is %d, should be %d or %d) [in module %s]"),
6839                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6840         }
6841
6842       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6843       info_ptr += 1;
6844     }
6845   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6846                                                           cu_header,
6847                                                           &bytes_read);
6848   info_ptr += bytes_read;
6849   if (cu_header->version < 5)
6850     {
6851       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6852       info_ptr += 1;
6853     }
6854   signed_addr = bfd_get_sign_extend_vma (abfd);
6855   if (signed_addr < 0)
6856     internal_error (__FILE__, __LINE__,
6857                     _("read_comp_unit_head: dwarf from non elf file"));
6858   cu_header->signed_addr_p = signed_addr;
6859
6860   if (section_kind == rcuh_kind::TYPE)
6861     {
6862       LONGEST type_offset;
6863
6864       cu_header->signature = read_8_bytes (abfd, info_ptr);
6865       info_ptr += 8;
6866
6867       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6868       info_ptr += bytes_read;
6869       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6870       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6871         error (_("Dwarf Error: Too big type_offset in compilation unit "
6872                "header (is %s) [in module %s]"), plongest (type_offset),
6873                filename);
6874     }
6875
6876   return info_ptr;
6877 }
6878
6879 /* Helper function that returns the proper abbrev section for
6880    THIS_CU.  */
6881
6882 static struct dwarf2_section_info *
6883 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6884 {
6885   struct dwarf2_section_info *abbrev;
6886   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6887
6888   if (this_cu->is_dwz)
6889     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6890   else
6891     abbrev = &dwarf2_per_objfile->abbrev;
6892
6893   return abbrev;
6894 }
6895
6896 /* Subroutine of read_and_check_comp_unit_head and
6897    read_and_check_type_unit_head to simplify them.
6898    Perform various error checking on the header.  */
6899
6900 static void
6901 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6902                             struct comp_unit_head *header,
6903                             struct dwarf2_section_info *section,
6904                             struct dwarf2_section_info *abbrev_section)
6905 {
6906   const char *filename = get_section_file_name (section);
6907
6908   if (header->version < 2 || header->version > 5)
6909     error (_("Dwarf Error: wrong version in compilation unit header "
6910            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6911            filename);
6912
6913   if (to_underlying (header->abbrev_sect_off)
6914       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6915     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6916            "(offset %s + 6) [in module %s]"),
6917            sect_offset_str (header->abbrev_sect_off),
6918            sect_offset_str (header->sect_off),
6919            filename);
6920
6921   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6922      avoid potential 32-bit overflow.  */
6923   if (((ULONGEST) header->sect_off + get_cu_length (header))
6924       > section->size)
6925     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6926            "(offset %s + 0) [in module %s]"),
6927            header->length, sect_offset_str (header->sect_off),
6928            filename);
6929 }
6930
6931 /* Read in a CU/TU header and perform some basic error checking.
6932    The contents of the header are stored in HEADER.
6933    The result is a pointer to the start of the first DIE.  */
6934
6935 static const gdb_byte *
6936 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6937                                struct comp_unit_head *header,
6938                                struct dwarf2_section_info *section,
6939                                struct dwarf2_section_info *abbrev_section,
6940                                const gdb_byte *info_ptr,
6941                                rcuh_kind section_kind)
6942 {
6943   const gdb_byte *beg_of_comp_unit = info_ptr;
6944
6945   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6946
6947   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6948
6949   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6950
6951   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6952                               abbrev_section);
6953
6954   return info_ptr;
6955 }
6956
6957 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6958
6959 static sect_offset
6960 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6961                     struct dwarf2_section_info *section,
6962                     sect_offset sect_off)
6963 {
6964   bfd *abfd = get_section_bfd_owner (section);
6965   const gdb_byte *info_ptr;
6966   unsigned int initial_length_size, offset_size;
6967   uint16_t version;
6968
6969   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6970   info_ptr = section->buffer + to_underlying (sect_off);
6971   read_initial_length (abfd, info_ptr, &initial_length_size);
6972   offset_size = initial_length_size == 4 ? 4 : 8;
6973   info_ptr += initial_length_size;
6974
6975   version = read_2_bytes (abfd, info_ptr);
6976   info_ptr += 2;
6977   if (version >= 5)
6978     {
6979       /* Skip unit type and address size.  */
6980       info_ptr += 2;
6981     }
6982
6983   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6984 }
6985
6986 /* Allocate a new partial symtab for file named NAME and mark this new
6987    partial symtab as being an include of PST.  */
6988
6989 static void
6990 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6991                                struct objfile *objfile)
6992 {
6993   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6994
6995   if (!IS_ABSOLUTE_PATH (subpst->filename))
6996     {
6997       /* It shares objfile->objfile_obstack.  */
6998       subpst->dirname = pst->dirname;
6999     }
7000
7001   subpst->textlow = 0;
7002   subpst->texthigh = 0;
7003
7004   subpst->dependencies
7005     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
7006   subpst->dependencies[0] = pst;
7007   subpst->number_of_dependencies = 1;
7008
7009   subpst->globals_offset = 0;
7010   subpst->n_global_syms = 0;
7011   subpst->statics_offset = 0;
7012   subpst->n_static_syms = 0;
7013   subpst->compunit_symtab = NULL;
7014   subpst->read_symtab = pst->read_symtab;
7015   subpst->readin = 0;
7016
7017   /* No private part is necessary for include psymtabs.  This property
7018      can be used to differentiate between such include psymtabs and
7019      the regular ones.  */
7020   subpst->read_symtab_private = NULL;
7021 }
7022
7023 /* Read the Line Number Program data and extract the list of files
7024    included by the source file represented by PST.  Build an include
7025    partial symtab for each of these included files.  */
7026
7027 static void
7028 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
7029                                struct die_info *die,
7030                                struct partial_symtab *pst)
7031 {
7032   line_header_up lh;
7033   struct attribute *attr;
7034
7035   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7036   if (attr)
7037     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
7038   if (lh == NULL)
7039     return;  /* No linetable, so no includes.  */
7040
7041   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
7042   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
7043 }
7044
7045 static hashval_t
7046 hash_signatured_type (const void *item)
7047 {
7048   const struct signatured_type *sig_type
7049     = (const struct signatured_type *) item;
7050
7051   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
7052   return sig_type->signature;
7053 }
7054
7055 static int
7056 eq_signatured_type (const void *item_lhs, const void *item_rhs)
7057 {
7058   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
7059   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
7060
7061   return lhs->signature == rhs->signature;
7062 }
7063
7064 /* Allocate a hash table for signatured types.  */
7065
7066 static htab_t
7067 allocate_signatured_type_table (struct objfile *objfile)
7068 {
7069   return htab_create_alloc_ex (41,
7070                                hash_signatured_type,
7071                                eq_signatured_type,
7072                                NULL,
7073                                &objfile->objfile_obstack,
7074                                hashtab_obstack_allocate,
7075                                dummy_obstack_deallocate);
7076 }
7077
7078 /* A helper function to add a signatured type CU to a table.  */
7079
7080 static int
7081 add_signatured_type_cu_to_table (void **slot, void *datum)
7082 {
7083   struct signatured_type *sigt = (struct signatured_type *) *slot;
7084   struct signatured_type ***datap = (struct signatured_type ***) datum;
7085
7086   **datap = sigt;
7087   ++*datap;
7088
7089   return 1;
7090 }
7091
7092 /* A helper for create_debug_types_hash_table.  Read types from SECTION
7093    and fill them into TYPES_HTAB.  It will process only type units,
7094    therefore DW_UT_type.  */
7095
7096 static void
7097 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7098                               struct dwo_file *dwo_file,
7099                               dwarf2_section_info *section, htab_t &types_htab,
7100                               rcuh_kind section_kind)
7101 {
7102   struct objfile *objfile = dwarf2_per_objfile->objfile;
7103   struct dwarf2_section_info *abbrev_section;
7104   bfd *abfd;
7105   const gdb_byte *info_ptr, *end_ptr;
7106
7107   abbrev_section = (dwo_file != NULL
7108                     ? &dwo_file->sections.abbrev
7109                     : &dwarf2_per_objfile->abbrev);
7110
7111   if (dwarf_read_debug)
7112     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7113                         get_section_name (section),
7114                         get_section_file_name (abbrev_section));
7115
7116   dwarf2_read_section (objfile, section);
7117   info_ptr = section->buffer;
7118
7119   if (info_ptr == NULL)
7120     return;
7121
7122   /* We can't set abfd until now because the section may be empty or
7123      not present, in which case the bfd is unknown.  */
7124   abfd = get_section_bfd_owner (section);
7125
7126   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7127      because we don't need to read any dies: the signature is in the
7128      header.  */
7129
7130   end_ptr = info_ptr + section->size;
7131   while (info_ptr < end_ptr)
7132     {
7133       struct signatured_type *sig_type;
7134       struct dwo_unit *dwo_tu;
7135       void **slot;
7136       const gdb_byte *ptr = info_ptr;
7137       struct comp_unit_head header;
7138       unsigned int length;
7139
7140       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7141
7142       /* Initialize it due to a false compiler warning.  */
7143       header.signature = -1;
7144       header.type_cu_offset_in_tu = (cu_offset) -1;
7145
7146       /* We need to read the type's signature in order to build the hash
7147          table, but we don't need anything else just yet.  */
7148
7149       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7150                                            abbrev_section, ptr, section_kind);
7151
7152       length = get_cu_length (&header);
7153
7154       /* Skip dummy type units.  */
7155       if (ptr >= info_ptr + length
7156           || peek_abbrev_code (abfd, ptr) == 0
7157           || header.unit_type != DW_UT_type)
7158         {
7159           info_ptr += length;
7160           continue;
7161         }
7162
7163       if (types_htab == NULL)
7164         {
7165           if (dwo_file)
7166             types_htab = allocate_dwo_unit_table (objfile);
7167           else
7168             types_htab = allocate_signatured_type_table (objfile);
7169         }
7170
7171       if (dwo_file)
7172         {
7173           sig_type = NULL;
7174           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7175                                    struct dwo_unit);
7176           dwo_tu->dwo_file = dwo_file;
7177           dwo_tu->signature = header.signature;
7178           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7179           dwo_tu->section = section;
7180           dwo_tu->sect_off = sect_off;
7181           dwo_tu->length = length;
7182         }
7183       else
7184         {
7185           /* N.B.: type_offset is not usable if this type uses a DWO file.
7186              The real type_offset is in the DWO file.  */
7187           dwo_tu = NULL;
7188           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7189                                      struct signatured_type);
7190           sig_type->signature = header.signature;
7191           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7192           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7193           sig_type->per_cu.is_debug_types = 1;
7194           sig_type->per_cu.section = section;
7195           sig_type->per_cu.sect_off = sect_off;
7196           sig_type->per_cu.length = length;
7197         }
7198
7199       slot = htab_find_slot (types_htab,
7200                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7201                              INSERT);
7202       gdb_assert (slot != NULL);
7203       if (*slot != NULL)
7204         {
7205           sect_offset dup_sect_off;
7206
7207           if (dwo_file)
7208             {
7209               const struct dwo_unit *dup_tu
7210                 = (const struct dwo_unit *) *slot;
7211
7212               dup_sect_off = dup_tu->sect_off;
7213             }
7214           else
7215             {
7216               const struct signatured_type *dup_tu
7217                 = (const struct signatured_type *) *slot;
7218
7219               dup_sect_off = dup_tu->per_cu.sect_off;
7220             }
7221
7222           complaint (&symfile_complaints,
7223                      _("debug type entry at offset %s is duplicate to"
7224                        " the entry at offset %s, signature %s"),
7225                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
7226                      hex_string (header.signature));
7227         }
7228       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7229
7230       if (dwarf_read_debug > 1)
7231         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
7232                             sect_offset_str (sect_off),
7233                             hex_string (header.signature));
7234
7235       info_ptr += length;
7236     }
7237 }
7238
7239 /* Create the hash table of all entries in the .debug_types
7240    (or .debug_types.dwo) section(s).
7241    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7242    otherwise it is NULL.
7243
7244    The result is a pointer to the hash table or NULL if there are no types.
7245
7246    Note: This function processes DWO files only, not DWP files.  */
7247
7248 static void
7249 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7250                                struct dwo_file *dwo_file,
7251                                VEC (dwarf2_section_info_def) *types,
7252                                htab_t &types_htab)
7253 {
7254   int ix;
7255   struct dwarf2_section_info *section;
7256
7257   if (VEC_empty (dwarf2_section_info_def, types))
7258     return;
7259
7260   for (ix = 0;
7261        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7262        ++ix)
7263     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7264                                   types_htab, rcuh_kind::TYPE);
7265 }
7266
7267 /* Create the hash table of all entries in the .debug_types section,
7268    and initialize all_type_units.
7269    The result is zero if there is an error (e.g. missing .debug_types section),
7270    otherwise non-zero.  */
7271
7272 static int
7273 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7274 {
7275   htab_t types_htab = NULL;
7276   struct signatured_type **iter;
7277
7278   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7279                                 &dwarf2_per_objfile->info, types_htab,
7280                                 rcuh_kind::COMPILE);
7281   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7282                                  dwarf2_per_objfile->types, types_htab);
7283   if (types_htab == NULL)
7284     {
7285       dwarf2_per_objfile->signatured_types = NULL;
7286       return 0;
7287     }
7288
7289   dwarf2_per_objfile->signatured_types = types_htab;
7290
7291   dwarf2_per_objfile->n_type_units
7292     = dwarf2_per_objfile->n_allocated_type_units
7293     = htab_elements (types_htab);
7294   dwarf2_per_objfile->all_type_units =
7295     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7296   iter = &dwarf2_per_objfile->all_type_units[0];
7297   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7298   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7299               == dwarf2_per_objfile->n_type_units);
7300
7301   return 1;
7302 }
7303
7304 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7305    If SLOT is non-NULL, it is the entry to use in the hash table.
7306    Otherwise we find one.  */
7307
7308 static struct signatured_type *
7309 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7310                void **slot)
7311 {
7312   struct objfile *objfile = dwarf2_per_objfile->objfile;
7313   int n_type_units = dwarf2_per_objfile->n_type_units;
7314   struct signatured_type *sig_type;
7315
7316   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7317   ++n_type_units;
7318   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7319     {
7320       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7321         dwarf2_per_objfile->n_allocated_type_units = 1;
7322       dwarf2_per_objfile->n_allocated_type_units *= 2;
7323       dwarf2_per_objfile->all_type_units
7324         = XRESIZEVEC (struct signatured_type *,
7325                       dwarf2_per_objfile->all_type_units,
7326                       dwarf2_per_objfile->n_allocated_type_units);
7327       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7328     }
7329   dwarf2_per_objfile->n_type_units = n_type_units;
7330
7331   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7332                              struct signatured_type);
7333   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7334   sig_type->signature = sig;
7335   sig_type->per_cu.is_debug_types = 1;
7336   if (dwarf2_per_objfile->using_index)
7337     {
7338       sig_type->per_cu.v.quick =
7339         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7340                         struct dwarf2_per_cu_quick_data);
7341     }
7342
7343   if (slot == NULL)
7344     {
7345       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7346                              sig_type, INSERT);
7347     }
7348   gdb_assert (*slot == NULL);
7349   *slot = sig_type;
7350   /* The rest of sig_type must be filled in by the caller.  */
7351   return sig_type;
7352 }
7353
7354 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7355    Fill in SIG_ENTRY with DWO_ENTRY.  */
7356
7357 static void
7358 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7359                                   struct signatured_type *sig_entry,
7360                                   struct dwo_unit *dwo_entry)
7361 {
7362   /* Make sure we're not clobbering something we don't expect to.  */
7363   gdb_assert (! sig_entry->per_cu.queued);
7364   gdb_assert (sig_entry->per_cu.cu == NULL);
7365   if (dwarf2_per_objfile->using_index)
7366     {
7367       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7368       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7369     }
7370   else
7371       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7372   gdb_assert (sig_entry->signature == dwo_entry->signature);
7373   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7374   gdb_assert (sig_entry->type_unit_group == NULL);
7375   gdb_assert (sig_entry->dwo_unit == NULL);
7376
7377   sig_entry->per_cu.section = dwo_entry->section;
7378   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7379   sig_entry->per_cu.length = dwo_entry->length;
7380   sig_entry->per_cu.reading_dwo_directly = 1;
7381   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7382   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7383   sig_entry->dwo_unit = dwo_entry;
7384 }
7385
7386 /* Subroutine of lookup_signatured_type.
7387    If we haven't read the TU yet, create the signatured_type data structure
7388    for a TU to be read in directly from a DWO file, bypassing the stub.
7389    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7390    using .gdb_index, then when reading a CU we want to stay in the DWO file
7391    containing that CU.  Otherwise we could end up reading several other DWO
7392    files (due to comdat folding) to process the transitive closure of all the
7393    mentioned TUs, and that can be slow.  The current DWO file will have every
7394    type signature that it needs.
7395    We only do this for .gdb_index because in the psymtab case we already have
7396    to read all the DWOs to build the type unit groups.  */
7397
7398 static struct signatured_type *
7399 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7400 {
7401   struct dwarf2_per_objfile *dwarf2_per_objfile
7402     = cu->per_cu->dwarf2_per_objfile;
7403   struct objfile *objfile = dwarf2_per_objfile->objfile;
7404   struct dwo_file *dwo_file;
7405   struct dwo_unit find_dwo_entry, *dwo_entry;
7406   struct signatured_type find_sig_entry, *sig_entry;
7407   void **slot;
7408
7409   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7410
7411   /* If TU skeletons have been removed then we may not have read in any
7412      TUs yet.  */
7413   if (dwarf2_per_objfile->signatured_types == NULL)
7414     {
7415       dwarf2_per_objfile->signatured_types
7416         = allocate_signatured_type_table (objfile);
7417     }
7418
7419   /* We only ever need to read in one copy of a signatured type.
7420      Use the global signatured_types array to do our own comdat-folding
7421      of types.  If this is the first time we're reading this TU, and
7422      the TU has an entry in .gdb_index, replace the recorded data from
7423      .gdb_index with this TU.  */
7424
7425   find_sig_entry.signature = sig;
7426   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7427                          &find_sig_entry, INSERT);
7428   sig_entry = (struct signatured_type *) *slot;
7429
7430   /* We can get here with the TU already read, *or* in the process of being
7431      read.  Don't reassign the global entry to point to this DWO if that's
7432      the case.  Also note that if the TU is already being read, it may not
7433      have come from a DWO, the program may be a mix of Fission-compiled
7434      code and non-Fission-compiled code.  */
7435
7436   /* Have we already tried to read this TU?
7437      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7438      needn't exist in the global table yet).  */
7439   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7440     return sig_entry;
7441
7442   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7443      dwo_unit of the TU itself.  */
7444   dwo_file = cu->dwo_unit->dwo_file;
7445
7446   /* Ok, this is the first time we're reading this TU.  */
7447   if (dwo_file->tus == NULL)
7448     return NULL;
7449   find_dwo_entry.signature = sig;
7450   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7451   if (dwo_entry == NULL)
7452     return NULL;
7453
7454   /* If the global table doesn't have an entry for this TU, add one.  */
7455   if (sig_entry == NULL)
7456     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7457
7458   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7459   sig_entry->per_cu.tu_read = 1;
7460   return sig_entry;
7461 }
7462
7463 /* Subroutine of lookup_signatured_type.
7464    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7465    then try the DWP file.  If the TU stub (skeleton) has been removed then
7466    it won't be in .gdb_index.  */
7467
7468 static struct signatured_type *
7469 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7470 {
7471   struct dwarf2_per_objfile *dwarf2_per_objfile
7472     = cu->per_cu->dwarf2_per_objfile;
7473   struct objfile *objfile = dwarf2_per_objfile->objfile;
7474   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7475   struct dwo_unit *dwo_entry;
7476   struct signatured_type find_sig_entry, *sig_entry;
7477   void **slot;
7478
7479   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7480   gdb_assert (dwp_file != NULL);
7481
7482   /* If TU skeletons have been removed then we may not have read in any
7483      TUs yet.  */
7484   if (dwarf2_per_objfile->signatured_types == NULL)
7485     {
7486       dwarf2_per_objfile->signatured_types
7487         = allocate_signatured_type_table (objfile);
7488     }
7489
7490   find_sig_entry.signature = sig;
7491   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7492                          &find_sig_entry, INSERT);
7493   sig_entry = (struct signatured_type *) *slot;
7494
7495   /* Have we already tried to read this TU?
7496      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7497      needn't exist in the global table yet).  */
7498   if (sig_entry != NULL)
7499     return sig_entry;
7500
7501   if (dwp_file->tus == NULL)
7502     return NULL;
7503   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7504                                       sig, 1 /* is_debug_types */);
7505   if (dwo_entry == NULL)
7506     return NULL;
7507
7508   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7509   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7510
7511   return sig_entry;
7512 }
7513
7514 /* Lookup a signature based type for DW_FORM_ref_sig8.
7515    Returns NULL if signature SIG is not present in the table.
7516    It is up to the caller to complain about this.  */
7517
7518 static struct signatured_type *
7519 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7520 {
7521   struct dwarf2_per_objfile *dwarf2_per_objfile
7522     = cu->per_cu->dwarf2_per_objfile;
7523
7524   if (cu->dwo_unit
7525       && dwarf2_per_objfile->using_index)
7526     {
7527       /* We're in a DWO/DWP file, and we're using .gdb_index.
7528          These cases require special processing.  */
7529       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7530         return lookup_dwo_signatured_type (cu, sig);
7531       else
7532         return lookup_dwp_signatured_type (cu, sig);
7533     }
7534   else
7535     {
7536       struct signatured_type find_entry, *entry;
7537
7538       if (dwarf2_per_objfile->signatured_types == NULL)
7539         return NULL;
7540       find_entry.signature = sig;
7541       entry = ((struct signatured_type *)
7542                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7543       return entry;
7544     }
7545 }
7546 \f
7547 /* Low level DIE reading support.  */
7548
7549 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7550
7551 static void
7552 init_cu_die_reader (struct die_reader_specs *reader,
7553                     struct dwarf2_cu *cu,
7554                     struct dwarf2_section_info *section,
7555                     struct dwo_file *dwo_file,
7556                     struct abbrev_table *abbrev_table)
7557 {
7558   gdb_assert (section->readin && section->buffer != NULL);
7559   reader->abfd = get_section_bfd_owner (section);
7560   reader->cu = cu;
7561   reader->dwo_file = dwo_file;
7562   reader->die_section = section;
7563   reader->buffer = section->buffer;
7564   reader->buffer_end = section->buffer + section->size;
7565   reader->comp_dir = NULL;
7566   reader->abbrev_table = abbrev_table;
7567 }
7568
7569 /* Subroutine of init_cutu_and_read_dies to simplify it.
7570    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7571    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7572    already.
7573
7574    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7575    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7576    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7577    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7578    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7579    STUB_COMP_DIR may be non-NULL.
7580    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7581    are filled in with the info of the DIE from the DWO file.
7582    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7583    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7584    kept around for at least as long as *RESULT_READER.
7585
7586    The result is non-zero if a valid (non-dummy) DIE was found.  */
7587
7588 static int
7589 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7590                         struct dwo_unit *dwo_unit,
7591                         struct die_info *stub_comp_unit_die,
7592                         const char *stub_comp_dir,
7593                         struct die_reader_specs *result_reader,
7594                         const gdb_byte **result_info_ptr,
7595                         struct die_info **result_comp_unit_die,
7596                         int *result_has_children,
7597                         abbrev_table_up *result_dwo_abbrev_table)
7598 {
7599   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7600   struct objfile *objfile = dwarf2_per_objfile->objfile;
7601   struct dwarf2_cu *cu = this_cu->cu;
7602   bfd *abfd;
7603   const gdb_byte *begin_info_ptr, *info_ptr;
7604   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7605   int i,num_extra_attrs;
7606   struct dwarf2_section_info *dwo_abbrev_section;
7607   struct attribute *attr;
7608   struct die_info *comp_unit_die;
7609
7610   /* At most one of these may be provided.  */
7611   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7612
7613   /* These attributes aren't processed until later:
7614      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7615      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7616      referenced later.  However, these attributes are found in the stub
7617      which we won't have later.  In order to not impose this complication
7618      on the rest of the code, we read them here and copy them to the
7619      DWO CU/TU die.  */
7620
7621   stmt_list = NULL;
7622   low_pc = NULL;
7623   high_pc = NULL;
7624   ranges = NULL;
7625   comp_dir = NULL;
7626
7627   if (stub_comp_unit_die != NULL)
7628     {
7629       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7630          DWO file.  */
7631       if (! this_cu->is_debug_types)
7632         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7633       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7634       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7635       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7636       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7637
7638       /* There should be a DW_AT_addr_base attribute here (if needed).
7639          We need the value before we can process DW_FORM_GNU_addr_index.  */
7640       cu->addr_base = 0;
7641       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7642       if (attr)
7643         cu->addr_base = DW_UNSND (attr);
7644
7645       /* There should be a DW_AT_ranges_base attribute here (if needed).
7646          We need the value before we can process DW_AT_ranges.  */
7647       cu->ranges_base = 0;
7648       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7649       if (attr)
7650         cu->ranges_base = DW_UNSND (attr);
7651     }
7652   else if (stub_comp_dir != NULL)
7653     {
7654       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7655       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7656       comp_dir->name = DW_AT_comp_dir;
7657       comp_dir->form = DW_FORM_string;
7658       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7659       DW_STRING (comp_dir) = stub_comp_dir;
7660     }
7661
7662   /* Set up for reading the DWO CU/TU.  */
7663   cu->dwo_unit = dwo_unit;
7664   dwarf2_section_info *section = dwo_unit->section;
7665   dwarf2_read_section (objfile, section);
7666   abfd = get_section_bfd_owner (section);
7667   begin_info_ptr = info_ptr = (section->buffer
7668                                + to_underlying (dwo_unit->sect_off));
7669   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7670
7671   if (this_cu->is_debug_types)
7672     {
7673       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7674
7675       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7676                                                 &cu->header, section,
7677                                                 dwo_abbrev_section,
7678                                                 info_ptr, rcuh_kind::TYPE);
7679       /* This is not an assert because it can be caused by bad debug info.  */
7680       if (sig_type->signature != cu->header.signature)
7681         {
7682           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7683                    " TU at offset %s [in module %s]"),
7684                  hex_string (sig_type->signature),
7685                  hex_string (cu->header.signature),
7686                  sect_offset_str (dwo_unit->sect_off),
7687                  bfd_get_filename (abfd));
7688         }
7689       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7690       /* For DWOs coming from DWP files, we don't know the CU length
7691          nor the type's offset in the TU until now.  */
7692       dwo_unit->length = get_cu_length (&cu->header);
7693       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7694
7695       /* Establish the type offset that can be used to lookup the type.
7696          For DWO files, we don't know it until now.  */
7697       sig_type->type_offset_in_section
7698         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7699     }
7700   else
7701     {
7702       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7703                                                 &cu->header, section,
7704                                                 dwo_abbrev_section,
7705                                                 info_ptr, rcuh_kind::COMPILE);
7706       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7707       /* For DWOs coming from DWP files, we don't know the CU length
7708          until now.  */
7709       dwo_unit->length = get_cu_length (&cu->header);
7710     }
7711
7712   *result_dwo_abbrev_table
7713     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7714                                cu->header.abbrev_sect_off);
7715   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7716                       result_dwo_abbrev_table->get ());
7717
7718   /* Read in the die, but leave space to copy over the attributes
7719      from the stub.  This has the benefit of simplifying the rest of
7720      the code - all the work to maintain the illusion of a single
7721      DW_TAG_{compile,type}_unit DIE is done here.  */
7722   num_extra_attrs = ((stmt_list != NULL)
7723                      + (low_pc != NULL)
7724                      + (high_pc != NULL)
7725                      + (ranges != NULL)
7726                      + (comp_dir != NULL));
7727   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7728                               result_has_children, num_extra_attrs);
7729
7730   /* Copy over the attributes from the stub to the DIE we just read in.  */
7731   comp_unit_die = *result_comp_unit_die;
7732   i = comp_unit_die->num_attrs;
7733   if (stmt_list != NULL)
7734     comp_unit_die->attrs[i++] = *stmt_list;
7735   if (low_pc != NULL)
7736     comp_unit_die->attrs[i++] = *low_pc;
7737   if (high_pc != NULL)
7738     comp_unit_die->attrs[i++] = *high_pc;
7739   if (ranges != NULL)
7740     comp_unit_die->attrs[i++] = *ranges;
7741   if (comp_dir != NULL)
7742     comp_unit_die->attrs[i++] = *comp_dir;
7743   comp_unit_die->num_attrs += num_extra_attrs;
7744
7745   if (dwarf_die_debug)
7746     {
7747       fprintf_unfiltered (gdb_stdlog,
7748                           "Read die from %s@0x%x of %s:\n",
7749                           get_section_name (section),
7750                           (unsigned) (begin_info_ptr - section->buffer),
7751                           bfd_get_filename (abfd));
7752       dump_die (comp_unit_die, dwarf_die_debug);
7753     }
7754
7755   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7756      TUs by skipping the stub and going directly to the entry in the DWO file.
7757      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7758      to get it via circuitous means.  Blech.  */
7759   if (comp_dir != NULL)
7760     result_reader->comp_dir = DW_STRING (comp_dir);
7761
7762   /* Skip dummy compilation units.  */
7763   if (info_ptr >= begin_info_ptr + dwo_unit->length
7764       || peek_abbrev_code (abfd, info_ptr) == 0)
7765     return 0;
7766
7767   *result_info_ptr = info_ptr;
7768   return 1;
7769 }
7770
7771 /* Subroutine of init_cutu_and_read_dies to simplify it.
7772    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7773    Returns NULL if the specified DWO unit cannot be found.  */
7774
7775 static struct dwo_unit *
7776 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7777                  struct die_info *comp_unit_die)
7778 {
7779   struct dwarf2_cu *cu = this_cu->cu;
7780   ULONGEST signature;
7781   struct dwo_unit *dwo_unit;
7782   const char *comp_dir, *dwo_name;
7783
7784   gdb_assert (cu != NULL);
7785
7786   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7787   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7788   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7789
7790   if (this_cu->is_debug_types)
7791     {
7792       struct signatured_type *sig_type;
7793
7794       /* Since this_cu is the first member of struct signatured_type,
7795          we can go from a pointer to one to a pointer to the other.  */
7796       sig_type = (struct signatured_type *) this_cu;
7797       signature = sig_type->signature;
7798       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7799     }
7800   else
7801     {
7802       struct attribute *attr;
7803
7804       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7805       if (! attr)
7806         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7807                  " [in module %s]"),
7808                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7809       signature = DW_UNSND (attr);
7810       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7811                                        signature);
7812     }
7813
7814   return dwo_unit;
7815 }
7816
7817 /* Subroutine of init_cutu_and_read_dies to simplify it.
7818    See it for a description of the parameters.
7819    Read a TU directly from a DWO file, bypassing the stub.  */
7820
7821 static void
7822 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7823                            int use_existing_cu, int keep,
7824                            die_reader_func_ftype *die_reader_func,
7825                            void *data)
7826 {
7827   std::unique_ptr<dwarf2_cu> new_cu;
7828   struct signatured_type *sig_type;
7829   struct die_reader_specs reader;
7830   const gdb_byte *info_ptr;
7831   struct die_info *comp_unit_die;
7832   int has_children;
7833   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7834
7835   /* Verify we can do the following downcast, and that we have the
7836      data we need.  */
7837   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7838   sig_type = (struct signatured_type *) this_cu;
7839   gdb_assert (sig_type->dwo_unit != NULL);
7840
7841   if (use_existing_cu && this_cu->cu != NULL)
7842     {
7843       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7844       /* There's no need to do the rereading_dwo_cu handling that
7845          init_cutu_and_read_dies does since we don't read the stub.  */
7846     }
7847   else
7848     {
7849       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7850       gdb_assert (this_cu->cu == NULL);
7851       new_cu.reset (new dwarf2_cu (this_cu));
7852     }
7853
7854   /* A future optimization, if needed, would be to use an existing
7855      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7856      could share abbrev tables.  */
7857
7858   /* The abbreviation table used by READER, this must live at least as long as
7859      READER.  */
7860   abbrev_table_up dwo_abbrev_table;
7861
7862   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7863                               NULL /* stub_comp_unit_die */,
7864                               sig_type->dwo_unit->dwo_file->comp_dir,
7865                               &reader, &info_ptr,
7866                               &comp_unit_die, &has_children,
7867                               &dwo_abbrev_table) == 0)
7868     {
7869       /* Dummy die.  */
7870       return;
7871     }
7872
7873   /* All the "real" work is done here.  */
7874   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7875
7876   /* This duplicates the code in init_cutu_and_read_dies,
7877      but the alternative is making the latter more complex.
7878      This function is only for the special case of using DWO files directly:
7879      no point in overly complicating the general case just to handle this.  */
7880   if (new_cu != NULL && keep)
7881     {
7882       /* Link this CU into read_in_chain.  */
7883       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7884       dwarf2_per_objfile->read_in_chain = this_cu;
7885       /* The chain owns it now.  */
7886       new_cu.release ();
7887     }
7888 }
7889
7890 /* Initialize a CU (or TU) and read its DIEs.
7891    If the CU defers to a DWO file, read the DWO file as well.
7892
7893    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7894    Otherwise the table specified in the comp unit header is read in and used.
7895    This is an optimization for when we already have the abbrev table.
7896
7897    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7898    Otherwise, a new CU is allocated with xmalloc.
7899
7900    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7901    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7902
7903    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7904    linker) then DIE_READER_FUNC will not get called.  */
7905
7906 static void
7907 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7908                          struct abbrev_table *abbrev_table,
7909                          int use_existing_cu, int keep,
7910                          die_reader_func_ftype *die_reader_func,
7911                          void *data)
7912 {
7913   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7914   struct objfile *objfile = dwarf2_per_objfile->objfile;
7915   struct dwarf2_section_info *section = this_cu->section;
7916   bfd *abfd = get_section_bfd_owner (section);
7917   struct dwarf2_cu *cu;
7918   const gdb_byte *begin_info_ptr, *info_ptr;
7919   struct die_reader_specs reader;
7920   struct die_info *comp_unit_die;
7921   int has_children;
7922   struct attribute *attr;
7923   struct signatured_type *sig_type = NULL;
7924   struct dwarf2_section_info *abbrev_section;
7925   /* Non-zero if CU currently points to a DWO file and we need to
7926      reread it.  When this happens we need to reread the skeleton die
7927      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7928   int rereading_dwo_cu = 0;
7929
7930   if (dwarf_die_debug)
7931     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7932                         this_cu->is_debug_types ? "type" : "comp",
7933                         sect_offset_str (this_cu->sect_off));
7934
7935   if (use_existing_cu)
7936     gdb_assert (keep);
7937
7938   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7939      file (instead of going through the stub), short-circuit all of this.  */
7940   if (this_cu->reading_dwo_directly)
7941     {
7942       /* Narrow down the scope of possibilities to have to understand.  */
7943       gdb_assert (this_cu->is_debug_types);
7944       gdb_assert (abbrev_table == NULL);
7945       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7946                                  die_reader_func, data);
7947       return;
7948     }
7949
7950   /* This is cheap if the section is already read in.  */
7951   dwarf2_read_section (objfile, section);
7952
7953   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7954
7955   abbrev_section = get_abbrev_section_for_cu (this_cu);
7956
7957   std::unique_ptr<dwarf2_cu> new_cu;
7958   if (use_existing_cu && this_cu->cu != NULL)
7959     {
7960       cu = this_cu->cu;
7961       /* If this CU is from a DWO file we need to start over, we need to
7962          refetch the attributes from the skeleton CU.
7963          This could be optimized by retrieving those attributes from when we
7964          were here the first time: the previous comp_unit_die was stored in
7965          comp_unit_obstack.  But there's no data yet that we need this
7966          optimization.  */
7967       if (cu->dwo_unit != NULL)
7968         rereading_dwo_cu = 1;
7969     }
7970   else
7971     {
7972       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7973       gdb_assert (this_cu->cu == NULL);
7974       new_cu.reset (new dwarf2_cu (this_cu));
7975       cu = new_cu.get ();
7976     }
7977
7978   /* Get the header.  */
7979   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7980     {
7981       /* We already have the header, there's no need to read it in again.  */
7982       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7983     }
7984   else
7985     {
7986       if (this_cu->is_debug_types)
7987         {
7988           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7989                                                     &cu->header, section,
7990                                                     abbrev_section, info_ptr,
7991                                                     rcuh_kind::TYPE);
7992
7993           /* Since per_cu is the first member of struct signatured_type,
7994              we can go from a pointer to one to a pointer to the other.  */
7995           sig_type = (struct signatured_type *) this_cu;
7996           gdb_assert (sig_type->signature == cu->header.signature);
7997           gdb_assert (sig_type->type_offset_in_tu
7998                       == cu->header.type_cu_offset_in_tu);
7999           gdb_assert (this_cu->sect_off == cu->header.sect_off);
8000
8001           /* LENGTH has not been set yet for type units if we're
8002              using .gdb_index.  */
8003           this_cu->length = get_cu_length (&cu->header);
8004
8005           /* Establish the type offset that can be used to lookup the type.  */
8006           sig_type->type_offset_in_section =
8007             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
8008
8009           this_cu->dwarf_version = cu->header.version;
8010         }
8011       else
8012         {
8013           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8014                                                     &cu->header, section,
8015                                                     abbrev_section,
8016                                                     info_ptr,
8017                                                     rcuh_kind::COMPILE);
8018
8019           gdb_assert (this_cu->sect_off == cu->header.sect_off);
8020           gdb_assert (this_cu->length == get_cu_length (&cu->header));
8021           this_cu->dwarf_version = cu->header.version;
8022         }
8023     }
8024
8025   /* Skip dummy compilation units.  */
8026   if (info_ptr >= begin_info_ptr + this_cu->length
8027       || peek_abbrev_code (abfd, info_ptr) == 0)
8028     return;
8029
8030   /* If we don't have them yet, read the abbrevs for this compilation unit.
8031      And if we need to read them now, make sure they're freed when we're
8032      done (own the table through ABBREV_TABLE_HOLDER).  */
8033   abbrev_table_up abbrev_table_holder;
8034   if (abbrev_table != NULL)
8035     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
8036   else
8037     {
8038       abbrev_table_holder
8039         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8040                                    cu->header.abbrev_sect_off);
8041       abbrev_table = abbrev_table_holder.get ();
8042     }
8043
8044   /* Read the top level CU/TU die.  */
8045   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
8046   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8047
8048   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
8049      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
8050      table from the DWO file and pass the ownership over to us.  It will be
8051      referenced from READER, so we must make sure to free it after we're done
8052      with READER.
8053
8054      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
8055      DWO CU, that this test will fail (the attribute will not be present).  */
8056   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
8057   abbrev_table_up dwo_abbrev_table;
8058   if (attr)
8059     {
8060       struct dwo_unit *dwo_unit;
8061       struct die_info *dwo_comp_unit_die;
8062
8063       if (has_children)
8064         {
8065           complaint (&symfile_complaints,
8066                      _("compilation unit with DW_AT_GNU_dwo_name"
8067                        " has children (offset %s) [in module %s]"),
8068                      sect_offset_str (this_cu->sect_off),
8069                      bfd_get_filename (abfd));
8070         }
8071       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
8072       if (dwo_unit != NULL)
8073         {
8074           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
8075                                       comp_unit_die, NULL,
8076                                       &reader, &info_ptr,
8077                                       &dwo_comp_unit_die, &has_children,
8078                                       &dwo_abbrev_table) == 0)
8079             {
8080               /* Dummy die.  */
8081               return;
8082             }
8083           comp_unit_die = dwo_comp_unit_die;
8084         }
8085       else
8086         {
8087           /* Yikes, we couldn't find the rest of the DIE, we only have
8088              the stub.  A complaint has already been logged.  There's
8089              not much more we can do except pass on the stub DIE to
8090              die_reader_func.  We don't want to throw an error on bad
8091              debug info.  */
8092         }
8093     }
8094
8095   /* All of the above is setup for this call.  Yikes.  */
8096   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8097
8098   /* Done, clean up.  */
8099   if (new_cu != NULL && keep)
8100     {
8101       /* Link this CU into read_in_chain.  */
8102       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8103       dwarf2_per_objfile->read_in_chain = this_cu;
8104       /* The chain owns it now.  */
8105       new_cu.release ();
8106     }
8107 }
8108
8109 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8110    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8111    to have already done the lookup to find the DWO file).
8112
8113    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8114    THIS_CU->is_debug_types, but nothing else.
8115
8116    We fill in THIS_CU->length.
8117
8118    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8119    linker) then DIE_READER_FUNC will not get called.
8120
8121    THIS_CU->cu is always freed when done.
8122    This is done in order to not leave THIS_CU->cu in a state where we have
8123    to care whether it refers to the "main" CU or the DWO CU.  */
8124
8125 static void
8126 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8127                                    struct dwo_file *dwo_file,
8128                                    die_reader_func_ftype *die_reader_func,
8129                                    void *data)
8130 {
8131   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8132   struct objfile *objfile = dwarf2_per_objfile->objfile;
8133   struct dwarf2_section_info *section = this_cu->section;
8134   bfd *abfd = get_section_bfd_owner (section);
8135   struct dwarf2_section_info *abbrev_section;
8136   const gdb_byte *begin_info_ptr, *info_ptr;
8137   struct die_reader_specs reader;
8138   struct die_info *comp_unit_die;
8139   int has_children;
8140
8141   if (dwarf_die_debug)
8142     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
8143                         this_cu->is_debug_types ? "type" : "comp",
8144                         sect_offset_str (this_cu->sect_off));
8145
8146   gdb_assert (this_cu->cu == NULL);
8147
8148   abbrev_section = (dwo_file != NULL
8149                     ? &dwo_file->sections.abbrev
8150                     : get_abbrev_section_for_cu (this_cu));
8151
8152   /* This is cheap if the section is already read in.  */
8153   dwarf2_read_section (objfile, section);
8154
8155   struct dwarf2_cu cu (this_cu);
8156
8157   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8158   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8159                                             &cu.header, section,
8160                                             abbrev_section, info_ptr,
8161                                             (this_cu->is_debug_types
8162                                              ? rcuh_kind::TYPE
8163                                              : rcuh_kind::COMPILE));
8164
8165   this_cu->length = get_cu_length (&cu.header);
8166
8167   /* Skip dummy compilation units.  */
8168   if (info_ptr >= begin_info_ptr + this_cu->length
8169       || peek_abbrev_code (abfd, info_ptr) == 0)
8170     return;
8171
8172   abbrev_table_up abbrev_table
8173     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8174                                cu.header.abbrev_sect_off);
8175
8176   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8177   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8178
8179   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8180 }
8181
8182 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8183    does not lookup the specified DWO file.
8184    This cannot be used to read DWO files.
8185
8186    THIS_CU->cu is always freed when done.
8187    This is done in order to not leave THIS_CU->cu in a state where we have
8188    to care whether it refers to the "main" CU or the DWO CU.
8189    We can revisit this if the data shows there's a performance issue.  */
8190
8191 static void
8192 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8193                                 die_reader_func_ftype *die_reader_func,
8194                                 void *data)
8195 {
8196   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8197 }
8198 \f
8199 /* Type Unit Groups.
8200
8201    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8202    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8203    so that all types coming from the same compilation (.o file) are grouped
8204    together.  A future step could be to put the types in the same symtab as
8205    the CU the types ultimately came from.  */
8206
8207 static hashval_t
8208 hash_type_unit_group (const void *item)
8209 {
8210   const struct type_unit_group *tu_group
8211     = (const struct type_unit_group *) item;
8212
8213   return hash_stmt_list_entry (&tu_group->hash);
8214 }
8215
8216 static int
8217 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8218 {
8219   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8220   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8221
8222   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8223 }
8224
8225 /* Allocate a hash table for type unit groups.  */
8226
8227 static htab_t
8228 allocate_type_unit_groups_table (struct objfile *objfile)
8229 {
8230   return htab_create_alloc_ex (3,
8231                                hash_type_unit_group,
8232                                eq_type_unit_group,
8233                                NULL,
8234                                &objfile->objfile_obstack,
8235                                hashtab_obstack_allocate,
8236                                dummy_obstack_deallocate);
8237 }
8238
8239 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8240    partial symtabs.  We combine several TUs per psymtab to not let the size
8241    of any one psymtab grow too big.  */
8242 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8243 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8244
8245 /* Helper routine for get_type_unit_group.
8246    Create the type_unit_group object used to hold one or more TUs.  */
8247
8248 static struct type_unit_group *
8249 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8250 {
8251   struct dwarf2_per_objfile *dwarf2_per_objfile
8252     = cu->per_cu->dwarf2_per_objfile;
8253   struct objfile *objfile = dwarf2_per_objfile->objfile;
8254   struct dwarf2_per_cu_data *per_cu;
8255   struct type_unit_group *tu_group;
8256
8257   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8258                              struct type_unit_group);
8259   per_cu = &tu_group->per_cu;
8260   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8261
8262   if (dwarf2_per_objfile->using_index)
8263     {
8264       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8265                                         struct dwarf2_per_cu_quick_data);
8266     }
8267   else
8268     {
8269       unsigned int line_offset = to_underlying (line_offset_struct);
8270       struct partial_symtab *pst;
8271       char *name;
8272
8273       /* Give the symtab a useful name for debug purposes.  */
8274       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8275         name = xstrprintf ("<type_units_%d>",
8276                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8277       else
8278         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8279
8280       pst = create_partial_symtab (per_cu, name);
8281       pst->anonymous = 1;
8282
8283       xfree (name);
8284     }
8285
8286   tu_group->hash.dwo_unit = cu->dwo_unit;
8287   tu_group->hash.line_sect_off = line_offset_struct;
8288
8289   return tu_group;
8290 }
8291
8292 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8293    STMT_LIST is a DW_AT_stmt_list attribute.  */
8294
8295 static struct type_unit_group *
8296 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8297 {
8298   struct dwarf2_per_objfile *dwarf2_per_objfile
8299     = cu->per_cu->dwarf2_per_objfile;
8300   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8301   struct type_unit_group *tu_group;
8302   void **slot;
8303   unsigned int line_offset;
8304   struct type_unit_group type_unit_group_for_lookup;
8305
8306   if (dwarf2_per_objfile->type_unit_groups == NULL)
8307     {
8308       dwarf2_per_objfile->type_unit_groups =
8309         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8310     }
8311
8312   /* Do we need to create a new group, or can we use an existing one?  */
8313
8314   if (stmt_list)
8315     {
8316       line_offset = DW_UNSND (stmt_list);
8317       ++tu_stats->nr_symtab_sharers;
8318     }
8319   else
8320     {
8321       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8322          We can do various things here like create one group per TU or
8323          spread them over multiple groups to split up the expansion work.
8324          To avoid worst case scenarios (too many groups or too large groups)
8325          we, umm, group them in bunches.  */
8326       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8327                      | (tu_stats->nr_stmt_less_type_units
8328                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8329       ++tu_stats->nr_stmt_less_type_units;
8330     }
8331
8332   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8333   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8334   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8335                          &type_unit_group_for_lookup, INSERT);
8336   if (*slot != NULL)
8337     {
8338       tu_group = (struct type_unit_group *) *slot;
8339       gdb_assert (tu_group != NULL);
8340     }
8341   else
8342     {
8343       sect_offset line_offset_struct = (sect_offset) line_offset;
8344       tu_group = create_type_unit_group (cu, line_offset_struct);
8345       *slot = tu_group;
8346       ++tu_stats->nr_symtabs;
8347     }
8348
8349   return tu_group;
8350 }
8351 \f
8352 /* Partial symbol tables.  */
8353
8354 /* Create a psymtab named NAME and assign it to PER_CU.
8355
8356    The caller must fill in the following details:
8357    dirname, textlow, texthigh.  */
8358
8359 static struct partial_symtab *
8360 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8361 {
8362   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8363   struct partial_symtab *pst;
8364
8365   pst = start_psymtab_common (objfile, name, 0,
8366                               objfile->global_psymbols,
8367                               objfile->static_psymbols);
8368
8369   pst->psymtabs_addrmap_supported = 1;
8370
8371   /* This is the glue that links PST into GDB's symbol API.  */
8372   pst->read_symtab_private = per_cu;
8373   pst->read_symtab = dwarf2_read_symtab;
8374   per_cu->v.psymtab = pst;
8375
8376   return pst;
8377 }
8378
8379 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8380    type.  */
8381
8382 struct process_psymtab_comp_unit_data
8383 {
8384   /* True if we are reading a DW_TAG_partial_unit.  */
8385
8386   int want_partial_unit;
8387
8388   /* The "pretend" language that is used if the CU doesn't declare a
8389      language.  */
8390
8391   enum language pretend_language;
8392 };
8393
8394 /* die_reader_func for process_psymtab_comp_unit.  */
8395
8396 static void
8397 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8398                                   const gdb_byte *info_ptr,
8399                                   struct die_info *comp_unit_die,
8400                                   int has_children,
8401                                   void *data)
8402 {
8403   struct dwarf2_cu *cu = reader->cu;
8404   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8405   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8406   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8407   CORE_ADDR baseaddr;
8408   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8409   struct partial_symtab *pst;
8410   enum pc_bounds_kind cu_bounds_kind;
8411   const char *filename;
8412   struct process_psymtab_comp_unit_data *info
8413     = (struct process_psymtab_comp_unit_data *) data;
8414
8415   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8416     return;
8417
8418   gdb_assert (! per_cu->is_debug_types);
8419
8420   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8421
8422   cu->list_in_scope = &file_symbols;
8423
8424   /* Allocate a new partial symbol table structure.  */
8425   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8426   if (filename == NULL)
8427     filename = "";
8428
8429   pst = create_partial_symtab (per_cu, filename);
8430
8431   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8432   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8433
8434   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8435
8436   dwarf2_find_base_address (comp_unit_die, cu);
8437
8438   /* Possibly set the default values of LOWPC and HIGHPC from
8439      `DW_AT_ranges'.  */
8440   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8441                                          &best_highpc, cu, pst);
8442   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8443     /* Store the contiguous range if it is not empty; it can be empty for
8444        CUs with no code.  */
8445     addrmap_set_empty (objfile->psymtabs_addrmap,
8446                        gdbarch_adjust_dwarf2_addr (gdbarch,
8447                                                    best_lowpc + baseaddr),
8448                        gdbarch_adjust_dwarf2_addr (gdbarch,
8449                                                    best_highpc + baseaddr) - 1,
8450                        pst);
8451
8452   /* Check if comp unit has_children.
8453      If so, read the rest of the partial symbols from this comp unit.
8454      If not, there's no more debug_info for this comp unit.  */
8455   if (has_children)
8456     {
8457       struct partial_die_info *first_die;
8458       CORE_ADDR lowpc, highpc;
8459
8460       lowpc = ((CORE_ADDR) -1);
8461       highpc = ((CORE_ADDR) 0);
8462
8463       first_die = load_partial_dies (reader, info_ptr, 1);
8464
8465       scan_partial_symbols (first_die, &lowpc, &highpc,
8466                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8467
8468       /* If we didn't find a lowpc, set it to highpc to avoid
8469          complaints from `maint check'.  */
8470       if (lowpc == ((CORE_ADDR) -1))
8471         lowpc = highpc;
8472
8473       /* If the compilation unit didn't have an explicit address range,
8474          then use the information extracted from its child dies.  */
8475       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8476         {
8477           best_lowpc = lowpc;
8478           best_highpc = highpc;
8479         }
8480     }
8481   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8482   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8483
8484   end_psymtab_common (objfile, pst);
8485
8486   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8487     {
8488       int i;
8489       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8490       struct dwarf2_per_cu_data *iter;
8491
8492       /* Fill in 'dependencies' here; we fill in 'users' in a
8493          post-pass.  */
8494       pst->number_of_dependencies = len;
8495       pst->dependencies =
8496         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8497       for (i = 0;
8498            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8499                         i, iter);
8500            ++i)
8501         pst->dependencies[i] = iter->v.psymtab;
8502
8503       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8504     }
8505
8506   /* Get the list of files included in the current compilation unit,
8507      and build a psymtab for each of them.  */
8508   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8509
8510   if (dwarf_read_debug)
8511     {
8512       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8513
8514       fprintf_unfiltered (gdb_stdlog,
8515                           "Psymtab for %s unit @%s: %s - %s"
8516                           ", %d global, %d static syms\n",
8517                           per_cu->is_debug_types ? "type" : "comp",
8518                           sect_offset_str (per_cu->sect_off),
8519                           paddress (gdbarch, pst->textlow),
8520                           paddress (gdbarch, pst->texthigh),
8521                           pst->n_global_syms, pst->n_static_syms);
8522     }
8523 }
8524
8525 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8526    Process compilation unit THIS_CU for a psymtab.  */
8527
8528 static void
8529 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8530                            int want_partial_unit,
8531                            enum language pretend_language)
8532 {
8533   /* If this compilation unit was already read in, free the
8534      cached copy in order to read it in again.  This is
8535      necessary because we skipped some symbols when we first
8536      read in the compilation unit (see load_partial_dies).
8537      This problem could be avoided, but the benefit is unclear.  */
8538   if (this_cu->cu != NULL)
8539     free_one_cached_comp_unit (this_cu);
8540
8541   if (this_cu->is_debug_types)
8542     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8543                              NULL);
8544   else
8545     {
8546       process_psymtab_comp_unit_data info;
8547       info.want_partial_unit = want_partial_unit;
8548       info.pretend_language = pretend_language;
8549       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8550                                process_psymtab_comp_unit_reader, &info);
8551     }
8552
8553   /* Age out any secondary CUs.  */
8554   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8555 }
8556
8557 /* Reader function for build_type_psymtabs.  */
8558
8559 static void
8560 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8561                             const gdb_byte *info_ptr,
8562                             struct die_info *type_unit_die,
8563                             int has_children,
8564                             void *data)
8565 {
8566   struct dwarf2_per_objfile *dwarf2_per_objfile
8567     = reader->cu->per_cu->dwarf2_per_objfile;
8568   struct objfile *objfile = dwarf2_per_objfile->objfile;
8569   struct dwarf2_cu *cu = reader->cu;
8570   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8571   struct signatured_type *sig_type;
8572   struct type_unit_group *tu_group;
8573   struct attribute *attr;
8574   struct partial_die_info *first_die;
8575   CORE_ADDR lowpc, highpc;
8576   struct partial_symtab *pst;
8577
8578   gdb_assert (data == NULL);
8579   gdb_assert (per_cu->is_debug_types);
8580   sig_type = (struct signatured_type *) per_cu;
8581
8582   if (! has_children)
8583     return;
8584
8585   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8586   tu_group = get_type_unit_group (cu, attr);
8587
8588   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8589
8590   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8591   cu->list_in_scope = &file_symbols;
8592   pst = create_partial_symtab (per_cu, "");
8593   pst->anonymous = 1;
8594
8595   first_die = load_partial_dies (reader, info_ptr, 1);
8596
8597   lowpc = (CORE_ADDR) -1;
8598   highpc = (CORE_ADDR) 0;
8599   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8600
8601   end_psymtab_common (objfile, pst);
8602 }
8603
8604 /* Struct used to sort TUs by their abbreviation table offset.  */
8605
8606 struct tu_abbrev_offset
8607 {
8608   struct signatured_type *sig_type;
8609   sect_offset abbrev_offset;
8610 };
8611
8612 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8613
8614 static int
8615 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8616 {
8617   const struct tu_abbrev_offset * const *a
8618     = (const struct tu_abbrev_offset * const*) ap;
8619   const struct tu_abbrev_offset * const *b
8620     = (const struct tu_abbrev_offset * const*) bp;
8621   sect_offset aoff = (*a)->abbrev_offset;
8622   sect_offset boff = (*b)->abbrev_offset;
8623
8624   return (aoff > boff) - (aoff < boff);
8625 }
8626
8627 /* Efficiently read all the type units.
8628    This does the bulk of the work for build_type_psymtabs.
8629
8630    The efficiency is because we sort TUs by the abbrev table they use and
8631    only read each abbrev table once.  In one program there are 200K TUs
8632    sharing 8K abbrev tables.
8633
8634    The main purpose of this function is to support building the
8635    dwarf2_per_objfile->type_unit_groups table.
8636    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8637    can collapse the search space by grouping them by stmt_list.
8638    The savings can be significant, in the same program from above the 200K TUs
8639    share 8K stmt_list tables.
8640
8641    FUNC is expected to call get_type_unit_group, which will create the
8642    struct type_unit_group if necessary and add it to
8643    dwarf2_per_objfile->type_unit_groups.  */
8644
8645 static void
8646 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8647 {
8648   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8649   struct cleanup *cleanups;
8650   abbrev_table_up abbrev_table;
8651   sect_offset abbrev_offset;
8652   struct tu_abbrev_offset *sorted_by_abbrev;
8653   int i;
8654
8655   /* It's up to the caller to not call us multiple times.  */
8656   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8657
8658   if (dwarf2_per_objfile->n_type_units == 0)
8659     return;
8660
8661   /* TUs typically share abbrev tables, and there can be way more TUs than
8662      abbrev tables.  Sort by abbrev table to reduce the number of times we
8663      read each abbrev table in.
8664      Alternatives are to punt or to maintain a cache of abbrev tables.
8665      This is simpler and efficient enough for now.
8666
8667      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8668      symtab to use).  Typically TUs with the same abbrev offset have the same
8669      stmt_list value too so in practice this should work well.
8670
8671      The basic algorithm here is:
8672
8673       sort TUs by abbrev table
8674       for each TU with same abbrev table:
8675         read abbrev table if first user
8676         read TU top level DIE
8677           [IWBN if DWO skeletons had DW_AT_stmt_list]
8678         call FUNC  */
8679
8680   if (dwarf_read_debug)
8681     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8682
8683   /* Sort in a separate table to maintain the order of all_type_units
8684      for .gdb_index: TU indices directly index all_type_units.  */
8685   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8686                               dwarf2_per_objfile->n_type_units);
8687   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8688     {
8689       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8690
8691       sorted_by_abbrev[i].sig_type = sig_type;
8692       sorted_by_abbrev[i].abbrev_offset =
8693         read_abbrev_offset (dwarf2_per_objfile,
8694                             sig_type->per_cu.section,
8695                             sig_type->per_cu.sect_off);
8696     }
8697   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8698   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8699          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8700
8701   abbrev_offset = (sect_offset) ~(unsigned) 0;
8702
8703   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8704     {
8705       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8706
8707       /* Switch to the next abbrev table if necessary.  */
8708       if (abbrev_table == NULL
8709           || tu->abbrev_offset != abbrev_offset)
8710         {
8711           abbrev_offset = tu->abbrev_offset;
8712           abbrev_table =
8713             abbrev_table_read_table (dwarf2_per_objfile,
8714                                      &dwarf2_per_objfile->abbrev,
8715                                      abbrev_offset);
8716           ++tu_stats->nr_uniq_abbrev_tables;
8717         }
8718
8719       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8720                                0, 0, build_type_psymtabs_reader, NULL);
8721     }
8722
8723   do_cleanups (cleanups);
8724 }
8725
8726 /* Print collected type unit statistics.  */
8727
8728 static void
8729 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8730 {
8731   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8732
8733   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8734   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8735                       dwarf2_per_objfile->n_type_units);
8736   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8737                       tu_stats->nr_uniq_abbrev_tables);
8738   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8739                       tu_stats->nr_symtabs);
8740   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8741                       tu_stats->nr_symtab_sharers);
8742   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8743                       tu_stats->nr_stmt_less_type_units);
8744   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8745                       tu_stats->nr_all_type_units_reallocs);
8746 }
8747
8748 /* Traversal function for build_type_psymtabs.  */
8749
8750 static int
8751 build_type_psymtab_dependencies (void **slot, void *info)
8752 {
8753   struct dwarf2_per_objfile *dwarf2_per_objfile
8754     = (struct dwarf2_per_objfile *) info;
8755   struct objfile *objfile = dwarf2_per_objfile->objfile;
8756   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8757   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8758   struct partial_symtab *pst = per_cu->v.psymtab;
8759   int len = VEC_length (sig_type_ptr, tu_group->tus);
8760   struct signatured_type *iter;
8761   int i;
8762
8763   gdb_assert (len > 0);
8764   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8765
8766   pst->number_of_dependencies = len;
8767   pst->dependencies =
8768     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8769   for (i = 0;
8770        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8771        ++i)
8772     {
8773       gdb_assert (iter->per_cu.is_debug_types);
8774       pst->dependencies[i] = iter->per_cu.v.psymtab;
8775       iter->type_unit_group = tu_group;
8776     }
8777
8778   VEC_free (sig_type_ptr, tu_group->tus);
8779
8780   return 1;
8781 }
8782
8783 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8784    Build partial symbol tables for the .debug_types comp-units.  */
8785
8786 static void
8787 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8788 {
8789   if (! create_all_type_units (dwarf2_per_objfile))
8790     return;
8791
8792   build_type_psymtabs_1 (dwarf2_per_objfile);
8793 }
8794
8795 /* Traversal function for process_skeletonless_type_unit.
8796    Read a TU in a DWO file and build partial symbols for it.  */
8797
8798 static int
8799 process_skeletonless_type_unit (void **slot, void *info)
8800 {
8801   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8802   struct dwarf2_per_objfile *dwarf2_per_objfile
8803     = (struct dwarf2_per_objfile *) info;
8804   struct signatured_type find_entry, *entry;
8805
8806   /* If this TU doesn't exist in the global table, add it and read it in.  */
8807
8808   if (dwarf2_per_objfile->signatured_types == NULL)
8809     {
8810       dwarf2_per_objfile->signatured_types
8811         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8812     }
8813
8814   find_entry.signature = dwo_unit->signature;
8815   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8816                          INSERT);
8817   /* If we've already seen this type there's nothing to do.  What's happening
8818      is we're doing our own version of comdat-folding here.  */
8819   if (*slot != NULL)
8820     return 1;
8821
8822   /* This does the job that create_all_type_units would have done for
8823      this TU.  */
8824   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8825   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8826   *slot = entry;
8827
8828   /* This does the job that build_type_psymtabs_1 would have done.  */
8829   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8830                            build_type_psymtabs_reader, NULL);
8831
8832   return 1;
8833 }
8834
8835 /* Traversal function for process_skeletonless_type_units.  */
8836
8837 static int
8838 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8839 {
8840   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8841
8842   if (dwo_file->tus != NULL)
8843     {
8844       htab_traverse_noresize (dwo_file->tus,
8845                               process_skeletonless_type_unit, info);
8846     }
8847
8848   return 1;
8849 }
8850
8851 /* Scan all TUs of DWO files, verifying we've processed them.
8852    This is needed in case a TU was emitted without its skeleton.
8853    Note: This can't be done until we know what all the DWO files are.  */
8854
8855 static void
8856 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8857 {
8858   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8859   if (get_dwp_file (dwarf2_per_objfile) == NULL
8860       && dwarf2_per_objfile->dwo_files != NULL)
8861     {
8862       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8863                               process_dwo_file_for_skeletonless_type_units,
8864                               dwarf2_per_objfile);
8865     }
8866 }
8867
8868 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8869
8870 static void
8871 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8872 {
8873   int i;
8874
8875   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8876     {
8877       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8878       struct partial_symtab *pst = per_cu->v.psymtab;
8879       int j;
8880
8881       if (pst == NULL)
8882         continue;
8883
8884       for (j = 0; j < pst->number_of_dependencies; ++j)
8885         {
8886           /* Set the 'user' field only if it is not already set.  */
8887           if (pst->dependencies[j]->user == NULL)
8888             pst->dependencies[j]->user = pst;
8889         }
8890     }
8891 }
8892
8893 /* Build the partial symbol table by doing a quick pass through the
8894    .debug_info and .debug_abbrev sections.  */
8895
8896 static void
8897 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8898 {
8899   struct cleanup *back_to;
8900   int i;
8901   struct objfile *objfile = dwarf2_per_objfile->objfile;
8902
8903   if (dwarf_read_debug)
8904     {
8905       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8906                           objfile_name (objfile));
8907     }
8908
8909   dwarf2_per_objfile->reading_partial_symbols = 1;
8910
8911   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8912
8913   /* Any cached compilation units will be linked by the per-objfile
8914      read_in_chain.  Make sure to free them when we're done.  */
8915   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8916
8917   build_type_psymtabs (dwarf2_per_objfile);
8918
8919   create_all_comp_units (dwarf2_per_objfile);
8920
8921   /* Create a temporary address map on a temporary obstack.  We later
8922      copy this to the final obstack.  */
8923   auto_obstack temp_obstack;
8924
8925   scoped_restore save_psymtabs_addrmap
8926     = make_scoped_restore (&objfile->psymtabs_addrmap,
8927                            addrmap_create_mutable (&temp_obstack));
8928
8929   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8930     {
8931       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8932
8933       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8934     }
8935
8936   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8937   process_skeletonless_type_units (dwarf2_per_objfile);
8938
8939   /* Now that all TUs have been processed we can fill in the dependencies.  */
8940   if (dwarf2_per_objfile->type_unit_groups != NULL)
8941     {
8942       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8943                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8944     }
8945
8946   if (dwarf_read_debug)
8947     print_tu_stats (dwarf2_per_objfile);
8948
8949   set_partial_user (dwarf2_per_objfile);
8950
8951   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8952                                                     &objfile->objfile_obstack);
8953   /* At this point we want to keep the address map.  */
8954   save_psymtabs_addrmap.release ();
8955
8956   do_cleanups (back_to);
8957
8958   if (dwarf_read_debug)
8959     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8960                         objfile_name (objfile));
8961 }
8962
8963 /* die_reader_func for load_partial_comp_unit.  */
8964
8965 static void
8966 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8967                                const gdb_byte *info_ptr,
8968                                struct die_info *comp_unit_die,
8969                                int has_children,
8970                                void *data)
8971 {
8972   struct dwarf2_cu *cu = reader->cu;
8973
8974   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8975
8976   /* Check if comp unit has_children.
8977      If so, read the rest of the partial symbols from this comp unit.
8978      If not, there's no more debug_info for this comp unit.  */
8979   if (has_children)
8980     load_partial_dies (reader, info_ptr, 0);
8981 }
8982
8983 /* Load the partial DIEs for a secondary CU into memory.
8984    This is also used when rereading a primary CU with load_all_dies.  */
8985
8986 static void
8987 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8988 {
8989   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8990                            load_partial_comp_unit_reader, NULL);
8991 }
8992
8993 static void
8994 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8995                               struct dwarf2_section_info *section,
8996                               struct dwarf2_section_info *abbrev_section,
8997                               unsigned int is_dwz,
8998                               int *n_allocated,
8999                               int *n_comp_units,
9000                               struct dwarf2_per_cu_data ***all_comp_units)
9001 {
9002   const gdb_byte *info_ptr;
9003   struct objfile *objfile = dwarf2_per_objfile->objfile;
9004
9005   if (dwarf_read_debug)
9006     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
9007                         get_section_name (section),
9008                         get_section_file_name (section));
9009
9010   dwarf2_read_section (objfile, section);
9011
9012   info_ptr = section->buffer;
9013
9014   while (info_ptr < section->buffer + section->size)
9015     {
9016       struct dwarf2_per_cu_data *this_cu;
9017
9018       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
9019
9020       comp_unit_head cu_header;
9021       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
9022                                      abbrev_section, info_ptr,
9023                                      rcuh_kind::COMPILE);
9024
9025       /* Save the compilation unit for later lookup.  */
9026       if (cu_header.unit_type != DW_UT_type)
9027         {
9028           this_cu = XOBNEW (&objfile->objfile_obstack,
9029                             struct dwarf2_per_cu_data);
9030           memset (this_cu, 0, sizeof (*this_cu));
9031         }
9032       else
9033         {
9034           auto sig_type = XOBNEW (&objfile->objfile_obstack,
9035                                   struct signatured_type);
9036           memset (sig_type, 0, sizeof (*sig_type));
9037           sig_type->signature = cu_header.signature;
9038           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
9039           this_cu = &sig_type->per_cu;
9040         }
9041       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
9042       this_cu->sect_off = sect_off;
9043       this_cu->length = cu_header.length + cu_header.initial_length_size;
9044       this_cu->is_dwz = is_dwz;
9045       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
9046       this_cu->section = section;
9047
9048       if (*n_comp_units == *n_allocated)
9049         {
9050           *n_allocated *= 2;
9051           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
9052                                         *all_comp_units, *n_allocated);
9053         }
9054       (*all_comp_units)[*n_comp_units] = this_cu;
9055       ++*n_comp_units;
9056
9057       info_ptr = info_ptr + this_cu->length;
9058     }
9059 }
9060
9061 /* Create a list of all compilation units in OBJFILE.
9062    This is only done for -readnow and building partial symtabs.  */
9063
9064 static void
9065 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
9066 {
9067   int n_allocated;
9068   int n_comp_units;
9069   struct dwarf2_per_cu_data **all_comp_units;
9070   struct dwz_file *dwz;
9071   struct objfile *objfile = dwarf2_per_objfile->objfile;
9072
9073   n_comp_units = 0;
9074   n_allocated = 10;
9075   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9076
9077   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9078                                 &dwarf2_per_objfile->abbrev, 0,
9079                                 &n_allocated, &n_comp_units, &all_comp_units);
9080
9081   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9082   if (dwz != NULL)
9083     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9084                                   1, &n_allocated, &n_comp_units,
9085                                   &all_comp_units);
9086
9087   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9088                                                   struct dwarf2_per_cu_data *,
9089                                                   n_comp_units);
9090   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9091           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9092   xfree (all_comp_units);
9093   dwarf2_per_objfile->n_comp_units = n_comp_units;
9094 }
9095
9096 /* Process all loaded DIEs for compilation unit CU, starting at
9097    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9098    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9099    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9100    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9101
9102 static void
9103 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9104                       CORE_ADDR *highpc, int set_addrmap,
9105                       struct dwarf2_cu *cu)
9106 {
9107   struct partial_die_info *pdi;
9108
9109   /* Now, march along the PDI's, descending into ones which have
9110      interesting children but skipping the children of the other ones,
9111      until we reach the end of the compilation unit.  */
9112
9113   pdi = first_die;
9114
9115   while (pdi != NULL)
9116     {
9117       pdi->fixup (cu);
9118
9119       /* Anonymous namespaces or modules have no name but have interesting
9120          children, so we need to look at them.  Ditto for anonymous
9121          enums.  */
9122
9123       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9124           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9125           || pdi->tag == DW_TAG_imported_unit
9126           || pdi->tag == DW_TAG_inlined_subroutine)
9127         {
9128           switch (pdi->tag)
9129             {
9130             case DW_TAG_subprogram:
9131             case DW_TAG_inlined_subroutine:
9132               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9133               break;
9134             case DW_TAG_constant:
9135             case DW_TAG_variable:
9136             case DW_TAG_typedef:
9137             case DW_TAG_union_type:
9138               if (!pdi->is_declaration)
9139                 {
9140                   add_partial_symbol (pdi, cu);
9141                 }
9142               break;
9143             case DW_TAG_class_type:
9144             case DW_TAG_interface_type:
9145             case DW_TAG_structure_type:
9146               if (!pdi->is_declaration)
9147                 {
9148                   add_partial_symbol (pdi, cu);
9149                 }
9150               if (cu->language == language_rust && pdi->has_children)
9151                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9152                                       set_addrmap, cu);
9153               break;
9154             case DW_TAG_enumeration_type:
9155               if (!pdi->is_declaration)
9156                 add_partial_enumeration (pdi, cu);
9157               break;
9158             case DW_TAG_base_type:
9159             case DW_TAG_subrange_type:
9160               /* File scope base type definitions are added to the partial
9161                  symbol table.  */
9162               add_partial_symbol (pdi, cu);
9163               break;
9164             case DW_TAG_namespace:
9165               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9166               break;
9167             case DW_TAG_module:
9168               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9169               break;
9170             case DW_TAG_imported_unit:
9171               {
9172                 struct dwarf2_per_cu_data *per_cu;
9173
9174                 /* For now we don't handle imported units in type units.  */
9175                 if (cu->per_cu->is_debug_types)
9176                   {
9177                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9178                              " supported in type units [in module %s]"),
9179                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9180                   }
9181
9182                 per_cu = dwarf2_find_containing_comp_unit
9183                            (pdi->d.sect_off, pdi->is_dwz,
9184                             cu->per_cu->dwarf2_per_objfile);
9185
9186                 /* Go read the partial unit, if needed.  */
9187                 if (per_cu->v.psymtab == NULL)
9188                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9189
9190                 VEC_safe_push (dwarf2_per_cu_ptr,
9191                                cu->per_cu->imported_symtabs, per_cu);
9192               }
9193               break;
9194             case DW_TAG_imported_declaration:
9195               add_partial_symbol (pdi, cu);
9196               break;
9197             default:
9198               break;
9199             }
9200         }
9201
9202       /* If the die has a sibling, skip to the sibling.  */
9203
9204       pdi = pdi->die_sibling;
9205     }
9206 }
9207
9208 /* Functions used to compute the fully scoped name of a partial DIE.
9209
9210    Normally, this is simple.  For C++, the parent DIE's fully scoped
9211    name is concatenated with "::" and the partial DIE's name.
9212    Enumerators are an exception; they use the scope of their parent
9213    enumeration type, i.e. the name of the enumeration type is not
9214    prepended to the enumerator.
9215
9216    There are two complexities.  One is DW_AT_specification; in this
9217    case "parent" means the parent of the target of the specification,
9218    instead of the direct parent of the DIE.  The other is compilers
9219    which do not emit DW_TAG_namespace; in this case we try to guess
9220    the fully qualified name of structure types from their members'
9221    linkage names.  This must be done using the DIE's children rather
9222    than the children of any DW_AT_specification target.  We only need
9223    to do this for structures at the top level, i.e. if the target of
9224    any DW_AT_specification (if any; otherwise the DIE itself) does not
9225    have a parent.  */
9226
9227 /* Compute the scope prefix associated with PDI's parent, in
9228    compilation unit CU.  The result will be allocated on CU's
9229    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9230    field.  NULL is returned if no prefix is necessary.  */
9231 static const char *
9232 partial_die_parent_scope (struct partial_die_info *pdi,
9233                           struct dwarf2_cu *cu)
9234 {
9235   const char *grandparent_scope;
9236   struct partial_die_info *parent, *real_pdi;
9237
9238   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9239      then this means the parent of the specification DIE.  */
9240
9241   real_pdi = pdi;
9242   while (real_pdi->has_specification)
9243     real_pdi = find_partial_die (real_pdi->spec_offset,
9244                                  real_pdi->spec_is_dwz, cu);
9245
9246   parent = real_pdi->die_parent;
9247   if (parent == NULL)
9248     return NULL;
9249
9250   if (parent->scope_set)
9251     return parent->scope;
9252
9253   parent->fixup (cu);
9254
9255   grandparent_scope = partial_die_parent_scope (parent, cu);
9256
9257   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9258      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9259      Work around this problem here.  */
9260   if (cu->language == language_cplus
9261       && parent->tag == DW_TAG_namespace
9262       && strcmp (parent->name, "::") == 0
9263       && grandparent_scope == NULL)
9264     {
9265       parent->scope = NULL;
9266       parent->scope_set = 1;
9267       return NULL;
9268     }
9269
9270   if (pdi->tag == DW_TAG_enumerator)
9271     /* Enumerators should not get the name of the enumeration as a prefix.  */
9272     parent->scope = grandparent_scope;
9273   else if (parent->tag == DW_TAG_namespace
9274       || parent->tag == DW_TAG_module
9275       || parent->tag == DW_TAG_structure_type
9276       || parent->tag == DW_TAG_class_type
9277       || parent->tag == DW_TAG_interface_type
9278       || parent->tag == DW_TAG_union_type
9279       || parent->tag == DW_TAG_enumeration_type)
9280     {
9281       if (grandparent_scope == NULL)
9282         parent->scope = parent->name;
9283       else
9284         parent->scope = typename_concat (&cu->comp_unit_obstack,
9285                                          grandparent_scope,
9286                                          parent->name, 0, cu);
9287     }
9288   else
9289     {
9290       /* FIXME drow/2004-04-01: What should we be doing with
9291          function-local names?  For partial symbols, we should probably be
9292          ignoring them.  */
9293       complaint (&symfile_complaints,
9294                  _("unhandled containing DIE tag %d for DIE at %s"),
9295                  parent->tag, sect_offset_str (pdi->sect_off));
9296       parent->scope = grandparent_scope;
9297     }
9298
9299   parent->scope_set = 1;
9300   return parent->scope;
9301 }
9302
9303 /* Return the fully scoped name associated with PDI, from compilation unit
9304    CU.  The result will be allocated with malloc.  */
9305
9306 static char *
9307 partial_die_full_name (struct partial_die_info *pdi,
9308                        struct dwarf2_cu *cu)
9309 {
9310   const char *parent_scope;
9311
9312   /* If this is a template instantiation, we can not work out the
9313      template arguments from partial DIEs.  So, unfortunately, we have
9314      to go through the full DIEs.  At least any work we do building
9315      types here will be reused if full symbols are loaded later.  */
9316   if (pdi->has_template_arguments)
9317     {
9318       pdi->fixup (cu);
9319
9320       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9321         {
9322           struct die_info *die;
9323           struct attribute attr;
9324           struct dwarf2_cu *ref_cu = cu;
9325
9326           /* DW_FORM_ref_addr is using section offset.  */
9327           attr.name = (enum dwarf_attribute) 0;
9328           attr.form = DW_FORM_ref_addr;
9329           attr.u.unsnd = to_underlying (pdi->sect_off);
9330           die = follow_die_ref (NULL, &attr, &ref_cu);
9331
9332           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9333         }
9334     }
9335
9336   parent_scope = partial_die_parent_scope (pdi, cu);
9337   if (parent_scope == NULL)
9338     return NULL;
9339   else
9340     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9341 }
9342
9343 static void
9344 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9345 {
9346   struct dwarf2_per_objfile *dwarf2_per_objfile
9347     = cu->per_cu->dwarf2_per_objfile;
9348   struct objfile *objfile = dwarf2_per_objfile->objfile;
9349   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9350   CORE_ADDR addr = 0;
9351   const char *actual_name = NULL;
9352   CORE_ADDR baseaddr;
9353   char *built_actual_name;
9354
9355   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9356
9357   built_actual_name = partial_die_full_name (pdi, cu);
9358   if (built_actual_name != NULL)
9359     actual_name = built_actual_name;
9360
9361   if (actual_name == NULL)
9362     actual_name = pdi->name;
9363
9364   switch (pdi->tag)
9365     {
9366     case DW_TAG_inlined_subroutine:
9367     case DW_TAG_subprogram:
9368       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9369       if (pdi->is_external || cu->language == language_ada)
9370         {
9371           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9372              of the global scope.  But in Ada, we want to be able to access
9373              nested procedures globally.  So all Ada subprograms are stored
9374              in the global scope.  */
9375           add_psymbol_to_list (actual_name, strlen (actual_name),
9376                                built_actual_name != NULL,
9377                                VAR_DOMAIN, LOC_BLOCK,
9378                                &objfile->global_psymbols,
9379                                addr, cu->language, objfile);
9380         }
9381       else
9382         {
9383           add_psymbol_to_list (actual_name, strlen (actual_name),
9384                                built_actual_name != NULL,
9385                                VAR_DOMAIN, LOC_BLOCK,
9386                                &objfile->static_psymbols,
9387                                addr, cu->language, objfile);
9388         }
9389
9390       if (pdi->main_subprogram && actual_name != NULL)
9391         set_objfile_main_name (objfile, actual_name, cu->language);
9392       break;
9393     case DW_TAG_constant:
9394       {
9395         std::vector<partial_symbol *> *list;
9396
9397         if (pdi->is_external)
9398           list = &objfile->global_psymbols;
9399         else
9400           list = &objfile->static_psymbols;
9401         add_psymbol_to_list (actual_name, strlen (actual_name),
9402                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9403                              list, 0, cu->language, objfile);
9404       }
9405       break;
9406     case DW_TAG_variable:
9407       if (pdi->d.locdesc)
9408         addr = decode_locdesc (pdi->d.locdesc, cu);
9409
9410       if (pdi->d.locdesc
9411           && addr == 0
9412           && !dwarf2_per_objfile->has_section_at_zero)
9413         {
9414           /* A global or static variable may also have been stripped
9415              out by the linker if unused, in which case its address
9416              will be nullified; do not add such variables into partial
9417              symbol table then.  */
9418         }
9419       else if (pdi->is_external)
9420         {
9421           /* Global Variable.
9422              Don't enter into the minimal symbol tables as there is
9423              a minimal symbol table entry from the ELF symbols already.
9424              Enter into partial symbol table if it has a location
9425              descriptor or a type.
9426              If the location descriptor is missing, new_symbol will create
9427              a LOC_UNRESOLVED symbol, the address of the variable will then
9428              be determined from the minimal symbol table whenever the variable
9429              is referenced.
9430              The address for the partial symbol table entry is not
9431              used by GDB, but it comes in handy for debugging partial symbol
9432              table building.  */
9433
9434           if (pdi->d.locdesc || pdi->has_type)
9435             add_psymbol_to_list (actual_name, strlen (actual_name),
9436                                  built_actual_name != NULL,
9437                                  VAR_DOMAIN, LOC_STATIC,
9438                                  &objfile->global_psymbols,
9439                                  addr + baseaddr,
9440                                  cu->language, objfile);
9441         }
9442       else
9443         {
9444           int has_loc = pdi->d.locdesc != NULL;
9445
9446           /* Static Variable.  Skip symbols whose value we cannot know (those
9447              without location descriptors or constant values).  */
9448           if (!has_loc && !pdi->has_const_value)
9449             {
9450               xfree (built_actual_name);
9451               return;
9452             }
9453
9454           add_psymbol_to_list (actual_name, strlen (actual_name),
9455                                built_actual_name != NULL,
9456                                VAR_DOMAIN, LOC_STATIC,
9457                                &objfile->static_psymbols,
9458                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9459                                cu->language, objfile);
9460         }
9461       break;
9462     case DW_TAG_typedef:
9463     case DW_TAG_base_type:
9464     case DW_TAG_subrange_type:
9465       add_psymbol_to_list (actual_name, strlen (actual_name),
9466                            built_actual_name != NULL,
9467                            VAR_DOMAIN, LOC_TYPEDEF,
9468                            &objfile->static_psymbols,
9469                            0, cu->language, objfile);
9470       break;
9471     case DW_TAG_imported_declaration:
9472     case DW_TAG_namespace:
9473       add_psymbol_to_list (actual_name, strlen (actual_name),
9474                            built_actual_name != NULL,
9475                            VAR_DOMAIN, LOC_TYPEDEF,
9476                            &objfile->global_psymbols,
9477                            0, cu->language, objfile);
9478       break;
9479     case DW_TAG_module:
9480       add_psymbol_to_list (actual_name, strlen (actual_name),
9481                            built_actual_name != NULL,
9482                            MODULE_DOMAIN, LOC_TYPEDEF,
9483                            &objfile->global_psymbols,
9484                            0, cu->language, objfile);
9485       break;
9486     case DW_TAG_class_type:
9487     case DW_TAG_interface_type:
9488     case DW_TAG_structure_type:
9489     case DW_TAG_union_type:
9490     case DW_TAG_enumeration_type:
9491       /* Skip external references.  The DWARF standard says in the section
9492          about "Structure, Union, and Class Type Entries": "An incomplete
9493          structure, union or class type is represented by a structure,
9494          union or class entry that does not have a byte size attribute
9495          and that has a DW_AT_declaration attribute."  */
9496       if (!pdi->has_byte_size && pdi->is_declaration)
9497         {
9498           xfree (built_actual_name);
9499           return;
9500         }
9501
9502       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9503          static vs. global.  */
9504       add_psymbol_to_list (actual_name, strlen (actual_name),
9505                            built_actual_name != NULL,
9506                            STRUCT_DOMAIN, LOC_TYPEDEF,
9507                            cu->language == language_cplus
9508                            ? &objfile->global_psymbols
9509                            : &objfile->static_psymbols,
9510                            0, cu->language, objfile);
9511
9512       break;
9513     case DW_TAG_enumerator:
9514       add_psymbol_to_list (actual_name, strlen (actual_name),
9515                            built_actual_name != NULL,
9516                            VAR_DOMAIN, LOC_CONST,
9517                            cu->language == language_cplus
9518                            ? &objfile->global_psymbols
9519                            : &objfile->static_psymbols,
9520                            0, cu->language, objfile);
9521       break;
9522     default:
9523       break;
9524     }
9525
9526   xfree (built_actual_name);
9527 }
9528
9529 /* Read a partial die corresponding to a namespace; also, add a symbol
9530    corresponding to that namespace to the symbol table.  NAMESPACE is
9531    the name of the enclosing namespace.  */
9532
9533 static void
9534 add_partial_namespace (struct partial_die_info *pdi,
9535                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9536                        int set_addrmap, struct dwarf2_cu *cu)
9537 {
9538   /* Add a symbol for the namespace.  */
9539
9540   add_partial_symbol (pdi, cu);
9541
9542   /* Now scan partial symbols in that namespace.  */
9543
9544   if (pdi->has_children)
9545     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9546 }
9547
9548 /* Read a partial die corresponding to a Fortran module.  */
9549
9550 static void
9551 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9552                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9553 {
9554   /* Add a symbol for the namespace.  */
9555
9556   add_partial_symbol (pdi, cu);
9557
9558   /* Now scan partial symbols in that module.  */
9559
9560   if (pdi->has_children)
9561     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9562 }
9563
9564 /* Read a partial die corresponding to a subprogram or an inlined
9565    subprogram and create a partial symbol for that subprogram.
9566    When the CU language allows it, this routine also defines a partial
9567    symbol for each nested subprogram that this subprogram contains.
9568    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9569    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9570
9571    PDI may also be a lexical block, in which case we simply search
9572    recursively for subprograms defined inside that lexical block.
9573    Again, this is only performed when the CU language allows this
9574    type of definitions.  */
9575
9576 static void
9577 add_partial_subprogram (struct partial_die_info *pdi,
9578                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9579                         int set_addrmap, struct dwarf2_cu *cu)
9580 {
9581   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9582     {
9583       if (pdi->has_pc_info)
9584         {
9585           if (pdi->lowpc < *lowpc)
9586             *lowpc = pdi->lowpc;
9587           if (pdi->highpc > *highpc)
9588             *highpc = pdi->highpc;
9589           if (set_addrmap)
9590             {
9591               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9592               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9593               CORE_ADDR baseaddr;
9594               CORE_ADDR highpc;
9595               CORE_ADDR lowpc;
9596
9597               baseaddr = ANOFFSET (objfile->section_offsets,
9598                                    SECT_OFF_TEXT (objfile));
9599               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9600                                                   pdi->lowpc + baseaddr);
9601               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9602                                                    pdi->highpc + baseaddr);
9603               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9604                                  cu->per_cu->v.psymtab);
9605             }
9606         }
9607
9608       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9609         {
9610           if (!pdi->is_declaration)
9611             /* Ignore subprogram DIEs that do not have a name, they are
9612                illegal.  Do not emit a complaint at this point, we will
9613                do so when we convert this psymtab into a symtab.  */
9614             if (pdi->name)
9615               add_partial_symbol (pdi, cu);
9616         }
9617     }
9618
9619   if (! pdi->has_children)
9620     return;
9621
9622   if (cu->language == language_ada)
9623     {
9624       pdi = pdi->die_child;
9625       while (pdi != NULL)
9626         {
9627           pdi->fixup (cu);
9628           if (pdi->tag == DW_TAG_subprogram
9629               || pdi->tag == DW_TAG_inlined_subroutine
9630               || pdi->tag == DW_TAG_lexical_block)
9631             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9632           pdi = pdi->die_sibling;
9633         }
9634     }
9635 }
9636
9637 /* Read a partial die corresponding to an enumeration type.  */
9638
9639 static void
9640 add_partial_enumeration (struct partial_die_info *enum_pdi,
9641                          struct dwarf2_cu *cu)
9642 {
9643   struct partial_die_info *pdi;
9644
9645   if (enum_pdi->name != NULL)
9646     add_partial_symbol (enum_pdi, cu);
9647
9648   pdi = enum_pdi->die_child;
9649   while (pdi)
9650     {
9651       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9652         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9653       else
9654         add_partial_symbol (pdi, cu);
9655       pdi = pdi->die_sibling;
9656     }
9657 }
9658
9659 /* Return the initial uleb128 in the die at INFO_PTR.  */
9660
9661 static unsigned int
9662 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9663 {
9664   unsigned int bytes_read;
9665
9666   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9667 }
9668
9669 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9670    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9671
9672    Return the corresponding abbrev, or NULL if the number is zero (indicating
9673    an empty DIE).  In either case *BYTES_READ will be set to the length of
9674    the initial number.  */
9675
9676 static struct abbrev_info *
9677 peek_die_abbrev (const die_reader_specs &reader,
9678                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9679 {
9680   dwarf2_cu *cu = reader.cu;
9681   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9682   unsigned int abbrev_number
9683     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9684
9685   if (abbrev_number == 0)
9686     return NULL;
9687
9688   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9689   if (!abbrev)
9690     {
9691       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9692                " at offset %s [in module %s]"),
9693              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9694              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9695     }
9696
9697   return abbrev;
9698 }
9699
9700 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9701    Returns a pointer to the end of a series of DIEs, terminated by an empty
9702    DIE.  Any children of the skipped DIEs will also be skipped.  */
9703
9704 static const gdb_byte *
9705 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9706 {
9707   while (1)
9708     {
9709       unsigned int bytes_read;
9710       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9711
9712       if (abbrev == NULL)
9713         return info_ptr + bytes_read;
9714       else
9715         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9716     }
9717 }
9718
9719 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9720    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9721    abbrev corresponding to that skipped uleb128 should be passed in
9722    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9723    children.  */
9724
9725 static const gdb_byte *
9726 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9727               struct abbrev_info *abbrev)
9728 {
9729   unsigned int bytes_read;
9730   struct attribute attr;
9731   bfd *abfd = reader->abfd;
9732   struct dwarf2_cu *cu = reader->cu;
9733   const gdb_byte *buffer = reader->buffer;
9734   const gdb_byte *buffer_end = reader->buffer_end;
9735   unsigned int form, i;
9736
9737   for (i = 0; i < abbrev->num_attrs; i++)
9738     {
9739       /* The only abbrev we care about is DW_AT_sibling.  */
9740       if (abbrev->attrs[i].name == DW_AT_sibling)
9741         {
9742           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9743           if (attr.form == DW_FORM_ref_addr)
9744             complaint (&symfile_complaints,
9745                        _("ignoring absolute DW_AT_sibling"));
9746           else
9747             {
9748               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9749               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9750
9751               if (sibling_ptr < info_ptr)
9752                 complaint (&symfile_complaints,
9753                            _("DW_AT_sibling points backwards"));
9754               else if (sibling_ptr > reader->buffer_end)
9755                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9756               else
9757                 return sibling_ptr;
9758             }
9759         }
9760
9761       /* If it isn't DW_AT_sibling, skip this attribute.  */
9762       form = abbrev->attrs[i].form;
9763     skip_attribute:
9764       switch (form)
9765         {
9766         case DW_FORM_ref_addr:
9767           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9768              and later it is offset sized.  */
9769           if (cu->header.version == 2)
9770             info_ptr += cu->header.addr_size;
9771           else
9772             info_ptr += cu->header.offset_size;
9773           break;
9774         case DW_FORM_GNU_ref_alt:
9775           info_ptr += cu->header.offset_size;
9776           break;
9777         case DW_FORM_addr:
9778           info_ptr += cu->header.addr_size;
9779           break;
9780         case DW_FORM_data1:
9781         case DW_FORM_ref1:
9782         case DW_FORM_flag:
9783           info_ptr += 1;
9784           break;
9785         case DW_FORM_flag_present:
9786         case DW_FORM_implicit_const:
9787           break;
9788         case DW_FORM_data2:
9789         case DW_FORM_ref2:
9790           info_ptr += 2;
9791           break;
9792         case DW_FORM_data4:
9793         case DW_FORM_ref4:
9794           info_ptr += 4;
9795           break;
9796         case DW_FORM_data8:
9797         case DW_FORM_ref8:
9798         case DW_FORM_ref_sig8:
9799           info_ptr += 8;
9800           break;
9801         case DW_FORM_data16:
9802           info_ptr += 16;
9803           break;
9804         case DW_FORM_string:
9805           read_direct_string (abfd, info_ptr, &bytes_read);
9806           info_ptr += bytes_read;
9807           break;
9808         case DW_FORM_sec_offset:
9809         case DW_FORM_strp:
9810         case DW_FORM_GNU_strp_alt:
9811           info_ptr += cu->header.offset_size;
9812           break;
9813         case DW_FORM_exprloc:
9814         case DW_FORM_block:
9815           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9816           info_ptr += bytes_read;
9817           break;
9818         case DW_FORM_block1:
9819           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9820           break;
9821         case DW_FORM_block2:
9822           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9823           break;
9824         case DW_FORM_block4:
9825           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9826           break;
9827         case DW_FORM_sdata:
9828         case DW_FORM_udata:
9829         case DW_FORM_ref_udata:
9830         case DW_FORM_GNU_addr_index:
9831         case DW_FORM_GNU_str_index:
9832           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9833           break;
9834         case DW_FORM_indirect:
9835           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9836           info_ptr += bytes_read;
9837           /* We need to continue parsing from here, so just go back to
9838              the top.  */
9839           goto skip_attribute;
9840
9841         default:
9842           error (_("Dwarf Error: Cannot handle %s "
9843                    "in DWARF reader [in module %s]"),
9844                  dwarf_form_name (form),
9845                  bfd_get_filename (abfd));
9846         }
9847     }
9848
9849   if (abbrev->has_children)
9850     return skip_children (reader, info_ptr);
9851   else
9852     return info_ptr;
9853 }
9854
9855 /* Locate ORIG_PDI's sibling.
9856    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9857
9858 static const gdb_byte *
9859 locate_pdi_sibling (const struct die_reader_specs *reader,
9860                     struct partial_die_info *orig_pdi,
9861                     const gdb_byte *info_ptr)
9862 {
9863   /* Do we know the sibling already?  */
9864
9865   if (orig_pdi->sibling)
9866     return orig_pdi->sibling;
9867
9868   /* Are there any children to deal with?  */
9869
9870   if (!orig_pdi->has_children)
9871     return info_ptr;
9872
9873   /* Skip the children the long way.  */
9874
9875   return skip_children (reader, info_ptr);
9876 }
9877
9878 /* Expand this partial symbol table into a full symbol table.  SELF is
9879    not NULL.  */
9880
9881 static void
9882 dwarf2_read_symtab (struct partial_symtab *self,
9883                     struct objfile *objfile)
9884 {
9885   struct dwarf2_per_objfile *dwarf2_per_objfile
9886     = get_dwarf2_per_objfile (objfile);
9887
9888   if (self->readin)
9889     {
9890       warning (_("bug: psymtab for %s is already read in."),
9891                self->filename);
9892     }
9893   else
9894     {
9895       if (info_verbose)
9896         {
9897           printf_filtered (_("Reading in symbols for %s..."),
9898                            self->filename);
9899           gdb_flush (gdb_stdout);
9900         }
9901
9902       /* If this psymtab is constructed from a debug-only objfile, the
9903          has_section_at_zero flag will not necessarily be correct.  We
9904          can get the correct value for this flag by looking at the data
9905          associated with the (presumably stripped) associated objfile.  */
9906       if (objfile->separate_debug_objfile_backlink)
9907         {
9908           struct dwarf2_per_objfile *dpo_backlink
9909             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9910
9911           dwarf2_per_objfile->has_section_at_zero
9912             = dpo_backlink->has_section_at_zero;
9913         }
9914
9915       dwarf2_per_objfile->reading_partial_symbols = 0;
9916
9917       psymtab_to_symtab_1 (self);
9918
9919       /* Finish up the debug error message.  */
9920       if (info_verbose)
9921         printf_filtered (_("done.\n"));
9922     }
9923
9924   process_cu_includes (dwarf2_per_objfile);
9925 }
9926 \f
9927 /* Reading in full CUs.  */
9928
9929 /* Add PER_CU to the queue.  */
9930
9931 static void
9932 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9933                  enum language pretend_language)
9934 {
9935   struct dwarf2_queue_item *item;
9936
9937   per_cu->queued = 1;
9938   item = XNEW (struct dwarf2_queue_item);
9939   item->per_cu = per_cu;
9940   item->pretend_language = pretend_language;
9941   item->next = NULL;
9942
9943   if (dwarf2_queue == NULL)
9944     dwarf2_queue = item;
9945   else
9946     dwarf2_queue_tail->next = item;
9947
9948   dwarf2_queue_tail = item;
9949 }
9950
9951 /* If PER_CU is not yet queued, add it to the queue.
9952    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9953    dependency.
9954    The result is non-zero if PER_CU was queued, otherwise the result is zero
9955    meaning either PER_CU is already queued or it is already loaded.
9956
9957    N.B. There is an invariant here that if a CU is queued then it is loaded.
9958    The caller is required to load PER_CU if we return non-zero.  */
9959
9960 static int
9961 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9962                        struct dwarf2_per_cu_data *per_cu,
9963                        enum language pretend_language)
9964 {
9965   /* We may arrive here during partial symbol reading, if we need full
9966      DIEs to process an unusual case (e.g. template arguments).  Do
9967      not queue PER_CU, just tell our caller to load its DIEs.  */
9968   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9969     {
9970       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9971         return 1;
9972       return 0;
9973     }
9974
9975   /* Mark the dependence relation so that we don't flush PER_CU
9976      too early.  */
9977   if (dependent_cu != NULL)
9978     dwarf2_add_dependence (dependent_cu, per_cu);
9979
9980   /* If it's already on the queue, we have nothing to do.  */
9981   if (per_cu->queued)
9982     return 0;
9983
9984   /* If the compilation unit is already loaded, just mark it as
9985      used.  */
9986   if (per_cu->cu != NULL)
9987     {
9988       per_cu->cu->last_used = 0;
9989       return 0;
9990     }
9991
9992   /* Add it to the queue.  */
9993   queue_comp_unit (per_cu, pretend_language);
9994
9995   return 1;
9996 }
9997
9998 /* Process the queue.  */
9999
10000 static void
10001 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
10002 {
10003   struct dwarf2_queue_item *item, *next_item;
10004
10005   if (dwarf_read_debug)
10006     {
10007       fprintf_unfiltered (gdb_stdlog,
10008                           "Expanding one or more symtabs of objfile %s ...\n",
10009                           objfile_name (dwarf2_per_objfile->objfile));
10010     }
10011
10012   /* The queue starts out with one item, but following a DIE reference
10013      may load a new CU, adding it to the end of the queue.  */
10014   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
10015     {
10016       if ((dwarf2_per_objfile->using_index
10017            ? !item->per_cu->v.quick->compunit_symtab
10018            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
10019           /* Skip dummy CUs.  */
10020           && item->per_cu->cu != NULL)
10021         {
10022           struct dwarf2_per_cu_data *per_cu = item->per_cu;
10023           unsigned int debug_print_threshold;
10024           char buf[100];
10025
10026           if (per_cu->is_debug_types)
10027             {
10028               struct signatured_type *sig_type =
10029                 (struct signatured_type *) per_cu;
10030
10031               sprintf (buf, "TU %s at offset %s",
10032                        hex_string (sig_type->signature),
10033                        sect_offset_str (per_cu->sect_off));
10034               /* There can be 100s of TUs.
10035                  Only print them in verbose mode.  */
10036               debug_print_threshold = 2;
10037             }
10038           else
10039             {
10040               sprintf (buf, "CU at offset %s",
10041                        sect_offset_str (per_cu->sect_off));
10042               debug_print_threshold = 1;
10043             }
10044
10045           if (dwarf_read_debug >= debug_print_threshold)
10046             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
10047
10048           if (per_cu->is_debug_types)
10049             process_full_type_unit (per_cu, item->pretend_language);
10050           else
10051             process_full_comp_unit (per_cu, item->pretend_language);
10052
10053           if (dwarf_read_debug >= debug_print_threshold)
10054             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
10055         }
10056
10057       item->per_cu->queued = 0;
10058       next_item = item->next;
10059       xfree (item);
10060     }
10061
10062   dwarf2_queue_tail = NULL;
10063
10064   if (dwarf_read_debug)
10065     {
10066       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
10067                           objfile_name (dwarf2_per_objfile->objfile));
10068     }
10069 }
10070
10071 /* Read in full symbols for PST, and anything it depends on.  */
10072
10073 static void
10074 psymtab_to_symtab_1 (struct partial_symtab *pst)
10075 {
10076   struct dwarf2_per_cu_data *per_cu;
10077   int i;
10078
10079   if (pst->readin)
10080     return;
10081
10082   for (i = 0; i < pst->number_of_dependencies; i++)
10083     if (!pst->dependencies[i]->readin
10084         && pst->dependencies[i]->user == NULL)
10085       {
10086         /* Inform about additional files that need to be read in.  */
10087         if (info_verbose)
10088           {
10089             /* FIXME: i18n: Need to make this a single string.  */
10090             fputs_filtered (" ", gdb_stdout);
10091             wrap_here ("");
10092             fputs_filtered ("and ", gdb_stdout);
10093             wrap_here ("");
10094             printf_filtered ("%s...", pst->dependencies[i]->filename);
10095             wrap_here ("");     /* Flush output.  */
10096             gdb_flush (gdb_stdout);
10097           }
10098         psymtab_to_symtab_1 (pst->dependencies[i]);
10099       }
10100
10101   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10102
10103   if (per_cu == NULL)
10104     {
10105       /* It's an include file, no symbols to read for it.
10106          Everything is in the parent symtab.  */
10107       pst->readin = 1;
10108       return;
10109     }
10110
10111   dw2_do_instantiate_symtab (per_cu);
10112 }
10113
10114 /* Trivial hash function for die_info: the hash value of a DIE
10115    is its offset in .debug_info for this objfile.  */
10116
10117 static hashval_t
10118 die_hash (const void *item)
10119 {
10120   const struct die_info *die = (const struct die_info *) item;
10121
10122   return to_underlying (die->sect_off);
10123 }
10124
10125 /* Trivial comparison function for die_info structures: two DIEs
10126    are equal if they have the same offset.  */
10127
10128 static int
10129 die_eq (const void *item_lhs, const void *item_rhs)
10130 {
10131   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10132   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10133
10134   return die_lhs->sect_off == die_rhs->sect_off;
10135 }
10136
10137 /* die_reader_func for load_full_comp_unit.
10138    This is identical to read_signatured_type_reader,
10139    but is kept separate for now.  */
10140
10141 static void
10142 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10143                             const gdb_byte *info_ptr,
10144                             struct die_info *comp_unit_die,
10145                             int has_children,
10146                             void *data)
10147 {
10148   struct dwarf2_cu *cu = reader->cu;
10149   enum language *language_ptr = (enum language *) data;
10150
10151   gdb_assert (cu->die_hash == NULL);
10152   cu->die_hash =
10153     htab_create_alloc_ex (cu->header.length / 12,
10154                           die_hash,
10155                           die_eq,
10156                           NULL,
10157                           &cu->comp_unit_obstack,
10158                           hashtab_obstack_allocate,
10159                           dummy_obstack_deallocate);
10160
10161   if (has_children)
10162     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10163                                                   &info_ptr, comp_unit_die);
10164   cu->dies = comp_unit_die;
10165   /* comp_unit_die is not stored in die_hash, no need.  */
10166
10167   /* We try not to read any attributes in this function, because not
10168      all CUs needed for references have been loaded yet, and symbol
10169      table processing isn't initialized.  But we have to set the CU language,
10170      or we won't be able to build types correctly.
10171      Similarly, if we do not read the producer, we can not apply
10172      producer-specific interpretation.  */
10173   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10174 }
10175
10176 /* Load the DIEs associated with PER_CU into memory.  */
10177
10178 static void
10179 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10180                      enum language pretend_language)
10181 {
10182   gdb_assert (! this_cu->is_debug_types);
10183
10184   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10185                            load_full_comp_unit_reader, &pretend_language);
10186 }
10187
10188 /* Add a DIE to the delayed physname list.  */
10189
10190 static void
10191 add_to_method_list (struct type *type, int fnfield_index, int index,
10192                     const char *name, struct die_info *die,
10193                     struct dwarf2_cu *cu)
10194 {
10195   struct delayed_method_info mi;
10196   mi.type = type;
10197   mi.fnfield_index = fnfield_index;
10198   mi.index = index;
10199   mi.name = name;
10200   mi.die = die;
10201   cu->method_list.push_back (mi);
10202 }
10203
10204 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10205    "const" / "volatile".  If so, decrements LEN by the length of the
10206    modifier and return true.  Otherwise return false.  */
10207
10208 template<size_t N>
10209 static bool
10210 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10211 {
10212   size_t mod_len = sizeof (mod) - 1;
10213   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10214     {
10215       len -= mod_len;
10216       return true;
10217     }
10218   return false;
10219 }
10220
10221 /* Compute the physnames of any methods on the CU's method list.
10222
10223    The computation of method physnames is delayed in order to avoid the
10224    (bad) condition that one of the method's formal parameters is of an as yet
10225    incomplete type.  */
10226
10227 static void
10228 compute_delayed_physnames (struct dwarf2_cu *cu)
10229 {
10230   /* Only C++ delays computing physnames.  */
10231   if (cu->method_list.empty ())
10232     return;
10233   gdb_assert (cu->language == language_cplus);
10234
10235   for (struct delayed_method_info &mi : cu->method_list)
10236     {
10237       const char *physname;
10238       struct fn_fieldlist *fn_flp
10239         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10240       physname = dwarf2_physname (mi.name, mi.die, cu);
10241       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10242         = physname ? physname : "";
10243
10244       /* Since there's no tag to indicate whether a method is a
10245          const/volatile overload, extract that information out of the
10246          demangled name.  */
10247       if (physname != NULL)
10248         {
10249           size_t len = strlen (physname);
10250
10251           while (1)
10252             {
10253               if (physname[len] == ')') /* shortcut */
10254                 break;
10255               else if (check_modifier (physname, len, " const"))
10256                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10257               else if (check_modifier (physname, len, " volatile"))
10258                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10259               else
10260                 break;
10261             }
10262         }
10263     }
10264
10265   /* The list is no longer needed.  */
10266   cu->method_list.clear ();
10267 }
10268
10269 /* Go objects should be embedded in a DW_TAG_module DIE,
10270    and it's not clear if/how imported objects will appear.
10271    To keep Go support simple until that's worked out,
10272    go back through what we've read and create something usable.
10273    We could do this while processing each DIE, and feels kinda cleaner,
10274    but that way is more invasive.
10275    This is to, for example, allow the user to type "p var" or "b main"
10276    without having to specify the package name, and allow lookups
10277    of module.object to work in contexts that use the expression
10278    parser.  */
10279
10280 static void
10281 fixup_go_packaging (struct dwarf2_cu *cu)
10282 {
10283   char *package_name = NULL;
10284   struct pending *list;
10285   int i;
10286
10287   for (list = global_symbols; list != NULL; list = list->next)
10288     {
10289       for (i = 0; i < list->nsyms; ++i)
10290         {
10291           struct symbol *sym = list->symbol[i];
10292
10293           if (SYMBOL_LANGUAGE (sym) == language_go
10294               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10295             {
10296               char *this_package_name = go_symbol_package_name (sym);
10297
10298               if (this_package_name == NULL)
10299                 continue;
10300               if (package_name == NULL)
10301                 package_name = this_package_name;
10302               else
10303                 {
10304                   struct objfile *objfile
10305                     = cu->per_cu->dwarf2_per_objfile->objfile;
10306                   if (strcmp (package_name, this_package_name) != 0)
10307                     complaint (&symfile_complaints,
10308                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10309                                (symbol_symtab (sym) != NULL
10310                                 ? symtab_to_filename_for_display
10311                                     (symbol_symtab (sym))
10312                                 : objfile_name (objfile)),
10313                                this_package_name, package_name);
10314                   xfree (this_package_name);
10315                 }
10316             }
10317         }
10318     }
10319
10320   if (package_name != NULL)
10321     {
10322       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10323       const char *saved_package_name
10324         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10325                                         package_name,
10326                                         strlen (package_name));
10327       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10328                                      saved_package_name);
10329       struct symbol *sym;
10330
10331       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10332
10333       sym = allocate_symbol (objfile);
10334       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10335       SYMBOL_SET_NAMES (sym, saved_package_name,
10336                         strlen (saved_package_name), 0, objfile);
10337       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10338          e.g., "main" finds the "main" module and not C's main().  */
10339       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10340       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10341       SYMBOL_TYPE (sym) = type;
10342
10343       add_symbol_to_list (sym, &global_symbols);
10344
10345       xfree (package_name);
10346     }
10347 }
10348
10349 /* Allocate a fully-qualified name consisting of the two parts on the
10350    obstack.  */
10351
10352 static const char *
10353 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
10354 {
10355   return obconcat (obstack, p1, "::", p2, (char *) NULL);
10356 }
10357
10358 /* A helper that allocates a struct discriminant_info to attach to a
10359    union type.  */
10360
10361 static struct discriminant_info *
10362 alloc_discriminant_info (struct type *type, int discriminant_index,
10363                          int default_index)
10364 {
10365   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
10366   gdb_assert (default_index == -1
10367               || (default_index > 0 && default_index < TYPE_NFIELDS (type)));
10368
10369   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
10370
10371   struct discriminant_info *disc
10372     = ((struct discriminant_info *)
10373        TYPE_ZALLOC (type,
10374                     offsetof (struct discriminant_info, discriminants)
10375                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
10376   disc->default_index = default_index;
10377   disc->discriminant_index = discriminant_index;
10378
10379   struct dynamic_prop prop;
10380   prop.kind = PROP_UNDEFINED;
10381   prop.data.baton = disc;
10382
10383   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
10384
10385   return disc;
10386 }
10387
10388 /* Some versions of rustc emitted enums in an unusual way.
10389
10390    Ordinary enums were emitted as unions.  The first element of each
10391    structure in the union was named "RUST$ENUM$DISR".  This element
10392    held the discriminant.
10393
10394    These versions of Rust also implemented the "non-zero"
10395    optimization.  When the enum had two values, and one is empty and
10396    the other holds a pointer that cannot be zero, the pointer is used
10397    as the discriminant, with a zero value meaning the empty variant.
10398    Here, the union's first member is of the form
10399    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
10400    where the fieldnos are the indices of the fields that should be
10401    traversed in order to find the field (which may be several fields deep)
10402    and the variantname is the name of the variant of the case when the
10403    field is zero.
10404
10405    This function recognizes whether TYPE is of one of these forms,
10406    and, if so, smashes it to be a variant type.  */
10407
10408 static void
10409 quirk_rust_enum (struct type *type, struct objfile *objfile)
10410 {
10411   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
10412
10413   /* We don't need to deal with empty enums.  */
10414   if (TYPE_NFIELDS (type) == 0)
10415     return;
10416
10417 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
10418   if (TYPE_NFIELDS (type) == 1
10419       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
10420     {
10421       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
10422
10423       /* Decode the field name to find the offset of the
10424          discriminant.  */
10425       ULONGEST bit_offset = 0;
10426       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
10427       while (name[0] >= '0' && name[0] <= '9')
10428         {
10429           char *tail;
10430           unsigned long index = strtoul (name, &tail, 10);
10431           name = tail;
10432           if (*name != '$'
10433               || index >= TYPE_NFIELDS (field_type)
10434               || (TYPE_FIELD_LOC_KIND (field_type, index)
10435                   != FIELD_LOC_KIND_BITPOS))
10436             {
10437               complaint (&symfile_complaints,
10438                          _("Could not parse Rust enum encoding string \"%s\""
10439                            "[in module %s]"),
10440                          TYPE_FIELD_NAME (type, 0),
10441                          objfile_name (objfile));
10442               return;
10443             }
10444           ++name;
10445
10446           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
10447           field_type = TYPE_FIELD_TYPE (field_type, index);
10448         }
10449
10450       /* Make a union to hold the variants.  */
10451       struct type *union_type = alloc_type (objfile);
10452       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10453       TYPE_NFIELDS (union_type) = 3;
10454       TYPE_FIELDS (union_type)
10455         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
10456       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10457
10458       /* Put the discriminant must at index 0.  */
10459       TYPE_FIELD_TYPE (union_type, 0) = field_type;
10460       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10461       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10462       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
10463
10464       /* The order of fields doesn't really matter, so put the real
10465          field at index 1 and the data-less field at index 2.  */
10466       struct discriminant_info *disc
10467         = alloc_discriminant_info (union_type, 0, 1);
10468       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
10469       TYPE_FIELD_NAME (union_type, 1)
10470         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
10471       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
10472         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10473                               TYPE_FIELD_NAME (union_type, 1));
10474
10475       const char *dataless_name
10476         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10477                               name);
10478       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10479                                               dataless_name);
10480       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10481       /* NAME points into the original discriminant name, which
10482          already has the correct lifetime.  */
10483       TYPE_FIELD_NAME (union_type, 2) = name;
10484       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10485       disc->discriminants[2] = 0;
10486
10487       /* Smash this type to be a structure type.  We have to do this
10488          because the type has already been recorded.  */
10489       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10490       TYPE_NFIELDS (type) = 1;
10491       TYPE_FIELDS (type)
10492         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10493
10494       /* Install the variant part.  */
10495       TYPE_FIELD_TYPE (type, 0) = union_type;
10496       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10497       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10498     }
10499   else if (TYPE_NFIELDS (type) == 1)
10500     {
10501       /* We assume that a union with a single field is a univariant
10502          enum.  */
10503       /* Smash this type to be a structure type.  We have to do this
10504          because the type has already been recorded.  */
10505       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10506
10507       /* Make a union to hold the variants.  */
10508       struct type *union_type = alloc_type (objfile);
10509       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10510       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10511       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10512       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10513
10514       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10515       const char *variant_name
10516         = rust_last_path_segment (TYPE_NAME (field_type));
10517       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10518       TYPE_NAME (field_type)
10519         = rust_fully_qualify (&objfile->objfile_obstack,
10520                               TYPE_NAME (field_type), variant_name);
10521
10522       /* Install the union in the outer struct type.  */
10523       TYPE_NFIELDS (type) = 1;
10524       TYPE_FIELDS (type)
10525         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10526       TYPE_FIELD_TYPE (type, 0) = union_type;
10527       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10528       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10529
10530       alloc_discriminant_info (union_type, -1, 0);
10531     }
10532   else
10533     {
10534       struct type *disr_type = nullptr;
10535       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10536         {
10537           disr_type = TYPE_FIELD_TYPE (type, i);
10538
10539           if (TYPE_NFIELDS (disr_type) == 0)
10540             {
10541               /* Could be data-less variant, so keep going.  */
10542             }
10543           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10544                            "RUST$ENUM$DISR") != 0)
10545             {
10546               /* Not a Rust enum.  */
10547               return;
10548             }
10549           else
10550             {
10551               /* Found one.  */
10552               break;
10553             }
10554         }
10555
10556       /* If we got here without a discriminant, then it's probably
10557          just a union.  */
10558       if (disr_type == nullptr)
10559         return;
10560
10561       /* Smash this type to be a structure type.  We have to do this
10562          because the type has already been recorded.  */
10563       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10564
10565       /* Make a union to hold the variants.  */
10566       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10567       struct type *union_type = alloc_type (objfile);
10568       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10569       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10570       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10571       TYPE_FIELDS (union_type)
10572         = (struct field *) TYPE_ZALLOC (union_type,
10573                                         (TYPE_NFIELDS (union_type)
10574                                          * sizeof (struct field)));
10575
10576       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10577               TYPE_NFIELDS (type) * sizeof (struct field));
10578
10579       /* Install the discriminant at index 0 in the union.  */
10580       TYPE_FIELD (union_type, 0) = *disr_field;
10581       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10582       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10583
10584       /* Install the union in the outer struct type.  */
10585       TYPE_FIELD_TYPE (type, 0) = union_type;
10586       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10587       TYPE_NFIELDS (type) = 1;
10588
10589       /* Set the size and offset of the union type.  */
10590       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10591
10592       /* We need a way to find the correct discriminant given a
10593          variant name.  For convenience we build a map here.  */
10594       struct type *enum_type = FIELD_TYPE (*disr_field);
10595       std::unordered_map<std::string, ULONGEST> discriminant_map;
10596       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10597         {
10598           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10599             {
10600               const char *name
10601                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10602               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10603             }
10604         }
10605
10606       int n_fields = TYPE_NFIELDS (union_type);
10607       struct discriminant_info *disc
10608         = alloc_discriminant_info (union_type, 0, -1);
10609       /* Skip the discriminant here.  */
10610       for (int i = 1; i < n_fields; ++i)
10611         {
10612           /* Find the final word in the name of this variant's type.
10613              That name can be used to look up the correct
10614              discriminant.  */
10615           const char *variant_name
10616             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10617                                                                   i)));
10618
10619           auto iter = discriminant_map.find (variant_name);
10620           if (iter != discriminant_map.end ())
10621             disc->discriminants[i] = iter->second;
10622
10623           /* Remove the discriminant field.  */
10624           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10625           --TYPE_NFIELDS (sub_type);
10626           ++TYPE_FIELDS (sub_type);
10627           TYPE_FIELD_NAME (union_type, i) = variant_name;
10628           TYPE_NAME (sub_type)
10629             = rust_fully_qualify (&objfile->objfile_obstack,
10630                                   TYPE_NAME (type), variant_name);
10631         }
10632     }
10633 }
10634
10635 /* Rewrite some Rust unions to be structures with variants parts.  */
10636
10637 static void
10638 rust_union_quirks (struct dwarf2_cu *cu)
10639 {
10640   gdb_assert (cu->language == language_rust);
10641   for (struct type *type : cu->rust_unions)
10642     quirk_rust_enum (type, cu->per_cu->dwarf2_per_objfile->objfile);
10643 }
10644
10645 /* Return the symtab for PER_CU.  This works properly regardless of
10646    whether we're using the index or psymtabs.  */
10647
10648 static struct compunit_symtab *
10649 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10650 {
10651   return (per_cu->dwarf2_per_objfile->using_index
10652           ? per_cu->v.quick->compunit_symtab
10653           : per_cu->v.psymtab->compunit_symtab);
10654 }
10655
10656 /* A helper function for computing the list of all symbol tables
10657    included by PER_CU.  */
10658
10659 static void
10660 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10661                                 htab_t all_children, htab_t all_type_symtabs,
10662                                 struct dwarf2_per_cu_data *per_cu,
10663                                 struct compunit_symtab *immediate_parent)
10664 {
10665   void **slot;
10666   int ix;
10667   struct compunit_symtab *cust;
10668   struct dwarf2_per_cu_data *iter;
10669
10670   slot = htab_find_slot (all_children, per_cu, INSERT);
10671   if (*slot != NULL)
10672     {
10673       /* This inclusion and its children have been processed.  */
10674       return;
10675     }
10676
10677   *slot = per_cu;
10678   /* Only add a CU if it has a symbol table.  */
10679   cust = get_compunit_symtab (per_cu);
10680   if (cust != NULL)
10681     {
10682       /* If this is a type unit only add its symbol table if we haven't
10683          seen it yet (type unit per_cu's can share symtabs).  */
10684       if (per_cu->is_debug_types)
10685         {
10686           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10687           if (*slot == NULL)
10688             {
10689               *slot = cust;
10690               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10691               if (cust->user == NULL)
10692                 cust->user = immediate_parent;
10693             }
10694         }
10695       else
10696         {
10697           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10698           if (cust->user == NULL)
10699             cust->user = immediate_parent;
10700         }
10701     }
10702
10703   for (ix = 0;
10704        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10705        ++ix)
10706     {
10707       recursively_compute_inclusions (result, all_children,
10708                                       all_type_symtabs, iter, cust);
10709     }
10710 }
10711
10712 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10713    PER_CU.  */
10714
10715 static void
10716 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10717 {
10718   gdb_assert (! per_cu->is_debug_types);
10719
10720   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10721     {
10722       int ix, len;
10723       struct dwarf2_per_cu_data *per_cu_iter;
10724       struct compunit_symtab *compunit_symtab_iter;
10725       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10726       htab_t all_children, all_type_symtabs;
10727       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10728
10729       /* If we don't have a symtab, we can just skip this case.  */
10730       if (cust == NULL)
10731         return;
10732
10733       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10734                                         NULL, xcalloc, xfree);
10735       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10736                                             NULL, xcalloc, xfree);
10737
10738       for (ix = 0;
10739            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10740                         ix, per_cu_iter);
10741            ++ix)
10742         {
10743           recursively_compute_inclusions (&result_symtabs, all_children,
10744                                           all_type_symtabs, per_cu_iter,
10745                                           cust);
10746         }
10747
10748       /* Now we have a transitive closure of all the included symtabs.  */
10749       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10750       cust->includes
10751         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10752                      struct compunit_symtab *, len + 1);
10753       for (ix = 0;
10754            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10755                         compunit_symtab_iter);
10756            ++ix)
10757         cust->includes[ix] = compunit_symtab_iter;
10758       cust->includes[len] = NULL;
10759
10760       VEC_free (compunit_symtab_ptr, result_symtabs);
10761       htab_delete (all_children);
10762       htab_delete (all_type_symtabs);
10763     }
10764 }
10765
10766 /* Compute the 'includes' field for the symtabs of all the CUs we just
10767    read.  */
10768
10769 static void
10770 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10771 {
10772   int ix;
10773   struct dwarf2_per_cu_data *iter;
10774
10775   for (ix = 0;
10776        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10777                     ix, iter);
10778        ++ix)
10779     {
10780       if (! iter->is_debug_types)
10781         compute_compunit_symtab_includes (iter);
10782     }
10783
10784   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10785 }
10786
10787 /* Generate full symbol information for PER_CU, whose DIEs have
10788    already been loaded into memory.  */
10789
10790 static void
10791 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10792                         enum language pretend_language)
10793 {
10794   struct dwarf2_cu *cu = per_cu->cu;
10795   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10796   struct objfile *objfile = dwarf2_per_objfile->objfile;
10797   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10798   CORE_ADDR lowpc, highpc;
10799   struct compunit_symtab *cust;
10800   CORE_ADDR baseaddr;
10801   struct block *static_block;
10802   CORE_ADDR addr;
10803
10804   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10805
10806   buildsym_init ();
10807   scoped_free_pendings free_pending;
10808
10809   /* Clear the list here in case something was left over.  */
10810   cu->method_list.clear ();
10811
10812   cu->list_in_scope = &file_symbols;
10813
10814   cu->language = pretend_language;
10815   cu->language_defn = language_def (cu->language);
10816
10817   /* Do line number decoding in read_file_scope () */
10818   process_die (cu->dies, cu);
10819
10820   /* For now fudge the Go package.  */
10821   if (cu->language == language_go)
10822     fixup_go_packaging (cu);
10823
10824   /* Now that we have processed all the DIEs in the CU, all the types 
10825      should be complete, and it should now be safe to compute all of the
10826      physnames.  */
10827   compute_delayed_physnames (cu);
10828
10829   if (cu->language == language_rust)
10830     rust_union_quirks (cu);
10831
10832   /* Some compilers don't define a DW_AT_high_pc attribute for the
10833      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10834      it, by scanning the DIE's below the compilation unit.  */
10835   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10836
10837   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10838   static_block = end_symtab_get_static_block (addr, 0, 1);
10839
10840   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10841      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10842      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10843      addrmap to help ensure it has an accurate map of pc values belonging to
10844      this comp unit.  */
10845   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10846
10847   cust = end_symtab_from_static_block (static_block,
10848                                        SECT_OFF_TEXT (objfile), 0);
10849
10850   if (cust != NULL)
10851     {
10852       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10853
10854       /* Set symtab language to language from DW_AT_language.  If the
10855          compilation is from a C file generated by language preprocessors, do
10856          not set the language if it was already deduced by start_subfile.  */
10857       if (!(cu->language == language_c
10858             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10859         COMPUNIT_FILETABS (cust)->language = cu->language;
10860
10861       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10862          produce DW_AT_location with location lists but it can be possibly
10863          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10864          there were bugs in prologue debug info, fixed later in GCC-4.5
10865          by "unwind info for epilogues" patch (which is not directly related).
10866
10867          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10868          needed, it would be wrong due to missing DW_AT_producer there.
10869
10870          Still one can confuse GDB by using non-standard GCC compilation
10871          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10872          */ 
10873       if (cu->has_loclist && gcc_4_minor >= 5)
10874         cust->locations_valid = 1;
10875
10876       if (gcc_4_minor >= 5)
10877         cust->epilogue_unwind_valid = 1;
10878
10879       cust->call_site_htab = cu->call_site_htab;
10880     }
10881
10882   if (dwarf2_per_objfile->using_index)
10883     per_cu->v.quick->compunit_symtab = cust;
10884   else
10885     {
10886       struct partial_symtab *pst = per_cu->v.psymtab;
10887       pst->compunit_symtab = cust;
10888       pst->readin = 1;
10889     }
10890
10891   /* Push it for inclusion processing later.  */
10892   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10893 }
10894
10895 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10896    already been loaded into memory.  */
10897
10898 static void
10899 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10900                         enum language pretend_language)
10901 {
10902   struct dwarf2_cu *cu = per_cu->cu;
10903   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10904   struct objfile *objfile = dwarf2_per_objfile->objfile;
10905   struct compunit_symtab *cust;
10906   struct signatured_type *sig_type;
10907
10908   gdb_assert (per_cu->is_debug_types);
10909   sig_type = (struct signatured_type *) per_cu;
10910
10911   buildsym_init ();
10912   scoped_free_pendings free_pending;
10913
10914   /* Clear the list here in case something was left over.  */
10915   cu->method_list.clear ();
10916
10917   cu->list_in_scope = &file_symbols;
10918
10919   cu->language = pretend_language;
10920   cu->language_defn = language_def (cu->language);
10921
10922   /* The symbol tables are set up in read_type_unit_scope.  */
10923   process_die (cu->dies, cu);
10924
10925   /* For now fudge the Go package.  */
10926   if (cu->language == language_go)
10927     fixup_go_packaging (cu);
10928
10929   /* Now that we have processed all the DIEs in the CU, all the types 
10930      should be complete, and it should now be safe to compute all of the
10931      physnames.  */
10932   compute_delayed_physnames (cu);
10933
10934   if (cu->language == language_rust)
10935     rust_union_quirks (cu);
10936
10937   /* TUs share symbol tables.
10938      If this is the first TU to use this symtab, complete the construction
10939      of it with end_expandable_symtab.  Otherwise, complete the addition of
10940      this TU's symbols to the existing symtab.  */
10941   if (sig_type->type_unit_group->compunit_symtab == NULL)
10942     {
10943       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10944       sig_type->type_unit_group->compunit_symtab = cust;
10945
10946       if (cust != NULL)
10947         {
10948           /* Set symtab language to language from DW_AT_language.  If the
10949              compilation is from a C file generated by language preprocessors,
10950              do not set the language if it was already deduced by
10951              start_subfile.  */
10952           if (!(cu->language == language_c
10953                 && COMPUNIT_FILETABS (cust)->language != language_c))
10954             COMPUNIT_FILETABS (cust)->language = cu->language;
10955         }
10956     }
10957   else
10958     {
10959       augment_type_symtab ();
10960       cust = sig_type->type_unit_group->compunit_symtab;
10961     }
10962
10963   if (dwarf2_per_objfile->using_index)
10964     per_cu->v.quick->compunit_symtab = cust;
10965   else
10966     {
10967       struct partial_symtab *pst = per_cu->v.psymtab;
10968       pst->compunit_symtab = cust;
10969       pst->readin = 1;
10970     }
10971 }
10972
10973 /* Process an imported unit DIE.  */
10974
10975 static void
10976 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10977 {
10978   struct attribute *attr;
10979
10980   /* For now we don't handle imported units in type units.  */
10981   if (cu->per_cu->is_debug_types)
10982     {
10983       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10984                " supported in type units [in module %s]"),
10985              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10986     }
10987
10988   attr = dwarf2_attr (die, DW_AT_import, cu);
10989   if (attr != NULL)
10990     {
10991       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10992       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10993       dwarf2_per_cu_data *per_cu
10994         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10995                                             cu->per_cu->dwarf2_per_objfile);
10996
10997       /* If necessary, add it to the queue and load its DIEs.  */
10998       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10999         load_full_comp_unit (per_cu, cu->language);
11000
11001       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
11002                      per_cu);
11003     }
11004 }
11005
11006 /* RAII object that represents a process_die scope: i.e.,
11007    starts/finishes processing a DIE.  */
11008 class process_die_scope
11009 {
11010 public:
11011   process_die_scope (die_info *die, dwarf2_cu *cu)
11012     : m_die (die), m_cu (cu)
11013   {
11014     /* We should only be processing DIEs not already in process.  */
11015     gdb_assert (!m_die->in_process);
11016     m_die->in_process = true;
11017   }
11018
11019   ~process_die_scope ()
11020   {
11021     m_die->in_process = false;
11022
11023     /* If we're done processing the DIE for the CU that owns the line
11024        header, we don't need the line header anymore.  */
11025     if (m_cu->line_header_die_owner == m_die)
11026       {
11027         delete m_cu->line_header;
11028         m_cu->line_header = NULL;
11029         m_cu->line_header_die_owner = NULL;
11030       }
11031   }
11032
11033 private:
11034   die_info *m_die;
11035   dwarf2_cu *m_cu;
11036 };
11037
11038 /* Process a die and its children.  */
11039
11040 static void
11041 process_die (struct die_info *die, struct dwarf2_cu *cu)
11042 {
11043   process_die_scope scope (die, cu);
11044
11045   switch (die->tag)
11046     {
11047     case DW_TAG_padding:
11048       break;
11049     case DW_TAG_compile_unit:
11050     case DW_TAG_partial_unit:
11051       read_file_scope (die, cu);
11052       break;
11053     case DW_TAG_type_unit:
11054       read_type_unit_scope (die, cu);
11055       break;
11056     case DW_TAG_subprogram:
11057     case DW_TAG_inlined_subroutine:
11058       read_func_scope (die, cu);
11059       break;
11060     case DW_TAG_lexical_block:
11061     case DW_TAG_try_block:
11062     case DW_TAG_catch_block:
11063       read_lexical_block_scope (die, cu);
11064       break;
11065     case DW_TAG_call_site:
11066     case DW_TAG_GNU_call_site:
11067       read_call_site_scope (die, cu);
11068       break;
11069     case DW_TAG_class_type:
11070     case DW_TAG_interface_type:
11071     case DW_TAG_structure_type:
11072     case DW_TAG_union_type:
11073       process_structure_scope (die, cu);
11074       break;
11075     case DW_TAG_enumeration_type:
11076       process_enumeration_scope (die, cu);
11077       break;
11078
11079     /* These dies have a type, but processing them does not create
11080        a symbol or recurse to process the children.  Therefore we can
11081        read them on-demand through read_type_die.  */
11082     case DW_TAG_subroutine_type:
11083     case DW_TAG_set_type:
11084     case DW_TAG_array_type:
11085     case DW_TAG_pointer_type:
11086     case DW_TAG_ptr_to_member_type:
11087     case DW_TAG_reference_type:
11088     case DW_TAG_rvalue_reference_type:
11089     case DW_TAG_string_type:
11090       break;
11091
11092     case DW_TAG_base_type:
11093     case DW_TAG_subrange_type:
11094     case DW_TAG_typedef:
11095       /* Add a typedef symbol for the type definition, if it has a
11096          DW_AT_name.  */
11097       new_symbol (die, read_type_die (die, cu), cu);
11098       break;
11099     case DW_TAG_common_block:
11100       read_common_block (die, cu);
11101       break;
11102     case DW_TAG_common_inclusion:
11103       break;
11104     case DW_TAG_namespace:
11105       cu->processing_has_namespace_info = 1;
11106       read_namespace (die, cu);
11107       break;
11108     case DW_TAG_module:
11109       cu->processing_has_namespace_info = 1;
11110       read_module (die, cu);
11111       break;
11112     case DW_TAG_imported_declaration:
11113       cu->processing_has_namespace_info = 1;
11114       if (read_namespace_alias (die, cu))
11115         break;
11116       /* The declaration is not a global namespace alias: fall through.  */
11117     case DW_TAG_imported_module:
11118       cu->processing_has_namespace_info = 1;
11119       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
11120                                  || cu->language != language_fortran))
11121         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
11122                    dwarf_tag_name (die->tag));
11123       read_import_statement (die, cu);
11124       break;
11125
11126     case DW_TAG_imported_unit:
11127       process_imported_unit_die (die, cu);
11128       break;
11129
11130     case DW_TAG_variable:
11131       read_variable (die, cu);
11132       break;
11133
11134     default:
11135       new_symbol (die, NULL, cu);
11136       break;
11137     }
11138 }
11139 \f
11140 /* DWARF name computation.  */
11141
11142 /* A helper function for dwarf2_compute_name which determines whether DIE
11143    needs to have the name of the scope prepended to the name listed in the
11144    die.  */
11145
11146 static int
11147 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
11148 {
11149   struct attribute *attr;
11150
11151   switch (die->tag)
11152     {
11153     case DW_TAG_namespace:
11154     case DW_TAG_typedef:
11155     case DW_TAG_class_type:
11156     case DW_TAG_interface_type:
11157     case DW_TAG_structure_type:
11158     case DW_TAG_union_type:
11159     case DW_TAG_enumeration_type:
11160     case DW_TAG_enumerator:
11161     case DW_TAG_subprogram:
11162     case DW_TAG_inlined_subroutine:
11163     case DW_TAG_member:
11164     case DW_TAG_imported_declaration:
11165       return 1;
11166
11167     case DW_TAG_variable:
11168     case DW_TAG_constant:
11169       /* We only need to prefix "globally" visible variables.  These include
11170          any variable marked with DW_AT_external or any variable that
11171          lives in a namespace.  [Variables in anonymous namespaces
11172          require prefixing, but they are not DW_AT_external.]  */
11173
11174       if (dwarf2_attr (die, DW_AT_specification, cu))
11175         {
11176           struct dwarf2_cu *spec_cu = cu;
11177
11178           return die_needs_namespace (die_specification (die, &spec_cu),
11179                                       spec_cu);
11180         }
11181
11182       attr = dwarf2_attr (die, DW_AT_external, cu);
11183       if (attr == NULL && die->parent->tag != DW_TAG_namespace
11184           && die->parent->tag != DW_TAG_module)
11185         return 0;
11186       /* A variable in a lexical block of some kind does not need a
11187          namespace, even though in C++ such variables may be external
11188          and have a mangled name.  */
11189       if (die->parent->tag ==  DW_TAG_lexical_block
11190           || die->parent->tag ==  DW_TAG_try_block
11191           || die->parent->tag ==  DW_TAG_catch_block
11192           || die->parent->tag == DW_TAG_subprogram)
11193         return 0;
11194       return 1;
11195
11196     default:
11197       return 0;
11198     }
11199 }
11200
11201 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
11202    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
11203    defined for the given DIE.  */
11204
11205 static struct attribute *
11206 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
11207 {
11208   struct attribute *attr;
11209
11210   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
11211   if (attr == NULL)
11212     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
11213
11214   return attr;
11215 }
11216
11217 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
11218    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
11219    defined for the given DIE.  */
11220
11221 static const char *
11222 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
11223 {
11224   const char *linkage_name;
11225
11226   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
11227   if (linkage_name == NULL)
11228     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
11229
11230   return linkage_name;
11231 }
11232
11233 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
11234    compute the physname for the object, which include a method's:
11235    - formal parameters (C++),
11236    - receiver type (Go),
11237
11238    The term "physname" is a bit confusing.
11239    For C++, for example, it is the demangled name.
11240    For Go, for example, it's the mangled name.
11241
11242    For Ada, return the DIE's linkage name rather than the fully qualified
11243    name.  PHYSNAME is ignored..
11244
11245    The result is allocated on the objfile_obstack and canonicalized.  */
11246
11247 static const char *
11248 dwarf2_compute_name (const char *name,
11249                      struct die_info *die, struct dwarf2_cu *cu,
11250                      int physname)
11251 {
11252   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11253
11254   if (name == NULL)
11255     name = dwarf2_name (die, cu);
11256
11257   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
11258      but otherwise compute it by typename_concat inside GDB.
11259      FIXME: Actually this is not really true, or at least not always true.
11260      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
11261      Fortran names because there is no mangling standard.  So new_symbol
11262      will set the demangled name to the result of dwarf2_full_name, and it is
11263      the demangled name that GDB uses if it exists.  */
11264   if (cu->language == language_ada
11265       || (cu->language == language_fortran && physname))
11266     {
11267       /* For Ada unit, we prefer the linkage name over the name, as
11268          the former contains the exported name, which the user expects
11269          to be able to reference.  Ideally, we want the user to be able
11270          to reference this entity using either natural or linkage name,
11271          but we haven't started looking at this enhancement yet.  */
11272       const char *linkage_name = dw2_linkage_name (die, cu);
11273
11274       if (linkage_name != NULL)
11275         return linkage_name;
11276     }
11277
11278   /* These are the only languages we know how to qualify names in.  */
11279   if (name != NULL
11280       && (cu->language == language_cplus
11281           || cu->language == language_fortran || cu->language == language_d
11282           || cu->language == language_rust))
11283     {
11284       if (die_needs_namespace (die, cu))
11285         {
11286           const char *prefix;
11287           const char *canonical_name = NULL;
11288
11289           string_file buf;
11290
11291           prefix = determine_prefix (die, cu);
11292           if (*prefix != '\0')
11293             {
11294               char *prefixed_name = typename_concat (NULL, prefix, name,
11295                                                      physname, cu);
11296
11297               buf.puts (prefixed_name);
11298               xfree (prefixed_name);
11299             }
11300           else
11301             buf.puts (name);
11302
11303           /* Template parameters may be specified in the DIE's DW_AT_name, or
11304              as children with DW_TAG_template_type_param or
11305              DW_TAG_value_type_param.  If the latter, add them to the name
11306              here.  If the name already has template parameters, then
11307              skip this step; some versions of GCC emit both, and
11308              it is more efficient to use the pre-computed name.
11309
11310              Something to keep in mind about this process: it is very
11311              unlikely, or in some cases downright impossible, to produce
11312              something that will match the mangled name of a function.
11313              If the definition of the function has the same debug info,
11314              we should be able to match up with it anyway.  But fallbacks
11315              using the minimal symbol, for instance to find a method
11316              implemented in a stripped copy of libstdc++, will not work.
11317              If we do not have debug info for the definition, we will have to
11318              match them up some other way.
11319
11320              When we do name matching there is a related problem with function
11321              templates; two instantiated function templates are allowed to
11322              differ only by their return types, which we do not add here.  */
11323
11324           if (cu->language == language_cplus && strchr (name, '<') == NULL)
11325             {
11326               struct attribute *attr;
11327               struct die_info *child;
11328               int first = 1;
11329
11330               die->building_fullname = 1;
11331
11332               for (child = die->child; child != NULL; child = child->sibling)
11333                 {
11334                   struct type *type;
11335                   LONGEST value;
11336                   const gdb_byte *bytes;
11337                   struct dwarf2_locexpr_baton *baton;
11338                   struct value *v;
11339
11340                   if (child->tag != DW_TAG_template_type_param
11341                       && child->tag != DW_TAG_template_value_param)
11342                     continue;
11343
11344                   if (first)
11345                     {
11346                       buf.puts ("<");
11347                       first = 0;
11348                     }
11349                   else
11350                     buf.puts (", ");
11351
11352                   attr = dwarf2_attr (child, DW_AT_type, cu);
11353                   if (attr == NULL)
11354                     {
11355                       complaint (&symfile_complaints,
11356                                  _("template parameter missing DW_AT_type"));
11357                       buf.puts ("UNKNOWN_TYPE");
11358                       continue;
11359                     }
11360                   type = die_type (child, cu);
11361
11362                   if (child->tag == DW_TAG_template_type_param)
11363                     {
11364                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11365                       continue;
11366                     }
11367
11368                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11369                   if (attr == NULL)
11370                     {
11371                       complaint (&symfile_complaints,
11372                                  _("template parameter missing "
11373                                    "DW_AT_const_value"));
11374                       buf.puts ("UNKNOWN_VALUE");
11375                       continue;
11376                     }
11377
11378                   dwarf2_const_value_attr (attr, type, name,
11379                                            &cu->comp_unit_obstack, cu,
11380                                            &value, &bytes, &baton);
11381
11382                   if (TYPE_NOSIGN (type))
11383                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11384                        changed, this can use value_print instead.  */
11385                     c_printchar (value, type, &buf);
11386                   else
11387                     {
11388                       struct value_print_options opts;
11389
11390                       if (baton != NULL)
11391                         v = dwarf2_evaluate_loc_desc (type, NULL,
11392                                                       baton->data,
11393                                                       baton->size,
11394                                                       baton->per_cu);
11395                       else if (bytes != NULL)
11396                         {
11397                           v = allocate_value (type);
11398                           memcpy (value_contents_writeable (v), bytes,
11399                                   TYPE_LENGTH (type));
11400                         }
11401                       else
11402                         v = value_from_longest (type, value);
11403
11404                       /* Specify decimal so that we do not depend on
11405                          the radix.  */
11406                       get_formatted_print_options (&opts, 'd');
11407                       opts.raw = 1;
11408                       value_print (v, &buf, &opts);
11409                       release_value (v);
11410                       value_free (v);
11411                     }
11412                 }
11413
11414               die->building_fullname = 0;
11415
11416               if (!first)
11417                 {
11418                   /* Close the argument list, with a space if necessary
11419                      (nested templates).  */
11420                   if (!buf.empty () && buf.string ().back () == '>')
11421                     buf.puts (" >");
11422                   else
11423                     buf.puts (">");
11424                 }
11425             }
11426
11427           /* For C++ methods, append formal parameter type
11428              information, if PHYSNAME.  */
11429
11430           if (physname && die->tag == DW_TAG_subprogram
11431               && cu->language == language_cplus)
11432             {
11433               struct type *type = read_type_die (die, cu);
11434
11435               c_type_print_args (type, &buf, 1, cu->language,
11436                                  &type_print_raw_options);
11437
11438               if (cu->language == language_cplus)
11439                 {
11440                   /* Assume that an artificial first parameter is
11441                      "this", but do not crash if it is not.  RealView
11442                      marks unnamed (and thus unused) parameters as
11443                      artificial; there is no way to differentiate
11444                      the two cases.  */
11445                   if (TYPE_NFIELDS (type) > 0
11446                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11447                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11448                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11449                                                                         0))))
11450                     buf.puts (" const");
11451                 }
11452             }
11453
11454           const std::string &intermediate_name = buf.string ();
11455
11456           if (cu->language == language_cplus)
11457             canonical_name
11458               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11459                                           &objfile->per_bfd->storage_obstack);
11460
11461           /* If we only computed INTERMEDIATE_NAME, or if
11462              INTERMEDIATE_NAME is already canonical, then we need to
11463              copy it to the appropriate obstack.  */
11464           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11465             name = ((const char *)
11466                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11467                                    intermediate_name.c_str (),
11468                                    intermediate_name.length ()));
11469           else
11470             name = canonical_name;
11471         }
11472     }
11473
11474   return name;
11475 }
11476
11477 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11478    If scope qualifiers are appropriate they will be added.  The result
11479    will be allocated on the storage_obstack, or NULL if the DIE does
11480    not have a name.  NAME may either be from a previous call to
11481    dwarf2_name or NULL.
11482
11483    The output string will be canonicalized (if C++).  */
11484
11485 static const char *
11486 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11487 {
11488   return dwarf2_compute_name (name, die, cu, 0);
11489 }
11490
11491 /* Construct a physname for the given DIE in CU.  NAME may either be
11492    from a previous call to dwarf2_name or NULL.  The result will be
11493    allocated on the objfile_objstack or NULL if the DIE does not have a
11494    name.
11495
11496    The output string will be canonicalized (if C++).  */
11497
11498 static const char *
11499 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11500 {
11501   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11502   const char *retval, *mangled = NULL, *canon = NULL;
11503   int need_copy = 1;
11504
11505   /* In this case dwarf2_compute_name is just a shortcut not building anything
11506      on its own.  */
11507   if (!die_needs_namespace (die, cu))
11508     return dwarf2_compute_name (name, die, cu, 1);
11509
11510   mangled = dw2_linkage_name (die, cu);
11511
11512   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11513      See https://github.com/rust-lang/rust/issues/32925.  */
11514   if (cu->language == language_rust && mangled != NULL
11515       && strchr (mangled, '{') != NULL)
11516     mangled = NULL;
11517
11518   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11519      has computed.  */
11520   gdb::unique_xmalloc_ptr<char> demangled;
11521   if (mangled != NULL)
11522     {
11523
11524       if (cu->language == language_go)
11525         {
11526           /* This is a lie, but we already lie to the caller new_symbol.
11527              new_symbol assumes we return the mangled name.
11528              This just undoes that lie until things are cleaned up.  */
11529         }
11530       else
11531         {
11532           /* Use DMGL_RET_DROP for C++ template functions to suppress
11533              their return type.  It is easier for GDB users to search
11534              for such functions as `name(params)' than `long name(params)'.
11535              In such case the minimal symbol names do not match the full
11536              symbol names but for template functions there is never a need
11537              to look up their definition from their declaration so
11538              the only disadvantage remains the minimal symbol variant
11539              `long name(params)' does not have the proper inferior type.  */
11540           demangled.reset (gdb_demangle (mangled,
11541                                          (DMGL_PARAMS | DMGL_ANSI
11542                                           | DMGL_RET_DROP)));
11543         }
11544       if (demangled)
11545         canon = demangled.get ();
11546       else
11547         {
11548           canon = mangled;
11549           need_copy = 0;
11550         }
11551     }
11552
11553   if (canon == NULL || check_physname)
11554     {
11555       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11556
11557       if (canon != NULL && strcmp (physname, canon) != 0)
11558         {
11559           /* It may not mean a bug in GDB.  The compiler could also
11560              compute DW_AT_linkage_name incorrectly.  But in such case
11561              GDB would need to be bug-to-bug compatible.  */
11562
11563           complaint (&symfile_complaints,
11564                      _("Computed physname <%s> does not match demangled <%s> "
11565                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11566                      physname, canon, mangled, sect_offset_str (die->sect_off),
11567                      objfile_name (objfile));
11568
11569           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11570              is available here - over computed PHYSNAME.  It is safer
11571              against both buggy GDB and buggy compilers.  */
11572
11573           retval = canon;
11574         }
11575       else
11576         {
11577           retval = physname;
11578           need_copy = 0;
11579         }
11580     }
11581   else
11582     retval = canon;
11583
11584   if (need_copy)
11585     retval = ((const char *)
11586               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11587                              retval, strlen (retval)));
11588
11589   return retval;
11590 }
11591
11592 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11593    a new symbol for it.
11594
11595    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11596
11597 static int
11598 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11599 {
11600   struct attribute *attr;
11601
11602   /* If the die does not have a name, this is not a namespace
11603      alias.  */
11604   attr = dwarf2_attr (die, DW_AT_name, cu);
11605   if (attr != NULL)
11606     {
11607       int num;
11608       struct die_info *d = die;
11609       struct dwarf2_cu *imported_cu = cu;
11610
11611       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11612          keep inspecting DIEs until we hit the underlying import.  */
11613 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11614       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11615         {
11616           attr = dwarf2_attr (d, DW_AT_import, cu);
11617           if (attr == NULL)
11618             break;
11619
11620           d = follow_die_ref (d, attr, &imported_cu);
11621           if (d->tag != DW_TAG_imported_declaration)
11622             break;
11623         }
11624
11625       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11626         {
11627           complaint (&symfile_complaints,
11628                      _("DIE at %s has too many recursively imported "
11629                        "declarations"), sect_offset_str (d->sect_off));
11630           return 0;
11631         }
11632
11633       if (attr != NULL)
11634         {
11635           struct type *type;
11636           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11637
11638           type = get_die_type_at_offset (sect_off, cu->per_cu);
11639           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11640             {
11641               /* This declaration is a global namespace alias.  Add
11642                  a symbol for it whose type is the aliased namespace.  */
11643               new_symbol (die, type, cu);
11644               return 1;
11645             }
11646         }
11647     }
11648
11649   return 0;
11650 }
11651
11652 /* Return the using directives repository (global or local?) to use in the
11653    current context for LANGUAGE.
11654
11655    For Ada, imported declarations can materialize renamings, which *may* be
11656    global.  However it is impossible (for now?) in DWARF to distinguish
11657    "external" imported declarations and "static" ones.  As all imported
11658    declarations seem to be static in all other languages, make them all CU-wide
11659    global only in Ada.  */
11660
11661 static struct using_direct **
11662 using_directives (enum language language)
11663 {
11664   if (language == language_ada && context_stack_depth == 0)
11665     return &global_using_directives;
11666   else
11667     return &local_using_directives;
11668 }
11669
11670 /* Read the import statement specified by the given die and record it.  */
11671
11672 static void
11673 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11674 {
11675   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11676   struct attribute *import_attr;
11677   struct die_info *imported_die, *child_die;
11678   struct dwarf2_cu *imported_cu;
11679   const char *imported_name;
11680   const char *imported_name_prefix;
11681   const char *canonical_name;
11682   const char *import_alias;
11683   const char *imported_declaration = NULL;
11684   const char *import_prefix;
11685   std::vector<const char *> excludes;
11686
11687   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11688   if (import_attr == NULL)
11689     {
11690       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11691                  dwarf_tag_name (die->tag));
11692       return;
11693     }
11694
11695   imported_cu = cu;
11696   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11697   imported_name = dwarf2_name (imported_die, imported_cu);
11698   if (imported_name == NULL)
11699     {
11700       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11701
11702         The import in the following code:
11703         namespace A
11704           {
11705             typedef int B;
11706           }
11707
11708         int main ()
11709           {
11710             using A::B;
11711             B b;
11712             return b;
11713           }
11714
11715         ...
11716          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11717             <52>   DW_AT_decl_file   : 1
11718             <53>   DW_AT_decl_line   : 6
11719             <54>   DW_AT_import      : <0x75>
11720          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11721             <59>   DW_AT_name        : B
11722             <5b>   DW_AT_decl_file   : 1
11723             <5c>   DW_AT_decl_line   : 2
11724             <5d>   DW_AT_type        : <0x6e>
11725         ...
11726          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11727             <76>   DW_AT_byte_size   : 4
11728             <77>   DW_AT_encoding    : 5        (signed)
11729
11730         imports the wrong die ( 0x75 instead of 0x58 ).
11731         This case will be ignored until the gcc bug is fixed.  */
11732       return;
11733     }
11734
11735   /* Figure out the local name after import.  */
11736   import_alias = dwarf2_name (die, cu);
11737
11738   /* Figure out where the statement is being imported to.  */
11739   import_prefix = determine_prefix (die, cu);
11740
11741   /* Figure out what the scope of the imported die is and prepend it
11742      to the name of the imported die.  */
11743   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11744
11745   if (imported_die->tag != DW_TAG_namespace
11746       && imported_die->tag != DW_TAG_module)
11747     {
11748       imported_declaration = imported_name;
11749       canonical_name = imported_name_prefix;
11750     }
11751   else if (strlen (imported_name_prefix) > 0)
11752     canonical_name = obconcat (&objfile->objfile_obstack,
11753                                imported_name_prefix,
11754                                (cu->language == language_d ? "." : "::"),
11755                                imported_name, (char *) NULL);
11756   else
11757     canonical_name = imported_name;
11758
11759   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11760     for (child_die = die->child; child_die && child_die->tag;
11761          child_die = sibling_die (child_die))
11762       {
11763         /* DWARF-4: A Fortran use statement with a “rename list” may be
11764            represented by an imported module entry with an import attribute
11765            referring to the module and owned entries corresponding to those
11766            entities that are renamed as part of being imported.  */
11767
11768         if (child_die->tag != DW_TAG_imported_declaration)
11769           {
11770             complaint (&symfile_complaints,
11771                        _("child DW_TAG_imported_declaration expected "
11772                          "- DIE at %s [in module %s]"),
11773                        sect_offset_str (child_die->sect_off),
11774                        objfile_name (objfile));
11775             continue;
11776           }
11777
11778         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11779         if (import_attr == NULL)
11780           {
11781             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11782                        dwarf_tag_name (child_die->tag));
11783             continue;
11784           }
11785
11786         imported_cu = cu;
11787         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11788                                               &imported_cu);
11789         imported_name = dwarf2_name (imported_die, imported_cu);
11790         if (imported_name == NULL)
11791           {
11792             complaint (&symfile_complaints,
11793                        _("child DW_TAG_imported_declaration has unknown "
11794                          "imported name - DIE at %s [in module %s]"),
11795                        sect_offset_str (child_die->sect_off),
11796                        objfile_name (objfile));
11797             continue;
11798           }
11799
11800         excludes.push_back (imported_name);
11801
11802         process_die (child_die, cu);
11803       }
11804
11805   add_using_directive (using_directives (cu->language),
11806                        import_prefix,
11807                        canonical_name,
11808                        import_alias,
11809                        imported_declaration,
11810                        excludes,
11811                        0,
11812                        &objfile->objfile_obstack);
11813 }
11814
11815 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11816    types, but gives them a size of zero.  Starting with version 14,
11817    ICC is compatible with GCC.  */
11818
11819 static int
11820 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11821 {
11822   if (!cu->checked_producer)
11823     check_producer (cu);
11824
11825   return cu->producer_is_icc_lt_14;
11826 }
11827
11828 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11829    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11830    this, it was first present in GCC release 4.3.0.  */
11831
11832 static int
11833 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11834 {
11835   if (!cu->checked_producer)
11836     check_producer (cu);
11837
11838   return cu->producer_is_gcc_lt_4_3;
11839 }
11840
11841 static file_and_directory
11842 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11843 {
11844   file_and_directory res;
11845
11846   /* Find the filename.  Do not use dwarf2_name here, since the filename
11847      is not a source language identifier.  */
11848   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11849   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11850
11851   if (res.comp_dir == NULL
11852       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11853       && IS_ABSOLUTE_PATH (res.name))
11854     {
11855       res.comp_dir_storage = ldirname (res.name);
11856       if (!res.comp_dir_storage.empty ())
11857         res.comp_dir = res.comp_dir_storage.c_str ();
11858     }
11859   if (res.comp_dir != NULL)
11860     {
11861       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11862          directory, get rid of it.  */
11863       const char *cp = strchr (res.comp_dir, ':');
11864
11865       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11866         res.comp_dir = cp + 1;
11867     }
11868
11869   if (res.name == NULL)
11870     res.name = "<unknown>";
11871
11872   return res;
11873 }
11874
11875 /* Handle DW_AT_stmt_list for a compilation unit.
11876    DIE is the DW_TAG_compile_unit die for CU.
11877    COMP_DIR is the compilation directory.  LOWPC is passed to
11878    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11879
11880 static void
11881 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11882                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11883 {
11884   struct dwarf2_per_objfile *dwarf2_per_objfile
11885     = cu->per_cu->dwarf2_per_objfile;
11886   struct objfile *objfile = dwarf2_per_objfile->objfile;
11887   struct attribute *attr;
11888   struct line_header line_header_local;
11889   hashval_t line_header_local_hash;
11890   void **slot;
11891   int decode_mapping;
11892
11893   gdb_assert (! cu->per_cu->is_debug_types);
11894
11895   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11896   if (attr == NULL)
11897     return;
11898
11899   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11900
11901   /* The line header hash table is only created if needed (it exists to
11902      prevent redundant reading of the line table for partial_units).
11903      If we're given a partial_unit, we'll need it.  If we're given a
11904      compile_unit, then use the line header hash table if it's already
11905      created, but don't create one just yet.  */
11906
11907   if (dwarf2_per_objfile->line_header_hash == NULL
11908       && die->tag == DW_TAG_partial_unit)
11909     {
11910       dwarf2_per_objfile->line_header_hash
11911         = htab_create_alloc_ex (127, line_header_hash_voidp,
11912                                 line_header_eq_voidp,
11913                                 free_line_header_voidp,
11914                                 &objfile->objfile_obstack,
11915                                 hashtab_obstack_allocate,
11916                                 dummy_obstack_deallocate);
11917     }
11918
11919   line_header_local.sect_off = line_offset;
11920   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11921   line_header_local_hash = line_header_hash (&line_header_local);
11922   if (dwarf2_per_objfile->line_header_hash != NULL)
11923     {
11924       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11925                                        &line_header_local,
11926                                        line_header_local_hash, NO_INSERT);
11927
11928       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11929          is not present in *SLOT (since if there is something in *SLOT then
11930          it will be for a partial_unit).  */
11931       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11932         {
11933           gdb_assert (*slot != NULL);
11934           cu->line_header = (struct line_header *) *slot;
11935           return;
11936         }
11937     }
11938
11939   /* dwarf_decode_line_header does not yet provide sufficient information.
11940      We always have to call also dwarf_decode_lines for it.  */
11941   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11942   if (lh == NULL)
11943     return;
11944
11945   cu->line_header = lh.release ();
11946   cu->line_header_die_owner = die;
11947
11948   if (dwarf2_per_objfile->line_header_hash == NULL)
11949     slot = NULL;
11950   else
11951     {
11952       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11953                                        &line_header_local,
11954                                        line_header_local_hash, INSERT);
11955       gdb_assert (slot != NULL);
11956     }
11957   if (slot != NULL && *slot == NULL)
11958     {
11959       /* This newly decoded line number information unit will be owned
11960          by line_header_hash hash table.  */
11961       *slot = cu->line_header;
11962       cu->line_header_die_owner = NULL;
11963     }
11964   else
11965     {
11966       /* We cannot free any current entry in (*slot) as that struct line_header
11967          may be already used by multiple CUs.  Create only temporary decoded
11968          line_header for this CU - it may happen at most once for each line
11969          number information unit.  And if we're not using line_header_hash
11970          then this is what we want as well.  */
11971       gdb_assert (die->tag != DW_TAG_partial_unit);
11972     }
11973   decode_mapping = (die->tag != DW_TAG_partial_unit);
11974   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11975                       decode_mapping);
11976
11977 }
11978
11979 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11980
11981 static void
11982 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11983 {
11984   struct dwarf2_per_objfile *dwarf2_per_objfile
11985     = cu->per_cu->dwarf2_per_objfile;
11986   struct objfile *objfile = dwarf2_per_objfile->objfile;
11987   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11988   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11989   CORE_ADDR highpc = ((CORE_ADDR) 0);
11990   struct attribute *attr;
11991   struct die_info *child_die;
11992   CORE_ADDR baseaddr;
11993
11994   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11995
11996   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11997
11998   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11999      from finish_block.  */
12000   if (lowpc == ((CORE_ADDR) -1))
12001     lowpc = highpc;
12002   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12003
12004   file_and_directory fnd = find_file_and_directory (die, cu);
12005
12006   prepare_one_comp_unit (cu, die, cu->language);
12007
12008   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
12009      standardised yet.  As a workaround for the language detection we fall
12010      back to the DW_AT_producer string.  */
12011   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
12012     cu->language = language_opencl;
12013
12014   /* Similar hack for Go.  */
12015   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
12016     set_cu_language (DW_LANG_Go, cu);
12017
12018   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
12019
12020   /* Decode line number information if present.  We do this before
12021      processing child DIEs, so that the line header table is available
12022      for DW_AT_decl_file.  */
12023   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
12024
12025   /* Process all dies in compilation unit.  */
12026   if (die->child != NULL)
12027     {
12028       child_die = die->child;
12029       while (child_die && child_die->tag)
12030         {
12031           process_die (child_die, cu);
12032           child_die = sibling_die (child_die);
12033         }
12034     }
12035
12036   /* Decode macro information, if present.  Dwarf 2 macro information
12037      refers to information in the line number info statement program
12038      header, so we can only read it if we've read the header
12039      successfully.  */
12040   attr = dwarf2_attr (die, DW_AT_macros, cu);
12041   if (attr == NULL)
12042     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
12043   if (attr && cu->line_header)
12044     {
12045       if (dwarf2_attr (die, DW_AT_macro_info, cu))
12046         complaint (&symfile_complaints,
12047                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
12048
12049       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
12050     }
12051   else
12052     {
12053       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
12054       if (attr && cu->line_header)
12055         {
12056           unsigned int macro_offset = DW_UNSND (attr);
12057
12058           dwarf_decode_macros (cu, macro_offset, 0);
12059         }
12060     }
12061 }
12062
12063 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
12064    Create the set of symtabs used by this TU, or if this TU is sharing
12065    symtabs with another TU and the symtabs have already been created
12066    then restore those symtabs in the line header.
12067    We don't need the pc/line-number mapping for type units.  */
12068
12069 static void
12070 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
12071 {
12072   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
12073   struct type_unit_group *tu_group;
12074   int first_time;
12075   struct attribute *attr;
12076   unsigned int i;
12077   struct signatured_type *sig_type;
12078
12079   gdb_assert (per_cu->is_debug_types);
12080   sig_type = (struct signatured_type *) per_cu;
12081
12082   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
12083
12084   /* If we're using .gdb_index (includes -readnow) then
12085      per_cu->type_unit_group may not have been set up yet.  */
12086   if (sig_type->type_unit_group == NULL)
12087     sig_type->type_unit_group = get_type_unit_group (cu, attr);
12088   tu_group = sig_type->type_unit_group;
12089
12090   /* If we've already processed this stmt_list there's no real need to
12091      do it again, we could fake it and just recreate the part we need
12092      (file name,index -> symtab mapping).  If data shows this optimization
12093      is useful we can do it then.  */
12094   first_time = tu_group->compunit_symtab == NULL;
12095
12096   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
12097      debug info.  */
12098   line_header_up lh;
12099   if (attr != NULL)
12100     {
12101       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
12102       lh = dwarf_decode_line_header (line_offset, cu);
12103     }
12104   if (lh == NULL)
12105     {
12106       if (first_time)
12107         dwarf2_start_symtab (cu, "", NULL, 0);
12108       else
12109         {
12110           gdb_assert (tu_group->symtabs == NULL);
12111           restart_symtab (tu_group->compunit_symtab, "", 0);
12112         }
12113       return;
12114     }
12115
12116   cu->line_header = lh.release ();
12117   cu->line_header_die_owner = die;
12118
12119   if (first_time)
12120     {
12121       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
12122
12123       /* Note: We don't assign tu_group->compunit_symtab yet because we're
12124          still initializing it, and our caller (a few levels up)
12125          process_full_type_unit still needs to know if this is the first
12126          time.  */
12127
12128       tu_group->num_symtabs = cu->line_header->file_names.size ();
12129       tu_group->symtabs = XNEWVEC (struct symtab *,
12130                                    cu->line_header->file_names.size ());
12131
12132       for (i = 0; i < cu->line_header->file_names.size (); ++i)
12133         {
12134           file_entry &fe = cu->line_header->file_names[i];
12135
12136           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
12137
12138           if (current_subfile->symtab == NULL)
12139             {
12140               /* NOTE: start_subfile will recognize when it's been
12141                  passed a file it has already seen.  So we can't
12142                  assume there's a simple mapping from
12143                  cu->line_header->file_names to subfiles, plus
12144                  cu->line_header->file_names may contain dups.  */
12145               current_subfile->symtab
12146                 = allocate_symtab (cust, current_subfile->name);
12147             }
12148
12149           fe.symtab = current_subfile->symtab;
12150           tu_group->symtabs[i] = fe.symtab;
12151         }
12152     }
12153   else
12154     {
12155       restart_symtab (tu_group->compunit_symtab, "", 0);
12156
12157       for (i = 0; i < cu->line_header->file_names.size (); ++i)
12158         {
12159           file_entry &fe = cu->line_header->file_names[i];
12160
12161           fe.symtab = tu_group->symtabs[i];
12162         }
12163     }
12164
12165   /* The main symtab is allocated last.  Type units don't have DW_AT_name
12166      so they don't have a "real" (so to speak) symtab anyway.
12167      There is later code that will assign the main symtab to all symbols
12168      that don't have one.  We need to handle the case of a symbol with a
12169      missing symtab (DW_AT_decl_file) anyway.  */
12170 }
12171
12172 /* Process DW_TAG_type_unit.
12173    For TUs we want to skip the first top level sibling if it's not the
12174    actual type being defined by this TU.  In this case the first top
12175    level sibling is there to provide context only.  */
12176
12177 static void
12178 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
12179 {
12180   struct die_info *child_die;
12181
12182   prepare_one_comp_unit (cu, die, language_minimal);
12183
12184   /* Initialize (or reinitialize) the machinery for building symtabs.
12185      We do this before processing child DIEs, so that the line header table
12186      is available for DW_AT_decl_file.  */
12187   setup_type_unit_groups (die, cu);
12188
12189   if (die->child != NULL)
12190     {
12191       child_die = die->child;
12192       while (child_die && child_die->tag)
12193         {
12194           process_die (child_die, cu);
12195           child_die = sibling_die (child_die);
12196         }
12197     }
12198 }
12199 \f
12200 /* DWO/DWP files.
12201
12202    http://gcc.gnu.org/wiki/DebugFission
12203    http://gcc.gnu.org/wiki/DebugFissionDWP
12204
12205    To simplify handling of both DWO files ("object" files with the DWARF info)
12206    and DWP files (a file with the DWOs packaged up into one file), we treat
12207    DWP files as having a collection of virtual DWO files.  */
12208
12209 static hashval_t
12210 hash_dwo_file (const void *item)
12211 {
12212   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
12213   hashval_t hash;
12214
12215   hash = htab_hash_string (dwo_file->dwo_name);
12216   if (dwo_file->comp_dir != NULL)
12217     hash += htab_hash_string (dwo_file->comp_dir);
12218   return hash;
12219 }
12220
12221 static int
12222 eq_dwo_file (const void *item_lhs, const void *item_rhs)
12223 {
12224   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
12225   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
12226
12227   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
12228     return 0;
12229   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
12230     return lhs->comp_dir == rhs->comp_dir;
12231   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
12232 }
12233
12234 /* Allocate a hash table for DWO files.  */
12235
12236 static htab_t
12237 allocate_dwo_file_hash_table (struct objfile *objfile)
12238 {
12239   return htab_create_alloc_ex (41,
12240                                hash_dwo_file,
12241                                eq_dwo_file,
12242                                NULL,
12243                                &objfile->objfile_obstack,
12244                                hashtab_obstack_allocate,
12245                                dummy_obstack_deallocate);
12246 }
12247
12248 /* Lookup DWO file DWO_NAME.  */
12249
12250 static void **
12251 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
12252                       const char *dwo_name,
12253                       const char *comp_dir)
12254 {
12255   struct dwo_file find_entry;
12256   void **slot;
12257
12258   if (dwarf2_per_objfile->dwo_files == NULL)
12259     dwarf2_per_objfile->dwo_files
12260       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
12261
12262   memset (&find_entry, 0, sizeof (find_entry));
12263   find_entry.dwo_name = dwo_name;
12264   find_entry.comp_dir = comp_dir;
12265   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
12266
12267   return slot;
12268 }
12269
12270 static hashval_t
12271 hash_dwo_unit (const void *item)
12272 {
12273   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12274
12275   /* This drops the top 32 bits of the id, but is ok for a hash.  */
12276   return dwo_unit->signature;
12277 }
12278
12279 static int
12280 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
12281 {
12282   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
12283   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
12284
12285   /* The signature is assumed to be unique within the DWO file.
12286      So while object file CU dwo_id's always have the value zero,
12287      that's OK, assuming each object file DWO file has only one CU,
12288      and that's the rule for now.  */
12289   return lhs->signature == rhs->signature;
12290 }
12291
12292 /* Allocate a hash table for DWO CUs,TUs.
12293    There is one of these tables for each of CUs,TUs for each DWO file.  */
12294
12295 static htab_t
12296 allocate_dwo_unit_table (struct objfile *objfile)
12297 {
12298   /* Start out with a pretty small number.
12299      Generally DWO files contain only one CU and maybe some TUs.  */
12300   return htab_create_alloc_ex (3,
12301                                hash_dwo_unit,
12302                                eq_dwo_unit,
12303                                NULL,
12304                                &objfile->objfile_obstack,
12305                                hashtab_obstack_allocate,
12306                                dummy_obstack_deallocate);
12307 }
12308
12309 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
12310
12311 struct create_dwo_cu_data
12312 {
12313   struct dwo_file *dwo_file;
12314   struct dwo_unit dwo_unit;
12315 };
12316
12317 /* die_reader_func for create_dwo_cu.  */
12318
12319 static void
12320 create_dwo_cu_reader (const struct die_reader_specs *reader,
12321                       const gdb_byte *info_ptr,
12322                       struct die_info *comp_unit_die,
12323                       int has_children,
12324                       void *datap)
12325 {
12326   struct dwarf2_cu *cu = reader->cu;
12327   sect_offset sect_off = cu->per_cu->sect_off;
12328   struct dwarf2_section_info *section = cu->per_cu->section;
12329   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
12330   struct dwo_file *dwo_file = data->dwo_file;
12331   struct dwo_unit *dwo_unit = &data->dwo_unit;
12332   struct attribute *attr;
12333
12334   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
12335   if (attr == NULL)
12336     {
12337       complaint (&symfile_complaints,
12338                  _("Dwarf Error: debug entry at offset %s is missing"
12339                    " its dwo_id [in module %s]"),
12340                  sect_offset_str (sect_off), dwo_file->dwo_name);
12341       return;
12342     }
12343
12344   dwo_unit->dwo_file = dwo_file;
12345   dwo_unit->signature = DW_UNSND (attr);
12346   dwo_unit->section = section;
12347   dwo_unit->sect_off = sect_off;
12348   dwo_unit->length = cu->per_cu->length;
12349
12350   if (dwarf_read_debug)
12351     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
12352                         sect_offset_str (sect_off),
12353                         hex_string (dwo_unit->signature));
12354 }
12355
12356 /* Create the dwo_units for the CUs in a DWO_FILE.
12357    Note: This function processes DWO files only, not DWP files.  */
12358
12359 static void
12360 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12361                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12362                        htab_t &cus_htab)
12363 {
12364   struct objfile *objfile = dwarf2_per_objfile->objfile;
12365   const gdb_byte *info_ptr, *end_ptr;
12366
12367   dwarf2_read_section (objfile, &section);
12368   info_ptr = section.buffer;
12369
12370   if (info_ptr == NULL)
12371     return;
12372
12373   if (dwarf_read_debug)
12374     {
12375       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12376                           get_section_name (&section),
12377                           get_section_file_name (&section));
12378     }
12379
12380   end_ptr = info_ptr + section.size;
12381   while (info_ptr < end_ptr)
12382     {
12383       struct dwarf2_per_cu_data per_cu;
12384       struct create_dwo_cu_data create_dwo_cu_data;
12385       struct dwo_unit *dwo_unit;
12386       void **slot;
12387       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12388
12389       memset (&create_dwo_cu_data.dwo_unit, 0,
12390               sizeof (create_dwo_cu_data.dwo_unit));
12391       memset (&per_cu, 0, sizeof (per_cu));
12392       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12393       per_cu.is_debug_types = 0;
12394       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12395       per_cu.section = &section;
12396       create_dwo_cu_data.dwo_file = &dwo_file;
12397
12398       init_cutu_and_read_dies_no_follow (
12399           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12400       info_ptr += per_cu.length;
12401
12402       // If the unit could not be parsed, skip it.
12403       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12404         continue;
12405
12406       if (cus_htab == NULL)
12407         cus_htab = allocate_dwo_unit_table (objfile);
12408
12409       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12410       *dwo_unit = create_dwo_cu_data.dwo_unit;
12411       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12412       gdb_assert (slot != NULL);
12413       if (*slot != NULL)
12414         {
12415           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12416           sect_offset dup_sect_off = dup_cu->sect_off;
12417
12418           complaint (&symfile_complaints,
12419                      _("debug cu entry at offset %s is duplicate to"
12420                        " the entry at offset %s, signature %s"),
12421                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
12422                      hex_string (dwo_unit->signature));
12423         }
12424       *slot = (void *)dwo_unit;
12425     }
12426 }
12427
12428 /* DWP file .debug_{cu,tu}_index section format:
12429    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12430
12431    DWP Version 1:
12432
12433    Both index sections have the same format, and serve to map a 64-bit
12434    signature to a set of section numbers.  Each section begins with a header,
12435    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12436    indexes, and a pool of 32-bit section numbers.  The index sections will be
12437    aligned at 8-byte boundaries in the file.
12438
12439    The index section header consists of:
12440
12441     V, 32 bit version number
12442     -, 32 bits unused
12443     N, 32 bit number of compilation units or type units in the index
12444     M, 32 bit number of slots in the hash table
12445
12446    Numbers are recorded using the byte order of the application binary.
12447
12448    The hash table begins at offset 16 in the section, and consists of an array
12449    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12450    order of the application binary).  Unused slots in the hash table are 0.
12451    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12452
12453    The parallel table begins immediately after the hash table
12454    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12455    array of 32-bit indexes (using the byte order of the application binary),
12456    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12457    table contains a 32-bit index into the pool of section numbers.  For unused
12458    hash table slots, the corresponding entry in the parallel table will be 0.
12459
12460    The pool of section numbers begins immediately following the hash table
12461    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12462    section numbers consists of an array of 32-bit words (using the byte order
12463    of the application binary).  Each item in the array is indexed starting
12464    from 0.  The hash table entry provides the index of the first section
12465    number in the set.  Additional section numbers in the set follow, and the
12466    set is terminated by a 0 entry (section number 0 is not used in ELF).
12467
12468    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12469    section must be the first entry in the set, and the .debug_abbrev.dwo must
12470    be the second entry. Other members of the set may follow in any order.
12471
12472    ---
12473
12474    DWP Version 2:
12475
12476    DWP Version 2 combines all the .debug_info, etc. sections into one,
12477    and the entries in the index tables are now offsets into these sections.
12478    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12479    section.
12480
12481    Index Section Contents:
12482     Header
12483     Hash Table of Signatures   dwp_hash_table.hash_table
12484     Parallel Table of Indices  dwp_hash_table.unit_table
12485     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12486     Table of Section Sizes     dwp_hash_table.v2.sizes
12487
12488    The index section header consists of:
12489
12490     V, 32 bit version number
12491     L, 32 bit number of columns in the table of section offsets
12492     N, 32 bit number of compilation units or type units in the index
12493     M, 32 bit number of slots in the hash table
12494
12495    Numbers are recorded using the byte order of the application binary.
12496
12497    The hash table has the same format as version 1.
12498    The parallel table of indices has the same format as version 1,
12499    except that the entries are origin-1 indices into the table of sections
12500    offsets and the table of section sizes.
12501
12502    The table of offsets begins immediately following the parallel table
12503    (at offset 16 + 12 * M from the beginning of the section).  The table is
12504    a two-dimensional array of 32-bit words (using the byte order of the
12505    application binary), with L columns and N+1 rows, in row-major order.
12506    Each row in the array is indexed starting from 0.  The first row provides
12507    a key to the remaining rows: each column in this row provides an identifier
12508    for a debug section, and the offsets in the same column of subsequent rows
12509    refer to that section.  The section identifiers are:
12510
12511     DW_SECT_INFO         1  .debug_info.dwo
12512     DW_SECT_TYPES        2  .debug_types.dwo
12513     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12514     DW_SECT_LINE         4  .debug_line.dwo
12515     DW_SECT_LOC          5  .debug_loc.dwo
12516     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12517     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12518     DW_SECT_MACRO        8  .debug_macro.dwo
12519
12520    The offsets provided by the CU and TU index sections are the base offsets
12521    for the contributions made by each CU or TU to the corresponding section
12522    in the package file.  Each CU and TU header contains an abbrev_offset
12523    field, used to find the abbreviations table for that CU or TU within the
12524    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12525    be interpreted as relative to the base offset given in the index section.
12526    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12527    should be interpreted as relative to the base offset for .debug_line.dwo,
12528    and offsets into other debug sections obtained from DWARF attributes should
12529    also be interpreted as relative to the corresponding base offset.
12530
12531    The table of sizes begins immediately following the table of offsets.
12532    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12533    with L columns and N rows, in row-major order.  Each row in the array is
12534    indexed starting from 1 (row 0 is shared by the two tables).
12535
12536    ---
12537
12538    Hash table lookup is handled the same in version 1 and 2:
12539
12540    We assume that N and M will not exceed 2^32 - 1.
12541    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12542
12543    Given a 64-bit compilation unit signature or a type signature S, an entry
12544    in the hash table is located as follows:
12545
12546    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12547       the low-order k bits all set to 1.
12548
12549    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12550
12551    3) If the hash table entry at index H matches the signature, use that
12552       entry.  If the hash table entry at index H is unused (all zeroes),
12553       terminate the search: the signature is not present in the table.
12554
12555    4) Let H = (H + H') modulo M. Repeat at Step 3.
12556
12557    Because M > N and H' and M are relatively prime, the search is guaranteed
12558    to stop at an unused slot or find the match.  */
12559
12560 /* Create a hash table to map DWO IDs to their CU/TU entry in
12561    .debug_{info,types}.dwo in DWP_FILE.
12562    Returns NULL if there isn't one.
12563    Note: This function processes DWP files only, not DWO files.  */
12564
12565 static struct dwp_hash_table *
12566 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12567                        struct dwp_file *dwp_file, int is_debug_types)
12568 {
12569   struct objfile *objfile = dwarf2_per_objfile->objfile;
12570   bfd *dbfd = dwp_file->dbfd;
12571   const gdb_byte *index_ptr, *index_end;
12572   struct dwarf2_section_info *index;
12573   uint32_t version, nr_columns, nr_units, nr_slots;
12574   struct dwp_hash_table *htab;
12575
12576   if (is_debug_types)
12577     index = &dwp_file->sections.tu_index;
12578   else
12579     index = &dwp_file->sections.cu_index;
12580
12581   if (dwarf2_section_empty_p (index))
12582     return NULL;
12583   dwarf2_read_section (objfile, index);
12584
12585   index_ptr = index->buffer;
12586   index_end = index_ptr + index->size;
12587
12588   version = read_4_bytes (dbfd, index_ptr);
12589   index_ptr += 4;
12590   if (version == 2)
12591     nr_columns = read_4_bytes (dbfd, index_ptr);
12592   else
12593     nr_columns = 0;
12594   index_ptr += 4;
12595   nr_units = read_4_bytes (dbfd, index_ptr);
12596   index_ptr += 4;
12597   nr_slots = read_4_bytes (dbfd, index_ptr);
12598   index_ptr += 4;
12599
12600   if (version != 1 && version != 2)
12601     {
12602       error (_("Dwarf Error: unsupported DWP file version (%s)"
12603                " [in module %s]"),
12604              pulongest (version), dwp_file->name);
12605     }
12606   if (nr_slots != (nr_slots & -nr_slots))
12607     {
12608       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12609                " is not power of 2 [in module %s]"),
12610              pulongest (nr_slots), dwp_file->name);
12611     }
12612
12613   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12614   htab->version = version;
12615   htab->nr_columns = nr_columns;
12616   htab->nr_units = nr_units;
12617   htab->nr_slots = nr_slots;
12618   htab->hash_table = index_ptr;
12619   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12620
12621   /* Exit early if the table is empty.  */
12622   if (nr_slots == 0 || nr_units == 0
12623       || (version == 2 && nr_columns == 0))
12624     {
12625       /* All must be zero.  */
12626       if (nr_slots != 0 || nr_units != 0
12627           || (version == 2 && nr_columns != 0))
12628         {
12629           complaint (&symfile_complaints,
12630                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12631                        " all zero [in modules %s]"),
12632                      dwp_file->name);
12633         }
12634       return htab;
12635     }
12636
12637   if (version == 1)
12638     {
12639       htab->section_pool.v1.indices =
12640         htab->unit_table + sizeof (uint32_t) * nr_slots;
12641       /* It's harder to decide whether the section is too small in v1.
12642          V1 is deprecated anyway so we punt.  */
12643     }
12644   else
12645     {
12646       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12647       int *ids = htab->section_pool.v2.section_ids;
12648       /* Reverse map for error checking.  */
12649       int ids_seen[DW_SECT_MAX + 1];
12650       int i;
12651
12652       if (nr_columns < 2)
12653         {
12654           error (_("Dwarf Error: bad DWP hash table, too few columns"
12655                    " in section table [in module %s]"),
12656                  dwp_file->name);
12657         }
12658       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12659         {
12660           error (_("Dwarf Error: bad DWP hash table, too many columns"
12661                    " in section table [in module %s]"),
12662                  dwp_file->name);
12663         }
12664       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12665       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12666       for (i = 0; i < nr_columns; ++i)
12667         {
12668           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12669
12670           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12671             {
12672               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12673                        " in section table [in module %s]"),
12674                      id, dwp_file->name);
12675             }
12676           if (ids_seen[id] != -1)
12677             {
12678               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12679                        " id %d in section table [in module %s]"),
12680                      id, dwp_file->name);
12681             }
12682           ids_seen[id] = i;
12683           ids[i] = id;
12684         }
12685       /* Must have exactly one info or types section.  */
12686       if (((ids_seen[DW_SECT_INFO] != -1)
12687            + (ids_seen[DW_SECT_TYPES] != -1))
12688           != 1)
12689         {
12690           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12691                    " DWO info/types section [in module %s]"),
12692                  dwp_file->name);
12693         }
12694       /* Must have an abbrev section.  */
12695       if (ids_seen[DW_SECT_ABBREV] == -1)
12696         {
12697           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12698                    " section [in module %s]"),
12699                  dwp_file->name);
12700         }
12701       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12702       htab->section_pool.v2.sizes =
12703         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12704                                          * nr_units * nr_columns);
12705       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12706                                           * nr_units * nr_columns))
12707           > index_end)
12708         {
12709           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12710                    " [in module %s]"),
12711                  dwp_file->name);
12712         }
12713     }
12714
12715   return htab;
12716 }
12717
12718 /* Update SECTIONS with the data from SECTP.
12719
12720    This function is like the other "locate" section routines that are
12721    passed to bfd_map_over_sections, but in this context the sections to
12722    read comes from the DWP V1 hash table, not the full ELF section table.
12723
12724    The result is non-zero for success, or zero if an error was found.  */
12725
12726 static int
12727 locate_v1_virtual_dwo_sections (asection *sectp,
12728                                 struct virtual_v1_dwo_sections *sections)
12729 {
12730   const struct dwop_section_names *names = &dwop_section_names;
12731
12732   if (section_is_p (sectp->name, &names->abbrev_dwo))
12733     {
12734       /* There can be only one.  */
12735       if (sections->abbrev.s.section != NULL)
12736         return 0;
12737       sections->abbrev.s.section = sectp;
12738       sections->abbrev.size = bfd_get_section_size (sectp);
12739     }
12740   else if (section_is_p (sectp->name, &names->info_dwo)
12741            || section_is_p (sectp->name, &names->types_dwo))
12742     {
12743       /* There can be only one.  */
12744       if (sections->info_or_types.s.section != NULL)
12745         return 0;
12746       sections->info_or_types.s.section = sectp;
12747       sections->info_or_types.size = bfd_get_section_size (sectp);
12748     }
12749   else if (section_is_p (sectp->name, &names->line_dwo))
12750     {
12751       /* There can be only one.  */
12752       if (sections->line.s.section != NULL)
12753         return 0;
12754       sections->line.s.section = sectp;
12755       sections->line.size = bfd_get_section_size (sectp);
12756     }
12757   else if (section_is_p (sectp->name, &names->loc_dwo))
12758     {
12759       /* There can be only one.  */
12760       if (sections->loc.s.section != NULL)
12761         return 0;
12762       sections->loc.s.section = sectp;
12763       sections->loc.size = bfd_get_section_size (sectp);
12764     }
12765   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12766     {
12767       /* There can be only one.  */
12768       if (sections->macinfo.s.section != NULL)
12769         return 0;
12770       sections->macinfo.s.section = sectp;
12771       sections->macinfo.size = bfd_get_section_size (sectp);
12772     }
12773   else if (section_is_p (sectp->name, &names->macro_dwo))
12774     {
12775       /* There can be only one.  */
12776       if (sections->macro.s.section != NULL)
12777         return 0;
12778       sections->macro.s.section = sectp;
12779       sections->macro.size = bfd_get_section_size (sectp);
12780     }
12781   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12782     {
12783       /* There can be only one.  */
12784       if (sections->str_offsets.s.section != NULL)
12785         return 0;
12786       sections->str_offsets.s.section = sectp;
12787       sections->str_offsets.size = bfd_get_section_size (sectp);
12788     }
12789   else
12790     {
12791       /* No other kind of section is valid.  */
12792       return 0;
12793     }
12794
12795   return 1;
12796 }
12797
12798 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12799    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12800    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12801    This is for DWP version 1 files.  */
12802
12803 static struct dwo_unit *
12804 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12805                            struct dwp_file *dwp_file,
12806                            uint32_t unit_index,
12807                            const char *comp_dir,
12808                            ULONGEST signature, int is_debug_types)
12809 {
12810   struct objfile *objfile = dwarf2_per_objfile->objfile;
12811   const struct dwp_hash_table *dwp_htab =
12812     is_debug_types ? dwp_file->tus : dwp_file->cus;
12813   bfd *dbfd = dwp_file->dbfd;
12814   const char *kind = is_debug_types ? "TU" : "CU";
12815   struct dwo_file *dwo_file;
12816   struct dwo_unit *dwo_unit;
12817   struct virtual_v1_dwo_sections sections;
12818   void **dwo_file_slot;
12819   int i;
12820
12821   gdb_assert (dwp_file->version == 1);
12822
12823   if (dwarf_read_debug)
12824     {
12825       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12826                           kind,
12827                           pulongest (unit_index), hex_string (signature),
12828                           dwp_file->name);
12829     }
12830
12831   /* Fetch the sections of this DWO unit.
12832      Put a limit on the number of sections we look for so that bad data
12833      doesn't cause us to loop forever.  */
12834
12835 #define MAX_NR_V1_DWO_SECTIONS \
12836   (1 /* .debug_info or .debug_types */ \
12837    + 1 /* .debug_abbrev */ \
12838    + 1 /* .debug_line */ \
12839    + 1 /* .debug_loc */ \
12840    + 1 /* .debug_str_offsets */ \
12841    + 1 /* .debug_macro or .debug_macinfo */ \
12842    + 1 /* trailing zero */)
12843
12844   memset (&sections, 0, sizeof (sections));
12845
12846   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12847     {
12848       asection *sectp;
12849       uint32_t section_nr =
12850         read_4_bytes (dbfd,
12851                       dwp_htab->section_pool.v1.indices
12852                       + (unit_index + i) * sizeof (uint32_t));
12853
12854       if (section_nr == 0)
12855         break;
12856       if (section_nr >= dwp_file->num_sections)
12857         {
12858           error (_("Dwarf Error: bad DWP hash table, section number too large"
12859                    " [in module %s]"),
12860                  dwp_file->name);
12861         }
12862
12863       sectp = dwp_file->elf_sections[section_nr];
12864       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12865         {
12866           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12867                    " [in module %s]"),
12868                  dwp_file->name);
12869         }
12870     }
12871
12872   if (i < 2
12873       || dwarf2_section_empty_p (&sections.info_or_types)
12874       || dwarf2_section_empty_p (&sections.abbrev))
12875     {
12876       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12877                " [in module %s]"),
12878              dwp_file->name);
12879     }
12880   if (i == MAX_NR_V1_DWO_SECTIONS)
12881     {
12882       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12883                " [in module %s]"),
12884              dwp_file->name);
12885     }
12886
12887   /* It's easier for the rest of the code if we fake a struct dwo_file and
12888      have dwo_unit "live" in that.  At least for now.
12889
12890      The DWP file can be made up of a random collection of CUs and TUs.
12891      However, for each CU + set of TUs that came from the same original DWO
12892      file, we can combine them back into a virtual DWO file to save space
12893      (fewer struct dwo_file objects to allocate).  Remember that for really
12894      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12895
12896   std::string virtual_dwo_name =
12897     string_printf ("virtual-dwo/%d-%d-%d-%d",
12898                    get_section_id (&sections.abbrev),
12899                    get_section_id (&sections.line),
12900                    get_section_id (&sections.loc),
12901                    get_section_id (&sections.str_offsets));
12902   /* Can we use an existing virtual DWO file?  */
12903   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12904                                         virtual_dwo_name.c_str (),
12905                                         comp_dir);
12906   /* Create one if necessary.  */
12907   if (*dwo_file_slot == NULL)
12908     {
12909       if (dwarf_read_debug)
12910         {
12911           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12912                               virtual_dwo_name.c_str ());
12913         }
12914       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12915       dwo_file->dwo_name
12916         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12917                                         virtual_dwo_name.c_str (),
12918                                         virtual_dwo_name.size ());
12919       dwo_file->comp_dir = comp_dir;
12920       dwo_file->sections.abbrev = sections.abbrev;
12921       dwo_file->sections.line = sections.line;
12922       dwo_file->sections.loc = sections.loc;
12923       dwo_file->sections.macinfo = sections.macinfo;
12924       dwo_file->sections.macro = sections.macro;
12925       dwo_file->sections.str_offsets = sections.str_offsets;
12926       /* The "str" section is global to the entire DWP file.  */
12927       dwo_file->sections.str = dwp_file->sections.str;
12928       /* The info or types section is assigned below to dwo_unit,
12929          there's no need to record it in dwo_file.
12930          Also, we can't simply record type sections in dwo_file because
12931          we record a pointer into the vector in dwo_unit.  As we collect more
12932          types we'll grow the vector and eventually have to reallocate space
12933          for it, invalidating all copies of pointers into the previous
12934          contents.  */
12935       *dwo_file_slot = dwo_file;
12936     }
12937   else
12938     {
12939       if (dwarf_read_debug)
12940         {
12941           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12942                               virtual_dwo_name.c_str ());
12943         }
12944       dwo_file = (struct dwo_file *) *dwo_file_slot;
12945     }
12946
12947   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12948   dwo_unit->dwo_file = dwo_file;
12949   dwo_unit->signature = signature;
12950   dwo_unit->section =
12951     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12952   *dwo_unit->section = sections.info_or_types;
12953   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12954
12955   return dwo_unit;
12956 }
12957
12958 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12959    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12960    piece within that section used by a TU/CU, return a virtual section
12961    of just that piece.  */
12962
12963 static struct dwarf2_section_info
12964 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12965                        struct dwarf2_section_info *section,
12966                        bfd_size_type offset, bfd_size_type size)
12967 {
12968   struct dwarf2_section_info result;
12969   asection *sectp;
12970
12971   gdb_assert (section != NULL);
12972   gdb_assert (!section->is_virtual);
12973
12974   memset (&result, 0, sizeof (result));
12975   result.s.containing_section = section;
12976   result.is_virtual = 1;
12977
12978   if (size == 0)
12979     return result;
12980
12981   sectp = get_section_bfd_section (section);
12982
12983   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12984      bounds of the real section.  This is a pretty-rare event, so just
12985      flag an error (easier) instead of a warning and trying to cope.  */
12986   if (sectp == NULL
12987       || offset + size > bfd_get_section_size (sectp))
12988     {
12989       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12990                " in section %s [in module %s]"),
12991              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12992              objfile_name (dwarf2_per_objfile->objfile));
12993     }
12994
12995   result.virtual_offset = offset;
12996   result.size = size;
12997   return result;
12998 }
12999
13000 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
13001    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
13002    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
13003    This is for DWP version 2 files.  */
13004
13005 static struct dwo_unit *
13006 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
13007                            struct dwp_file *dwp_file,
13008                            uint32_t unit_index,
13009                            const char *comp_dir,
13010                            ULONGEST signature, int is_debug_types)
13011 {
13012   struct objfile *objfile = dwarf2_per_objfile->objfile;
13013   const struct dwp_hash_table *dwp_htab =
13014     is_debug_types ? dwp_file->tus : dwp_file->cus;
13015   bfd *dbfd = dwp_file->dbfd;
13016   const char *kind = is_debug_types ? "TU" : "CU";
13017   struct dwo_file *dwo_file;
13018   struct dwo_unit *dwo_unit;
13019   struct virtual_v2_dwo_sections sections;
13020   void **dwo_file_slot;
13021   int i;
13022
13023   gdb_assert (dwp_file->version == 2);
13024
13025   if (dwarf_read_debug)
13026     {
13027       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
13028                           kind,
13029                           pulongest (unit_index), hex_string (signature),
13030                           dwp_file->name);
13031     }
13032
13033   /* Fetch the section offsets of this DWO unit.  */
13034
13035   memset (&sections, 0, sizeof (sections));
13036
13037   for (i = 0; i < dwp_htab->nr_columns; ++i)
13038     {
13039       uint32_t offset = read_4_bytes (dbfd,
13040                                       dwp_htab->section_pool.v2.offsets
13041                                       + (((unit_index - 1) * dwp_htab->nr_columns
13042                                           + i)
13043                                          * sizeof (uint32_t)));
13044       uint32_t size = read_4_bytes (dbfd,
13045                                     dwp_htab->section_pool.v2.sizes
13046                                     + (((unit_index - 1) * dwp_htab->nr_columns
13047                                         + i)
13048                                        * sizeof (uint32_t)));
13049
13050       switch (dwp_htab->section_pool.v2.section_ids[i])
13051         {
13052         case DW_SECT_INFO:
13053         case DW_SECT_TYPES:
13054           sections.info_or_types_offset = offset;
13055           sections.info_or_types_size = size;
13056           break;
13057         case DW_SECT_ABBREV:
13058           sections.abbrev_offset = offset;
13059           sections.abbrev_size = size;
13060           break;
13061         case DW_SECT_LINE:
13062           sections.line_offset = offset;
13063           sections.line_size = size;
13064           break;
13065         case DW_SECT_LOC:
13066           sections.loc_offset = offset;
13067           sections.loc_size = size;
13068           break;
13069         case DW_SECT_STR_OFFSETS:
13070           sections.str_offsets_offset = offset;
13071           sections.str_offsets_size = size;
13072           break;
13073         case DW_SECT_MACINFO:
13074           sections.macinfo_offset = offset;
13075           sections.macinfo_size = size;
13076           break;
13077         case DW_SECT_MACRO:
13078           sections.macro_offset = offset;
13079           sections.macro_size = size;
13080           break;
13081         }
13082     }
13083
13084   /* It's easier for the rest of the code if we fake a struct dwo_file and
13085      have dwo_unit "live" in that.  At least for now.
13086
13087      The DWP file can be made up of a random collection of CUs and TUs.
13088      However, for each CU + set of TUs that came from the same original DWO
13089      file, we can combine them back into a virtual DWO file to save space
13090      (fewer struct dwo_file objects to allocate).  Remember that for really
13091      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
13092
13093   std::string virtual_dwo_name =
13094     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
13095                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
13096                    (long) (sections.line_size ? sections.line_offset : 0),
13097                    (long) (sections.loc_size ? sections.loc_offset : 0),
13098                    (long) (sections.str_offsets_size
13099                            ? sections.str_offsets_offset : 0));
13100   /* Can we use an existing virtual DWO file?  */
13101   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13102                                         virtual_dwo_name.c_str (),
13103                                         comp_dir);
13104   /* Create one if necessary.  */
13105   if (*dwo_file_slot == NULL)
13106     {
13107       if (dwarf_read_debug)
13108         {
13109           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
13110                               virtual_dwo_name.c_str ());
13111         }
13112       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13113       dwo_file->dwo_name
13114         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
13115                                         virtual_dwo_name.c_str (),
13116                                         virtual_dwo_name.size ());
13117       dwo_file->comp_dir = comp_dir;
13118       dwo_file->sections.abbrev =
13119         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
13120                                sections.abbrev_offset, sections.abbrev_size);
13121       dwo_file->sections.line =
13122         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
13123                                sections.line_offset, sections.line_size);
13124       dwo_file->sections.loc =
13125         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
13126                                sections.loc_offset, sections.loc_size);
13127       dwo_file->sections.macinfo =
13128         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
13129                                sections.macinfo_offset, sections.macinfo_size);
13130       dwo_file->sections.macro =
13131         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
13132                                sections.macro_offset, sections.macro_size);
13133       dwo_file->sections.str_offsets =
13134         create_dwp_v2_section (dwarf2_per_objfile,
13135                                &dwp_file->sections.str_offsets,
13136                                sections.str_offsets_offset,
13137                                sections.str_offsets_size);
13138       /* The "str" section is global to the entire DWP file.  */
13139       dwo_file->sections.str = dwp_file->sections.str;
13140       /* The info or types section is assigned below to dwo_unit,
13141          there's no need to record it in dwo_file.
13142          Also, we can't simply record type sections in dwo_file because
13143          we record a pointer into the vector in dwo_unit.  As we collect more
13144          types we'll grow the vector and eventually have to reallocate space
13145          for it, invalidating all copies of pointers into the previous
13146          contents.  */
13147       *dwo_file_slot = dwo_file;
13148     }
13149   else
13150     {
13151       if (dwarf_read_debug)
13152         {
13153           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
13154                               virtual_dwo_name.c_str ());
13155         }
13156       dwo_file = (struct dwo_file *) *dwo_file_slot;
13157     }
13158
13159   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
13160   dwo_unit->dwo_file = dwo_file;
13161   dwo_unit->signature = signature;
13162   dwo_unit->section =
13163     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
13164   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
13165                                               is_debug_types
13166                                               ? &dwp_file->sections.types
13167                                               : &dwp_file->sections.info,
13168                                               sections.info_or_types_offset,
13169                                               sections.info_or_types_size);
13170   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
13171
13172   return dwo_unit;
13173 }
13174
13175 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
13176    Returns NULL if the signature isn't found.  */
13177
13178 static struct dwo_unit *
13179 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
13180                         struct dwp_file *dwp_file, const char *comp_dir,
13181                         ULONGEST signature, int is_debug_types)
13182 {
13183   const struct dwp_hash_table *dwp_htab =
13184     is_debug_types ? dwp_file->tus : dwp_file->cus;
13185   bfd *dbfd = dwp_file->dbfd;
13186   uint32_t mask = dwp_htab->nr_slots - 1;
13187   uint32_t hash = signature & mask;
13188   uint32_t hash2 = ((signature >> 32) & mask) | 1;
13189   unsigned int i;
13190   void **slot;
13191   struct dwo_unit find_dwo_cu;
13192
13193   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
13194   find_dwo_cu.signature = signature;
13195   slot = htab_find_slot (is_debug_types
13196                          ? dwp_file->loaded_tus
13197                          : dwp_file->loaded_cus,
13198                          &find_dwo_cu, INSERT);
13199
13200   if (*slot != NULL)
13201     return (struct dwo_unit *) *slot;
13202
13203   /* Use a for loop so that we don't loop forever on bad debug info.  */
13204   for (i = 0; i < dwp_htab->nr_slots; ++i)
13205     {
13206       ULONGEST signature_in_table;
13207
13208       signature_in_table =
13209         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
13210       if (signature_in_table == signature)
13211         {
13212           uint32_t unit_index =
13213             read_4_bytes (dbfd,
13214                           dwp_htab->unit_table + hash * sizeof (uint32_t));
13215
13216           if (dwp_file->version == 1)
13217             {
13218               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
13219                                                  dwp_file, unit_index,
13220                                                  comp_dir, signature,
13221                                                  is_debug_types);
13222             }
13223           else
13224             {
13225               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
13226                                                  dwp_file, unit_index,
13227                                                  comp_dir, signature,
13228                                                  is_debug_types);
13229             }
13230           return (struct dwo_unit *) *slot;
13231         }
13232       if (signature_in_table == 0)
13233         return NULL;
13234       hash = (hash + hash2) & mask;
13235     }
13236
13237   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
13238            " [in module %s]"),
13239          dwp_file->name);
13240 }
13241
13242 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
13243    Open the file specified by FILE_NAME and hand it off to BFD for
13244    preliminary analysis.  Return a newly initialized bfd *, which
13245    includes a canonicalized copy of FILE_NAME.
13246    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
13247    SEARCH_CWD is true if the current directory is to be searched.
13248    It will be searched before debug-file-directory.
13249    If successful, the file is added to the bfd include table of the
13250    objfile's bfd (see gdb_bfd_record_inclusion).
13251    If unable to find/open the file, return NULL.
13252    NOTE: This function is derived from symfile_bfd_open.  */
13253
13254 static gdb_bfd_ref_ptr
13255 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13256                     const char *file_name, int is_dwp, int search_cwd)
13257 {
13258   int desc;
13259   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
13260      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
13261      to debug_file_directory.  */
13262   const char *search_path;
13263   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
13264
13265   gdb::unique_xmalloc_ptr<char> search_path_holder;
13266   if (search_cwd)
13267     {
13268       if (*debug_file_directory != '\0')
13269         {
13270           search_path_holder.reset (concat (".", dirname_separator_string,
13271                                             debug_file_directory,
13272                                             (char *) NULL));
13273           search_path = search_path_holder.get ();
13274         }
13275       else
13276         search_path = ".";
13277     }
13278   else
13279     search_path = debug_file_directory;
13280
13281   openp_flags flags = OPF_RETURN_REALPATH;
13282   if (is_dwp)
13283     flags |= OPF_SEARCH_IN_PATH;
13284
13285   gdb::unique_xmalloc_ptr<char> absolute_name;
13286   desc = openp (search_path, flags, file_name,
13287                 O_RDONLY | O_BINARY, &absolute_name);
13288   if (desc < 0)
13289     return NULL;
13290
13291   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
13292                                          gnutarget, desc));
13293   if (sym_bfd == NULL)
13294     return NULL;
13295   bfd_set_cacheable (sym_bfd.get (), 1);
13296
13297   if (!bfd_check_format (sym_bfd.get (), bfd_object))
13298     return NULL;
13299
13300   /* Success.  Record the bfd as having been included by the objfile's bfd.
13301      This is important because things like demangled_names_hash lives in the
13302      objfile's per_bfd space and may have references to things like symbol
13303      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
13304   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
13305
13306   return sym_bfd;
13307 }
13308
13309 /* Try to open DWO file FILE_NAME.
13310    COMP_DIR is the DW_AT_comp_dir attribute.
13311    The result is the bfd handle of the file.
13312    If there is a problem finding or opening the file, return NULL.
13313    Upon success, the canonicalized path of the file is stored in the bfd,
13314    same as symfile_bfd_open.  */
13315
13316 static gdb_bfd_ref_ptr
13317 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13318                const char *file_name, const char *comp_dir)
13319 {
13320   if (IS_ABSOLUTE_PATH (file_name))
13321     return try_open_dwop_file (dwarf2_per_objfile, file_name,
13322                                0 /*is_dwp*/, 0 /*search_cwd*/);
13323
13324   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
13325
13326   if (comp_dir != NULL)
13327     {
13328       char *path_to_try = concat (comp_dir, SLASH_STRING,
13329                                   file_name, (char *) NULL);
13330
13331       /* NOTE: If comp_dir is a relative path, this will also try the
13332          search path, which seems useful.  */
13333       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
13334                                                 path_to_try,
13335                                                 0 /*is_dwp*/,
13336                                                 1 /*search_cwd*/));
13337       xfree (path_to_try);
13338       if (abfd != NULL)
13339         return abfd;
13340     }
13341
13342   /* That didn't work, try debug-file-directory, which, despite its name,
13343      is a list of paths.  */
13344
13345   if (*debug_file_directory == '\0')
13346     return NULL;
13347
13348   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13349                              0 /*is_dwp*/, 1 /*search_cwd*/);
13350 }
13351
13352 /* This function is mapped across the sections and remembers the offset and
13353    size of each of the DWO debugging sections we are interested in.  */
13354
13355 static void
13356 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13357 {
13358   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13359   const struct dwop_section_names *names = &dwop_section_names;
13360
13361   if (section_is_p (sectp->name, &names->abbrev_dwo))
13362     {
13363       dwo_sections->abbrev.s.section = sectp;
13364       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13365     }
13366   else if (section_is_p (sectp->name, &names->info_dwo))
13367     {
13368       dwo_sections->info.s.section = sectp;
13369       dwo_sections->info.size = bfd_get_section_size (sectp);
13370     }
13371   else if (section_is_p (sectp->name, &names->line_dwo))
13372     {
13373       dwo_sections->line.s.section = sectp;
13374       dwo_sections->line.size = bfd_get_section_size (sectp);
13375     }
13376   else if (section_is_p (sectp->name, &names->loc_dwo))
13377     {
13378       dwo_sections->loc.s.section = sectp;
13379       dwo_sections->loc.size = bfd_get_section_size (sectp);
13380     }
13381   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13382     {
13383       dwo_sections->macinfo.s.section = sectp;
13384       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13385     }
13386   else if (section_is_p (sectp->name, &names->macro_dwo))
13387     {
13388       dwo_sections->macro.s.section = sectp;
13389       dwo_sections->macro.size = bfd_get_section_size (sectp);
13390     }
13391   else if (section_is_p (sectp->name, &names->str_dwo))
13392     {
13393       dwo_sections->str.s.section = sectp;
13394       dwo_sections->str.size = bfd_get_section_size (sectp);
13395     }
13396   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13397     {
13398       dwo_sections->str_offsets.s.section = sectp;
13399       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13400     }
13401   else if (section_is_p (sectp->name, &names->types_dwo))
13402     {
13403       struct dwarf2_section_info type_section;
13404
13405       memset (&type_section, 0, sizeof (type_section));
13406       type_section.s.section = sectp;
13407       type_section.size = bfd_get_section_size (sectp);
13408       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13409                      &type_section);
13410     }
13411 }
13412
13413 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13414    by PER_CU.  This is for the non-DWP case.
13415    The result is NULL if DWO_NAME can't be found.  */
13416
13417 static struct dwo_file *
13418 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13419                         const char *dwo_name, const char *comp_dir)
13420 {
13421   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13422   struct objfile *objfile = dwarf2_per_objfile->objfile;
13423   struct dwo_file *dwo_file;
13424   struct cleanup *cleanups;
13425
13426   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13427   if (dbfd == NULL)
13428     {
13429       if (dwarf_read_debug)
13430         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13431       return NULL;
13432     }
13433   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13434   dwo_file->dwo_name = dwo_name;
13435   dwo_file->comp_dir = comp_dir;
13436   dwo_file->dbfd = dbfd.release ();
13437
13438   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13439   cleanup_data->dwo_file = dwo_file;
13440   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13441
13442   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13443
13444   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13445                          &dwo_file->sections);
13446
13447   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13448                          dwo_file->cus);
13449
13450   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13451                                  dwo_file->sections.types, dwo_file->tus);
13452
13453   discard_cleanups (cleanups);
13454
13455   if (dwarf_read_debug)
13456     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13457
13458   return dwo_file;
13459 }
13460
13461 /* This function is mapped across the sections and remembers the offset and
13462    size of each of the DWP debugging sections common to version 1 and 2 that
13463    we are interested in.  */
13464
13465 static void
13466 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13467                                    void *dwp_file_ptr)
13468 {
13469   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13470   const struct dwop_section_names *names = &dwop_section_names;
13471   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13472
13473   /* Record the ELF section number for later lookup: this is what the
13474      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13475   gdb_assert (elf_section_nr < dwp_file->num_sections);
13476   dwp_file->elf_sections[elf_section_nr] = sectp;
13477
13478   /* Look for specific sections that we need.  */
13479   if (section_is_p (sectp->name, &names->str_dwo))
13480     {
13481       dwp_file->sections.str.s.section = sectp;
13482       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13483     }
13484   else if (section_is_p (sectp->name, &names->cu_index))
13485     {
13486       dwp_file->sections.cu_index.s.section = sectp;
13487       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13488     }
13489   else if (section_is_p (sectp->name, &names->tu_index))
13490     {
13491       dwp_file->sections.tu_index.s.section = sectp;
13492       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13493     }
13494 }
13495
13496 /* This function is mapped across the sections and remembers the offset and
13497    size of each of the DWP version 2 debugging sections that we are interested
13498    in.  This is split into a separate function because we don't know if we
13499    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13500
13501 static void
13502 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13503 {
13504   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13505   const struct dwop_section_names *names = &dwop_section_names;
13506   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13507
13508   /* Record the ELF section number for later lookup: this is what the
13509      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13510   gdb_assert (elf_section_nr < dwp_file->num_sections);
13511   dwp_file->elf_sections[elf_section_nr] = sectp;
13512
13513   /* Look for specific sections that we need.  */
13514   if (section_is_p (sectp->name, &names->abbrev_dwo))
13515     {
13516       dwp_file->sections.abbrev.s.section = sectp;
13517       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13518     }
13519   else if (section_is_p (sectp->name, &names->info_dwo))
13520     {
13521       dwp_file->sections.info.s.section = sectp;
13522       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13523     }
13524   else if (section_is_p (sectp->name, &names->line_dwo))
13525     {
13526       dwp_file->sections.line.s.section = sectp;
13527       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13528     }
13529   else if (section_is_p (sectp->name, &names->loc_dwo))
13530     {
13531       dwp_file->sections.loc.s.section = sectp;
13532       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13533     }
13534   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13535     {
13536       dwp_file->sections.macinfo.s.section = sectp;
13537       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13538     }
13539   else if (section_is_p (sectp->name, &names->macro_dwo))
13540     {
13541       dwp_file->sections.macro.s.section = sectp;
13542       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13543     }
13544   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13545     {
13546       dwp_file->sections.str_offsets.s.section = sectp;
13547       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13548     }
13549   else if (section_is_p (sectp->name, &names->types_dwo))
13550     {
13551       dwp_file->sections.types.s.section = sectp;
13552       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13553     }
13554 }
13555
13556 /* Hash function for dwp_file loaded CUs/TUs.  */
13557
13558 static hashval_t
13559 hash_dwp_loaded_cutus (const void *item)
13560 {
13561   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13562
13563   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13564   return dwo_unit->signature;
13565 }
13566
13567 /* Equality function for dwp_file loaded CUs/TUs.  */
13568
13569 static int
13570 eq_dwp_loaded_cutus (const void *a, const void *b)
13571 {
13572   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13573   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13574
13575   return dua->signature == dub->signature;
13576 }
13577
13578 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13579
13580 static htab_t
13581 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13582 {
13583   return htab_create_alloc_ex (3,
13584                                hash_dwp_loaded_cutus,
13585                                eq_dwp_loaded_cutus,
13586                                NULL,
13587                                &objfile->objfile_obstack,
13588                                hashtab_obstack_allocate,
13589                                dummy_obstack_deallocate);
13590 }
13591
13592 /* Try to open DWP file FILE_NAME.
13593    The result is the bfd handle of the file.
13594    If there is a problem finding or opening the file, return NULL.
13595    Upon success, the canonicalized path of the file is stored in the bfd,
13596    same as symfile_bfd_open.  */
13597
13598 static gdb_bfd_ref_ptr
13599 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13600                const char *file_name)
13601 {
13602   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13603                                             1 /*is_dwp*/,
13604                                             1 /*search_cwd*/));
13605   if (abfd != NULL)
13606     return abfd;
13607
13608   /* Work around upstream bug 15652.
13609      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13610      [Whether that's a "bug" is debatable, but it is getting in our way.]
13611      We have no real idea where the dwp file is, because gdb's realpath-ing
13612      of the executable's path may have discarded the needed info.
13613      [IWBN if the dwp file name was recorded in the executable, akin to
13614      .gnu_debuglink, but that doesn't exist yet.]
13615      Strip the directory from FILE_NAME and search again.  */
13616   if (*debug_file_directory != '\0')
13617     {
13618       /* Don't implicitly search the current directory here.
13619          If the user wants to search "." to handle this case,
13620          it must be added to debug-file-directory.  */
13621       return try_open_dwop_file (dwarf2_per_objfile,
13622                                  lbasename (file_name), 1 /*is_dwp*/,
13623                                  0 /*search_cwd*/);
13624     }
13625
13626   return NULL;
13627 }
13628
13629 /* Initialize the use of the DWP file for the current objfile.
13630    By convention the name of the DWP file is ${objfile}.dwp.
13631    The result is NULL if it can't be found.  */
13632
13633 static struct dwp_file *
13634 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13635 {
13636   struct objfile *objfile = dwarf2_per_objfile->objfile;
13637   struct dwp_file *dwp_file;
13638
13639   /* Try to find first .dwp for the binary file before any symbolic links
13640      resolving.  */
13641
13642   /* If the objfile is a debug file, find the name of the real binary
13643      file and get the name of dwp file from there.  */
13644   std::string dwp_name;
13645   if (objfile->separate_debug_objfile_backlink != NULL)
13646     {
13647       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13648       const char *backlink_basename = lbasename (backlink->original_name);
13649
13650       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13651     }
13652   else
13653     dwp_name = objfile->original_name;
13654
13655   dwp_name += ".dwp";
13656
13657   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13658   if (dbfd == NULL
13659       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13660     {
13661       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13662       dwp_name = objfile_name (objfile);
13663       dwp_name += ".dwp";
13664       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13665     }
13666
13667   if (dbfd == NULL)
13668     {
13669       if (dwarf_read_debug)
13670         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13671       return NULL;
13672     }
13673   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13674   dwp_file->name = bfd_get_filename (dbfd.get ());
13675   dwp_file->dbfd = dbfd.release ();
13676
13677   /* +1: section 0 is unused */
13678   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13679   dwp_file->elf_sections =
13680     OBSTACK_CALLOC (&objfile->objfile_obstack,
13681                     dwp_file->num_sections, asection *);
13682
13683   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13684                          dwp_file);
13685
13686   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13687
13688   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13689
13690   /* The DWP file version is stored in the hash table.  Oh well.  */
13691   if (dwp_file->cus && dwp_file->tus
13692       && dwp_file->cus->version != dwp_file->tus->version)
13693     {
13694       /* Technically speaking, we should try to limp along, but this is
13695          pretty bizarre.  We use pulongest here because that's the established
13696          portability solution (e.g, we cannot use %u for uint32_t).  */
13697       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13698                " TU version %s [in DWP file %s]"),
13699              pulongest (dwp_file->cus->version),
13700              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13701     }
13702
13703   if (dwp_file->cus)
13704     dwp_file->version = dwp_file->cus->version;
13705   else if (dwp_file->tus)
13706     dwp_file->version = dwp_file->tus->version;
13707   else
13708     dwp_file->version = 2;
13709
13710   if (dwp_file->version == 2)
13711     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13712                            dwp_file);
13713
13714   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13715   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13716
13717   if (dwarf_read_debug)
13718     {
13719       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13720       fprintf_unfiltered (gdb_stdlog,
13721                           "    %s CUs, %s TUs\n",
13722                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13723                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13724     }
13725
13726   return dwp_file;
13727 }
13728
13729 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13730
13731 static struct dwp_file *
13732 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13733 {
13734   if (! dwarf2_per_objfile->dwp_checked)
13735     {
13736       dwarf2_per_objfile->dwp_file
13737         = open_and_init_dwp_file (dwarf2_per_objfile);
13738       dwarf2_per_objfile->dwp_checked = 1;
13739     }
13740   return dwarf2_per_objfile->dwp_file;
13741 }
13742
13743 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13744    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13745    or in the DWP file for the objfile, referenced by THIS_UNIT.
13746    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13747    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13748
13749    This is called, for example, when wanting to read a variable with a
13750    complex location.  Therefore we don't want to do file i/o for every call.
13751    Therefore we don't want to look for a DWO file on every call.
13752    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13753    then we check if we've already seen DWO_NAME, and only THEN do we check
13754    for a DWO file.
13755
13756    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13757    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13758
13759 static struct dwo_unit *
13760 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13761                  const char *dwo_name, const char *comp_dir,
13762                  ULONGEST signature, int is_debug_types)
13763 {
13764   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13765   struct objfile *objfile = dwarf2_per_objfile->objfile;
13766   const char *kind = is_debug_types ? "TU" : "CU";
13767   void **dwo_file_slot;
13768   struct dwo_file *dwo_file;
13769   struct dwp_file *dwp_file;
13770
13771   /* First see if there's a DWP file.
13772      If we have a DWP file but didn't find the DWO inside it, don't
13773      look for the original DWO file.  It makes gdb behave differently
13774      depending on whether one is debugging in the build tree.  */
13775
13776   dwp_file = get_dwp_file (dwarf2_per_objfile);
13777   if (dwp_file != NULL)
13778     {
13779       const struct dwp_hash_table *dwp_htab =
13780         is_debug_types ? dwp_file->tus : dwp_file->cus;
13781
13782       if (dwp_htab != NULL)
13783         {
13784           struct dwo_unit *dwo_cutu =
13785             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13786                                     signature, is_debug_types);
13787
13788           if (dwo_cutu != NULL)
13789             {
13790               if (dwarf_read_debug)
13791                 {
13792                   fprintf_unfiltered (gdb_stdlog,
13793                                       "Virtual DWO %s %s found: @%s\n",
13794                                       kind, hex_string (signature),
13795                                       host_address_to_string (dwo_cutu));
13796                 }
13797               return dwo_cutu;
13798             }
13799         }
13800     }
13801   else
13802     {
13803       /* No DWP file, look for the DWO file.  */
13804
13805       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13806                                             dwo_name, comp_dir);
13807       if (*dwo_file_slot == NULL)
13808         {
13809           /* Read in the file and build a table of the CUs/TUs it contains.  */
13810           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13811         }
13812       /* NOTE: This will be NULL if unable to open the file.  */
13813       dwo_file = (struct dwo_file *) *dwo_file_slot;
13814
13815       if (dwo_file != NULL)
13816         {
13817           struct dwo_unit *dwo_cutu = NULL;
13818
13819           if (is_debug_types && dwo_file->tus)
13820             {
13821               struct dwo_unit find_dwo_cutu;
13822
13823               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13824               find_dwo_cutu.signature = signature;
13825               dwo_cutu
13826                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13827             }
13828           else if (!is_debug_types && dwo_file->cus)
13829             {
13830               struct dwo_unit find_dwo_cutu;
13831
13832               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13833               find_dwo_cutu.signature = signature;
13834               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13835                                                        &find_dwo_cutu);
13836             }
13837
13838           if (dwo_cutu != NULL)
13839             {
13840               if (dwarf_read_debug)
13841                 {
13842                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13843                                       kind, dwo_name, hex_string (signature),
13844                                       host_address_to_string (dwo_cutu));
13845                 }
13846               return dwo_cutu;
13847             }
13848         }
13849     }
13850
13851   /* We didn't find it.  This could mean a dwo_id mismatch, or
13852      someone deleted the DWO/DWP file, or the search path isn't set up
13853      correctly to find the file.  */
13854
13855   if (dwarf_read_debug)
13856     {
13857       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13858                           kind, dwo_name, hex_string (signature));
13859     }
13860
13861   /* This is a warning and not a complaint because it can be caused by
13862      pilot error (e.g., user accidentally deleting the DWO).  */
13863   {
13864     /* Print the name of the DWP file if we looked there, helps the user
13865        better diagnose the problem.  */
13866     std::string dwp_text;
13867
13868     if (dwp_file != NULL)
13869       dwp_text = string_printf (" [in DWP file %s]",
13870                                 lbasename (dwp_file->name));
13871
13872     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13873                " [in module %s]"),
13874              kind, dwo_name, hex_string (signature),
13875              dwp_text.c_str (),
13876              this_unit->is_debug_types ? "TU" : "CU",
13877              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13878   }
13879   return NULL;
13880 }
13881
13882 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13883    See lookup_dwo_cutu_unit for details.  */
13884
13885 static struct dwo_unit *
13886 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13887                       const char *dwo_name, const char *comp_dir,
13888                       ULONGEST signature)
13889 {
13890   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13891 }
13892
13893 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13894    See lookup_dwo_cutu_unit for details.  */
13895
13896 static struct dwo_unit *
13897 lookup_dwo_type_unit (struct signatured_type *this_tu,
13898                       const char *dwo_name, const char *comp_dir)
13899 {
13900   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13901 }
13902
13903 /* Traversal function for queue_and_load_all_dwo_tus.  */
13904
13905 static int
13906 queue_and_load_dwo_tu (void **slot, void *info)
13907 {
13908   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13909   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13910   ULONGEST signature = dwo_unit->signature;
13911   struct signatured_type *sig_type =
13912     lookup_dwo_signatured_type (per_cu->cu, signature);
13913
13914   if (sig_type != NULL)
13915     {
13916       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13917
13918       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13919          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13920          while processing PER_CU.  */
13921       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13922         load_full_type_unit (sig_cu);
13923       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13924     }
13925
13926   return 1;
13927 }
13928
13929 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13930    The DWO may have the only definition of the type, though it may not be
13931    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13932    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13933
13934 static void
13935 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13936 {
13937   struct dwo_unit *dwo_unit;
13938   struct dwo_file *dwo_file;
13939
13940   gdb_assert (!per_cu->is_debug_types);
13941   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13942   gdb_assert (per_cu->cu != NULL);
13943
13944   dwo_unit = per_cu->cu->dwo_unit;
13945   gdb_assert (dwo_unit != NULL);
13946
13947   dwo_file = dwo_unit->dwo_file;
13948   if (dwo_file->tus != NULL)
13949     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13950 }
13951
13952 /* Free all resources associated with DWO_FILE.
13953    Close the DWO file and munmap the sections.
13954    All memory should be on the objfile obstack.  */
13955
13956 static void
13957 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13958 {
13959
13960   /* Note: dbfd is NULL for virtual DWO files.  */
13961   gdb_bfd_unref (dwo_file->dbfd);
13962
13963   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13964 }
13965
13966 /* Wrapper for free_dwo_file for use in cleanups.  */
13967
13968 static void
13969 free_dwo_file_cleanup (void *arg)
13970 {
13971   struct free_dwo_file_cleanup_data *data
13972     = (struct free_dwo_file_cleanup_data *) arg;
13973   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13974
13975   free_dwo_file (data->dwo_file, objfile);
13976
13977   xfree (data);
13978 }
13979
13980 /* Traversal function for free_dwo_files.  */
13981
13982 static int
13983 free_dwo_file_from_slot (void **slot, void *info)
13984 {
13985   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13986   struct objfile *objfile = (struct objfile *) info;
13987
13988   free_dwo_file (dwo_file, objfile);
13989
13990   return 1;
13991 }
13992
13993 /* Free all resources associated with DWO_FILES.  */
13994
13995 static void
13996 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13997 {
13998   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13999 }
14000 \f
14001 /* Read in various DIEs.  */
14002
14003 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
14004    Inherit only the children of the DW_AT_abstract_origin DIE not being
14005    already referenced by DW_AT_abstract_origin from the children of the
14006    current DIE.  */
14007
14008 static void
14009 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
14010 {
14011   struct die_info *child_die;
14012   sect_offset *offsetp;
14013   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
14014   struct die_info *origin_die;
14015   /* Iterator of the ORIGIN_DIE children.  */
14016   struct die_info *origin_child_die;
14017   struct attribute *attr;
14018   struct dwarf2_cu *origin_cu;
14019   struct pending **origin_previous_list_in_scope;
14020
14021   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14022   if (!attr)
14023     return;
14024
14025   /* Note that following die references may follow to a die in a
14026      different cu.  */
14027
14028   origin_cu = cu;
14029   origin_die = follow_die_ref (die, attr, &origin_cu);
14030
14031   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
14032      symbols in.  */
14033   origin_previous_list_in_scope = origin_cu->list_in_scope;
14034   origin_cu->list_in_scope = cu->list_in_scope;
14035
14036   if (die->tag != origin_die->tag
14037       && !(die->tag == DW_TAG_inlined_subroutine
14038            && origin_die->tag == DW_TAG_subprogram))
14039     complaint (&symfile_complaints,
14040                _("DIE %s and its abstract origin %s have different tags"),
14041                sect_offset_str (die->sect_off),
14042                sect_offset_str (origin_die->sect_off));
14043
14044   std::vector<sect_offset> offsets;
14045
14046   for (child_die = die->child;
14047        child_die && child_die->tag;
14048        child_die = sibling_die (child_die))
14049     {
14050       struct die_info *child_origin_die;
14051       struct dwarf2_cu *child_origin_cu;
14052
14053       /* We are trying to process concrete instance entries:
14054          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
14055          it's not relevant to our analysis here. i.e. detecting DIEs that are
14056          present in the abstract instance but not referenced in the concrete
14057          one.  */
14058       if (child_die->tag == DW_TAG_call_site
14059           || child_die->tag == DW_TAG_GNU_call_site)
14060         continue;
14061
14062       /* For each CHILD_DIE, find the corresponding child of
14063          ORIGIN_DIE.  If there is more than one layer of
14064          DW_AT_abstract_origin, follow them all; there shouldn't be,
14065          but GCC versions at least through 4.4 generate this (GCC PR
14066          40573).  */
14067       child_origin_die = child_die;
14068       child_origin_cu = cu;
14069       while (1)
14070         {
14071           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
14072                               child_origin_cu);
14073           if (attr == NULL)
14074             break;
14075           child_origin_die = follow_die_ref (child_origin_die, attr,
14076                                              &child_origin_cu);
14077         }
14078
14079       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
14080          counterpart may exist.  */
14081       if (child_origin_die != child_die)
14082         {
14083           if (child_die->tag != child_origin_die->tag
14084               && !(child_die->tag == DW_TAG_inlined_subroutine
14085                    && child_origin_die->tag == DW_TAG_subprogram))
14086             complaint (&symfile_complaints,
14087                        _("Child DIE %s and its abstract origin %s have "
14088                          "different tags"),
14089                        sect_offset_str (child_die->sect_off),
14090                        sect_offset_str (child_origin_die->sect_off));
14091           if (child_origin_die->parent != origin_die)
14092             complaint (&symfile_complaints,
14093                        _("Child DIE %s and its abstract origin %s have "
14094                          "different parents"),
14095                        sect_offset_str (child_die->sect_off),
14096                        sect_offset_str (child_origin_die->sect_off));
14097           else
14098             offsets.push_back (child_origin_die->sect_off);
14099         }
14100     }
14101   std::sort (offsets.begin (), offsets.end ());
14102   sect_offset *offsets_end = offsets.data () + offsets.size ();
14103   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
14104     if (offsetp[-1] == *offsetp)
14105       complaint (&symfile_complaints,
14106                  _("Multiple children of DIE %s refer "
14107                    "to DIE %s as their abstract origin"),
14108                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
14109
14110   offsetp = offsets.data ();
14111   origin_child_die = origin_die->child;
14112   while (origin_child_die && origin_child_die->tag)
14113     {
14114       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
14115       while (offsetp < offsets_end
14116              && *offsetp < origin_child_die->sect_off)
14117         offsetp++;
14118       if (offsetp >= offsets_end
14119           || *offsetp > origin_child_die->sect_off)
14120         {
14121           /* Found that ORIGIN_CHILD_DIE is really not referenced.
14122              Check whether we're already processing ORIGIN_CHILD_DIE.
14123              This can happen with mutually referenced abstract_origins.
14124              PR 16581.  */
14125           if (!origin_child_die->in_process)
14126             process_die (origin_child_die, origin_cu);
14127         }
14128       origin_child_die = sibling_die (origin_child_die);
14129     }
14130   origin_cu->list_in_scope = origin_previous_list_in_scope;
14131 }
14132
14133 static void
14134 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
14135 {
14136   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14137   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14138   struct context_stack *newobj;
14139   CORE_ADDR lowpc;
14140   CORE_ADDR highpc;
14141   struct die_info *child_die;
14142   struct attribute *attr, *call_line, *call_file;
14143   const char *name;
14144   CORE_ADDR baseaddr;
14145   struct block *block;
14146   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
14147   std::vector<struct symbol *> template_args;
14148   struct template_symbol *templ_func = NULL;
14149
14150   if (inlined_func)
14151     {
14152       /* If we do not have call site information, we can't show the
14153          caller of this inlined function.  That's too confusing, so
14154          only use the scope for local variables.  */
14155       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
14156       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
14157       if (call_line == NULL || call_file == NULL)
14158         {
14159           read_lexical_block_scope (die, cu);
14160           return;
14161         }
14162     }
14163
14164   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14165
14166   name = dwarf2_name (die, cu);
14167
14168   /* Ignore functions with missing or empty names.  These are actually
14169      illegal according to the DWARF standard.  */
14170   if (name == NULL)
14171     {
14172       complaint (&symfile_complaints,
14173                  _("missing name for subprogram DIE at %s"),
14174                  sect_offset_str (die->sect_off));
14175       return;
14176     }
14177
14178   /* Ignore functions with missing or invalid low and high pc attributes.  */
14179   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
14180       <= PC_BOUNDS_INVALID)
14181     {
14182       attr = dwarf2_attr (die, DW_AT_external, cu);
14183       if (!attr || !DW_UNSND (attr))
14184         complaint (&symfile_complaints,
14185                    _("cannot get low and high bounds "
14186                      "for subprogram DIE at %s"),
14187                    sect_offset_str (die->sect_off));
14188       return;
14189     }
14190
14191   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14192   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14193
14194   /* If we have any template arguments, then we must allocate a
14195      different sort of symbol.  */
14196   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
14197     {
14198       if (child_die->tag == DW_TAG_template_type_param
14199           || child_die->tag == DW_TAG_template_value_param)
14200         {
14201           templ_func = allocate_template_symbol (objfile);
14202           templ_func->subclass = SYMBOL_TEMPLATE;
14203           break;
14204         }
14205     }
14206
14207   newobj = push_context (0, lowpc);
14208   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
14209                              (struct symbol *) templ_func);
14210
14211   /* If there is a location expression for DW_AT_frame_base, record
14212      it.  */
14213   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
14214   if (attr)
14215     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
14216
14217   /* If there is a location for the static link, record it.  */
14218   newobj->static_link = NULL;
14219   attr = dwarf2_attr (die, DW_AT_static_link, cu);
14220   if (attr)
14221     {
14222       newobj->static_link
14223         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
14224       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
14225     }
14226
14227   cu->list_in_scope = &local_symbols;
14228
14229   if (die->child != NULL)
14230     {
14231       child_die = die->child;
14232       while (child_die && child_die->tag)
14233         {
14234           if (child_die->tag == DW_TAG_template_type_param
14235               || child_die->tag == DW_TAG_template_value_param)
14236             {
14237               struct symbol *arg = new_symbol (child_die, NULL, cu);
14238
14239               if (arg != NULL)
14240                 template_args.push_back (arg);
14241             }
14242           else
14243             process_die (child_die, cu);
14244           child_die = sibling_die (child_die);
14245         }
14246     }
14247
14248   inherit_abstract_dies (die, cu);
14249
14250   /* If we have a DW_AT_specification, we might need to import using
14251      directives from the context of the specification DIE.  See the
14252      comment in determine_prefix.  */
14253   if (cu->language == language_cplus
14254       && dwarf2_attr (die, DW_AT_specification, cu))
14255     {
14256       struct dwarf2_cu *spec_cu = cu;
14257       struct die_info *spec_die = die_specification (die, &spec_cu);
14258
14259       while (spec_die)
14260         {
14261           child_die = spec_die->child;
14262           while (child_die && child_die->tag)
14263             {
14264               if (child_die->tag == DW_TAG_imported_module)
14265                 process_die (child_die, spec_cu);
14266               child_die = sibling_die (child_die);
14267             }
14268
14269           /* In some cases, GCC generates specification DIEs that
14270              themselves contain DW_AT_specification attributes.  */
14271           spec_die = die_specification (spec_die, &spec_cu);
14272         }
14273     }
14274
14275   newobj = pop_context ();
14276   /* Make a block for the local symbols within.  */
14277   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
14278                         newobj->static_link, lowpc, highpc);
14279
14280   /* For C++, set the block's scope.  */
14281   if ((cu->language == language_cplus
14282        || cu->language == language_fortran
14283        || cu->language == language_d
14284        || cu->language == language_rust)
14285       && cu->processing_has_namespace_info)
14286     block_set_scope (block, determine_prefix (die, cu),
14287                      &objfile->objfile_obstack);
14288
14289   /* If we have address ranges, record them.  */
14290   dwarf2_record_block_ranges (die, block, baseaddr, cu);
14291
14292   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
14293
14294   /* Attach template arguments to function.  */
14295   if (!template_args.empty ())
14296     {
14297       gdb_assert (templ_func != NULL);
14298
14299       templ_func->n_template_arguments = template_args.size ();
14300       templ_func->template_arguments
14301         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
14302                      templ_func->n_template_arguments);
14303       memcpy (templ_func->template_arguments,
14304               template_args.data (),
14305               (templ_func->n_template_arguments * sizeof (struct symbol *)));
14306     }
14307
14308   /* In C++, we can have functions nested inside functions (e.g., when
14309      a function declares a class that has methods).  This means that
14310      when we finish processing a function scope, we may need to go
14311      back to building a containing block's symbol lists.  */
14312   local_symbols = newobj->locals;
14313   local_using_directives = newobj->local_using_directives;
14314
14315   /* If we've finished processing a top-level function, subsequent
14316      symbols go in the file symbol list.  */
14317   if (outermost_context_p ())
14318     cu->list_in_scope = &file_symbols;
14319 }
14320
14321 /* Process all the DIES contained within a lexical block scope.  Start
14322    a new scope, process the dies, and then close the scope.  */
14323
14324 static void
14325 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
14326 {
14327   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14328   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14329   struct context_stack *newobj;
14330   CORE_ADDR lowpc, highpc;
14331   struct die_info *child_die;
14332   CORE_ADDR baseaddr;
14333
14334   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14335
14336   /* Ignore blocks with missing or invalid low and high pc attributes.  */
14337   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
14338      as multiple lexical blocks?  Handling children in a sane way would
14339      be nasty.  Might be easier to properly extend generic blocks to
14340      describe ranges.  */
14341   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14342     {
14343     case PC_BOUNDS_NOT_PRESENT:
14344       /* DW_TAG_lexical_block has no attributes, process its children as if
14345          there was no wrapping by that DW_TAG_lexical_block.
14346          GCC does no longer produces such DWARF since GCC r224161.  */
14347       for (child_die = die->child;
14348            child_die != NULL && child_die->tag;
14349            child_die = sibling_die (child_die))
14350         process_die (child_die, cu);
14351       return;
14352     case PC_BOUNDS_INVALID:
14353       return;
14354     }
14355   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14356   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14357
14358   push_context (0, lowpc);
14359   if (die->child != NULL)
14360     {
14361       child_die = die->child;
14362       while (child_die && child_die->tag)
14363         {
14364           process_die (child_die, cu);
14365           child_die = sibling_die (child_die);
14366         }
14367     }
14368   inherit_abstract_dies (die, cu);
14369   newobj = pop_context ();
14370
14371   if (local_symbols != NULL || local_using_directives != NULL)
14372     {
14373       struct block *block
14374         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14375                         newobj->start_addr, highpc);
14376
14377       /* Note that recording ranges after traversing children, as we
14378          do here, means that recording a parent's ranges entails
14379          walking across all its children's ranges as they appear in
14380          the address map, which is quadratic behavior.
14381
14382          It would be nicer to record the parent's ranges before
14383          traversing its children, simply overriding whatever you find
14384          there.  But since we don't even decide whether to create a
14385          block until after we've traversed its children, that's hard
14386          to do.  */
14387       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14388     }
14389   local_symbols = newobj->locals;
14390   local_using_directives = newobj->local_using_directives;
14391 }
14392
14393 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14394
14395 static void
14396 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14397 {
14398   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14399   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14400   CORE_ADDR pc, baseaddr;
14401   struct attribute *attr;
14402   struct call_site *call_site, call_site_local;
14403   void **slot;
14404   int nparams;
14405   struct die_info *child_die;
14406
14407   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14408
14409   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14410   if (attr == NULL)
14411     {
14412       /* This was a pre-DWARF-5 GNU extension alias
14413          for DW_AT_call_return_pc.  */
14414       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14415     }
14416   if (!attr)
14417     {
14418       complaint (&symfile_complaints,
14419                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14420                    "DIE %s [in module %s]"),
14421                  sect_offset_str (die->sect_off), objfile_name (objfile));
14422       return;
14423     }
14424   pc = attr_value_as_address (attr) + baseaddr;
14425   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14426
14427   if (cu->call_site_htab == NULL)
14428     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14429                                                NULL, &objfile->objfile_obstack,
14430                                                hashtab_obstack_allocate, NULL);
14431   call_site_local.pc = pc;
14432   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14433   if (*slot != NULL)
14434     {
14435       complaint (&symfile_complaints,
14436                  _("Duplicate PC %s for DW_TAG_call_site "
14437                    "DIE %s [in module %s]"),
14438                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
14439                  objfile_name (objfile));
14440       return;
14441     }
14442
14443   /* Count parameters at the caller.  */
14444
14445   nparams = 0;
14446   for (child_die = die->child; child_die && child_die->tag;
14447        child_die = sibling_die (child_die))
14448     {
14449       if (child_die->tag != DW_TAG_call_site_parameter
14450           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14451         {
14452           complaint (&symfile_complaints,
14453                      _("Tag %d is not DW_TAG_call_site_parameter in "
14454                        "DW_TAG_call_site child DIE %s [in module %s]"),
14455                      child_die->tag, sect_offset_str (child_die->sect_off),
14456                      objfile_name (objfile));
14457           continue;
14458         }
14459
14460       nparams++;
14461     }
14462
14463   call_site
14464     = ((struct call_site *)
14465        obstack_alloc (&objfile->objfile_obstack,
14466                       sizeof (*call_site)
14467                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14468   *slot = call_site;
14469   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14470   call_site->pc = pc;
14471
14472   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14473       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14474     {
14475       struct die_info *func_die;
14476
14477       /* Skip also over DW_TAG_inlined_subroutine.  */
14478       for (func_die = die->parent;
14479            func_die && func_die->tag != DW_TAG_subprogram
14480            && func_die->tag != DW_TAG_subroutine_type;
14481            func_die = func_die->parent);
14482
14483       /* DW_AT_call_all_calls is a superset
14484          of DW_AT_call_all_tail_calls.  */
14485       if (func_die
14486           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14487           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14488           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14489           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14490         {
14491           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14492              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14493              both the initial caller containing the real return address PC and
14494              the final callee containing the current PC of a chain of tail
14495              calls do not need to have the tail call list complete.  But any
14496              function candidate for a virtual tail call frame searched via
14497              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14498              determined unambiguously.  */
14499         }
14500       else
14501         {
14502           struct type *func_type = NULL;
14503
14504           if (func_die)
14505             func_type = get_die_type (func_die, cu);
14506           if (func_type != NULL)
14507             {
14508               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14509
14510               /* Enlist this call site to the function.  */
14511               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14512               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14513             }
14514           else
14515             complaint (&symfile_complaints,
14516                        _("Cannot find function owning DW_TAG_call_site "
14517                          "DIE %s [in module %s]"),
14518                        sect_offset_str (die->sect_off), objfile_name (objfile));
14519         }
14520     }
14521
14522   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14523   if (attr == NULL)
14524     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14525   if (attr == NULL)
14526     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14527   if (attr == NULL)
14528     {
14529       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14530       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14531     }
14532   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14533   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14534     /* Keep NULL DWARF_BLOCK.  */;
14535   else if (attr_form_is_block (attr))
14536     {
14537       struct dwarf2_locexpr_baton *dlbaton;
14538
14539       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14540       dlbaton->data = DW_BLOCK (attr)->data;
14541       dlbaton->size = DW_BLOCK (attr)->size;
14542       dlbaton->per_cu = cu->per_cu;
14543
14544       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14545     }
14546   else if (attr_form_is_ref (attr))
14547     {
14548       struct dwarf2_cu *target_cu = cu;
14549       struct die_info *target_die;
14550
14551       target_die = follow_die_ref (die, attr, &target_cu);
14552       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14553       if (die_is_declaration (target_die, target_cu))
14554         {
14555           const char *target_physname;
14556
14557           /* Prefer the mangled name; otherwise compute the demangled one.  */
14558           target_physname = dw2_linkage_name (target_die, target_cu);
14559           if (target_physname == NULL)
14560             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14561           if (target_physname == NULL)
14562             complaint (&symfile_complaints,
14563                        _("DW_AT_call_target target DIE has invalid "
14564                          "physname, for referencing DIE %s [in module %s]"),
14565                        sect_offset_str (die->sect_off), objfile_name (objfile));
14566           else
14567             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14568         }
14569       else
14570         {
14571           CORE_ADDR lowpc;
14572
14573           /* DW_AT_entry_pc should be preferred.  */
14574           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14575               <= PC_BOUNDS_INVALID)
14576             complaint (&symfile_complaints,
14577                        _("DW_AT_call_target target DIE has invalid "
14578                          "low pc, for referencing DIE %s [in module %s]"),
14579                        sect_offset_str (die->sect_off), objfile_name (objfile));
14580           else
14581             {
14582               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14583               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14584             }
14585         }
14586     }
14587   else
14588     complaint (&symfile_complaints,
14589                _("DW_TAG_call_site DW_AT_call_target is neither "
14590                  "block nor reference, for DIE %s [in module %s]"),
14591                sect_offset_str (die->sect_off), objfile_name (objfile));
14592
14593   call_site->per_cu = cu->per_cu;
14594
14595   for (child_die = die->child;
14596        child_die && child_die->tag;
14597        child_die = sibling_die (child_die))
14598     {
14599       struct call_site_parameter *parameter;
14600       struct attribute *loc, *origin;
14601
14602       if (child_die->tag != DW_TAG_call_site_parameter
14603           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14604         {
14605           /* Already printed the complaint above.  */
14606           continue;
14607         }
14608
14609       gdb_assert (call_site->parameter_count < nparams);
14610       parameter = &call_site->parameter[call_site->parameter_count];
14611
14612       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14613          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14614          register is contained in DW_AT_call_value.  */
14615
14616       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14617       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14618       if (origin == NULL)
14619         {
14620           /* This was a pre-DWARF-5 GNU extension alias
14621              for DW_AT_call_parameter.  */
14622           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14623         }
14624       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14625         {
14626           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14627
14628           sect_offset sect_off
14629             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14630           if (!offset_in_cu_p (&cu->header, sect_off))
14631             {
14632               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14633                  binding can be done only inside one CU.  Such referenced DIE
14634                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14635               complaint (&symfile_complaints,
14636                          _("DW_AT_call_parameter offset is not in CU for "
14637                            "DW_TAG_call_site child DIE %s [in module %s]"),
14638                          sect_offset_str (child_die->sect_off),
14639                          objfile_name (objfile));
14640               continue;
14641             }
14642           parameter->u.param_cu_off
14643             = (cu_offset) (sect_off - cu->header.sect_off);
14644         }
14645       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14646         {
14647           complaint (&symfile_complaints,
14648                      _("No DW_FORM_block* DW_AT_location for "
14649                        "DW_TAG_call_site child DIE %s [in module %s]"),
14650                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14651           continue;
14652         }
14653       else
14654         {
14655           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14656             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14657           if (parameter->u.dwarf_reg != -1)
14658             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14659           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14660                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14661                                              &parameter->u.fb_offset))
14662             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14663           else
14664             {
14665               complaint (&symfile_complaints,
14666                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14667                            "for DW_FORM_block* DW_AT_location is supported for "
14668                            "DW_TAG_call_site child DIE %s "
14669                            "[in module %s]"),
14670                          sect_offset_str (child_die->sect_off),
14671                          objfile_name (objfile));
14672               continue;
14673             }
14674         }
14675
14676       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14677       if (attr == NULL)
14678         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14679       if (!attr_form_is_block (attr))
14680         {
14681           complaint (&symfile_complaints,
14682                      _("No DW_FORM_block* DW_AT_call_value for "
14683                        "DW_TAG_call_site child DIE %s [in module %s]"),
14684                      sect_offset_str (child_die->sect_off),
14685                      objfile_name (objfile));
14686           continue;
14687         }
14688       parameter->value = DW_BLOCK (attr)->data;
14689       parameter->value_size = DW_BLOCK (attr)->size;
14690
14691       /* Parameters are not pre-cleared by memset above.  */
14692       parameter->data_value = NULL;
14693       parameter->data_value_size = 0;
14694       call_site->parameter_count++;
14695
14696       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14697       if (attr == NULL)
14698         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14699       if (attr)
14700         {
14701           if (!attr_form_is_block (attr))
14702             complaint (&symfile_complaints,
14703                        _("No DW_FORM_block* DW_AT_call_data_value for "
14704                          "DW_TAG_call_site child DIE %s [in module %s]"),
14705                        sect_offset_str (child_die->sect_off),
14706                        objfile_name (objfile));
14707           else
14708             {
14709               parameter->data_value = DW_BLOCK (attr)->data;
14710               parameter->data_value_size = DW_BLOCK (attr)->size;
14711             }
14712         }
14713     }
14714 }
14715
14716 /* Helper function for read_variable.  If DIE represents a virtual
14717    table, then return the type of the concrete object that is
14718    associated with the virtual table.  Otherwise, return NULL.  */
14719
14720 static struct type *
14721 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14722 {
14723   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14724   if (attr == NULL)
14725     return NULL;
14726
14727   /* Find the type DIE.  */
14728   struct die_info *type_die = NULL;
14729   struct dwarf2_cu *type_cu = cu;
14730
14731   if (attr_form_is_ref (attr))
14732     type_die = follow_die_ref (die, attr, &type_cu);
14733   if (type_die == NULL)
14734     return NULL;
14735
14736   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14737     return NULL;
14738   return die_containing_type (type_die, type_cu);
14739 }
14740
14741 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14742
14743 static void
14744 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14745 {
14746   struct rust_vtable_symbol *storage = NULL;
14747
14748   if (cu->language == language_rust)
14749     {
14750       struct type *containing_type = rust_containing_type (die, cu);
14751
14752       if (containing_type != NULL)
14753         {
14754           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14755
14756           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14757                                     struct rust_vtable_symbol);
14758           initialize_objfile_symbol (storage);
14759           storage->concrete_type = containing_type;
14760           storage->subclass = SYMBOL_RUST_VTABLE;
14761         }
14762     }
14763
14764   new_symbol (die, NULL, cu, storage);
14765 }
14766
14767 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14768    reading .debug_rnglists.
14769    Callback's type should be:
14770     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14771    Return true if the attributes are present and valid, otherwise,
14772    return false.  */
14773
14774 template <typename Callback>
14775 static bool
14776 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14777                          Callback &&callback)
14778 {
14779   struct dwarf2_per_objfile *dwarf2_per_objfile
14780     = cu->per_cu->dwarf2_per_objfile;
14781   struct objfile *objfile = dwarf2_per_objfile->objfile;
14782   bfd *obfd = objfile->obfd;
14783   /* Base address selection entry.  */
14784   CORE_ADDR base;
14785   int found_base;
14786   const gdb_byte *buffer;
14787   CORE_ADDR baseaddr;
14788   bool overflow = false;
14789
14790   found_base = cu->base_known;
14791   base = cu->base_address;
14792
14793   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14794   if (offset >= dwarf2_per_objfile->rnglists.size)
14795     {
14796       complaint (&symfile_complaints,
14797                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14798                  offset);
14799       return false;
14800     }
14801   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14802
14803   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14804
14805   while (1)
14806     {
14807       /* Initialize it due to a false compiler warning.  */
14808       CORE_ADDR range_beginning = 0, range_end = 0;
14809       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14810                                  + dwarf2_per_objfile->rnglists.size);
14811       unsigned int bytes_read;
14812
14813       if (buffer == buf_end)
14814         {
14815           overflow = true;
14816           break;
14817         }
14818       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14819       switch (rlet)
14820         {
14821         case DW_RLE_end_of_list:
14822           break;
14823         case DW_RLE_base_address:
14824           if (buffer + cu->header.addr_size > buf_end)
14825             {
14826               overflow = true;
14827               break;
14828             }
14829           base = read_address (obfd, buffer, cu, &bytes_read);
14830           found_base = 1;
14831           buffer += bytes_read;
14832           break;
14833         case DW_RLE_start_length:
14834           if (buffer + cu->header.addr_size > buf_end)
14835             {
14836               overflow = true;
14837               break;
14838             }
14839           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14840           buffer += bytes_read;
14841           range_end = (range_beginning
14842                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14843           buffer += bytes_read;
14844           if (buffer > buf_end)
14845             {
14846               overflow = true;
14847               break;
14848             }
14849           break;
14850         case DW_RLE_offset_pair:
14851           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14852           buffer += bytes_read;
14853           if (buffer > buf_end)
14854             {
14855               overflow = true;
14856               break;
14857             }
14858           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14859           buffer += bytes_read;
14860           if (buffer > buf_end)
14861             {
14862               overflow = true;
14863               break;
14864             }
14865           break;
14866         case DW_RLE_start_end:
14867           if (buffer + 2 * cu->header.addr_size > buf_end)
14868             {
14869               overflow = true;
14870               break;
14871             }
14872           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14873           buffer += bytes_read;
14874           range_end = read_address (obfd, buffer, cu, &bytes_read);
14875           buffer += bytes_read;
14876           break;
14877         default:
14878           complaint (&symfile_complaints,
14879                      _("Invalid .debug_rnglists data (no base address)"));
14880           return false;
14881         }
14882       if (rlet == DW_RLE_end_of_list || overflow)
14883         break;
14884       if (rlet == DW_RLE_base_address)
14885         continue;
14886
14887       if (!found_base)
14888         {
14889           /* We have no valid base address for the ranges
14890              data.  */
14891           complaint (&symfile_complaints,
14892                      _("Invalid .debug_rnglists data (no base address)"));
14893           return false;
14894         }
14895
14896       if (range_beginning > range_end)
14897         {
14898           /* Inverted range entries are invalid.  */
14899           complaint (&symfile_complaints,
14900                      _("Invalid .debug_rnglists data (inverted range)"));
14901           return false;
14902         }
14903
14904       /* Empty range entries have no effect.  */
14905       if (range_beginning == range_end)
14906         continue;
14907
14908       range_beginning += base;
14909       range_end += base;
14910
14911       /* A not-uncommon case of bad debug info.
14912          Don't pollute the addrmap with bad data.  */
14913       if (range_beginning + baseaddr == 0
14914           && !dwarf2_per_objfile->has_section_at_zero)
14915         {
14916           complaint (&symfile_complaints,
14917                      _(".debug_rnglists entry has start address of zero"
14918                        " [in module %s]"), objfile_name (objfile));
14919           continue;
14920         }
14921
14922       callback (range_beginning, range_end);
14923     }
14924
14925   if (overflow)
14926     {
14927       complaint (&symfile_complaints,
14928                  _("Offset %d is not terminated "
14929                    "for DW_AT_ranges attribute"),
14930                  offset);
14931       return false;
14932     }
14933
14934   return true;
14935 }
14936
14937 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14938    Callback's type should be:
14939     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14940    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14941
14942 template <typename Callback>
14943 static int
14944 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14945                        Callback &&callback)
14946 {
14947   struct dwarf2_per_objfile *dwarf2_per_objfile
14948       = cu->per_cu->dwarf2_per_objfile;
14949   struct objfile *objfile = dwarf2_per_objfile->objfile;
14950   struct comp_unit_head *cu_header = &cu->header;
14951   bfd *obfd = objfile->obfd;
14952   unsigned int addr_size = cu_header->addr_size;
14953   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14954   /* Base address selection entry.  */
14955   CORE_ADDR base;
14956   int found_base;
14957   unsigned int dummy;
14958   const gdb_byte *buffer;
14959   CORE_ADDR baseaddr;
14960
14961   if (cu_header->version >= 5)
14962     return dwarf2_rnglists_process (offset, cu, callback);
14963
14964   found_base = cu->base_known;
14965   base = cu->base_address;
14966
14967   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14968   if (offset >= dwarf2_per_objfile->ranges.size)
14969     {
14970       complaint (&symfile_complaints,
14971                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14972                  offset);
14973       return 0;
14974     }
14975   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14976
14977   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14978
14979   while (1)
14980     {
14981       CORE_ADDR range_beginning, range_end;
14982
14983       range_beginning = read_address (obfd, buffer, cu, &dummy);
14984       buffer += addr_size;
14985       range_end = read_address (obfd, buffer, cu, &dummy);
14986       buffer += addr_size;
14987       offset += 2 * addr_size;
14988
14989       /* An end of list marker is a pair of zero addresses.  */
14990       if (range_beginning == 0 && range_end == 0)
14991         /* Found the end of list entry.  */
14992         break;
14993
14994       /* Each base address selection entry is a pair of 2 values.
14995          The first is the largest possible address, the second is
14996          the base address.  Check for a base address here.  */
14997       if ((range_beginning & mask) == mask)
14998         {
14999           /* If we found the largest possible address, then we already
15000              have the base address in range_end.  */
15001           base = range_end;
15002           found_base = 1;
15003           continue;
15004         }
15005
15006       if (!found_base)
15007         {
15008           /* We have no valid base address for the ranges
15009              data.  */
15010           complaint (&symfile_complaints,
15011                      _("Invalid .debug_ranges data (no base address)"));
15012           return 0;
15013         }
15014
15015       if (range_beginning > range_end)
15016         {
15017           /* Inverted range entries are invalid.  */
15018           complaint (&symfile_complaints,
15019                      _("Invalid .debug_ranges data (inverted range)"));
15020           return 0;
15021         }
15022
15023       /* Empty range entries have no effect.  */
15024       if (range_beginning == range_end)
15025         continue;
15026
15027       range_beginning += base;
15028       range_end += base;
15029
15030       /* A not-uncommon case of bad debug info.
15031          Don't pollute the addrmap with bad data.  */
15032       if (range_beginning + baseaddr == 0
15033           && !dwarf2_per_objfile->has_section_at_zero)
15034         {
15035           complaint (&symfile_complaints,
15036                      _(".debug_ranges entry has start address of zero"
15037                        " [in module %s]"), objfile_name (objfile));
15038           continue;
15039         }
15040
15041       callback (range_beginning, range_end);
15042     }
15043
15044   return 1;
15045 }
15046
15047 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
15048    Return 1 if the attributes are present and valid, otherwise, return 0.
15049    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
15050
15051 static int
15052 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
15053                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
15054                     struct partial_symtab *ranges_pst)
15055 {
15056   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15057   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15058   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
15059                                        SECT_OFF_TEXT (objfile));
15060   int low_set = 0;
15061   CORE_ADDR low = 0;
15062   CORE_ADDR high = 0;
15063   int retval;
15064
15065   retval = dwarf2_ranges_process (offset, cu,
15066     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
15067     {
15068       if (ranges_pst != NULL)
15069         {
15070           CORE_ADDR lowpc;
15071           CORE_ADDR highpc;
15072
15073           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
15074                                               range_beginning + baseaddr);
15075           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
15076                                                range_end + baseaddr);
15077           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
15078                              ranges_pst);
15079         }
15080
15081       /* FIXME: This is recording everything as a low-high
15082          segment of consecutive addresses.  We should have a
15083          data structure for discontiguous block ranges
15084          instead.  */
15085       if (! low_set)
15086         {
15087           low = range_beginning;
15088           high = range_end;
15089           low_set = 1;
15090         }
15091       else
15092         {
15093           if (range_beginning < low)
15094             low = range_beginning;
15095           if (range_end > high)
15096             high = range_end;
15097         }
15098     });
15099   if (!retval)
15100     return 0;
15101
15102   if (! low_set)
15103     /* If the first entry is an end-of-list marker, the range
15104        describes an empty scope, i.e. no instructions.  */
15105     return 0;
15106
15107   if (low_return)
15108     *low_return = low;
15109   if (high_return)
15110     *high_return = high;
15111   return 1;
15112 }
15113
15114 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
15115    definition for the return value.  *LOWPC and *HIGHPC are set iff
15116    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
15117
15118 static enum pc_bounds_kind
15119 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
15120                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
15121                       struct partial_symtab *pst)
15122 {
15123   struct dwarf2_per_objfile *dwarf2_per_objfile
15124     = cu->per_cu->dwarf2_per_objfile;
15125   struct attribute *attr;
15126   struct attribute *attr_high;
15127   CORE_ADDR low = 0;
15128   CORE_ADDR high = 0;
15129   enum pc_bounds_kind ret;
15130
15131   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
15132   if (attr_high)
15133     {
15134       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15135       if (attr)
15136         {
15137           low = attr_value_as_address (attr);
15138           high = attr_value_as_address (attr_high);
15139           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
15140             high += low;
15141         }
15142       else
15143         /* Found high w/o low attribute.  */
15144         return PC_BOUNDS_INVALID;
15145
15146       /* Found consecutive range of addresses.  */
15147       ret = PC_BOUNDS_HIGH_LOW;
15148     }
15149   else
15150     {
15151       attr = dwarf2_attr (die, DW_AT_ranges, cu);
15152       if (attr != NULL)
15153         {
15154           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
15155              We take advantage of the fact that DW_AT_ranges does not appear
15156              in DW_TAG_compile_unit of DWO files.  */
15157           int need_ranges_base = die->tag != DW_TAG_compile_unit;
15158           unsigned int ranges_offset = (DW_UNSND (attr)
15159                                         + (need_ranges_base
15160                                            ? cu->ranges_base
15161                                            : 0));
15162
15163           /* Value of the DW_AT_ranges attribute is the offset in the
15164              .debug_ranges section.  */
15165           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
15166             return PC_BOUNDS_INVALID;
15167           /* Found discontinuous range of addresses.  */
15168           ret = PC_BOUNDS_RANGES;
15169         }
15170       else
15171         return PC_BOUNDS_NOT_PRESENT;
15172     }
15173
15174   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
15175   if (high <= low)
15176     return PC_BOUNDS_INVALID;
15177
15178   /* When using the GNU linker, .gnu.linkonce. sections are used to
15179      eliminate duplicate copies of functions and vtables and such.
15180      The linker will arbitrarily choose one and discard the others.
15181      The AT_*_pc values for such functions refer to local labels in
15182      these sections.  If the section from that file was discarded, the
15183      labels are not in the output, so the relocs get a value of 0.
15184      If this is a discarded function, mark the pc bounds as invalid,
15185      so that GDB will ignore it.  */
15186   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
15187     return PC_BOUNDS_INVALID;
15188
15189   *lowpc = low;
15190   if (highpc)
15191     *highpc = high;
15192   return ret;
15193 }
15194
15195 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
15196    its low and high PC addresses.  Do nothing if these addresses could not
15197    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
15198    and HIGHPC to the high address if greater than HIGHPC.  */
15199
15200 static void
15201 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
15202                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
15203                                  struct dwarf2_cu *cu)
15204 {
15205   CORE_ADDR low, high;
15206   struct die_info *child = die->child;
15207
15208   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
15209     {
15210       *lowpc = std::min (*lowpc, low);
15211       *highpc = std::max (*highpc, high);
15212     }
15213
15214   /* If the language does not allow nested subprograms (either inside
15215      subprograms or lexical blocks), we're done.  */
15216   if (cu->language != language_ada)
15217     return;
15218
15219   /* Check all the children of the given DIE.  If it contains nested
15220      subprograms, then check their pc bounds.  Likewise, we need to
15221      check lexical blocks as well, as they may also contain subprogram
15222      definitions.  */
15223   while (child && child->tag)
15224     {
15225       if (child->tag == DW_TAG_subprogram
15226           || child->tag == DW_TAG_lexical_block)
15227         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
15228       child = sibling_die (child);
15229     }
15230 }
15231
15232 /* Get the low and high pc's represented by the scope DIE, and store
15233    them in *LOWPC and *HIGHPC.  If the correct values can't be
15234    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
15235
15236 static void
15237 get_scope_pc_bounds (struct die_info *die,
15238                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
15239                      struct dwarf2_cu *cu)
15240 {
15241   CORE_ADDR best_low = (CORE_ADDR) -1;
15242   CORE_ADDR best_high = (CORE_ADDR) 0;
15243   CORE_ADDR current_low, current_high;
15244
15245   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
15246       >= PC_BOUNDS_RANGES)
15247     {
15248       best_low = current_low;
15249       best_high = current_high;
15250     }
15251   else
15252     {
15253       struct die_info *child = die->child;
15254
15255       while (child && child->tag)
15256         {
15257           switch (child->tag) {
15258           case DW_TAG_subprogram:
15259             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
15260             break;
15261           case DW_TAG_namespace:
15262           case DW_TAG_module:
15263             /* FIXME: carlton/2004-01-16: Should we do this for
15264                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
15265                that current GCC's always emit the DIEs corresponding
15266                to definitions of methods of classes as children of a
15267                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
15268                the DIEs giving the declarations, which could be
15269                anywhere).  But I don't see any reason why the
15270                standards says that they have to be there.  */
15271             get_scope_pc_bounds (child, &current_low, &current_high, cu);
15272
15273             if (current_low != ((CORE_ADDR) -1))
15274               {
15275                 best_low = std::min (best_low, current_low);
15276                 best_high = std::max (best_high, current_high);
15277               }
15278             break;
15279           default:
15280             /* Ignore.  */
15281             break;
15282           }
15283
15284           child = sibling_die (child);
15285         }
15286     }
15287
15288   *lowpc = best_low;
15289   *highpc = best_high;
15290 }
15291
15292 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
15293    in DIE.  */
15294
15295 static void
15296 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
15297                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
15298 {
15299   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15300   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15301   struct attribute *attr;
15302   struct attribute *attr_high;
15303
15304   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
15305   if (attr_high)
15306     {
15307       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15308       if (attr)
15309         {
15310           CORE_ADDR low = attr_value_as_address (attr);
15311           CORE_ADDR high = attr_value_as_address (attr_high);
15312
15313           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
15314             high += low;
15315
15316           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
15317           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
15318           record_block_range (block, low, high - 1);
15319         }
15320     }
15321
15322   attr = dwarf2_attr (die, DW_AT_ranges, cu);
15323   if (attr)
15324     {
15325       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
15326          We take advantage of the fact that DW_AT_ranges does not appear
15327          in DW_TAG_compile_unit of DWO files.  */
15328       int need_ranges_base = die->tag != DW_TAG_compile_unit;
15329
15330       /* The value of the DW_AT_ranges attribute is the offset of the
15331          address range list in the .debug_ranges section.  */
15332       unsigned long offset = (DW_UNSND (attr)
15333                               + (need_ranges_base ? cu->ranges_base : 0));
15334       const gdb_byte *buffer;
15335
15336       /* For some target architectures, but not others, the
15337          read_address function sign-extends the addresses it returns.
15338          To recognize base address selection entries, we need a
15339          mask.  */
15340       unsigned int addr_size = cu->header.addr_size;
15341       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15342
15343       /* The base address, to which the next pair is relative.  Note
15344          that this 'base' is a DWARF concept: most entries in a range
15345          list are relative, to reduce the number of relocs against the
15346          debugging information.  This is separate from this function's
15347          'baseaddr' argument, which GDB uses to relocate debugging
15348          information from a shared library based on the address at
15349          which the library was loaded.  */
15350       CORE_ADDR base = cu->base_address;
15351       int base_known = cu->base_known;
15352
15353       dwarf2_ranges_process (offset, cu,
15354         [&] (CORE_ADDR start, CORE_ADDR end)
15355         {
15356           start += baseaddr;
15357           end += baseaddr;
15358           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15359           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15360           record_block_range (block, start, end - 1);
15361         });
15362     }
15363 }
15364
15365 /* Check whether the producer field indicates either of GCC < 4.6, or the
15366    Intel C/C++ compiler, and cache the result in CU.  */
15367
15368 static void
15369 check_producer (struct dwarf2_cu *cu)
15370 {
15371   int major, minor;
15372
15373   if (cu->producer == NULL)
15374     {
15375       /* For unknown compilers expect their behavior is DWARF version
15376          compliant.
15377
15378          GCC started to support .debug_types sections by -gdwarf-4 since
15379          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15380          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15381          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15382          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15383     }
15384   else if (producer_is_gcc (cu->producer, &major, &minor))
15385     {
15386       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15387       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15388     }
15389   else if (producer_is_icc (cu->producer, &major, &minor))
15390     cu->producer_is_icc_lt_14 = major < 14;
15391   else
15392     {
15393       /* For other non-GCC compilers, expect their behavior is DWARF version
15394          compliant.  */
15395     }
15396
15397   cu->checked_producer = 1;
15398 }
15399
15400 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15401    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15402    during 4.6.0 experimental.  */
15403
15404 static int
15405 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15406 {
15407   if (!cu->checked_producer)
15408     check_producer (cu);
15409
15410   return cu->producer_is_gxx_lt_4_6;
15411 }
15412
15413 /* Return the default accessibility type if it is not overriden by
15414    DW_AT_accessibility.  */
15415
15416 static enum dwarf_access_attribute
15417 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15418 {
15419   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15420     {
15421       /* The default DWARF 2 accessibility for members is public, the default
15422          accessibility for inheritance is private.  */
15423
15424       if (die->tag != DW_TAG_inheritance)
15425         return DW_ACCESS_public;
15426       else
15427         return DW_ACCESS_private;
15428     }
15429   else
15430     {
15431       /* DWARF 3+ defines the default accessibility a different way.  The same
15432          rules apply now for DW_TAG_inheritance as for the members and it only
15433          depends on the container kind.  */
15434
15435       if (die->parent->tag == DW_TAG_class_type)
15436         return DW_ACCESS_private;
15437       else
15438         return DW_ACCESS_public;
15439     }
15440 }
15441
15442 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15443    offset.  If the attribute was not found return 0, otherwise return
15444    1.  If it was found but could not properly be handled, set *OFFSET
15445    to 0.  */
15446
15447 static int
15448 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15449                              LONGEST *offset)
15450 {
15451   struct attribute *attr;
15452
15453   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15454   if (attr != NULL)
15455     {
15456       *offset = 0;
15457
15458       /* Note that we do not check for a section offset first here.
15459          This is because DW_AT_data_member_location is new in DWARF 4,
15460          so if we see it, we can assume that a constant form is really
15461          a constant and not a section offset.  */
15462       if (attr_form_is_constant (attr))
15463         *offset = dwarf2_get_attr_constant_value (attr, 0);
15464       else if (attr_form_is_section_offset (attr))
15465         dwarf2_complex_location_expr_complaint ();
15466       else if (attr_form_is_block (attr))
15467         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15468       else
15469         dwarf2_complex_location_expr_complaint ();
15470
15471       return 1;
15472     }
15473
15474   return 0;
15475 }
15476
15477 /* Add an aggregate field to the field list.  */
15478
15479 static void
15480 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15481                   struct dwarf2_cu *cu)
15482 {
15483   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15484   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15485   struct nextfield *new_field;
15486   struct attribute *attr;
15487   struct field *fp;
15488   const char *fieldname = "";
15489
15490   /* Allocate a new field list entry and link it in.  */
15491   new_field = XNEW (struct nextfield);
15492   make_cleanup (xfree, new_field);
15493   memset (new_field, 0, sizeof (struct nextfield));
15494
15495   if (die->tag == DW_TAG_inheritance)
15496     {
15497       new_field->next = fip->baseclasses;
15498       fip->baseclasses = new_field;
15499     }
15500   else
15501     {
15502       new_field->next = fip->fields;
15503       fip->fields = new_field;
15504     }
15505   fip->nfields++;
15506
15507   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15508   if (attr)
15509     new_field->accessibility = DW_UNSND (attr);
15510   else
15511     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15512   if (new_field->accessibility != DW_ACCESS_public)
15513     fip->non_public_fields = 1;
15514
15515   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15516   if (attr)
15517     new_field->virtuality = DW_UNSND (attr);
15518   else
15519     new_field->virtuality = DW_VIRTUALITY_none;
15520
15521   fp = &new_field->field;
15522
15523   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15524     {
15525       LONGEST offset;
15526
15527       /* Data member other than a C++ static data member.  */
15528
15529       /* Get type of field.  */
15530       fp->type = die_type (die, cu);
15531
15532       SET_FIELD_BITPOS (*fp, 0);
15533
15534       /* Get bit size of field (zero if none).  */
15535       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15536       if (attr)
15537         {
15538           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15539         }
15540       else
15541         {
15542           FIELD_BITSIZE (*fp) = 0;
15543         }
15544
15545       /* Get bit offset of field.  */
15546       if (handle_data_member_location (die, cu, &offset))
15547         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15548       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15549       if (attr)
15550         {
15551           if (gdbarch_bits_big_endian (gdbarch))
15552             {
15553               /* For big endian bits, the DW_AT_bit_offset gives the
15554                  additional bit offset from the MSB of the containing
15555                  anonymous object to the MSB of the field.  We don't
15556                  have to do anything special since we don't need to
15557                  know the size of the anonymous object.  */
15558               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15559             }
15560           else
15561             {
15562               /* For little endian bits, compute the bit offset to the
15563                  MSB of the anonymous object, subtract off the number of
15564                  bits from the MSB of the field to the MSB of the
15565                  object, and then subtract off the number of bits of
15566                  the field itself.  The result is the bit offset of
15567                  the LSB of the field.  */
15568               int anonymous_size;
15569               int bit_offset = DW_UNSND (attr);
15570
15571               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15572               if (attr)
15573                 {
15574                   /* The size of the anonymous object containing
15575                      the bit field is explicit, so use the
15576                      indicated size (in bytes).  */
15577                   anonymous_size = DW_UNSND (attr);
15578                 }
15579               else
15580                 {
15581                   /* The size of the anonymous object containing
15582                      the bit field must be inferred from the type
15583                      attribute of the data member containing the
15584                      bit field.  */
15585                   anonymous_size = TYPE_LENGTH (fp->type);
15586                 }
15587               SET_FIELD_BITPOS (*fp,
15588                                 (FIELD_BITPOS (*fp)
15589                                  + anonymous_size * bits_per_byte
15590                                  - bit_offset - FIELD_BITSIZE (*fp)));
15591             }
15592         }
15593       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15594       if (attr != NULL)
15595         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15596                                 + dwarf2_get_attr_constant_value (attr, 0)));
15597
15598       /* Get name of field.  */
15599       fieldname = dwarf2_name (die, cu);
15600       if (fieldname == NULL)
15601         fieldname = "";
15602
15603       /* The name is already allocated along with this objfile, so we don't
15604          need to duplicate it for the type.  */
15605       fp->name = fieldname;
15606
15607       /* Change accessibility for artificial fields (e.g. virtual table
15608          pointer or virtual base class pointer) to private.  */
15609       if (dwarf2_attr (die, DW_AT_artificial, cu))
15610         {
15611           FIELD_ARTIFICIAL (*fp) = 1;
15612           new_field->accessibility = DW_ACCESS_private;
15613           fip->non_public_fields = 1;
15614         }
15615     }
15616   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15617     {
15618       /* C++ static member.  */
15619
15620       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15621          is a declaration, but all versions of G++ as of this writing
15622          (so through at least 3.2.1) incorrectly generate
15623          DW_TAG_variable tags.  */
15624
15625       const char *physname;
15626
15627       /* Get name of field.  */
15628       fieldname = dwarf2_name (die, cu);
15629       if (fieldname == NULL)
15630         return;
15631
15632       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15633       if (attr
15634           /* Only create a symbol if this is an external value.
15635              new_symbol checks this and puts the value in the global symbol
15636              table, which we want.  If it is not external, new_symbol
15637              will try to put the value in cu->list_in_scope which is wrong.  */
15638           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15639         {
15640           /* A static const member, not much different than an enum as far as
15641              we're concerned, except that we can support more types.  */
15642           new_symbol (die, NULL, cu);
15643         }
15644
15645       /* Get physical name.  */
15646       physname = dwarf2_physname (fieldname, die, cu);
15647
15648       /* The name is already allocated along with this objfile, so we don't
15649          need to duplicate it for the type.  */
15650       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15651       FIELD_TYPE (*fp) = die_type (die, cu);
15652       FIELD_NAME (*fp) = fieldname;
15653     }
15654   else if (die->tag == DW_TAG_inheritance)
15655     {
15656       LONGEST offset;
15657
15658       /* C++ base class field.  */
15659       if (handle_data_member_location (die, cu, &offset))
15660         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15661       FIELD_BITSIZE (*fp) = 0;
15662       FIELD_TYPE (*fp) = die_type (die, cu);
15663       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15664       fip->nbaseclasses++;
15665     }
15666   else if (die->tag == DW_TAG_variant_part)
15667     {
15668       /* process_structure_scope will treat this DIE as a union.  */
15669       process_structure_scope (die, cu);
15670
15671       /* The variant part is relative to the start of the enclosing
15672          structure.  */
15673       SET_FIELD_BITPOS (*fp, 0);
15674       fp->type = get_die_type (die, cu);
15675       fp->artificial = 1;
15676       fp->name = "<<variant>>";
15677     }
15678   else
15679     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15680 }
15681
15682 /* Can the type given by DIE define another type?  */
15683
15684 static bool
15685 type_can_define_types (const struct die_info *die)
15686 {
15687   switch (die->tag)
15688     {
15689     case DW_TAG_typedef:
15690     case DW_TAG_class_type:
15691     case DW_TAG_structure_type:
15692     case DW_TAG_union_type:
15693     case DW_TAG_enumeration_type:
15694       return true;
15695
15696     default:
15697       return false;
15698     }
15699 }
15700
15701 /* Add a type definition defined in the scope of the FIP's class.  */
15702
15703 static void
15704 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15705                       struct dwarf2_cu *cu)
15706 {
15707   struct decl_field_list *new_field;
15708   struct decl_field *fp;
15709
15710   /* Allocate a new field list entry and link it in.  */
15711   new_field = XCNEW (struct decl_field_list);
15712   make_cleanup (xfree, new_field);
15713
15714   gdb_assert (type_can_define_types (die));
15715
15716   fp = &new_field->field;
15717
15718   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15719   fp->name = dwarf2_name (die, cu);
15720   fp->type = read_type_die (die, cu);
15721
15722   /* Save accessibility.  */
15723   enum dwarf_access_attribute accessibility;
15724   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15725   if (attr != NULL)
15726     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15727   else
15728     accessibility = dwarf2_default_access_attribute (die, cu);
15729   switch (accessibility)
15730     {
15731     case DW_ACCESS_public:
15732       /* The assumed value if neither private nor protected.  */
15733       break;
15734     case DW_ACCESS_private:
15735       fp->is_private = 1;
15736       break;
15737     case DW_ACCESS_protected:
15738       fp->is_protected = 1;
15739       break;
15740     default:
15741       complaint (&symfile_complaints,
15742                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15743     }
15744
15745   if (die->tag == DW_TAG_typedef)
15746     {
15747       new_field->next = fip->typedef_field_list;
15748       fip->typedef_field_list = new_field;
15749       fip->typedef_field_list_count++;
15750     }
15751   else
15752     {
15753       new_field->next = fip->nested_types_list;
15754       fip->nested_types_list = new_field;
15755       fip->nested_types_list_count++;
15756     }
15757 }
15758
15759 /* Create the vector of fields, and attach it to the type.  */
15760
15761 static void
15762 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15763                               struct dwarf2_cu *cu)
15764 {
15765   int nfields = fip->nfields;
15766
15767   /* Record the field count, allocate space for the array of fields,
15768      and create blank accessibility bitfields if necessary.  */
15769   TYPE_NFIELDS (type) = nfields;
15770   TYPE_FIELDS (type) = (struct field *)
15771     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15772   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15773
15774   if (fip->non_public_fields && cu->language != language_ada)
15775     {
15776       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15777
15778       TYPE_FIELD_PRIVATE_BITS (type) =
15779         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15780       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15781
15782       TYPE_FIELD_PROTECTED_BITS (type) =
15783         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15784       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15785
15786       TYPE_FIELD_IGNORE_BITS (type) =
15787         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15788       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15789     }
15790
15791   /* If the type has baseclasses, allocate and clear a bit vector for
15792      TYPE_FIELD_VIRTUAL_BITS.  */
15793   if (fip->nbaseclasses && cu->language != language_ada)
15794     {
15795       int num_bytes = B_BYTES (fip->nbaseclasses);
15796       unsigned char *pointer;
15797
15798       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15799       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15800       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15801       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15802       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15803     }
15804
15805   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15806     {
15807       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15808
15809       int index = nfields - 1;
15810       struct nextfield *field = fip->fields;
15811
15812       while (index >= 0)
15813         {
15814           if (field->variant.is_discriminant)
15815             di->discriminant_index = index;
15816           else if (field->variant.default_branch)
15817             di->default_index = index;
15818           else
15819             di->discriminants[index] = field->variant.discriminant_value;
15820
15821           --index;
15822           field = field->next;
15823         }
15824     }
15825
15826   /* Copy the saved-up fields into the field vector.  Start from the head of
15827      the list, adding to the tail of the field array, so that they end up in
15828      the same order in the array in which they were added to the list.  */
15829   while (nfields-- > 0)
15830     {
15831       struct nextfield *fieldp;
15832
15833       if (fip->fields)
15834         {
15835           fieldp = fip->fields;
15836           fip->fields = fieldp->next;
15837         }
15838       else
15839         {
15840           fieldp = fip->baseclasses;
15841           fip->baseclasses = fieldp->next;
15842         }
15843
15844       TYPE_FIELD (type, nfields) = fieldp->field;
15845       switch (fieldp->accessibility)
15846         {
15847         case DW_ACCESS_private:
15848           if (cu->language != language_ada)
15849             SET_TYPE_FIELD_PRIVATE (type, nfields);
15850           break;
15851
15852         case DW_ACCESS_protected:
15853           if (cu->language != language_ada)
15854             SET_TYPE_FIELD_PROTECTED (type, nfields);
15855           break;
15856
15857         case DW_ACCESS_public:
15858           break;
15859
15860         default:
15861           /* Unknown accessibility.  Complain and treat it as public.  */
15862           {
15863             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15864                        fieldp->accessibility);
15865           }
15866           break;
15867         }
15868       if (nfields < fip->nbaseclasses)
15869         {
15870           switch (fieldp->virtuality)
15871             {
15872             case DW_VIRTUALITY_virtual:
15873             case DW_VIRTUALITY_pure_virtual:
15874               if (cu->language == language_ada)
15875                 error (_("unexpected virtuality in component of Ada type"));
15876               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15877               break;
15878             }
15879         }
15880     }
15881 }
15882
15883 /* Return true if this member function is a constructor, false
15884    otherwise.  */
15885
15886 static int
15887 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15888 {
15889   const char *fieldname;
15890   const char *type_name;
15891   int len;
15892
15893   if (die->parent == NULL)
15894     return 0;
15895
15896   if (die->parent->tag != DW_TAG_structure_type
15897       && die->parent->tag != DW_TAG_union_type
15898       && die->parent->tag != DW_TAG_class_type)
15899     return 0;
15900
15901   fieldname = dwarf2_name (die, cu);
15902   type_name = dwarf2_name (die->parent, cu);
15903   if (fieldname == NULL || type_name == NULL)
15904     return 0;
15905
15906   len = strlen (fieldname);
15907   return (strncmp (fieldname, type_name, len) == 0
15908           && (type_name[len] == '\0' || type_name[len] == '<'));
15909 }
15910
15911 /* Add a member function to the proper fieldlist.  */
15912
15913 static void
15914 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15915                       struct type *type, struct dwarf2_cu *cu)
15916 {
15917   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15918   struct attribute *attr;
15919   struct fnfieldlist *flp;
15920   int i;
15921   struct fn_field *fnp;
15922   const char *fieldname;
15923   struct nextfnfield *new_fnfield;
15924   struct type *this_type;
15925   enum dwarf_access_attribute accessibility;
15926
15927   if (cu->language == language_ada)
15928     error (_("unexpected member function in Ada type"));
15929
15930   /* Get name of member function.  */
15931   fieldname = dwarf2_name (die, cu);
15932   if (fieldname == NULL)
15933     return;
15934
15935   /* Look up member function name in fieldlist.  */
15936   for (i = 0; i < fip->nfnfields; i++)
15937     {
15938       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15939         break;
15940     }
15941
15942   /* Create new list element if necessary.  */
15943   if (i < fip->nfnfields)
15944     flp = &fip->fnfieldlists[i];
15945   else
15946     {
15947       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15948         {
15949           fip->fnfieldlists = (struct fnfieldlist *)
15950             xrealloc (fip->fnfieldlists,
15951                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15952                       * sizeof (struct fnfieldlist));
15953           if (fip->nfnfields == 0)
15954             make_cleanup (free_current_contents, &fip->fnfieldlists);
15955         }
15956       flp = &fip->fnfieldlists[fip->nfnfields];
15957       flp->name = fieldname;
15958       flp->length = 0;
15959       flp->head = NULL;
15960       i = fip->nfnfields++;
15961     }
15962
15963   /* Create a new member function field and chain it to the field list
15964      entry.  */
15965   new_fnfield = XNEW (struct nextfnfield);
15966   make_cleanup (xfree, new_fnfield);
15967   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15968   new_fnfield->next = flp->head;
15969   flp->head = new_fnfield;
15970   flp->length++;
15971
15972   /* Fill in the member function field info.  */
15973   fnp = &new_fnfield->fnfield;
15974
15975   /* Delay processing of the physname until later.  */
15976   if (cu->language == language_cplus)
15977     {
15978       add_to_method_list (type, i, flp->length - 1, fieldname,
15979                           die, cu);
15980     }
15981   else
15982     {
15983       const char *physname = dwarf2_physname (fieldname, die, cu);
15984       fnp->physname = physname ? physname : "";
15985     }
15986
15987   fnp->type = alloc_type (objfile);
15988   this_type = read_type_die (die, cu);
15989   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15990     {
15991       int nparams = TYPE_NFIELDS (this_type);
15992
15993       /* TYPE is the domain of this method, and THIS_TYPE is the type
15994            of the method itself (TYPE_CODE_METHOD).  */
15995       smash_to_method_type (fnp->type, type,
15996                             TYPE_TARGET_TYPE (this_type),
15997                             TYPE_FIELDS (this_type),
15998                             TYPE_NFIELDS (this_type),
15999                             TYPE_VARARGS (this_type));
16000
16001       /* Handle static member functions.
16002          Dwarf2 has no clean way to discern C++ static and non-static
16003          member functions.  G++ helps GDB by marking the first
16004          parameter for non-static member functions (which is the this
16005          pointer) as artificial.  We obtain this information from
16006          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
16007       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
16008         fnp->voffset = VOFFSET_STATIC;
16009     }
16010   else
16011     complaint (&symfile_complaints, _("member function type missing for '%s'"),
16012                dwarf2_full_name (fieldname, die, cu));
16013
16014   /* Get fcontext from DW_AT_containing_type if present.  */
16015   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16016     fnp->fcontext = die_containing_type (die, cu);
16017
16018   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
16019      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
16020
16021   /* Get accessibility.  */
16022   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
16023   if (attr)
16024     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
16025   else
16026     accessibility = dwarf2_default_access_attribute (die, cu);
16027   switch (accessibility)
16028     {
16029     case DW_ACCESS_private:
16030       fnp->is_private = 1;
16031       break;
16032     case DW_ACCESS_protected:
16033       fnp->is_protected = 1;
16034       break;
16035     }
16036
16037   /* Check for artificial methods.  */
16038   attr = dwarf2_attr (die, DW_AT_artificial, cu);
16039   if (attr && DW_UNSND (attr) != 0)
16040     fnp->is_artificial = 1;
16041
16042   fnp->is_constructor = dwarf2_is_constructor (die, cu);
16043
16044   /* Get index in virtual function table if it is a virtual member
16045      function.  For older versions of GCC, this is an offset in the
16046      appropriate virtual table, as specified by DW_AT_containing_type.
16047      For everyone else, it is an expression to be evaluated relative
16048      to the object address.  */
16049
16050   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
16051   if (attr)
16052     {
16053       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
16054         {
16055           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
16056             {
16057               /* Old-style GCC.  */
16058               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
16059             }
16060           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
16061                    || (DW_BLOCK (attr)->size > 1
16062                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
16063                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
16064             {
16065               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
16066               if ((fnp->voffset % cu->header.addr_size) != 0)
16067                 dwarf2_complex_location_expr_complaint ();
16068               else
16069                 fnp->voffset /= cu->header.addr_size;
16070               fnp->voffset += 2;
16071             }
16072           else
16073             dwarf2_complex_location_expr_complaint ();
16074
16075           if (!fnp->fcontext)
16076             {
16077               /* If there is no `this' field and no DW_AT_containing_type,
16078                  we cannot actually find a base class context for the
16079                  vtable!  */
16080               if (TYPE_NFIELDS (this_type) == 0
16081                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
16082                 {
16083                   complaint (&symfile_complaints,
16084                              _("cannot determine context for virtual member "
16085                                "function \"%s\" (offset %s)"),
16086                              fieldname, sect_offset_str (die->sect_off));
16087                 }
16088               else
16089                 {
16090                   fnp->fcontext
16091                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
16092                 }
16093             }
16094         }
16095       else if (attr_form_is_section_offset (attr))
16096         {
16097           dwarf2_complex_location_expr_complaint ();
16098         }
16099       else
16100         {
16101           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
16102                                                  fieldname);
16103         }
16104     }
16105   else
16106     {
16107       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
16108       if (attr && DW_UNSND (attr))
16109         {
16110           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
16111           complaint (&symfile_complaints,
16112                      _("Member function \"%s\" (offset %s) is virtual "
16113                        "but the vtable offset is not specified"),
16114                      fieldname, sect_offset_str (die->sect_off));
16115           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16116           TYPE_CPLUS_DYNAMIC (type) = 1;
16117         }
16118     }
16119 }
16120
16121 /* Create the vector of member function fields, and attach it to the type.  */
16122
16123 static void
16124 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
16125                                  struct dwarf2_cu *cu)
16126 {
16127   struct fnfieldlist *flp;
16128   int i;
16129
16130   if (cu->language == language_ada)
16131     error (_("unexpected member functions in Ada type"));
16132
16133   ALLOCATE_CPLUS_STRUCT_TYPE (type);
16134   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
16135     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
16136
16137   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
16138     {
16139       struct nextfnfield *nfp = flp->head;
16140       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
16141       int k;
16142
16143       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
16144       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
16145       fn_flp->fn_fields = (struct fn_field *)
16146         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
16147       for (k = flp->length; (k--, nfp); nfp = nfp->next)
16148         fn_flp->fn_fields[k] = nfp->fnfield;
16149     }
16150
16151   TYPE_NFN_FIELDS (type) = fip->nfnfields;
16152 }
16153
16154 /* Returns non-zero if NAME is the name of a vtable member in CU's
16155    language, zero otherwise.  */
16156 static int
16157 is_vtable_name (const char *name, struct dwarf2_cu *cu)
16158 {
16159   static const char vptr[] = "_vptr";
16160
16161   /* Look for the C++ form of the vtable.  */
16162   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
16163     return 1;
16164
16165   return 0;
16166 }
16167
16168 /* GCC outputs unnamed structures that are really pointers to member
16169    functions, with the ABI-specified layout.  If TYPE describes
16170    such a structure, smash it into a member function type.
16171
16172    GCC shouldn't do this; it should just output pointer to member DIEs.
16173    This is GCC PR debug/28767.  */
16174
16175 static void
16176 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
16177 {
16178   struct type *pfn_type, *self_type, *new_type;
16179
16180   /* Check for a structure with no name and two children.  */
16181   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
16182     return;
16183
16184   /* Check for __pfn and __delta members.  */
16185   if (TYPE_FIELD_NAME (type, 0) == NULL
16186       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
16187       || TYPE_FIELD_NAME (type, 1) == NULL
16188       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
16189     return;
16190
16191   /* Find the type of the method.  */
16192   pfn_type = TYPE_FIELD_TYPE (type, 0);
16193   if (pfn_type == NULL
16194       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
16195       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
16196     return;
16197
16198   /* Look for the "this" argument.  */
16199   pfn_type = TYPE_TARGET_TYPE (pfn_type);
16200   if (TYPE_NFIELDS (pfn_type) == 0
16201       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
16202       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
16203     return;
16204
16205   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
16206   new_type = alloc_type (objfile);
16207   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
16208                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
16209                         TYPE_VARARGS (pfn_type));
16210   smash_to_methodptr_type (type, new_type);
16211 }
16212
16213
16214 /* Called when we find the DIE that starts a structure or union scope
16215    (definition) to create a type for the structure or union.  Fill in
16216    the type's name and general properties; the members will not be
16217    processed until process_structure_scope.  A symbol table entry for
16218    the type will also not be done until process_structure_scope (assuming
16219    the type has a name).
16220
16221    NOTE: we need to call these functions regardless of whether or not the
16222    DIE has a DW_AT_name attribute, since it might be an anonymous
16223    structure or union.  This gets the type entered into our set of
16224    user defined types.  */
16225
16226 static struct type *
16227 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
16228 {
16229   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16230   struct type *type;
16231   struct attribute *attr;
16232   const char *name;
16233
16234   /* If the definition of this type lives in .debug_types, read that type.
16235      Don't follow DW_AT_specification though, that will take us back up
16236      the chain and we want to go down.  */
16237   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16238   if (attr)
16239     {
16240       type = get_DW_AT_signature_type (die, attr, cu);
16241
16242       /* The type's CU may not be the same as CU.
16243          Ensure TYPE is recorded with CU in die_type_hash.  */
16244       return set_die_type (die, type, cu);
16245     }
16246
16247   type = alloc_type (objfile);
16248   INIT_CPLUS_SPECIFIC (type);
16249
16250   name = dwarf2_name (die, cu);
16251   if (name != NULL)
16252     {
16253       if (cu->language == language_cplus
16254           || cu->language == language_d
16255           || cu->language == language_rust)
16256         {
16257           const char *full_name = dwarf2_full_name (name, die, cu);
16258
16259           /* dwarf2_full_name might have already finished building the DIE's
16260              type.  If so, there is no need to continue.  */
16261           if (get_die_type (die, cu) != NULL)
16262             return get_die_type (die, cu);
16263
16264           TYPE_TAG_NAME (type) = full_name;
16265           if (die->tag == DW_TAG_structure_type
16266               || die->tag == DW_TAG_class_type)
16267             TYPE_NAME (type) = TYPE_TAG_NAME (type);
16268         }
16269       else
16270         {
16271           /* The name is already allocated along with this objfile, so
16272              we don't need to duplicate it for the type.  */
16273           TYPE_TAG_NAME (type) = name;
16274           if (die->tag == DW_TAG_class_type)
16275             TYPE_NAME (type) = TYPE_TAG_NAME (type);
16276         }
16277     }
16278
16279   if (die->tag == DW_TAG_structure_type)
16280     {
16281       TYPE_CODE (type) = TYPE_CODE_STRUCT;
16282     }
16283   else if (die->tag == DW_TAG_union_type)
16284     {
16285       TYPE_CODE (type) = TYPE_CODE_UNION;
16286     }
16287   else if (die->tag == DW_TAG_variant_part)
16288     {
16289       TYPE_CODE (type) = TYPE_CODE_UNION;
16290       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
16291     }
16292   else
16293     {
16294       TYPE_CODE (type) = TYPE_CODE_STRUCT;
16295     }
16296
16297   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
16298     TYPE_DECLARED_CLASS (type) = 1;
16299
16300   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16301   if (attr)
16302     {
16303       if (attr_form_is_constant (attr))
16304         TYPE_LENGTH (type) = DW_UNSND (attr);
16305       else
16306         {
16307           /* For the moment, dynamic type sizes are not supported
16308              by GDB's struct type.  The actual size is determined
16309              on-demand when resolving the type of a given object,
16310              so set the type's length to zero for now.  Otherwise,
16311              we record an expression as the length, and that expression
16312              could lead to a very large value, which could eventually
16313              lead to us trying to allocate that much memory when creating
16314              a value of that type.  */
16315           TYPE_LENGTH (type) = 0;
16316         }
16317     }
16318   else
16319     {
16320       TYPE_LENGTH (type) = 0;
16321     }
16322
16323   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
16324     {
16325       /* ICC<14 does not output the required DW_AT_declaration on
16326          incomplete types, but gives them a size of zero.  */
16327       TYPE_STUB (type) = 1;
16328     }
16329   else
16330     TYPE_STUB_SUPPORTED (type) = 1;
16331
16332   if (die_is_declaration (die, cu))
16333     TYPE_STUB (type) = 1;
16334   else if (attr == NULL && die->child == NULL
16335            && producer_is_realview (cu->producer))
16336     /* RealView does not output the required DW_AT_declaration
16337        on incomplete types.  */
16338     TYPE_STUB (type) = 1;
16339
16340   /* We need to add the type field to the die immediately so we don't
16341      infinitely recurse when dealing with pointers to the structure
16342      type within the structure itself.  */
16343   set_die_type (die, type, cu);
16344
16345   /* set_die_type should be already done.  */
16346   set_descriptive_type (type, die, cu);
16347
16348   return type;
16349 }
16350
16351 /* A helper for process_structure_scope that handles a single member
16352    DIE.  */
16353
16354 static void
16355 handle_struct_member_die (struct die_info *child_die, struct type *type,
16356                           struct field_info *fi,
16357                           std::vector<struct symbol *> *template_args,
16358                           struct dwarf2_cu *cu)
16359 {
16360   if (child_die->tag == DW_TAG_member
16361       || child_die->tag == DW_TAG_variable
16362       || child_die->tag == DW_TAG_variant_part)
16363     {
16364       /* NOTE: carlton/2002-11-05: A C++ static data member
16365          should be a DW_TAG_member that is a declaration, but
16366          all versions of G++ as of this writing (so through at
16367          least 3.2.1) incorrectly generate DW_TAG_variable
16368          tags for them instead.  */
16369       dwarf2_add_field (fi, child_die, cu);
16370     }
16371   else if (child_die->tag == DW_TAG_subprogram)
16372     {
16373       /* Rust doesn't have member functions in the C++ sense.
16374          However, it does emit ordinary functions as children
16375          of a struct DIE.  */
16376       if (cu->language == language_rust)
16377         read_func_scope (child_die, cu);
16378       else
16379         {
16380           /* C++ member function.  */
16381           dwarf2_add_member_fn (fi, child_die, type, cu);
16382         }
16383     }
16384   else if (child_die->tag == DW_TAG_inheritance)
16385     {
16386       /* C++ base class field.  */
16387       dwarf2_add_field (fi, child_die, cu);
16388     }
16389   else if (type_can_define_types (child_die))
16390     dwarf2_add_type_defn (fi, child_die, cu);
16391   else if (child_die->tag == DW_TAG_template_type_param
16392            || child_die->tag == DW_TAG_template_value_param)
16393     {
16394       struct symbol *arg = new_symbol (child_die, NULL, cu);
16395
16396       if (arg != NULL)
16397         template_args->push_back (arg);
16398     }
16399   else if (child_die->tag == DW_TAG_variant)
16400     {
16401       /* In a variant we want to get the discriminant and also add a
16402          field for our sole member child.  */
16403       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
16404
16405       for (struct die_info *variant_child = child_die->child;
16406            variant_child != NULL;
16407            variant_child = sibling_die (variant_child))
16408         {
16409           if (variant_child->tag == DW_TAG_member)
16410             {
16411               handle_struct_member_die (variant_child, type, fi,
16412                                         template_args, cu);
16413               /* Only handle the one.  */
16414               break;
16415             }
16416         }
16417
16418       /* We don't handle this but we might as well report it if we see
16419          it.  */
16420       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
16421           complaint (&symfile_complaints,
16422                      _("DW_AT_discr_list is not supported yet"
16423                        " - DIE at %s [in module %s]"),
16424                      sect_offset_str (child_die->sect_off),
16425                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16426
16427       /* The first field was just added, so we can stash the
16428          discriminant there.  */
16429       gdb_assert (fi->fields != NULL);
16430       if (discr == NULL)
16431         fi->fields->variant.default_branch = true;
16432       else
16433         fi->fields->variant.discriminant_value = DW_UNSND (discr);
16434     }
16435 }
16436
16437 /* Finish creating a structure or union type, including filling in
16438    its members and creating a symbol for it.  */
16439
16440 static void
16441 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
16442 {
16443   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16444   struct die_info *child_die;
16445   struct type *type;
16446
16447   type = get_die_type (die, cu);
16448   if (type == NULL)
16449     type = read_structure_type (die, cu);
16450
16451   /* When reading a DW_TAG_variant_part, we need to notice when we
16452      read the discriminant member, so we can record it later in the
16453      discriminant_info.  */
16454   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
16455   sect_offset discr_offset;
16456
16457   if (is_variant_part)
16458     {
16459       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
16460       if (discr == NULL)
16461         {
16462           /* Maybe it's a univariant form, an extension we support.
16463              In this case arrange not to check the offset.  */
16464           is_variant_part = false;
16465         }
16466       else if (attr_form_is_ref (discr))
16467         {
16468           struct dwarf2_cu *target_cu = cu;
16469           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
16470
16471           discr_offset = target_die->sect_off;
16472         }
16473       else
16474         {
16475           complaint (&symfile_complaints,
16476                      _("DW_AT_discr does not have DIE reference form"
16477                        " - DIE at %s [in module %s]"),
16478                      sect_offset_str (die->sect_off),
16479                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16480           is_variant_part = false;
16481         }
16482     }
16483
16484   if (die->child != NULL && ! die_is_declaration (die, cu))
16485     {
16486       struct field_info fi;
16487       std::vector<struct symbol *> template_args;
16488       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
16489
16490       memset (&fi, 0, sizeof (struct field_info));
16491
16492       child_die = die->child;
16493
16494       while (child_die && child_die->tag)
16495         {
16496           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
16497
16498           if (is_variant_part && discr_offset == child_die->sect_off)
16499             fi.fields->variant.is_discriminant = true;
16500
16501           child_die = sibling_die (child_die);
16502         }
16503
16504       /* Attach template arguments to type.  */
16505       if (!template_args.empty ())
16506         {
16507           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16508           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16509           TYPE_TEMPLATE_ARGUMENTS (type)
16510             = XOBNEWVEC (&objfile->objfile_obstack,
16511                          struct symbol *,
16512                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16513           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16514                   template_args.data (),
16515                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16516                    * sizeof (struct symbol *)));
16517         }
16518
16519       /* Attach fields and member functions to the type.  */
16520       if (fi.nfields)
16521         dwarf2_attach_fields_to_type (&fi, type, cu);
16522       if (fi.nfnfields)
16523         {
16524           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16525
16526           /* Get the type which refers to the base class (possibly this
16527              class itself) which contains the vtable pointer for the current
16528              class from the DW_AT_containing_type attribute.  This use of
16529              DW_AT_containing_type is a GNU extension.  */
16530
16531           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16532             {
16533               struct type *t = die_containing_type (die, cu);
16534
16535               set_type_vptr_basetype (type, t);
16536               if (type == t)
16537                 {
16538                   int i;
16539
16540                   /* Our own class provides vtbl ptr.  */
16541                   for (i = TYPE_NFIELDS (t) - 1;
16542                        i >= TYPE_N_BASECLASSES (t);
16543                        --i)
16544                     {
16545                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16546
16547                       if (is_vtable_name (fieldname, cu))
16548                         {
16549                           set_type_vptr_fieldno (type, i);
16550                           break;
16551                         }
16552                     }
16553
16554                   /* Complain if virtual function table field not found.  */
16555                   if (i < TYPE_N_BASECLASSES (t))
16556                     complaint (&symfile_complaints,
16557                                _("virtual function table pointer "
16558                                  "not found when defining class '%s'"),
16559                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16560                                "");
16561                 }
16562               else
16563                 {
16564                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16565                 }
16566             }
16567           else if (cu->producer
16568                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16569             {
16570               /* The IBM XLC compiler does not provide direct indication
16571                  of the containing type, but the vtable pointer is
16572                  always named __vfp.  */
16573
16574               int i;
16575
16576               for (i = TYPE_NFIELDS (type) - 1;
16577                    i >= TYPE_N_BASECLASSES (type);
16578                    --i)
16579                 {
16580                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16581                     {
16582                       set_type_vptr_fieldno (type, i);
16583                       set_type_vptr_basetype (type, type);
16584                       break;
16585                     }
16586                 }
16587             }
16588         }
16589
16590       /* Copy fi.typedef_field_list linked list elements content into the
16591          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16592       if (fi.typedef_field_list)
16593         {
16594           int i = fi.typedef_field_list_count;
16595
16596           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16597           TYPE_TYPEDEF_FIELD_ARRAY (type)
16598             = ((struct decl_field *)
16599                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16600           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16601
16602           /* Reverse the list order to keep the debug info elements order.  */
16603           while (--i >= 0)
16604             {
16605               struct decl_field *dest, *src;
16606
16607               dest = &TYPE_TYPEDEF_FIELD (type, i);
16608               src = &fi.typedef_field_list->field;
16609               fi.typedef_field_list = fi.typedef_field_list->next;
16610               *dest = *src;
16611             }
16612         }
16613
16614       /* Copy fi.nested_types_list linked list elements content into the
16615          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16616       if (fi.nested_types_list != NULL && cu->language != language_ada)
16617         {
16618           int i = fi.nested_types_list_count;
16619
16620           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16621           TYPE_NESTED_TYPES_ARRAY (type)
16622             = ((struct decl_field *)
16623                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16624           TYPE_NESTED_TYPES_COUNT (type) = i;
16625
16626           /* Reverse the list order to keep the debug info elements order.  */
16627           while (--i >= 0)
16628             {
16629               struct decl_field *dest, *src;
16630
16631               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16632               src = &fi.nested_types_list->field;
16633               fi.nested_types_list = fi.nested_types_list->next;
16634               *dest = *src;
16635             }
16636         }
16637
16638       do_cleanups (back_to);
16639     }
16640
16641   quirk_gcc_member_function_pointer (type, objfile);
16642   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16643     cu->rust_unions.push_back (type);
16644
16645   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16646      snapshots) has been known to create a die giving a declaration
16647      for a class that has, as a child, a die giving a definition for a
16648      nested class.  So we have to process our children even if the
16649      current die is a declaration.  Normally, of course, a declaration
16650      won't have any children at all.  */
16651
16652   child_die = die->child;
16653
16654   while (child_die != NULL && child_die->tag)
16655     {
16656       if (child_die->tag == DW_TAG_member
16657           || child_die->tag == DW_TAG_variable
16658           || child_die->tag == DW_TAG_inheritance
16659           || child_die->tag == DW_TAG_template_value_param
16660           || child_die->tag == DW_TAG_template_type_param)
16661         {
16662           /* Do nothing.  */
16663         }
16664       else
16665         process_die (child_die, cu);
16666
16667       child_die = sibling_die (child_die);
16668     }
16669
16670   /* Do not consider external references.  According to the DWARF standard,
16671      these DIEs are identified by the fact that they have no byte_size
16672      attribute, and a declaration attribute.  */
16673   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16674       || !die_is_declaration (die, cu))
16675     new_symbol (die, type, cu);
16676 }
16677
16678 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16679    update TYPE using some information only available in DIE's children.  */
16680
16681 static void
16682 update_enumeration_type_from_children (struct die_info *die,
16683                                        struct type *type,
16684                                        struct dwarf2_cu *cu)
16685 {
16686   struct die_info *child_die;
16687   int unsigned_enum = 1;
16688   int flag_enum = 1;
16689   ULONGEST mask = 0;
16690
16691   auto_obstack obstack;
16692
16693   for (child_die = die->child;
16694        child_die != NULL && child_die->tag;
16695        child_die = sibling_die (child_die))
16696     {
16697       struct attribute *attr;
16698       LONGEST value;
16699       const gdb_byte *bytes;
16700       struct dwarf2_locexpr_baton *baton;
16701       const char *name;
16702
16703       if (child_die->tag != DW_TAG_enumerator)
16704         continue;
16705
16706       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16707       if (attr == NULL)
16708         continue;
16709
16710       name = dwarf2_name (child_die, cu);
16711       if (name == NULL)
16712         name = "<anonymous enumerator>";
16713
16714       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16715                                &value, &bytes, &baton);
16716       if (value < 0)
16717         {
16718           unsigned_enum = 0;
16719           flag_enum = 0;
16720         }
16721       else if ((mask & value) != 0)
16722         flag_enum = 0;
16723       else
16724         mask |= value;
16725
16726       /* If we already know that the enum type is neither unsigned, nor
16727          a flag type, no need to look at the rest of the enumerates.  */
16728       if (!unsigned_enum && !flag_enum)
16729         break;
16730     }
16731
16732   if (unsigned_enum)
16733     TYPE_UNSIGNED (type) = 1;
16734   if (flag_enum)
16735     TYPE_FLAG_ENUM (type) = 1;
16736 }
16737
16738 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16739    complete the type's fields yet, or create any symbols.  */
16740
16741 static struct type *
16742 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16743 {
16744   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16745   struct type *type;
16746   struct attribute *attr;
16747   const char *name;
16748
16749   /* If the definition of this type lives in .debug_types, read that type.
16750      Don't follow DW_AT_specification though, that will take us back up
16751      the chain and we want to go down.  */
16752   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16753   if (attr)
16754     {
16755       type = get_DW_AT_signature_type (die, attr, cu);
16756
16757       /* The type's CU may not be the same as CU.
16758          Ensure TYPE is recorded with CU in die_type_hash.  */
16759       return set_die_type (die, type, cu);
16760     }
16761
16762   type = alloc_type (objfile);
16763
16764   TYPE_CODE (type) = TYPE_CODE_ENUM;
16765   name = dwarf2_full_name (NULL, die, cu);
16766   if (name != NULL)
16767     TYPE_TAG_NAME (type) = name;
16768
16769   attr = dwarf2_attr (die, DW_AT_type, cu);
16770   if (attr != NULL)
16771     {
16772       struct type *underlying_type = die_type (die, cu);
16773
16774       TYPE_TARGET_TYPE (type) = underlying_type;
16775     }
16776
16777   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16778   if (attr)
16779     {
16780       TYPE_LENGTH (type) = DW_UNSND (attr);
16781     }
16782   else
16783     {
16784       TYPE_LENGTH (type) = 0;
16785     }
16786
16787   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16788      declared as private in the package spec, and then defined only
16789      inside the package body.  Such types are known as Taft Amendment
16790      Types.  When another package uses such a type, an incomplete DIE
16791      may be generated by the compiler.  */
16792   if (die_is_declaration (die, cu))
16793     TYPE_STUB (type) = 1;
16794
16795   /* Finish the creation of this type by using the enum's children.
16796      We must call this even when the underlying type has been provided
16797      so that we can determine if we're looking at a "flag" enum.  */
16798   update_enumeration_type_from_children (die, type, cu);
16799
16800   /* If this type has an underlying type that is not a stub, then we
16801      may use its attributes.  We always use the "unsigned" attribute
16802      in this situation, because ordinarily we guess whether the type
16803      is unsigned -- but the guess can be wrong and the underlying type
16804      can tell us the reality.  However, we defer to a local size
16805      attribute if one exists, because this lets the compiler override
16806      the underlying type if needed.  */
16807   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16808     {
16809       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16810       if (TYPE_LENGTH (type) == 0)
16811         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16812     }
16813
16814   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16815
16816   return set_die_type (die, type, cu);
16817 }
16818
16819 /* Given a pointer to a die which begins an enumeration, process all
16820    the dies that define the members of the enumeration, and create the
16821    symbol for the enumeration type.
16822
16823    NOTE: We reverse the order of the element list.  */
16824
16825 static void
16826 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16827 {
16828   struct type *this_type;
16829
16830   this_type = get_die_type (die, cu);
16831   if (this_type == NULL)
16832     this_type = read_enumeration_type (die, cu);
16833
16834   if (die->child != NULL)
16835     {
16836       struct die_info *child_die;
16837       struct symbol *sym;
16838       struct field *fields = NULL;
16839       int num_fields = 0;
16840       const char *name;
16841
16842       child_die = die->child;
16843       while (child_die && child_die->tag)
16844         {
16845           if (child_die->tag != DW_TAG_enumerator)
16846             {
16847               process_die (child_die, cu);
16848             }
16849           else
16850             {
16851               name = dwarf2_name (child_die, cu);
16852               if (name)
16853                 {
16854                   sym = new_symbol (child_die, this_type, cu);
16855
16856                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16857                     {
16858                       fields = (struct field *)
16859                         xrealloc (fields,
16860                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16861                                   * sizeof (struct field));
16862                     }
16863
16864                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16865                   FIELD_TYPE (fields[num_fields]) = NULL;
16866                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16867                   FIELD_BITSIZE (fields[num_fields]) = 0;
16868
16869                   num_fields++;
16870                 }
16871             }
16872
16873           child_die = sibling_die (child_die);
16874         }
16875
16876       if (num_fields)
16877         {
16878           TYPE_NFIELDS (this_type) = num_fields;
16879           TYPE_FIELDS (this_type) = (struct field *)
16880             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16881           memcpy (TYPE_FIELDS (this_type), fields,
16882                   sizeof (struct field) * num_fields);
16883           xfree (fields);
16884         }
16885     }
16886
16887   /* If we are reading an enum from a .debug_types unit, and the enum
16888      is a declaration, and the enum is not the signatured type in the
16889      unit, then we do not want to add a symbol for it.  Adding a
16890      symbol would in some cases obscure the true definition of the
16891      enum, giving users an incomplete type when the definition is
16892      actually available.  Note that we do not want to do this for all
16893      enums which are just declarations, because C++0x allows forward
16894      enum declarations.  */
16895   if (cu->per_cu->is_debug_types
16896       && die_is_declaration (die, cu))
16897     {
16898       struct signatured_type *sig_type;
16899
16900       sig_type = (struct signatured_type *) cu->per_cu;
16901       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16902       if (sig_type->type_offset_in_section != die->sect_off)
16903         return;
16904     }
16905
16906   new_symbol (die, this_type, cu);
16907 }
16908
16909 /* Extract all information from a DW_TAG_array_type DIE and put it in
16910    the DIE's type field.  For now, this only handles one dimensional
16911    arrays.  */
16912
16913 static struct type *
16914 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16915 {
16916   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16917   struct die_info *child_die;
16918   struct type *type;
16919   struct type *element_type, *range_type, *index_type;
16920   struct attribute *attr;
16921   const char *name;
16922   struct dynamic_prop *byte_stride_prop = NULL;
16923   unsigned int bit_stride = 0;
16924
16925   element_type = die_type (die, cu);
16926
16927   /* The die_type call above may have already set the type for this DIE.  */
16928   type = get_die_type (die, cu);
16929   if (type)
16930     return type;
16931
16932   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16933   if (attr != NULL)
16934     {
16935       int stride_ok;
16936
16937       byte_stride_prop
16938         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16939       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16940       if (!stride_ok)
16941         {
16942           complaint (&symfile_complaints,
16943                      _("unable to read array DW_AT_byte_stride "
16944                        " - DIE at %s [in module %s]"),
16945                      sect_offset_str (die->sect_off),
16946                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16947           /* Ignore this attribute.  We will likely not be able to print
16948              arrays of this type correctly, but there is little we can do
16949              to help if we cannot read the attribute's value.  */
16950           byte_stride_prop = NULL;
16951         }
16952     }
16953
16954   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16955   if (attr != NULL)
16956     bit_stride = DW_UNSND (attr);
16957
16958   /* Irix 6.2 native cc creates array types without children for
16959      arrays with unspecified length.  */
16960   if (die->child == NULL)
16961     {
16962       index_type = objfile_type (objfile)->builtin_int;
16963       range_type = create_static_range_type (NULL, index_type, 0, -1);
16964       type = create_array_type_with_stride (NULL, element_type, range_type,
16965                                             byte_stride_prop, bit_stride);
16966       return set_die_type (die, type, cu);
16967     }
16968
16969   std::vector<struct type *> range_types;
16970   child_die = die->child;
16971   while (child_die && child_die->tag)
16972     {
16973       if (child_die->tag == DW_TAG_subrange_type)
16974         {
16975           struct type *child_type = read_type_die (child_die, cu);
16976
16977           if (child_type != NULL)
16978             {
16979               /* The range type was succesfully read.  Save it for the
16980                  array type creation.  */
16981               range_types.push_back (child_type);
16982             }
16983         }
16984       child_die = sibling_die (child_die);
16985     }
16986
16987   /* Dwarf2 dimensions are output from left to right, create the
16988      necessary array types in backwards order.  */
16989
16990   type = element_type;
16991
16992   if (read_array_order (die, cu) == DW_ORD_col_major)
16993     {
16994       int i = 0;
16995
16996       while (i < range_types.size ())
16997         type = create_array_type_with_stride (NULL, type, range_types[i++],
16998                                               byte_stride_prop, bit_stride);
16999     }
17000   else
17001     {
17002       size_t ndim = range_types.size ();
17003       while (ndim-- > 0)
17004         type = create_array_type_with_stride (NULL, type, range_types[ndim],
17005                                               byte_stride_prop, bit_stride);
17006     }
17007
17008   /* Understand Dwarf2 support for vector types (like they occur on
17009      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
17010      array type.  This is not part of the Dwarf2/3 standard yet, but a
17011      custom vendor extension.  The main difference between a regular
17012      array and the vector variant is that vectors are passed by value
17013      to functions.  */
17014   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
17015   if (attr)
17016     make_vector_type (type);
17017
17018   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
17019      implementation may choose to implement triple vectors using this
17020      attribute.  */
17021   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17022   if (attr)
17023     {
17024       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
17025         TYPE_LENGTH (type) = DW_UNSND (attr);
17026       else
17027         complaint (&symfile_complaints,
17028                    _("DW_AT_byte_size for array type smaller "
17029                      "than the total size of elements"));
17030     }
17031
17032   name = dwarf2_name (die, cu);
17033   if (name)
17034     TYPE_NAME (type) = name;
17035
17036   /* Install the type in the die.  */
17037   set_die_type (die, type, cu);
17038
17039   /* set_die_type should be already done.  */
17040   set_descriptive_type (type, die, cu);
17041
17042   return type;
17043 }
17044
17045 static enum dwarf_array_dim_ordering
17046 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
17047 {
17048   struct attribute *attr;
17049
17050   attr = dwarf2_attr (die, DW_AT_ordering, cu);
17051
17052   if (attr)
17053     return (enum dwarf_array_dim_ordering) DW_SND (attr);
17054
17055   /* GNU F77 is a special case, as at 08/2004 array type info is the
17056      opposite order to the dwarf2 specification, but data is still
17057      laid out as per normal fortran.
17058
17059      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
17060      version checking.  */
17061
17062   if (cu->language == language_fortran
17063       && cu->producer && strstr (cu->producer, "GNU F77"))
17064     {
17065       return DW_ORD_row_major;
17066     }
17067
17068   switch (cu->language_defn->la_array_ordering)
17069     {
17070     case array_column_major:
17071       return DW_ORD_col_major;
17072     case array_row_major:
17073     default:
17074       return DW_ORD_row_major;
17075     };
17076 }
17077
17078 /* Extract all information from a DW_TAG_set_type DIE and put it in
17079    the DIE's type field.  */
17080
17081 static struct type *
17082 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
17083 {
17084   struct type *domain_type, *set_type;
17085   struct attribute *attr;
17086
17087   domain_type = die_type (die, cu);
17088
17089   /* The die_type call above may have already set the type for this DIE.  */
17090   set_type = get_die_type (die, cu);
17091   if (set_type)
17092     return set_type;
17093
17094   set_type = create_set_type (NULL, domain_type);
17095
17096   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17097   if (attr)
17098     TYPE_LENGTH (set_type) = DW_UNSND (attr);
17099
17100   return set_die_type (die, set_type, cu);
17101 }
17102
17103 /* A helper for read_common_block that creates a locexpr baton.
17104    SYM is the symbol which we are marking as computed.
17105    COMMON_DIE is the DIE for the common block.
17106    COMMON_LOC is the location expression attribute for the common
17107    block itself.
17108    MEMBER_LOC is the location expression attribute for the particular
17109    member of the common block that we are processing.
17110    CU is the CU from which the above come.  */
17111
17112 static void
17113 mark_common_block_symbol_computed (struct symbol *sym,
17114                                    struct die_info *common_die,
17115                                    struct attribute *common_loc,
17116                                    struct attribute *member_loc,
17117                                    struct dwarf2_cu *cu)
17118 {
17119   struct dwarf2_per_objfile *dwarf2_per_objfile
17120     = cu->per_cu->dwarf2_per_objfile;
17121   struct objfile *objfile = dwarf2_per_objfile->objfile;
17122   struct dwarf2_locexpr_baton *baton;
17123   gdb_byte *ptr;
17124   unsigned int cu_off;
17125   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
17126   LONGEST offset = 0;
17127
17128   gdb_assert (common_loc && member_loc);
17129   gdb_assert (attr_form_is_block (common_loc));
17130   gdb_assert (attr_form_is_block (member_loc)
17131               || attr_form_is_constant (member_loc));
17132
17133   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
17134   baton->per_cu = cu->per_cu;
17135   gdb_assert (baton->per_cu);
17136
17137   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
17138
17139   if (attr_form_is_constant (member_loc))
17140     {
17141       offset = dwarf2_get_attr_constant_value (member_loc, 0);
17142       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
17143     }
17144   else
17145     baton->size += DW_BLOCK (member_loc)->size;
17146
17147   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
17148   baton->data = ptr;
17149
17150   *ptr++ = DW_OP_call4;
17151   cu_off = common_die->sect_off - cu->per_cu->sect_off;
17152   store_unsigned_integer (ptr, 4, byte_order, cu_off);
17153   ptr += 4;
17154
17155   if (attr_form_is_constant (member_loc))
17156     {
17157       *ptr++ = DW_OP_addr;
17158       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
17159       ptr += cu->header.addr_size;
17160     }
17161   else
17162     {
17163       /* We have to copy the data here, because DW_OP_call4 will only
17164          use a DW_AT_location attribute.  */
17165       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
17166       ptr += DW_BLOCK (member_loc)->size;
17167     }
17168
17169   *ptr++ = DW_OP_plus;
17170   gdb_assert (ptr - baton->data == baton->size);
17171
17172   SYMBOL_LOCATION_BATON (sym) = baton;
17173   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17174 }
17175
17176 /* Create appropriate locally-scoped variables for all the
17177    DW_TAG_common_block entries.  Also create a struct common_block
17178    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
17179    is used to sepate the common blocks name namespace from regular
17180    variable names.  */
17181
17182 static void
17183 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
17184 {
17185   struct attribute *attr;
17186
17187   attr = dwarf2_attr (die, DW_AT_location, cu);
17188   if (attr)
17189     {
17190       /* Support the .debug_loc offsets.  */
17191       if (attr_form_is_block (attr))
17192         {
17193           /* Ok.  */
17194         }
17195       else if (attr_form_is_section_offset (attr))
17196         {
17197           dwarf2_complex_location_expr_complaint ();
17198           attr = NULL;
17199         }
17200       else
17201         {
17202           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17203                                                  "common block member");
17204           attr = NULL;
17205         }
17206     }
17207
17208   if (die->child != NULL)
17209     {
17210       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17211       struct die_info *child_die;
17212       size_t n_entries = 0, size;
17213       struct common_block *common_block;
17214       struct symbol *sym;
17215
17216       for (child_die = die->child;
17217            child_die && child_die->tag;
17218            child_die = sibling_die (child_die))
17219         ++n_entries;
17220
17221       size = (sizeof (struct common_block)
17222               + (n_entries - 1) * sizeof (struct symbol *));
17223       common_block
17224         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
17225                                                  size);
17226       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
17227       common_block->n_entries = 0;
17228
17229       for (child_die = die->child;
17230            child_die && child_die->tag;
17231            child_die = sibling_die (child_die))
17232         {
17233           /* Create the symbol in the DW_TAG_common_block block in the current
17234              symbol scope.  */
17235           sym = new_symbol (child_die, NULL, cu);
17236           if (sym != NULL)
17237             {
17238               struct attribute *member_loc;
17239
17240               common_block->contents[common_block->n_entries++] = sym;
17241
17242               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
17243                                         cu);
17244               if (member_loc)
17245                 {
17246                   /* GDB has handled this for a long time, but it is
17247                      not specified by DWARF.  It seems to have been
17248                      emitted by gfortran at least as recently as:
17249                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
17250                   complaint (&symfile_complaints,
17251                              _("Variable in common block has "
17252                                "DW_AT_data_member_location "
17253                                "- DIE at %s [in module %s]"),
17254                                sect_offset_str (child_die->sect_off),
17255                              objfile_name (objfile));
17256
17257                   if (attr_form_is_section_offset (member_loc))
17258                     dwarf2_complex_location_expr_complaint ();
17259                   else if (attr_form_is_constant (member_loc)
17260                            || attr_form_is_block (member_loc))
17261                     {
17262                       if (attr)
17263                         mark_common_block_symbol_computed (sym, die, attr,
17264                                                            member_loc, cu);
17265                     }
17266                   else
17267                     dwarf2_complex_location_expr_complaint ();
17268                 }
17269             }
17270         }
17271
17272       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
17273       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
17274     }
17275 }
17276
17277 /* Create a type for a C++ namespace.  */
17278
17279 static struct type *
17280 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
17281 {
17282   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17283   const char *previous_prefix, *name;
17284   int is_anonymous;
17285   struct type *type;
17286
17287   /* For extensions, reuse the type of the original namespace.  */
17288   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
17289     {
17290       struct die_info *ext_die;
17291       struct dwarf2_cu *ext_cu = cu;
17292
17293       ext_die = dwarf2_extension (die, &ext_cu);
17294       type = read_type_die (ext_die, ext_cu);
17295
17296       /* EXT_CU may not be the same as CU.
17297          Ensure TYPE is recorded with CU in die_type_hash.  */
17298       return set_die_type (die, type, cu);
17299     }
17300
17301   name = namespace_name (die, &is_anonymous, cu);
17302
17303   /* Now build the name of the current namespace.  */
17304
17305   previous_prefix = determine_prefix (die, cu);
17306   if (previous_prefix[0] != '\0')
17307     name = typename_concat (&objfile->objfile_obstack,
17308                             previous_prefix, name, 0, cu);
17309
17310   /* Create the type.  */
17311   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
17312   TYPE_TAG_NAME (type) = TYPE_NAME (type);
17313
17314   return set_die_type (die, type, cu);
17315 }
17316
17317 /* Read a namespace scope.  */
17318
17319 static void
17320 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
17321 {
17322   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17323   int is_anonymous;
17324
17325   /* Add a symbol associated to this if we haven't seen the namespace
17326      before.  Also, add a using directive if it's an anonymous
17327      namespace.  */
17328
17329   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
17330     {
17331       struct type *type;
17332
17333       type = read_type_die (die, cu);
17334       new_symbol (die, type, cu);
17335
17336       namespace_name (die, &is_anonymous, cu);
17337       if (is_anonymous)
17338         {
17339           const char *previous_prefix = determine_prefix (die, cu);
17340
17341           std::vector<const char *> excludes;
17342           add_using_directive (using_directives (cu->language),
17343                                previous_prefix, TYPE_NAME (type), NULL,
17344                                NULL, excludes, 0, &objfile->objfile_obstack);
17345         }
17346     }
17347
17348   if (die->child != NULL)
17349     {
17350       struct die_info *child_die = die->child;
17351
17352       while (child_die && child_die->tag)
17353         {
17354           process_die (child_die, cu);
17355           child_die = sibling_die (child_die);
17356         }
17357     }
17358 }
17359
17360 /* Read a Fortran module as type.  This DIE can be only a declaration used for
17361    imported module.  Still we need that type as local Fortran "use ... only"
17362    declaration imports depend on the created type in determine_prefix.  */
17363
17364 static struct type *
17365 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
17366 {
17367   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17368   const char *module_name;
17369   struct type *type;
17370
17371   module_name = dwarf2_name (die, cu);
17372   if (!module_name)
17373     complaint (&symfile_complaints,
17374                _("DW_TAG_module has no name, offset %s"),
17375                sect_offset_str (die->sect_off));
17376   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
17377
17378   /* determine_prefix uses TYPE_TAG_NAME.  */
17379   TYPE_TAG_NAME (type) = TYPE_NAME (type);
17380
17381   return set_die_type (die, type, cu);
17382 }
17383
17384 /* Read a Fortran module.  */
17385
17386 static void
17387 read_module (struct die_info *die, struct dwarf2_cu *cu)
17388 {
17389   struct die_info *child_die = die->child;
17390   struct type *type;
17391
17392   type = read_type_die (die, cu);
17393   new_symbol (die, type, cu);
17394
17395   while (child_die && child_die->tag)
17396     {
17397       process_die (child_die, cu);
17398       child_die = sibling_die (child_die);
17399     }
17400 }
17401
17402 /* Return the name of the namespace represented by DIE.  Set
17403    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
17404    namespace.  */
17405
17406 static const char *
17407 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
17408 {
17409   struct die_info *current_die;
17410   const char *name = NULL;
17411
17412   /* Loop through the extensions until we find a name.  */
17413
17414   for (current_die = die;
17415        current_die != NULL;
17416        current_die = dwarf2_extension (die, &cu))
17417     {
17418       /* We don't use dwarf2_name here so that we can detect the absence
17419          of a name -> anonymous namespace.  */
17420       name = dwarf2_string_attr (die, DW_AT_name, cu);
17421
17422       if (name != NULL)
17423         break;
17424     }
17425
17426   /* Is it an anonymous namespace?  */
17427
17428   *is_anonymous = (name == NULL);
17429   if (*is_anonymous)
17430     name = CP_ANONYMOUS_NAMESPACE_STR;
17431
17432   return name;
17433 }
17434
17435 /* Extract all information from a DW_TAG_pointer_type DIE and add to
17436    the user defined type vector.  */
17437
17438 static struct type *
17439 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
17440 {
17441   struct gdbarch *gdbarch
17442     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
17443   struct comp_unit_head *cu_header = &cu->header;
17444   struct type *type;
17445   struct attribute *attr_byte_size;
17446   struct attribute *attr_address_class;
17447   int byte_size, addr_class;
17448   struct type *target_type;
17449
17450   target_type = die_type (die, cu);
17451
17452   /* The die_type call above may have already set the type for this DIE.  */
17453   type = get_die_type (die, cu);
17454   if (type)
17455     return type;
17456
17457   type = lookup_pointer_type (target_type);
17458
17459   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17460   if (attr_byte_size)
17461     byte_size = DW_UNSND (attr_byte_size);
17462   else
17463     byte_size = cu_header->addr_size;
17464
17465   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17466   if (attr_address_class)
17467     addr_class = DW_UNSND (attr_address_class);
17468   else
17469     addr_class = DW_ADDR_none;
17470
17471   /* If the pointer size or address class is different than the
17472      default, create a type variant marked as such and set the
17473      length accordingly.  */
17474   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17475     {
17476       if (gdbarch_address_class_type_flags_p (gdbarch))
17477         {
17478           int type_flags;
17479
17480           type_flags = gdbarch_address_class_type_flags
17481                          (gdbarch, byte_size, addr_class);
17482           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17483                       == 0);
17484           type = make_type_with_address_space (type, type_flags);
17485         }
17486       else if (TYPE_LENGTH (type) != byte_size)
17487         {
17488           complaint (&symfile_complaints,
17489                      _("invalid pointer size %d"), byte_size);
17490         }
17491       else
17492         {
17493           /* Should we also complain about unhandled address classes?  */
17494         }
17495     }
17496
17497   TYPE_LENGTH (type) = byte_size;
17498   return set_die_type (die, type, cu);
17499 }
17500
17501 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17502    the user defined type vector.  */
17503
17504 static struct type *
17505 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17506 {
17507   struct type *type;
17508   struct type *to_type;
17509   struct type *domain;
17510
17511   to_type = die_type (die, cu);
17512   domain = die_containing_type (die, cu);
17513
17514   /* The calls above may have already set the type for this DIE.  */
17515   type = get_die_type (die, cu);
17516   if (type)
17517     return type;
17518
17519   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17520     type = lookup_methodptr_type (to_type);
17521   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17522     {
17523       struct type *new_type
17524         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17525
17526       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17527                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17528                             TYPE_VARARGS (to_type));
17529       type = lookup_methodptr_type (new_type);
17530     }
17531   else
17532     type = lookup_memberptr_type (to_type, domain);
17533
17534   return set_die_type (die, type, cu);
17535 }
17536
17537 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17538    the user defined type vector.  */
17539
17540 static struct type *
17541 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17542                           enum type_code refcode)
17543 {
17544   struct comp_unit_head *cu_header = &cu->header;
17545   struct type *type, *target_type;
17546   struct attribute *attr;
17547
17548   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17549
17550   target_type = die_type (die, cu);
17551
17552   /* The die_type call above may have already set the type for this DIE.  */
17553   type = get_die_type (die, cu);
17554   if (type)
17555     return type;
17556
17557   type = lookup_reference_type (target_type, refcode);
17558   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17559   if (attr)
17560     {
17561       TYPE_LENGTH (type) = DW_UNSND (attr);
17562     }
17563   else
17564     {
17565       TYPE_LENGTH (type) = cu_header->addr_size;
17566     }
17567   return set_die_type (die, type, cu);
17568 }
17569
17570 /* Add the given cv-qualifiers to the element type of the array.  GCC
17571    outputs DWARF type qualifiers that apply to an array, not the
17572    element type.  But GDB relies on the array element type to carry
17573    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17574    specification.  */
17575
17576 static struct type *
17577 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17578                    struct type *base_type, int cnst, int voltl)
17579 {
17580   struct type *el_type, *inner_array;
17581
17582   base_type = copy_type (base_type);
17583   inner_array = base_type;
17584
17585   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17586     {
17587       TYPE_TARGET_TYPE (inner_array) =
17588         copy_type (TYPE_TARGET_TYPE (inner_array));
17589       inner_array = TYPE_TARGET_TYPE (inner_array);
17590     }
17591
17592   el_type = TYPE_TARGET_TYPE (inner_array);
17593   cnst |= TYPE_CONST (el_type);
17594   voltl |= TYPE_VOLATILE (el_type);
17595   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17596
17597   return set_die_type (die, base_type, cu);
17598 }
17599
17600 static struct type *
17601 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17602 {
17603   struct type *base_type, *cv_type;
17604
17605   base_type = die_type (die, cu);
17606
17607   /* The die_type call above may have already set the type for this DIE.  */
17608   cv_type = get_die_type (die, cu);
17609   if (cv_type)
17610     return cv_type;
17611
17612   /* In case the const qualifier is applied to an array type, the element type
17613      is so qualified, not the array type (section 6.7.3 of C99).  */
17614   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17615     return add_array_cv_type (die, cu, base_type, 1, 0);
17616
17617   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17618   return set_die_type (die, cv_type, cu);
17619 }
17620
17621 static struct type *
17622 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17623 {
17624   struct type *base_type, *cv_type;
17625
17626   base_type = die_type (die, cu);
17627
17628   /* The die_type call above may have already set the type for this DIE.  */
17629   cv_type = get_die_type (die, cu);
17630   if (cv_type)
17631     return cv_type;
17632
17633   /* In case the volatile qualifier is applied to an array type, the
17634      element type is so qualified, not the array type (section 6.7.3
17635      of C99).  */
17636   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17637     return add_array_cv_type (die, cu, base_type, 0, 1);
17638
17639   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17640   return set_die_type (die, cv_type, cu);
17641 }
17642
17643 /* Handle DW_TAG_restrict_type.  */
17644
17645 static struct type *
17646 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17647 {
17648   struct type *base_type, *cv_type;
17649
17650   base_type = die_type (die, cu);
17651
17652   /* The die_type call above may have already set the type for this DIE.  */
17653   cv_type = get_die_type (die, cu);
17654   if (cv_type)
17655     return cv_type;
17656
17657   cv_type = make_restrict_type (base_type);
17658   return set_die_type (die, cv_type, cu);
17659 }
17660
17661 /* Handle DW_TAG_atomic_type.  */
17662
17663 static struct type *
17664 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17665 {
17666   struct type *base_type, *cv_type;
17667
17668   base_type = die_type (die, cu);
17669
17670   /* The die_type call above may have already set the type for this DIE.  */
17671   cv_type = get_die_type (die, cu);
17672   if (cv_type)
17673     return cv_type;
17674
17675   cv_type = make_atomic_type (base_type);
17676   return set_die_type (die, cv_type, cu);
17677 }
17678
17679 /* Extract all information from a DW_TAG_string_type DIE and add to
17680    the user defined type vector.  It isn't really a user defined type,
17681    but it behaves like one, with other DIE's using an AT_user_def_type
17682    attribute to reference it.  */
17683
17684 static struct type *
17685 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17686 {
17687   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17688   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17689   struct type *type, *range_type, *index_type, *char_type;
17690   struct attribute *attr;
17691   unsigned int length;
17692
17693   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17694   if (attr)
17695     {
17696       length = DW_UNSND (attr);
17697     }
17698   else
17699     {
17700       /* Check for the DW_AT_byte_size attribute.  */
17701       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17702       if (attr)
17703         {
17704           length = DW_UNSND (attr);
17705         }
17706       else
17707         {
17708           length = 1;
17709         }
17710     }
17711
17712   index_type = objfile_type (objfile)->builtin_int;
17713   range_type = create_static_range_type (NULL, index_type, 1, length);
17714   char_type = language_string_char_type (cu->language_defn, gdbarch);
17715   type = create_string_type (NULL, char_type, range_type);
17716
17717   return set_die_type (die, type, cu);
17718 }
17719
17720 /* Assuming that DIE corresponds to a function, returns nonzero
17721    if the function is prototyped.  */
17722
17723 static int
17724 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17725 {
17726   struct attribute *attr;
17727
17728   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17729   if (attr && (DW_UNSND (attr) != 0))
17730     return 1;
17731
17732   /* The DWARF standard implies that the DW_AT_prototyped attribute
17733      is only meaninful for C, but the concept also extends to other
17734      languages that allow unprototyped functions (Eg: Objective C).
17735      For all other languages, assume that functions are always
17736      prototyped.  */
17737   if (cu->language != language_c
17738       && cu->language != language_objc
17739       && cu->language != language_opencl)
17740     return 1;
17741
17742   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17743      prototyped and unprototyped functions; default to prototyped,
17744      since that is more common in modern code (and RealView warns
17745      about unprototyped functions).  */
17746   if (producer_is_realview (cu->producer))
17747     return 1;
17748
17749   return 0;
17750 }
17751
17752 /* Handle DIES due to C code like:
17753
17754    struct foo
17755    {
17756    int (*funcp)(int a, long l);
17757    int b;
17758    };
17759
17760    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17761
17762 static struct type *
17763 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17764 {
17765   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17766   struct type *type;            /* Type that this function returns.  */
17767   struct type *ftype;           /* Function that returns above type.  */
17768   struct attribute *attr;
17769
17770   type = die_type (die, cu);
17771
17772   /* The die_type call above may have already set the type for this DIE.  */
17773   ftype = get_die_type (die, cu);
17774   if (ftype)
17775     return ftype;
17776
17777   ftype = lookup_function_type (type);
17778
17779   if (prototyped_function_p (die, cu))
17780     TYPE_PROTOTYPED (ftype) = 1;
17781
17782   /* Store the calling convention in the type if it's available in
17783      the subroutine die.  Otherwise set the calling convention to
17784      the default value DW_CC_normal.  */
17785   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17786   if (attr)
17787     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17788   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17789     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17790   else
17791     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17792
17793   /* Record whether the function returns normally to its caller or not
17794      if the DWARF producer set that information.  */
17795   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17796   if (attr && (DW_UNSND (attr) != 0))
17797     TYPE_NO_RETURN (ftype) = 1;
17798
17799   /* We need to add the subroutine type to the die immediately so
17800      we don't infinitely recurse when dealing with parameters
17801      declared as the same subroutine type.  */
17802   set_die_type (die, ftype, cu);
17803
17804   if (die->child != NULL)
17805     {
17806       struct type *void_type = objfile_type (objfile)->builtin_void;
17807       struct die_info *child_die;
17808       int nparams, iparams;
17809
17810       /* Count the number of parameters.
17811          FIXME: GDB currently ignores vararg functions, but knows about
17812          vararg member functions.  */
17813       nparams = 0;
17814       child_die = die->child;
17815       while (child_die && child_die->tag)
17816         {
17817           if (child_die->tag == DW_TAG_formal_parameter)
17818             nparams++;
17819           else if (child_die->tag == DW_TAG_unspecified_parameters)
17820             TYPE_VARARGS (ftype) = 1;
17821           child_die = sibling_die (child_die);
17822         }
17823
17824       /* Allocate storage for parameters and fill them in.  */
17825       TYPE_NFIELDS (ftype) = nparams;
17826       TYPE_FIELDS (ftype) = (struct field *)
17827         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17828
17829       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17830          even if we error out during the parameters reading below.  */
17831       for (iparams = 0; iparams < nparams; iparams++)
17832         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17833
17834       iparams = 0;
17835       child_die = die->child;
17836       while (child_die && child_die->tag)
17837         {
17838           if (child_die->tag == DW_TAG_formal_parameter)
17839             {
17840               struct type *arg_type;
17841
17842               /* DWARF version 2 has no clean way to discern C++
17843                  static and non-static member functions.  G++ helps
17844                  GDB by marking the first parameter for non-static
17845                  member functions (which is the this pointer) as
17846                  artificial.  We pass this information to
17847                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17848
17849                  DWARF version 3 added DW_AT_object_pointer, which GCC
17850                  4.5 does not yet generate.  */
17851               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17852               if (attr)
17853                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17854               else
17855                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17856               arg_type = die_type (child_die, cu);
17857
17858               /* RealView does not mark THIS as const, which the testsuite
17859                  expects.  GCC marks THIS as const in method definitions,
17860                  but not in the class specifications (GCC PR 43053).  */
17861               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17862                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17863                 {
17864                   int is_this = 0;
17865                   struct dwarf2_cu *arg_cu = cu;
17866                   const char *name = dwarf2_name (child_die, cu);
17867
17868                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17869                   if (attr)
17870                     {
17871                       /* If the compiler emits this, use it.  */
17872                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17873                         is_this = 1;
17874                     }
17875                   else if (name && strcmp (name, "this") == 0)
17876                     /* Function definitions will have the argument names.  */
17877                     is_this = 1;
17878                   else if (name == NULL && iparams == 0)
17879                     /* Declarations may not have the names, so like
17880                        elsewhere in GDB, assume an artificial first
17881                        argument is "this".  */
17882                     is_this = 1;
17883
17884                   if (is_this)
17885                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17886                                              arg_type, 0);
17887                 }
17888
17889               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17890               iparams++;
17891             }
17892           child_die = sibling_die (child_die);
17893         }
17894     }
17895
17896   return ftype;
17897 }
17898
17899 static struct type *
17900 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17901 {
17902   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17903   const char *name = NULL;
17904   struct type *this_type, *target_type;
17905
17906   name = dwarf2_full_name (NULL, die, cu);
17907   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17908   TYPE_TARGET_STUB (this_type) = 1;
17909   set_die_type (die, this_type, cu);
17910   target_type = die_type (die, cu);
17911   if (target_type != this_type)
17912     TYPE_TARGET_TYPE (this_type) = target_type;
17913   else
17914     {
17915       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17916          spec and cause infinite loops in GDB.  */
17917       complaint (&symfile_complaints,
17918                  _("Self-referential DW_TAG_typedef "
17919                    "- DIE at %s [in module %s]"),
17920                  sect_offset_str (die->sect_off), objfile_name (objfile));
17921       TYPE_TARGET_TYPE (this_type) = NULL;
17922     }
17923   return this_type;
17924 }
17925
17926 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17927    (which may be different from NAME) to the architecture back-end to allow
17928    it to guess the correct format if necessary.  */
17929
17930 static struct type *
17931 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17932                         const char *name_hint)
17933 {
17934   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17935   const struct floatformat **format;
17936   struct type *type;
17937
17938   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17939   if (format)
17940     type = init_float_type (objfile, bits, name, format);
17941   else
17942     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17943
17944   return type;
17945 }
17946
17947 /* Find a representation of a given base type and install
17948    it in the TYPE field of the die.  */
17949
17950 static struct type *
17951 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17952 {
17953   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17954   struct type *type;
17955   struct attribute *attr;
17956   int encoding = 0, bits = 0;
17957   const char *name;
17958
17959   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17960   if (attr)
17961     {
17962       encoding = DW_UNSND (attr);
17963     }
17964   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17965   if (attr)
17966     {
17967       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17968     }
17969   name = dwarf2_name (die, cu);
17970   if (!name)
17971     {
17972       complaint (&symfile_complaints,
17973                  _("DW_AT_name missing from DW_TAG_base_type"));
17974     }
17975
17976   switch (encoding)
17977     {
17978       case DW_ATE_address:
17979         /* Turn DW_ATE_address into a void * pointer.  */
17980         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17981         type = init_pointer_type (objfile, bits, name, type);
17982         break;
17983       case DW_ATE_boolean:
17984         type = init_boolean_type (objfile, bits, 1, name);
17985         break;
17986       case DW_ATE_complex_float:
17987         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17988         type = init_complex_type (objfile, name, type);
17989         break;
17990       case DW_ATE_decimal_float:
17991         type = init_decfloat_type (objfile, bits, name);
17992         break;
17993       case DW_ATE_float:
17994         type = dwarf2_init_float_type (objfile, bits, name, name);
17995         break;
17996       case DW_ATE_signed:
17997         type = init_integer_type (objfile, bits, 0, name);
17998         break;
17999       case DW_ATE_unsigned:
18000         if (cu->language == language_fortran
18001             && name
18002             && startswith (name, "character("))
18003           type = init_character_type (objfile, bits, 1, name);
18004         else
18005           type = init_integer_type (objfile, bits, 1, name);
18006         break;
18007       case DW_ATE_signed_char:
18008         if (cu->language == language_ada || cu->language == language_m2
18009             || cu->language == language_pascal
18010             || cu->language == language_fortran)
18011           type = init_character_type (objfile, bits, 0, name);
18012         else
18013           type = init_integer_type (objfile, bits, 0, name);
18014         break;
18015       case DW_ATE_unsigned_char:
18016         if (cu->language == language_ada || cu->language == language_m2
18017             || cu->language == language_pascal
18018             || cu->language == language_fortran
18019             || cu->language == language_rust)
18020           type = init_character_type (objfile, bits, 1, name);
18021         else
18022           type = init_integer_type (objfile, bits, 1, name);
18023         break;
18024       case DW_ATE_UTF:
18025         {
18026           gdbarch *arch = get_objfile_arch (objfile);
18027
18028           if (bits == 16)
18029             type = builtin_type (arch)->builtin_char16;
18030           else if (bits == 32)
18031             type = builtin_type (arch)->builtin_char32;
18032           else
18033             {
18034               complaint (&symfile_complaints,
18035                          _("unsupported DW_ATE_UTF bit size: '%d'"),
18036                          bits);
18037               type = init_integer_type (objfile, bits, 1, name);
18038             }
18039           return set_die_type (die, type, cu);
18040         }
18041         break;
18042
18043       default:
18044         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
18045                    dwarf_type_encoding_name (encoding));
18046         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
18047         break;
18048     }
18049
18050   if (name && strcmp (name, "char") == 0)
18051     TYPE_NOSIGN (type) = 1;
18052
18053   return set_die_type (die, type, cu);
18054 }
18055
18056 /* Parse dwarf attribute if it's a block, reference or constant and put the
18057    resulting value of the attribute into struct bound_prop.
18058    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
18059
18060 static int
18061 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
18062                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
18063 {
18064   struct dwarf2_property_baton *baton;
18065   struct obstack *obstack
18066     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
18067
18068   if (attr == NULL || prop == NULL)
18069     return 0;
18070
18071   if (attr_form_is_block (attr))
18072     {
18073       baton = XOBNEW (obstack, struct dwarf2_property_baton);
18074       baton->referenced_type = NULL;
18075       baton->locexpr.per_cu = cu->per_cu;
18076       baton->locexpr.size = DW_BLOCK (attr)->size;
18077       baton->locexpr.data = DW_BLOCK (attr)->data;
18078       prop->data.baton = baton;
18079       prop->kind = PROP_LOCEXPR;
18080       gdb_assert (prop->data.baton != NULL);
18081     }
18082   else if (attr_form_is_ref (attr))
18083     {
18084       struct dwarf2_cu *target_cu = cu;
18085       struct die_info *target_die;
18086       struct attribute *target_attr;
18087
18088       target_die = follow_die_ref (die, attr, &target_cu);
18089       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
18090       if (target_attr == NULL)
18091         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
18092                                    target_cu);
18093       if (target_attr == NULL)
18094         return 0;
18095
18096       switch (target_attr->name)
18097         {
18098           case DW_AT_location:
18099             if (attr_form_is_section_offset (target_attr))
18100               {
18101                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
18102                 baton->referenced_type = die_type (target_die, target_cu);
18103                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
18104                 prop->data.baton = baton;
18105                 prop->kind = PROP_LOCLIST;
18106                 gdb_assert (prop->data.baton != NULL);
18107               }
18108             else if (attr_form_is_block (target_attr))
18109               {
18110                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
18111                 baton->referenced_type = die_type (target_die, target_cu);
18112                 baton->locexpr.per_cu = cu->per_cu;
18113                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
18114                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
18115                 prop->data.baton = baton;
18116                 prop->kind = PROP_LOCEXPR;
18117                 gdb_assert (prop->data.baton != NULL);
18118               }
18119             else
18120               {
18121                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18122                                                        "dynamic property");
18123                 return 0;
18124               }
18125             break;
18126           case DW_AT_data_member_location:
18127             {
18128               LONGEST offset;
18129
18130               if (!handle_data_member_location (target_die, target_cu,
18131                                                 &offset))
18132                 return 0;
18133
18134               baton = XOBNEW (obstack, struct dwarf2_property_baton);
18135               baton->referenced_type = read_type_die (target_die->parent,
18136                                                       target_cu);
18137               baton->offset_info.offset = offset;
18138               baton->offset_info.type = die_type (target_die, target_cu);
18139               prop->data.baton = baton;
18140               prop->kind = PROP_ADDR_OFFSET;
18141               break;
18142             }
18143         }
18144     }
18145   else if (attr_form_is_constant (attr))
18146     {
18147       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
18148       prop->kind = PROP_CONST;
18149     }
18150   else
18151     {
18152       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
18153                                              dwarf2_name (die, cu));
18154       return 0;
18155     }
18156
18157   return 1;
18158 }
18159
18160 /* Read the given DW_AT_subrange DIE.  */
18161
18162 static struct type *
18163 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
18164 {
18165   struct type *base_type, *orig_base_type;
18166   struct type *range_type;
18167   struct attribute *attr;
18168   struct dynamic_prop low, high;
18169   int low_default_is_valid;
18170   int high_bound_is_count = 0;
18171   const char *name;
18172   LONGEST negative_mask;
18173
18174   orig_base_type = die_type (die, cu);
18175   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
18176      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
18177      creating the range type, but we use the result of check_typedef
18178      when examining properties of the type.  */
18179   base_type = check_typedef (orig_base_type);
18180
18181   /* The die_type call above may have already set the type for this DIE.  */
18182   range_type = get_die_type (die, cu);
18183   if (range_type)
18184     return range_type;
18185
18186   low.kind = PROP_CONST;
18187   high.kind = PROP_CONST;
18188   high.data.const_val = 0;
18189
18190   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
18191      omitting DW_AT_lower_bound.  */
18192   switch (cu->language)
18193     {
18194     case language_c:
18195     case language_cplus:
18196       low.data.const_val = 0;
18197       low_default_is_valid = 1;
18198       break;
18199     case language_fortran:
18200       low.data.const_val = 1;
18201       low_default_is_valid = 1;
18202       break;
18203     case language_d:
18204     case language_objc:
18205     case language_rust:
18206       low.data.const_val = 0;
18207       low_default_is_valid = (cu->header.version >= 4);
18208       break;
18209     case language_ada:
18210     case language_m2:
18211     case language_pascal:
18212       low.data.const_val = 1;
18213       low_default_is_valid = (cu->header.version >= 4);
18214       break;
18215     default:
18216       low.data.const_val = 0;
18217       low_default_is_valid = 0;
18218       break;
18219     }
18220
18221   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
18222   if (attr)
18223     attr_to_dynamic_prop (attr, die, cu, &low);
18224   else if (!low_default_is_valid)
18225     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
18226                                       "- DIE at %s [in module %s]"),
18227                sect_offset_str (die->sect_off),
18228                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
18229
18230   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
18231   if (!attr_to_dynamic_prop (attr, die, cu, &high))
18232     {
18233       attr = dwarf2_attr (die, DW_AT_count, cu);
18234       if (attr_to_dynamic_prop (attr, die, cu, &high))
18235         {
18236           /* If bounds are constant do the final calculation here.  */
18237           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
18238             high.data.const_val = low.data.const_val + high.data.const_val - 1;
18239           else
18240             high_bound_is_count = 1;
18241         }
18242     }
18243
18244   /* Dwarf-2 specifications explicitly allows to create subrange types
18245      without specifying a base type.
18246      In that case, the base type must be set to the type of
18247      the lower bound, upper bound or count, in that order, if any of these
18248      three attributes references an object that has a type.
18249      If no base type is found, the Dwarf-2 specifications say that
18250      a signed integer type of size equal to the size of an address should
18251      be used.
18252      For the following C code: `extern char gdb_int [];'
18253      GCC produces an empty range DIE.
18254      FIXME: muller/2010-05-28: Possible references to object for low bound,
18255      high bound or count are not yet handled by this code.  */
18256   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
18257     {
18258       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18259       struct gdbarch *gdbarch = get_objfile_arch (objfile);
18260       int addr_size = gdbarch_addr_bit (gdbarch) /8;
18261       struct type *int_type = objfile_type (objfile)->builtin_int;
18262
18263       /* Test "int", "long int", and "long long int" objfile types,
18264          and select the first one having a size above or equal to the
18265          architecture address size.  */
18266       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
18267         base_type = int_type;
18268       else
18269         {
18270           int_type = objfile_type (objfile)->builtin_long;
18271           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
18272             base_type = int_type;
18273           else
18274             {
18275               int_type = objfile_type (objfile)->builtin_long_long;
18276               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
18277                 base_type = int_type;
18278             }
18279         }
18280     }
18281
18282   /* Normally, the DWARF producers are expected to use a signed
18283      constant form (Eg. DW_FORM_sdata) to express negative bounds.
18284      But this is unfortunately not always the case, as witnessed
18285      with GCC, for instance, where the ambiguous DW_FORM_dataN form
18286      is used instead.  To work around that ambiguity, we treat
18287      the bounds as signed, and thus sign-extend their values, when
18288      the base type is signed.  */
18289   negative_mask =
18290     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
18291   if (low.kind == PROP_CONST
18292       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
18293     low.data.const_val |= negative_mask;
18294   if (high.kind == PROP_CONST
18295       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
18296     high.data.const_val |= negative_mask;
18297
18298   range_type = create_range_type (NULL, orig_base_type, &low, &high);
18299
18300   if (high_bound_is_count)
18301     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
18302
18303   /* Ada expects an empty array on no boundary attributes.  */
18304   if (attr == NULL && cu->language != language_ada)
18305     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
18306
18307   name = dwarf2_name (die, cu);
18308   if (name)
18309     TYPE_NAME (range_type) = name;
18310
18311   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18312   if (attr)
18313     TYPE_LENGTH (range_type) = DW_UNSND (attr);
18314
18315   set_die_type (die, range_type, cu);
18316
18317   /* set_die_type should be already done.  */
18318   set_descriptive_type (range_type, die, cu);
18319
18320   return range_type;
18321 }
18322
18323 static struct type *
18324 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
18325 {
18326   struct type *type;
18327
18328   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
18329                     NULL);
18330   TYPE_NAME (type) = dwarf2_name (die, cu);
18331
18332   /* In Ada, an unspecified type is typically used when the description
18333      of the type is defered to a different unit.  When encountering
18334      such a type, we treat it as a stub, and try to resolve it later on,
18335      when needed.  */
18336   if (cu->language == language_ada)
18337     TYPE_STUB (type) = 1;
18338
18339   return set_die_type (die, type, cu);
18340 }
18341
18342 /* Read a single die and all its descendents.  Set the die's sibling
18343    field to NULL; set other fields in the die correctly, and set all
18344    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18345    location of the info_ptr after reading all of those dies.  PARENT
18346    is the parent of the die in question.  */
18347
18348 static struct die_info *
18349 read_die_and_children (const struct die_reader_specs *reader,
18350                        const gdb_byte *info_ptr,
18351                        const gdb_byte **new_info_ptr,
18352                        struct die_info *parent)
18353 {
18354   struct die_info *die;
18355   const gdb_byte *cur_ptr;
18356   int has_children;
18357
18358   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
18359   if (die == NULL)
18360     {
18361       *new_info_ptr = cur_ptr;
18362       return NULL;
18363     }
18364   store_in_ref_table (die, reader->cu);
18365
18366   if (has_children)
18367     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18368   else
18369     {
18370       die->child = NULL;
18371       *new_info_ptr = cur_ptr;
18372     }
18373
18374   die->sibling = NULL;
18375   die->parent = parent;
18376   return die;
18377 }
18378
18379 /* Read a die, all of its descendents, and all of its siblings; set
18380    all of the fields of all of the dies correctly.  Arguments are as
18381    in read_die_and_children.  */
18382
18383 static struct die_info *
18384 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18385                          const gdb_byte *info_ptr,
18386                          const gdb_byte **new_info_ptr,
18387                          struct die_info *parent)
18388 {
18389   struct die_info *first_die, *last_sibling;
18390   const gdb_byte *cur_ptr;
18391
18392   cur_ptr = info_ptr;
18393   first_die = last_sibling = NULL;
18394
18395   while (1)
18396     {
18397       struct die_info *die
18398         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18399
18400       if (die == NULL)
18401         {
18402           *new_info_ptr = cur_ptr;
18403           return first_die;
18404         }
18405
18406       if (!first_die)
18407         first_die = die;
18408       else
18409         last_sibling->sibling = die;
18410
18411       last_sibling = die;
18412     }
18413 }
18414
18415 /* Read a die, all of its descendents, and all of its siblings; set
18416    all of the fields of all of the dies correctly.  Arguments are as
18417    in read_die_and_children.
18418    This the main entry point for reading a DIE and all its children.  */
18419
18420 static struct die_info *
18421 read_die_and_siblings (const struct die_reader_specs *reader,
18422                        const gdb_byte *info_ptr,
18423                        const gdb_byte **new_info_ptr,
18424                        struct die_info *parent)
18425 {
18426   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18427                                                   new_info_ptr, parent);
18428
18429   if (dwarf_die_debug)
18430     {
18431       fprintf_unfiltered (gdb_stdlog,
18432                           "Read die from %s@0x%x of %s:\n",
18433                           get_section_name (reader->die_section),
18434                           (unsigned) (info_ptr - reader->die_section->buffer),
18435                           bfd_get_filename (reader->abfd));
18436       dump_die (die, dwarf_die_debug);
18437     }
18438
18439   return die;
18440 }
18441
18442 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18443    attributes.
18444    The caller is responsible for filling in the extra attributes
18445    and updating (*DIEP)->num_attrs.
18446    Set DIEP to point to a newly allocated die with its information,
18447    except for its child, sibling, and parent fields.
18448    Set HAS_CHILDREN to tell whether the die has children or not.  */
18449
18450 static const gdb_byte *
18451 read_full_die_1 (const struct die_reader_specs *reader,
18452                  struct die_info **diep, const gdb_byte *info_ptr,
18453                  int *has_children, int num_extra_attrs)
18454 {
18455   unsigned int abbrev_number, bytes_read, i;
18456   struct abbrev_info *abbrev;
18457   struct die_info *die;
18458   struct dwarf2_cu *cu = reader->cu;
18459   bfd *abfd = reader->abfd;
18460
18461   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18462   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18463   info_ptr += bytes_read;
18464   if (!abbrev_number)
18465     {
18466       *diep = NULL;
18467       *has_children = 0;
18468       return info_ptr;
18469     }
18470
18471   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18472   if (!abbrev)
18473     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18474            abbrev_number,
18475            bfd_get_filename (abfd));
18476
18477   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18478   die->sect_off = sect_off;
18479   die->tag = abbrev->tag;
18480   die->abbrev = abbrev_number;
18481
18482   /* Make the result usable.
18483      The caller needs to update num_attrs after adding the extra
18484      attributes.  */
18485   die->num_attrs = abbrev->num_attrs;
18486
18487   for (i = 0; i < abbrev->num_attrs; ++i)
18488     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18489                                info_ptr);
18490
18491   *diep = die;
18492   *has_children = abbrev->has_children;
18493   return info_ptr;
18494 }
18495
18496 /* Read a die and all its attributes.
18497    Set DIEP to point to a newly allocated die with its information,
18498    except for its child, sibling, and parent fields.
18499    Set HAS_CHILDREN to tell whether the die has children or not.  */
18500
18501 static const gdb_byte *
18502 read_full_die (const struct die_reader_specs *reader,
18503                struct die_info **diep, const gdb_byte *info_ptr,
18504                int *has_children)
18505 {
18506   const gdb_byte *result;
18507
18508   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18509
18510   if (dwarf_die_debug)
18511     {
18512       fprintf_unfiltered (gdb_stdlog,
18513                           "Read die from %s@0x%x of %s:\n",
18514                           get_section_name (reader->die_section),
18515                           (unsigned) (info_ptr - reader->die_section->buffer),
18516                           bfd_get_filename (reader->abfd));
18517       dump_die (*diep, dwarf_die_debug);
18518     }
18519
18520   return result;
18521 }
18522 \f
18523 /* Abbreviation tables.
18524
18525    In DWARF version 2, the description of the debugging information is
18526    stored in a separate .debug_abbrev section.  Before we read any
18527    dies from a section we read in all abbreviations and install them
18528    in a hash table.  */
18529
18530 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18531
18532 struct abbrev_info *
18533 abbrev_table::alloc_abbrev ()
18534 {
18535   struct abbrev_info *abbrev;
18536
18537   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18538   memset (abbrev, 0, sizeof (struct abbrev_info));
18539
18540   return abbrev;
18541 }
18542
18543 /* Add an abbreviation to the table.  */
18544
18545 void
18546 abbrev_table::add_abbrev (unsigned int abbrev_number,
18547                           struct abbrev_info *abbrev)
18548 {
18549   unsigned int hash_number;
18550
18551   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18552   abbrev->next = m_abbrevs[hash_number];
18553   m_abbrevs[hash_number] = abbrev;
18554 }
18555
18556 /* Look up an abbrev in the table.
18557    Returns NULL if the abbrev is not found.  */
18558
18559 struct abbrev_info *
18560 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18561 {
18562   unsigned int hash_number;
18563   struct abbrev_info *abbrev;
18564
18565   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18566   abbrev = m_abbrevs[hash_number];
18567
18568   while (abbrev)
18569     {
18570       if (abbrev->number == abbrev_number)
18571         return abbrev;
18572       abbrev = abbrev->next;
18573     }
18574   return NULL;
18575 }
18576
18577 /* Read in an abbrev table.  */
18578
18579 static abbrev_table_up
18580 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18581                          struct dwarf2_section_info *section,
18582                          sect_offset sect_off)
18583 {
18584   struct objfile *objfile = dwarf2_per_objfile->objfile;
18585   bfd *abfd = get_section_bfd_owner (section);
18586   const gdb_byte *abbrev_ptr;
18587   struct abbrev_info *cur_abbrev;
18588   unsigned int abbrev_number, bytes_read, abbrev_name;
18589   unsigned int abbrev_form;
18590   struct attr_abbrev *cur_attrs;
18591   unsigned int allocated_attrs;
18592
18593   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18594
18595   dwarf2_read_section (objfile, section);
18596   abbrev_ptr = section->buffer + to_underlying (sect_off);
18597   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18598   abbrev_ptr += bytes_read;
18599
18600   allocated_attrs = ATTR_ALLOC_CHUNK;
18601   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18602
18603   /* Loop until we reach an abbrev number of 0.  */
18604   while (abbrev_number)
18605     {
18606       cur_abbrev = abbrev_table->alloc_abbrev ();
18607
18608       /* read in abbrev header */
18609       cur_abbrev->number = abbrev_number;
18610       cur_abbrev->tag
18611         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18612       abbrev_ptr += bytes_read;
18613       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18614       abbrev_ptr += 1;
18615
18616       /* now read in declarations */
18617       for (;;)
18618         {
18619           LONGEST implicit_const;
18620
18621           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18622           abbrev_ptr += bytes_read;
18623           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18624           abbrev_ptr += bytes_read;
18625           if (abbrev_form == DW_FORM_implicit_const)
18626             {
18627               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18628                                                    &bytes_read);
18629               abbrev_ptr += bytes_read;
18630             }
18631           else
18632             {
18633               /* Initialize it due to a false compiler warning.  */
18634               implicit_const = -1;
18635             }
18636
18637           if (abbrev_name == 0)
18638             break;
18639
18640           if (cur_abbrev->num_attrs == allocated_attrs)
18641             {
18642               allocated_attrs += ATTR_ALLOC_CHUNK;
18643               cur_attrs
18644                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18645             }
18646
18647           cur_attrs[cur_abbrev->num_attrs].name
18648             = (enum dwarf_attribute) abbrev_name;
18649           cur_attrs[cur_abbrev->num_attrs].form
18650             = (enum dwarf_form) abbrev_form;
18651           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18652           ++cur_abbrev->num_attrs;
18653         }
18654
18655       cur_abbrev->attrs =
18656         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18657                    cur_abbrev->num_attrs);
18658       memcpy (cur_abbrev->attrs, cur_attrs,
18659               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18660
18661       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18662
18663       /* Get next abbreviation.
18664          Under Irix6 the abbreviations for a compilation unit are not
18665          always properly terminated with an abbrev number of 0.
18666          Exit loop if we encounter an abbreviation which we have
18667          already read (which means we are about to read the abbreviations
18668          for the next compile unit) or if the end of the abbreviation
18669          table is reached.  */
18670       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18671         break;
18672       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18673       abbrev_ptr += bytes_read;
18674       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18675         break;
18676     }
18677
18678   xfree (cur_attrs);
18679   return abbrev_table;
18680 }
18681
18682 /* Returns nonzero if TAG represents a type that we might generate a partial
18683    symbol for.  */
18684
18685 static int
18686 is_type_tag_for_partial (int tag)
18687 {
18688   switch (tag)
18689     {
18690 #if 0
18691     /* Some types that would be reasonable to generate partial symbols for,
18692        that we don't at present.  */
18693     case DW_TAG_array_type:
18694     case DW_TAG_file_type:
18695     case DW_TAG_ptr_to_member_type:
18696     case DW_TAG_set_type:
18697     case DW_TAG_string_type:
18698     case DW_TAG_subroutine_type:
18699 #endif
18700     case DW_TAG_base_type:
18701     case DW_TAG_class_type:
18702     case DW_TAG_interface_type:
18703     case DW_TAG_enumeration_type:
18704     case DW_TAG_structure_type:
18705     case DW_TAG_subrange_type:
18706     case DW_TAG_typedef:
18707     case DW_TAG_union_type:
18708       return 1;
18709     default:
18710       return 0;
18711     }
18712 }
18713
18714 /* Load all DIEs that are interesting for partial symbols into memory.  */
18715
18716 static struct partial_die_info *
18717 load_partial_dies (const struct die_reader_specs *reader,
18718                    const gdb_byte *info_ptr, int building_psymtab)
18719 {
18720   struct dwarf2_cu *cu = reader->cu;
18721   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18722   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18723   unsigned int bytes_read;
18724   unsigned int load_all = 0;
18725   int nesting_level = 1;
18726
18727   parent_die = NULL;
18728   last_die = NULL;
18729
18730   gdb_assert (cu->per_cu != NULL);
18731   if (cu->per_cu->load_all_dies)
18732     load_all = 1;
18733
18734   cu->partial_dies
18735     = htab_create_alloc_ex (cu->header.length / 12,
18736                             partial_die_hash,
18737                             partial_die_eq,
18738                             NULL,
18739                             &cu->comp_unit_obstack,
18740                             hashtab_obstack_allocate,
18741                             dummy_obstack_deallocate);
18742
18743   while (1)
18744     {
18745       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18746
18747       /* A NULL abbrev means the end of a series of children.  */
18748       if (abbrev == NULL)
18749         {
18750           if (--nesting_level == 0)
18751             return first_die;
18752
18753           info_ptr += bytes_read;
18754           last_die = parent_die;
18755           parent_die = parent_die->die_parent;
18756           continue;
18757         }
18758
18759       /* Check for template arguments.  We never save these; if
18760          they're seen, we just mark the parent, and go on our way.  */
18761       if (parent_die != NULL
18762           && cu->language == language_cplus
18763           && (abbrev->tag == DW_TAG_template_type_param
18764               || abbrev->tag == DW_TAG_template_value_param))
18765         {
18766           parent_die->has_template_arguments = 1;
18767
18768           if (!load_all)
18769             {
18770               /* We don't need a partial DIE for the template argument.  */
18771               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18772               continue;
18773             }
18774         }
18775
18776       /* We only recurse into c++ subprograms looking for template arguments.
18777          Skip their other children.  */
18778       if (!load_all
18779           && cu->language == language_cplus
18780           && parent_die != NULL
18781           && parent_die->tag == DW_TAG_subprogram)
18782         {
18783           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18784           continue;
18785         }
18786
18787       /* Check whether this DIE is interesting enough to save.  Normally
18788          we would not be interested in members here, but there may be
18789          later variables referencing them via DW_AT_specification (for
18790          static members).  */
18791       if (!load_all
18792           && !is_type_tag_for_partial (abbrev->tag)
18793           && abbrev->tag != DW_TAG_constant
18794           && abbrev->tag != DW_TAG_enumerator
18795           && abbrev->tag != DW_TAG_subprogram
18796           && abbrev->tag != DW_TAG_inlined_subroutine
18797           && abbrev->tag != DW_TAG_lexical_block
18798           && abbrev->tag != DW_TAG_variable
18799           && abbrev->tag != DW_TAG_namespace
18800           && abbrev->tag != DW_TAG_module
18801           && abbrev->tag != DW_TAG_member
18802           && abbrev->tag != DW_TAG_imported_unit
18803           && abbrev->tag != DW_TAG_imported_declaration)
18804         {
18805           /* Otherwise we skip to the next sibling, if any.  */
18806           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18807           continue;
18808         }
18809
18810       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18811                                    abbrev);
18812
18813       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18814
18815       /* This two-pass algorithm for processing partial symbols has a
18816          high cost in cache pressure.  Thus, handle some simple cases
18817          here which cover the majority of C partial symbols.  DIEs
18818          which neither have specification tags in them, nor could have
18819          specification tags elsewhere pointing at them, can simply be
18820          processed and discarded.
18821
18822          This segment is also optional; scan_partial_symbols and
18823          add_partial_symbol will handle these DIEs if we chain
18824          them in normally.  When compilers which do not emit large
18825          quantities of duplicate debug information are more common,
18826          this code can probably be removed.  */
18827
18828       /* Any complete simple types at the top level (pretty much all
18829          of them, for a language without namespaces), can be processed
18830          directly.  */
18831       if (parent_die == NULL
18832           && pdi.has_specification == 0
18833           && pdi.is_declaration == 0
18834           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18835               || pdi.tag == DW_TAG_base_type
18836               || pdi.tag == DW_TAG_subrange_type))
18837         {
18838           if (building_psymtab && pdi.name != NULL)
18839             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18840                                  VAR_DOMAIN, LOC_TYPEDEF,
18841                                  &objfile->static_psymbols,
18842                                  0, cu->language, objfile);
18843           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18844           continue;
18845         }
18846
18847       /* The exception for DW_TAG_typedef with has_children above is
18848          a workaround of GCC PR debug/47510.  In the case of this complaint
18849          type_name_no_tag_or_error will error on such types later.
18850
18851          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18852          it could not find the child DIEs referenced later, this is checked
18853          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18854
18855       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18856         complaint (&symfile_complaints,
18857                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18858                      "- DIE at %s [in module %s]"),
18859                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18860
18861       /* If we're at the second level, and we're an enumerator, and
18862          our parent has no specification (meaning possibly lives in a
18863          namespace elsewhere), then we can add the partial symbol now
18864          instead of queueing it.  */
18865       if (pdi.tag == DW_TAG_enumerator
18866           && parent_die != NULL
18867           && parent_die->die_parent == NULL
18868           && parent_die->tag == DW_TAG_enumeration_type
18869           && parent_die->has_specification == 0)
18870         {
18871           if (pdi.name == NULL)
18872             complaint (&symfile_complaints,
18873                        _("malformed enumerator DIE ignored"));
18874           else if (building_psymtab)
18875             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18876                                  VAR_DOMAIN, LOC_CONST,
18877                                  cu->language == language_cplus
18878                                  ? &objfile->global_psymbols
18879                                  : &objfile->static_psymbols,
18880                                  0, cu->language, objfile);
18881
18882           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18883           continue;
18884         }
18885
18886       struct partial_die_info *part_die
18887         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18888
18889       /* We'll save this DIE so link it in.  */
18890       part_die->die_parent = parent_die;
18891       part_die->die_sibling = NULL;
18892       part_die->die_child = NULL;
18893
18894       if (last_die && last_die == parent_die)
18895         last_die->die_child = part_die;
18896       else if (last_die)
18897         last_die->die_sibling = part_die;
18898
18899       last_die = part_die;
18900
18901       if (first_die == NULL)
18902         first_die = part_die;
18903
18904       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18905          find interesting need to be in the hash table, because we
18906          also have the parent/sibling/child chains; only those that we
18907          might refer to by offset later during partial symbol reading.
18908
18909          For now this means things that might have be the target of a
18910          DW_AT_specification, DW_AT_abstract_origin, or
18911          DW_AT_extension.  DW_AT_extension will refer only to
18912          namespaces; DW_AT_abstract_origin refers to functions (and
18913          many things under the function DIE, but we do not recurse
18914          into function DIEs during partial symbol reading) and
18915          possibly variables as well; DW_AT_specification refers to
18916          declarations.  Declarations ought to have the DW_AT_declaration
18917          flag.  It happens that GCC forgets to put it in sometimes, but
18918          only for functions, not for types.
18919
18920          Adding more things than necessary to the hash table is harmless
18921          except for the performance cost.  Adding too few will result in
18922          wasted time in find_partial_die, when we reread the compilation
18923          unit with load_all_dies set.  */
18924
18925       if (load_all
18926           || abbrev->tag == DW_TAG_constant
18927           || abbrev->tag == DW_TAG_subprogram
18928           || abbrev->tag == DW_TAG_variable
18929           || abbrev->tag == DW_TAG_namespace
18930           || part_die->is_declaration)
18931         {
18932           void **slot;
18933
18934           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18935                                            to_underlying (part_die->sect_off),
18936                                            INSERT);
18937           *slot = part_die;
18938         }
18939
18940       /* For some DIEs we want to follow their children (if any).  For C
18941          we have no reason to follow the children of structures; for other
18942          languages we have to, so that we can get at method physnames
18943          to infer fully qualified class names, for DW_AT_specification,
18944          and for C++ template arguments.  For C++, we also look one level
18945          inside functions to find template arguments (if the name of the
18946          function does not already contain the template arguments).
18947
18948          For Ada, we need to scan the children of subprograms and lexical
18949          blocks as well because Ada allows the definition of nested
18950          entities that could be interesting for the debugger, such as
18951          nested subprograms for instance.  */
18952       if (last_die->has_children
18953           && (load_all
18954               || last_die->tag == DW_TAG_namespace
18955               || last_die->tag == DW_TAG_module
18956               || last_die->tag == DW_TAG_enumeration_type
18957               || (cu->language == language_cplus
18958                   && last_die->tag == DW_TAG_subprogram
18959                   && (last_die->name == NULL
18960                       || strchr (last_die->name, '<') == NULL))
18961               || (cu->language != language_c
18962                   && (last_die->tag == DW_TAG_class_type
18963                       || last_die->tag == DW_TAG_interface_type
18964                       || last_die->tag == DW_TAG_structure_type
18965                       || last_die->tag == DW_TAG_union_type))
18966               || (cu->language == language_ada
18967                   && (last_die->tag == DW_TAG_subprogram
18968                       || last_die->tag == DW_TAG_lexical_block))))
18969         {
18970           nesting_level++;
18971           parent_die = last_die;
18972           continue;
18973         }
18974
18975       /* Otherwise we skip to the next sibling, if any.  */
18976       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18977
18978       /* Back to the top, do it again.  */
18979     }
18980 }
18981
18982 partial_die_info::partial_die_info (sect_offset sect_off_,
18983                                     struct abbrev_info *abbrev)
18984   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18985 {
18986 }
18987
18988 /* Read a minimal amount of information into the minimal die structure.
18989    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18990
18991 const gdb_byte *
18992 partial_die_info::read (const struct die_reader_specs *reader,
18993                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18994 {
18995   struct dwarf2_cu *cu = reader->cu;
18996   struct dwarf2_per_objfile *dwarf2_per_objfile
18997     = cu->per_cu->dwarf2_per_objfile;
18998   unsigned int i;
18999   int has_low_pc_attr = 0;
19000   int has_high_pc_attr = 0;
19001   int high_pc_relative = 0;
19002
19003   for (i = 0; i < abbrev.num_attrs; ++i)
19004     {
19005       struct attribute attr;
19006
19007       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
19008
19009       /* Store the data if it is of an attribute we want to keep in a
19010          partial symbol table.  */
19011       switch (attr.name)
19012         {
19013         case DW_AT_name:
19014           switch (tag)
19015             {
19016             case DW_TAG_compile_unit:
19017             case DW_TAG_partial_unit:
19018             case DW_TAG_type_unit:
19019               /* Compilation units have a DW_AT_name that is a filename, not
19020                  a source language identifier.  */
19021             case DW_TAG_enumeration_type:
19022             case DW_TAG_enumerator:
19023               /* These tags always have simple identifiers already; no need
19024                  to canonicalize them.  */
19025               name = DW_STRING (&attr);
19026               break;
19027             default:
19028               {
19029                 struct objfile *objfile = dwarf2_per_objfile->objfile;
19030
19031                 name
19032                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
19033                                               &objfile->per_bfd->storage_obstack);
19034               }
19035               break;
19036             }
19037           break;
19038         case DW_AT_linkage_name:
19039         case DW_AT_MIPS_linkage_name:
19040           /* Note that both forms of linkage name might appear.  We
19041              assume they will be the same, and we only store the last
19042              one we see.  */
19043           if (cu->language == language_ada)
19044             name = DW_STRING (&attr);
19045           linkage_name = DW_STRING (&attr);
19046           break;
19047         case DW_AT_low_pc:
19048           has_low_pc_attr = 1;
19049           lowpc = attr_value_as_address (&attr);
19050           break;
19051         case DW_AT_high_pc:
19052           has_high_pc_attr = 1;
19053           highpc = attr_value_as_address (&attr);
19054           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
19055                 high_pc_relative = 1;
19056           break;
19057         case DW_AT_location:
19058           /* Support the .debug_loc offsets.  */
19059           if (attr_form_is_block (&attr))
19060             {
19061                d.locdesc = DW_BLOCK (&attr);
19062             }
19063           else if (attr_form_is_section_offset (&attr))
19064             {
19065               dwarf2_complex_location_expr_complaint ();
19066             }
19067           else
19068             {
19069               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
19070                                                      "partial symbol information");
19071             }
19072           break;
19073         case DW_AT_external:
19074           is_external = DW_UNSND (&attr);
19075           break;
19076         case DW_AT_declaration:
19077           is_declaration = DW_UNSND (&attr);
19078           break;
19079         case DW_AT_type:
19080           has_type = 1;
19081           break;
19082         case DW_AT_abstract_origin:
19083         case DW_AT_specification:
19084         case DW_AT_extension:
19085           has_specification = 1;
19086           spec_offset = dwarf2_get_ref_die_offset (&attr);
19087           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19088                                    || cu->per_cu->is_dwz);
19089           break;
19090         case DW_AT_sibling:
19091           /* Ignore absolute siblings, they might point outside of
19092              the current compile unit.  */
19093           if (attr.form == DW_FORM_ref_addr)
19094             complaint (&symfile_complaints,
19095                        _("ignoring absolute DW_AT_sibling"));
19096           else
19097             {
19098               const gdb_byte *buffer = reader->buffer;
19099               sect_offset off = dwarf2_get_ref_die_offset (&attr);
19100               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
19101
19102               if (sibling_ptr < info_ptr)
19103                 complaint (&symfile_complaints,
19104                            _("DW_AT_sibling points backwards"));
19105               else if (sibling_ptr > reader->buffer_end)
19106                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
19107               else
19108                 sibling = sibling_ptr;
19109             }
19110           break;
19111         case DW_AT_byte_size:
19112           has_byte_size = 1;
19113           break;
19114         case DW_AT_const_value:
19115           has_const_value = 1;
19116           break;
19117         case DW_AT_calling_convention:
19118           /* DWARF doesn't provide a way to identify a program's source-level
19119              entry point.  DW_AT_calling_convention attributes are only meant
19120              to describe functions' calling conventions.
19121
19122              However, because it's a necessary piece of information in
19123              Fortran, and before DWARF 4 DW_CC_program was the only
19124              piece of debugging information whose definition refers to
19125              a 'main program' at all, several compilers marked Fortran
19126              main programs with DW_CC_program --- even when those
19127              functions use the standard calling conventions.
19128
19129              Although DWARF now specifies a way to provide this
19130              information, we support this practice for backward
19131              compatibility.  */
19132           if (DW_UNSND (&attr) == DW_CC_program
19133               && cu->language == language_fortran)
19134             main_subprogram = 1;
19135           break;
19136         case DW_AT_inline:
19137           if (DW_UNSND (&attr) == DW_INL_inlined
19138               || DW_UNSND (&attr) == DW_INL_declared_inlined)
19139             may_be_inlined = 1;
19140           break;
19141
19142         case DW_AT_import:
19143           if (tag == DW_TAG_imported_unit)
19144             {
19145               d.sect_off = dwarf2_get_ref_die_offset (&attr);
19146               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19147                                   || cu->per_cu->is_dwz);
19148             }
19149           break;
19150
19151         case DW_AT_main_subprogram:
19152           main_subprogram = DW_UNSND (&attr);
19153           break;
19154
19155         default:
19156           break;
19157         }
19158     }
19159
19160   if (high_pc_relative)
19161     highpc += lowpc;
19162
19163   if (has_low_pc_attr && has_high_pc_attr)
19164     {
19165       /* When using the GNU linker, .gnu.linkonce. sections are used to
19166          eliminate duplicate copies of functions and vtables and such.
19167          The linker will arbitrarily choose one and discard the others.
19168          The AT_*_pc values for such functions refer to local labels in
19169          these sections.  If the section from that file was discarded, the
19170          labels are not in the output, so the relocs get a value of 0.
19171          If this is a discarded function, mark the pc bounds as invalid,
19172          so that GDB will ignore it.  */
19173       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
19174         {
19175           struct objfile *objfile = dwarf2_per_objfile->objfile;
19176           struct gdbarch *gdbarch = get_objfile_arch (objfile);
19177
19178           complaint (&symfile_complaints,
19179                      _("DW_AT_low_pc %s is zero "
19180                        "for DIE at %s [in module %s]"),
19181                      paddress (gdbarch, lowpc),
19182                      sect_offset_str (sect_off),
19183                      objfile_name (objfile));
19184         }
19185       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
19186       else if (lowpc >= highpc)
19187         {
19188           struct objfile *objfile = dwarf2_per_objfile->objfile;
19189           struct gdbarch *gdbarch = get_objfile_arch (objfile);
19190
19191           complaint (&symfile_complaints,
19192                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
19193                        "for DIE at %s [in module %s]"),
19194                      paddress (gdbarch, lowpc),
19195                      paddress (gdbarch, highpc),
19196                      sect_offset_str (sect_off),
19197                      objfile_name (objfile));
19198         }
19199       else
19200         has_pc_info = 1;
19201     }
19202
19203   return info_ptr;
19204 }
19205
19206 /* Find a cached partial DIE at OFFSET in CU.  */
19207
19208 struct partial_die_info *
19209 dwarf2_cu::find_partial_die (sect_offset sect_off)
19210 {
19211   struct partial_die_info *lookup_die = NULL;
19212   struct partial_die_info part_die (sect_off);
19213
19214   lookup_die = ((struct partial_die_info *)
19215                 htab_find_with_hash (partial_dies, &part_die,
19216                                      to_underlying (sect_off)));
19217
19218   return lookup_die;
19219 }
19220
19221 /* Find a partial DIE at OFFSET, which may or may not be in CU,
19222    except in the case of .debug_types DIEs which do not reference
19223    outside their CU (they do however referencing other types via
19224    DW_FORM_ref_sig8).  */
19225
19226 static struct partial_die_info *
19227 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
19228 {
19229   struct dwarf2_per_objfile *dwarf2_per_objfile
19230     = cu->per_cu->dwarf2_per_objfile;
19231   struct objfile *objfile = dwarf2_per_objfile->objfile;
19232   struct dwarf2_per_cu_data *per_cu = NULL;
19233   struct partial_die_info *pd = NULL;
19234
19235   if (offset_in_dwz == cu->per_cu->is_dwz
19236       && offset_in_cu_p (&cu->header, sect_off))
19237     {
19238       pd = cu->find_partial_die (sect_off);
19239       if (pd != NULL)
19240         return pd;
19241       /* We missed recording what we needed.
19242          Load all dies and try again.  */
19243       per_cu = cu->per_cu;
19244     }
19245   else
19246     {
19247       /* TUs don't reference other CUs/TUs (except via type signatures).  */
19248       if (cu->per_cu->is_debug_types)
19249         {
19250           error (_("Dwarf Error: Type Unit at offset %s contains"
19251                    " external reference to offset %s [in module %s].\n"),
19252                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
19253                  bfd_get_filename (objfile->obfd));
19254         }
19255       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
19256                                                  dwarf2_per_objfile);
19257
19258       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
19259         load_partial_comp_unit (per_cu);
19260
19261       per_cu->cu->last_used = 0;
19262       pd = per_cu->cu->find_partial_die (sect_off);
19263     }
19264
19265   /* If we didn't find it, and not all dies have been loaded,
19266      load them all and try again.  */
19267
19268   if (pd == NULL && per_cu->load_all_dies == 0)
19269     {
19270       per_cu->load_all_dies = 1;
19271
19272       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
19273          THIS_CU->cu may already be in use.  So we can't just free it and
19274          replace its DIEs with the ones we read in.  Instead, we leave those
19275          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
19276          and clobber THIS_CU->cu->partial_dies with the hash table for the new
19277          set.  */
19278       load_partial_comp_unit (per_cu);
19279
19280       pd = per_cu->cu->find_partial_die (sect_off);
19281     }
19282
19283   if (pd == NULL)
19284     internal_error (__FILE__, __LINE__,
19285                     _("could not find partial DIE %s "
19286                       "in cache [from module %s]\n"),
19287                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
19288   return pd;
19289 }
19290
19291 /* See if we can figure out if the class lives in a namespace.  We do
19292    this by looking for a member function; its demangled name will
19293    contain namespace info, if there is any.  */
19294
19295 static void
19296 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
19297                                   struct dwarf2_cu *cu)
19298 {
19299   /* NOTE: carlton/2003-10-07: Getting the info this way changes
19300      what template types look like, because the demangler
19301      frequently doesn't give the same name as the debug info.  We
19302      could fix this by only using the demangled name to get the
19303      prefix (but see comment in read_structure_type).  */
19304
19305   struct partial_die_info *real_pdi;
19306   struct partial_die_info *child_pdi;
19307
19308   /* If this DIE (this DIE's specification, if any) has a parent, then
19309      we should not do this.  We'll prepend the parent's fully qualified
19310      name when we create the partial symbol.  */
19311
19312   real_pdi = struct_pdi;
19313   while (real_pdi->has_specification)
19314     real_pdi = find_partial_die (real_pdi->spec_offset,
19315                                  real_pdi->spec_is_dwz, cu);
19316
19317   if (real_pdi->die_parent != NULL)
19318     return;
19319
19320   for (child_pdi = struct_pdi->die_child;
19321        child_pdi != NULL;
19322        child_pdi = child_pdi->die_sibling)
19323     {
19324       if (child_pdi->tag == DW_TAG_subprogram
19325           && child_pdi->linkage_name != NULL)
19326         {
19327           char *actual_class_name
19328             = language_class_name_from_physname (cu->language_defn,
19329                                                  child_pdi->linkage_name);
19330           if (actual_class_name != NULL)
19331             {
19332               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19333               struct_pdi->name
19334                 = ((const char *)
19335                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
19336                                   actual_class_name,
19337                                   strlen (actual_class_name)));
19338               xfree (actual_class_name);
19339             }
19340           break;
19341         }
19342     }
19343 }
19344
19345 void
19346 partial_die_info::fixup (struct dwarf2_cu *cu)
19347 {
19348   /* Once we've fixed up a die, there's no point in doing so again.
19349      This also avoids a memory leak if we were to call
19350      guess_partial_die_structure_name multiple times.  */
19351   if (fixup_called)
19352     return;
19353
19354   /* If we found a reference attribute and the DIE has no name, try
19355      to find a name in the referred to DIE.  */
19356
19357   if (name == NULL && has_specification)
19358     {
19359       struct partial_die_info *spec_die;
19360
19361       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
19362
19363       spec_die->fixup (cu);
19364
19365       if (spec_die->name)
19366         {
19367           name = spec_die->name;
19368
19369           /* Copy DW_AT_external attribute if it is set.  */
19370           if (spec_die->is_external)
19371             is_external = spec_die->is_external;
19372         }
19373     }
19374
19375   /* Set default names for some unnamed DIEs.  */
19376
19377   if (name == NULL && tag == DW_TAG_namespace)
19378     name = CP_ANONYMOUS_NAMESPACE_STR;
19379
19380   /* If there is no parent die to provide a namespace, and there are
19381      children, see if we can determine the namespace from their linkage
19382      name.  */
19383   if (cu->language == language_cplus
19384       && !VEC_empty (dwarf2_section_info_def,
19385                      cu->per_cu->dwarf2_per_objfile->types)
19386       && die_parent == NULL
19387       && has_children
19388       && (tag == DW_TAG_class_type
19389           || tag == DW_TAG_structure_type
19390           || tag == DW_TAG_union_type))
19391     guess_partial_die_structure_name (this, cu);
19392
19393   /* GCC might emit a nameless struct or union that has a linkage
19394      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19395   if (name == NULL
19396       && (tag == DW_TAG_class_type
19397           || tag == DW_TAG_interface_type
19398           || tag == DW_TAG_structure_type
19399           || tag == DW_TAG_union_type)
19400       && linkage_name != NULL)
19401     {
19402       char *demangled;
19403
19404       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
19405       if (demangled)
19406         {
19407           const char *base;
19408
19409           /* Strip any leading namespaces/classes, keep only the base name.
19410              DW_AT_name for named DIEs does not contain the prefixes.  */
19411           base = strrchr (demangled, ':');
19412           if (base && base > demangled && base[-1] == ':')
19413             base++;
19414           else
19415             base = demangled;
19416
19417           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19418           name
19419             = ((const char *)
19420                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19421                               base, strlen (base)));
19422           xfree (demangled);
19423         }
19424     }
19425
19426   fixup_called = 1;
19427 }
19428
19429 /* Read an attribute value described by an attribute form.  */
19430
19431 static const gdb_byte *
19432 read_attribute_value (const struct die_reader_specs *reader,
19433                       struct attribute *attr, unsigned form,
19434                       LONGEST implicit_const, const gdb_byte *info_ptr)
19435 {
19436   struct dwarf2_cu *cu = reader->cu;
19437   struct dwarf2_per_objfile *dwarf2_per_objfile
19438     = cu->per_cu->dwarf2_per_objfile;
19439   struct objfile *objfile = dwarf2_per_objfile->objfile;
19440   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19441   bfd *abfd = reader->abfd;
19442   struct comp_unit_head *cu_header = &cu->header;
19443   unsigned int bytes_read;
19444   struct dwarf_block *blk;
19445
19446   attr->form = (enum dwarf_form) form;
19447   switch (form)
19448     {
19449     case DW_FORM_ref_addr:
19450       if (cu->header.version == 2)
19451         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19452       else
19453         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19454                                        &cu->header, &bytes_read);
19455       info_ptr += bytes_read;
19456       break;
19457     case DW_FORM_GNU_ref_alt:
19458       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19459       info_ptr += bytes_read;
19460       break;
19461     case DW_FORM_addr:
19462       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19463       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19464       info_ptr += bytes_read;
19465       break;
19466     case DW_FORM_block2:
19467       blk = dwarf_alloc_block (cu);
19468       blk->size = read_2_bytes (abfd, info_ptr);
19469       info_ptr += 2;
19470       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19471       info_ptr += blk->size;
19472       DW_BLOCK (attr) = blk;
19473       break;
19474     case DW_FORM_block4:
19475       blk = dwarf_alloc_block (cu);
19476       blk->size = read_4_bytes (abfd, info_ptr);
19477       info_ptr += 4;
19478       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19479       info_ptr += blk->size;
19480       DW_BLOCK (attr) = blk;
19481       break;
19482     case DW_FORM_data2:
19483       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19484       info_ptr += 2;
19485       break;
19486     case DW_FORM_data4:
19487       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19488       info_ptr += 4;
19489       break;
19490     case DW_FORM_data8:
19491       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19492       info_ptr += 8;
19493       break;
19494     case DW_FORM_data16:
19495       blk = dwarf_alloc_block (cu);
19496       blk->size = 16;
19497       blk->data = read_n_bytes (abfd, info_ptr, 16);
19498       info_ptr += 16;
19499       DW_BLOCK (attr) = blk;
19500       break;
19501     case DW_FORM_sec_offset:
19502       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19503       info_ptr += bytes_read;
19504       break;
19505     case DW_FORM_string:
19506       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19507       DW_STRING_IS_CANONICAL (attr) = 0;
19508       info_ptr += bytes_read;
19509       break;
19510     case DW_FORM_strp:
19511       if (!cu->per_cu->is_dwz)
19512         {
19513           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19514                                                    abfd, info_ptr, cu_header,
19515                                                    &bytes_read);
19516           DW_STRING_IS_CANONICAL (attr) = 0;
19517           info_ptr += bytes_read;
19518           break;
19519         }
19520       /* FALLTHROUGH */
19521     case DW_FORM_line_strp:
19522       if (!cu->per_cu->is_dwz)
19523         {
19524           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19525                                                         abfd, info_ptr,
19526                                                         cu_header, &bytes_read);
19527           DW_STRING_IS_CANONICAL (attr) = 0;
19528           info_ptr += bytes_read;
19529           break;
19530         }
19531       /* FALLTHROUGH */
19532     case DW_FORM_GNU_strp_alt:
19533       {
19534         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19535         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19536                                           &bytes_read);
19537
19538         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19539                                                           dwz, str_offset);
19540         DW_STRING_IS_CANONICAL (attr) = 0;
19541         info_ptr += bytes_read;
19542       }
19543       break;
19544     case DW_FORM_exprloc:
19545     case DW_FORM_block:
19546       blk = dwarf_alloc_block (cu);
19547       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19548       info_ptr += bytes_read;
19549       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19550       info_ptr += blk->size;
19551       DW_BLOCK (attr) = blk;
19552       break;
19553     case DW_FORM_block1:
19554       blk = dwarf_alloc_block (cu);
19555       blk->size = read_1_byte (abfd, info_ptr);
19556       info_ptr += 1;
19557       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19558       info_ptr += blk->size;
19559       DW_BLOCK (attr) = blk;
19560       break;
19561     case DW_FORM_data1:
19562       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19563       info_ptr += 1;
19564       break;
19565     case DW_FORM_flag:
19566       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19567       info_ptr += 1;
19568       break;
19569     case DW_FORM_flag_present:
19570       DW_UNSND (attr) = 1;
19571       break;
19572     case DW_FORM_sdata:
19573       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19574       info_ptr += bytes_read;
19575       break;
19576     case DW_FORM_udata:
19577       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19578       info_ptr += bytes_read;
19579       break;
19580     case DW_FORM_ref1:
19581       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19582                          + read_1_byte (abfd, info_ptr));
19583       info_ptr += 1;
19584       break;
19585     case DW_FORM_ref2:
19586       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19587                          + read_2_bytes (abfd, info_ptr));
19588       info_ptr += 2;
19589       break;
19590     case DW_FORM_ref4:
19591       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19592                          + read_4_bytes (abfd, info_ptr));
19593       info_ptr += 4;
19594       break;
19595     case DW_FORM_ref8:
19596       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19597                          + read_8_bytes (abfd, info_ptr));
19598       info_ptr += 8;
19599       break;
19600     case DW_FORM_ref_sig8:
19601       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19602       info_ptr += 8;
19603       break;
19604     case DW_FORM_ref_udata:
19605       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19606                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19607       info_ptr += bytes_read;
19608       break;
19609     case DW_FORM_indirect:
19610       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19611       info_ptr += bytes_read;
19612       if (form == DW_FORM_implicit_const)
19613         {
19614           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19615           info_ptr += bytes_read;
19616         }
19617       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19618                                        info_ptr);
19619       break;
19620     case DW_FORM_implicit_const:
19621       DW_SND (attr) = implicit_const;
19622       break;
19623     case DW_FORM_GNU_addr_index:
19624       if (reader->dwo_file == NULL)
19625         {
19626           /* For now flag a hard error.
19627              Later we can turn this into a complaint.  */
19628           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19629                  dwarf_form_name (form),
19630                  bfd_get_filename (abfd));
19631         }
19632       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19633       info_ptr += bytes_read;
19634       break;
19635     case DW_FORM_GNU_str_index:
19636       if (reader->dwo_file == NULL)
19637         {
19638           /* For now flag a hard error.
19639              Later we can turn this into a complaint if warranted.  */
19640           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19641                  dwarf_form_name (form),
19642                  bfd_get_filename (abfd));
19643         }
19644       {
19645         ULONGEST str_index =
19646           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19647
19648         DW_STRING (attr) = read_str_index (reader, str_index);
19649         DW_STRING_IS_CANONICAL (attr) = 0;
19650         info_ptr += bytes_read;
19651       }
19652       break;
19653     default:
19654       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19655              dwarf_form_name (form),
19656              bfd_get_filename (abfd));
19657     }
19658
19659   /* Super hack.  */
19660   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19661     attr->form = DW_FORM_GNU_ref_alt;
19662
19663   /* We have seen instances where the compiler tried to emit a byte
19664      size attribute of -1 which ended up being encoded as an unsigned
19665      0xffffffff.  Although 0xffffffff is technically a valid size value,
19666      an object of this size seems pretty unlikely so we can relatively
19667      safely treat these cases as if the size attribute was invalid and
19668      treat them as zero by default.  */
19669   if (attr->name == DW_AT_byte_size
19670       && form == DW_FORM_data4
19671       && DW_UNSND (attr) >= 0xffffffff)
19672     {
19673       complaint
19674         (&symfile_complaints,
19675          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19676          hex_string (DW_UNSND (attr)));
19677       DW_UNSND (attr) = 0;
19678     }
19679
19680   return info_ptr;
19681 }
19682
19683 /* Read an attribute described by an abbreviated attribute.  */
19684
19685 static const gdb_byte *
19686 read_attribute (const struct die_reader_specs *reader,
19687                 struct attribute *attr, struct attr_abbrev *abbrev,
19688                 const gdb_byte *info_ptr)
19689 {
19690   attr->name = abbrev->name;
19691   return read_attribute_value (reader, attr, abbrev->form,
19692                                abbrev->implicit_const, info_ptr);
19693 }
19694
19695 /* Read dwarf information from a buffer.  */
19696
19697 static unsigned int
19698 read_1_byte (bfd *abfd, const gdb_byte *buf)
19699 {
19700   return bfd_get_8 (abfd, buf);
19701 }
19702
19703 static int
19704 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19705 {
19706   return bfd_get_signed_8 (abfd, buf);
19707 }
19708
19709 static unsigned int
19710 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19711 {
19712   return bfd_get_16 (abfd, buf);
19713 }
19714
19715 static int
19716 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19717 {
19718   return bfd_get_signed_16 (abfd, buf);
19719 }
19720
19721 static unsigned int
19722 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19723 {
19724   return bfd_get_32 (abfd, buf);
19725 }
19726
19727 static int
19728 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19729 {
19730   return bfd_get_signed_32 (abfd, buf);
19731 }
19732
19733 static ULONGEST
19734 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19735 {
19736   return bfd_get_64 (abfd, buf);
19737 }
19738
19739 static CORE_ADDR
19740 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19741               unsigned int *bytes_read)
19742 {
19743   struct comp_unit_head *cu_header = &cu->header;
19744   CORE_ADDR retval = 0;
19745
19746   if (cu_header->signed_addr_p)
19747     {
19748       switch (cu_header->addr_size)
19749         {
19750         case 2:
19751           retval = bfd_get_signed_16 (abfd, buf);
19752           break;
19753         case 4:
19754           retval = bfd_get_signed_32 (abfd, buf);
19755           break;
19756         case 8:
19757           retval = bfd_get_signed_64 (abfd, buf);
19758           break;
19759         default:
19760           internal_error (__FILE__, __LINE__,
19761                           _("read_address: bad switch, signed [in module %s]"),
19762                           bfd_get_filename (abfd));
19763         }
19764     }
19765   else
19766     {
19767       switch (cu_header->addr_size)
19768         {
19769         case 2:
19770           retval = bfd_get_16 (abfd, buf);
19771           break;
19772         case 4:
19773           retval = bfd_get_32 (abfd, buf);
19774           break;
19775         case 8:
19776           retval = bfd_get_64 (abfd, buf);
19777           break;
19778         default:
19779           internal_error (__FILE__, __LINE__,
19780                           _("read_address: bad switch, "
19781                             "unsigned [in module %s]"),
19782                           bfd_get_filename (abfd));
19783         }
19784     }
19785
19786   *bytes_read = cu_header->addr_size;
19787   return retval;
19788 }
19789
19790 /* Read the initial length from a section.  The (draft) DWARF 3
19791    specification allows the initial length to take up either 4 bytes
19792    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19793    bytes describe the length and all offsets will be 8 bytes in length
19794    instead of 4.
19795
19796    An older, non-standard 64-bit format is also handled by this
19797    function.  The older format in question stores the initial length
19798    as an 8-byte quantity without an escape value.  Lengths greater
19799    than 2^32 aren't very common which means that the initial 4 bytes
19800    is almost always zero.  Since a length value of zero doesn't make
19801    sense for the 32-bit format, this initial zero can be considered to
19802    be an escape value which indicates the presence of the older 64-bit
19803    format.  As written, the code can't detect (old format) lengths
19804    greater than 4GB.  If it becomes necessary to handle lengths
19805    somewhat larger than 4GB, we could allow other small values (such
19806    as the non-sensical values of 1, 2, and 3) to also be used as
19807    escape values indicating the presence of the old format.
19808
19809    The value returned via bytes_read should be used to increment the
19810    relevant pointer after calling read_initial_length().
19811
19812    [ Note:  read_initial_length() and read_offset() are based on the
19813      document entitled "DWARF Debugging Information Format", revision
19814      3, draft 8, dated November 19, 2001.  This document was obtained
19815      from:
19816
19817         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19818
19819      This document is only a draft and is subject to change.  (So beware.)
19820
19821      Details regarding the older, non-standard 64-bit format were
19822      determined empirically by examining 64-bit ELF files produced by
19823      the SGI toolchain on an IRIX 6.5 machine.
19824
19825      - Kevin, July 16, 2002
19826    ] */
19827
19828 static LONGEST
19829 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19830 {
19831   LONGEST length = bfd_get_32 (abfd, buf);
19832
19833   if (length == 0xffffffff)
19834     {
19835       length = bfd_get_64 (abfd, buf + 4);
19836       *bytes_read = 12;
19837     }
19838   else if (length == 0)
19839     {
19840       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19841       length = bfd_get_64 (abfd, buf);
19842       *bytes_read = 8;
19843     }
19844   else
19845     {
19846       *bytes_read = 4;
19847     }
19848
19849   return length;
19850 }
19851
19852 /* Cover function for read_initial_length.
19853    Returns the length of the object at BUF, and stores the size of the
19854    initial length in *BYTES_READ and stores the size that offsets will be in
19855    *OFFSET_SIZE.
19856    If the initial length size is not equivalent to that specified in
19857    CU_HEADER then issue a complaint.
19858    This is useful when reading non-comp-unit headers.  */
19859
19860 static LONGEST
19861 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19862                                         const struct comp_unit_head *cu_header,
19863                                         unsigned int *bytes_read,
19864                                         unsigned int *offset_size)
19865 {
19866   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19867
19868   gdb_assert (cu_header->initial_length_size == 4
19869               || cu_header->initial_length_size == 8
19870               || cu_header->initial_length_size == 12);
19871
19872   if (cu_header->initial_length_size != *bytes_read)
19873     complaint (&symfile_complaints,
19874                _("intermixed 32-bit and 64-bit DWARF sections"));
19875
19876   *offset_size = (*bytes_read == 4) ? 4 : 8;
19877   return length;
19878 }
19879
19880 /* Read an offset from the data stream.  The size of the offset is
19881    given by cu_header->offset_size.  */
19882
19883 static LONGEST
19884 read_offset (bfd *abfd, const gdb_byte *buf,
19885              const struct comp_unit_head *cu_header,
19886              unsigned int *bytes_read)
19887 {
19888   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19889
19890   *bytes_read = cu_header->offset_size;
19891   return offset;
19892 }
19893
19894 /* Read an offset from the data stream.  */
19895
19896 static LONGEST
19897 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19898 {
19899   LONGEST retval = 0;
19900
19901   switch (offset_size)
19902     {
19903     case 4:
19904       retval = bfd_get_32 (abfd, buf);
19905       break;
19906     case 8:
19907       retval = bfd_get_64 (abfd, buf);
19908       break;
19909     default:
19910       internal_error (__FILE__, __LINE__,
19911                       _("read_offset_1: bad switch [in module %s]"),
19912                       bfd_get_filename (abfd));
19913     }
19914
19915   return retval;
19916 }
19917
19918 static const gdb_byte *
19919 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19920 {
19921   /* If the size of a host char is 8 bits, we can return a pointer
19922      to the buffer, otherwise we have to copy the data to a buffer
19923      allocated on the temporary obstack.  */
19924   gdb_assert (HOST_CHAR_BIT == 8);
19925   return buf;
19926 }
19927
19928 static const char *
19929 read_direct_string (bfd *abfd, const gdb_byte *buf,
19930                     unsigned int *bytes_read_ptr)
19931 {
19932   /* If the size of a host char is 8 bits, we can return a pointer
19933      to the string, otherwise we have to copy the string to a buffer
19934      allocated on the temporary obstack.  */
19935   gdb_assert (HOST_CHAR_BIT == 8);
19936   if (*buf == '\0')
19937     {
19938       *bytes_read_ptr = 1;
19939       return NULL;
19940     }
19941   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19942   return (const char *) buf;
19943 }
19944
19945 /* Return pointer to string at section SECT offset STR_OFFSET with error
19946    reporting strings FORM_NAME and SECT_NAME.  */
19947
19948 static const char *
19949 read_indirect_string_at_offset_from (struct objfile *objfile,
19950                                      bfd *abfd, LONGEST str_offset,
19951                                      struct dwarf2_section_info *sect,
19952                                      const char *form_name,
19953                                      const char *sect_name)
19954 {
19955   dwarf2_read_section (objfile, sect);
19956   if (sect->buffer == NULL)
19957     error (_("%s used without %s section [in module %s]"),
19958            form_name, sect_name, bfd_get_filename (abfd));
19959   if (str_offset >= sect->size)
19960     error (_("%s pointing outside of %s section [in module %s]"),
19961            form_name, sect_name, bfd_get_filename (abfd));
19962   gdb_assert (HOST_CHAR_BIT == 8);
19963   if (sect->buffer[str_offset] == '\0')
19964     return NULL;
19965   return (const char *) (sect->buffer + str_offset);
19966 }
19967
19968 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19969
19970 static const char *
19971 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19972                                 bfd *abfd, LONGEST str_offset)
19973 {
19974   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19975                                               abfd, str_offset,
19976                                               &dwarf2_per_objfile->str,
19977                                               "DW_FORM_strp", ".debug_str");
19978 }
19979
19980 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19981
19982 static const char *
19983 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19984                                      bfd *abfd, LONGEST str_offset)
19985 {
19986   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19987                                               abfd, str_offset,
19988                                               &dwarf2_per_objfile->line_str,
19989                                               "DW_FORM_line_strp",
19990                                               ".debug_line_str");
19991 }
19992
19993 /* Read a string at offset STR_OFFSET in the .debug_str section from
19994    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19995    the string consists of a single NUL byte, return NULL; otherwise
19996    return a pointer to the string.  */
19997
19998 static const char *
19999 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
20000                                LONGEST str_offset)
20001 {
20002   dwarf2_read_section (objfile, &dwz->str);
20003
20004   if (dwz->str.buffer == NULL)
20005     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
20006              "section [in module %s]"),
20007            bfd_get_filename (dwz->dwz_bfd));
20008   if (str_offset >= dwz->str.size)
20009     error (_("DW_FORM_GNU_strp_alt pointing outside of "
20010              ".debug_str section [in module %s]"),
20011            bfd_get_filename (dwz->dwz_bfd));
20012   gdb_assert (HOST_CHAR_BIT == 8);
20013   if (dwz->str.buffer[str_offset] == '\0')
20014     return NULL;
20015   return (const char *) (dwz->str.buffer + str_offset);
20016 }
20017
20018 /* Return pointer to string at .debug_str offset as read from BUF.
20019    BUF is assumed to be in a compilation unit described by CU_HEADER.
20020    Return *BYTES_READ_PTR count of bytes read from BUF.  */
20021
20022 static const char *
20023 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
20024                       const gdb_byte *buf,
20025                       const struct comp_unit_head *cu_header,
20026                       unsigned int *bytes_read_ptr)
20027 {
20028   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
20029
20030   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
20031 }
20032
20033 /* Return pointer to string at .debug_line_str offset as read from BUF.
20034    BUF is assumed to be in a compilation unit described by CU_HEADER.
20035    Return *BYTES_READ_PTR count of bytes read from BUF.  */
20036
20037 static const char *
20038 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
20039                            bfd *abfd, const gdb_byte *buf,
20040                            const struct comp_unit_head *cu_header,
20041                            unsigned int *bytes_read_ptr)
20042 {
20043   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
20044
20045   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
20046                                               str_offset);
20047 }
20048
20049 ULONGEST
20050 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
20051                           unsigned int *bytes_read_ptr)
20052 {
20053   ULONGEST result;
20054   unsigned int num_read;
20055   int shift;
20056   unsigned char byte;
20057
20058   result = 0;
20059   shift = 0;
20060   num_read = 0;
20061   while (1)
20062     {
20063       byte = bfd_get_8 (abfd, buf);
20064       buf++;
20065       num_read++;
20066       result |= ((ULONGEST) (byte & 127) << shift);
20067       if ((byte & 128) == 0)
20068         {
20069           break;
20070         }
20071       shift += 7;
20072     }
20073   *bytes_read_ptr = num_read;
20074   return result;
20075 }
20076
20077 static LONGEST
20078 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
20079                     unsigned int *bytes_read_ptr)
20080 {
20081   LONGEST result;
20082   int shift, num_read;
20083   unsigned char byte;
20084
20085   result = 0;
20086   shift = 0;
20087   num_read = 0;
20088   while (1)
20089     {
20090       byte = bfd_get_8 (abfd, buf);
20091       buf++;
20092       num_read++;
20093       result |= ((LONGEST) (byte & 127) << shift);
20094       shift += 7;
20095       if ((byte & 128) == 0)
20096         {
20097           break;
20098         }
20099     }
20100   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
20101     result |= -(((LONGEST) 1) << shift);
20102   *bytes_read_ptr = num_read;
20103   return result;
20104 }
20105
20106 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
20107    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
20108    ADDR_SIZE is the size of addresses from the CU header.  */
20109
20110 static CORE_ADDR
20111 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
20112                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
20113 {
20114   struct objfile *objfile = dwarf2_per_objfile->objfile;
20115   bfd *abfd = objfile->obfd;
20116   const gdb_byte *info_ptr;
20117
20118   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
20119   if (dwarf2_per_objfile->addr.buffer == NULL)
20120     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
20121            objfile_name (objfile));
20122   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
20123     error (_("DW_FORM_addr_index pointing outside of "
20124              ".debug_addr section [in module %s]"),
20125            objfile_name (objfile));
20126   info_ptr = (dwarf2_per_objfile->addr.buffer
20127               + addr_base + addr_index * addr_size);
20128   if (addr_size == 4)
20129     return bfd_get_32 (abfd, info_ptr);
20130   else
20131     return bfd_get_64 (abfd, info_ptr);
20132 }
20133
20134 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
20135
20136 static CORE_ADDR
20137 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
20138 {
20139   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
20140                             cu->addr_base, cu->header.addr_size);
20141 }
20142
20143 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
20144
20145 static CORE_ADDR
20146 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
20147                              unsigned int *bytes_read)
20148 {
20149   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
20150   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
20151
20152   return read_addr_index (cu, addr_index);
20153 }
20154
20155 /* Data structure to pass results from dwarf2_read_addr_index_reader
20156    back to dwarf2_read_addr_index.  */
20157
20158 struct dwarf2_read_addr_index_data
20159 {
20160   ULONGEST addr_base;
20161   int addr_size;
20162 };
20163
20164 /* die_reader_func for dwarf2_read_addr_index.  */
20165
20166 static void
20167 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
20168                                const gdb_byte *info_ptr,
20169                                struct die_info *comp_unit_die,
20170                                int has_children,
20171                                void *data)
20172 {
20173   struct dwarf2_cu *cu = reader->cu;
20174   struct dwarf2_read_addr_index_data *aidata =
20175     (struct dwarf2_read_addr_index_data *) data;
20176
20177   aidata->addr_base = cu->addr_base;
20178   aidata->addr_size = cu->header.addr_size;
20179 }
20180
20181 /* Given an index in .debug_addr, fetch the value.
20182    NOTE: This can be called during dwarf expression evaluation,
20183    long after the debug information has been read, and thus per_cu->cu
20184    may no longer exist.  */
20185
20186 CORE_ADDR
20187 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
20188                         unsigned int addr_index)
20189 {
20190   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
20191   struct objfile *objfile = dwarf2_per_objfile->objfile;
20192   struct dwarf2_cu *cu = per_cu->cu;
20193   ULONGEST addr_base;
20194   int addr_size;
20195
20196   /* We need addr_base and addr_size.
20197      If we don't have PER_CU->cu, we have to get it.
20198      Nasty, but the alternative is storing the needed info in PER_CU,
20199      which at this point doesn't seem justified: it's not clear how frequently
20200      it would get used and it would increase the size of every PER_CU.
20201      Entry points like dwarf2_per_cu_addr_size do a similar thing
20202      so we're not in uncharted territory here.
20203      Alas we need to be a bit more complicated as addr_base is contained
20204      in the DIE.
20205
20206      We don't need to read the entire CU(/TU).
20207      We just need the header and top level die.
20208
20209      IWBN to use the aging mechanism to let us lazily later discard the CU.
20210      For now we skip this optimization.  */
20211
20212   if (cu != NULL)
20213     {
20214       addr_base = cu->addr_base;
20215       addr_size = cu->header.addr_size;
20216     }
20217   else
20218     {
20219       struct dwarf2_read_addr_index_data aidata;
20220
20221       /* Note: We can't use init_cutu_and_read_dies_simple here,
20222          we need addr_base.  */
20223       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
20224                                dwarf2_read_addr_index_reader, &aidata);
20225       addr_base = aidata.addr_base;
20226       addr_size = aidata.addr_size;
20227     }
20228
20229   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
20230                             addr_size);
20231 }
20232
20233 /* Given a DW_FORM_GNU_str_index, fetch the string.
20234    This is only used by the Fission support.  */
20235
20236 static const char *
20237 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
20238 {
20239   struct dwarf2_cu *cu = reader->cu;
20240   struct dwarf2_per_objfile *dwarf2_per_objfile
20241     = cu->per_cu->dwarf2_per_objfile;
20242   struct objfile *objfile = dwarf2_per_objfile->objfile;
20243   const char *objf_name = objfile_name (objfile);
20244   bfd *abfd = objfile->obfd;
20245   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
20246   struct dwarf2_section_info *str_offsets_section =
20247     &reader->dwo_file->sections.str_offsets;
20248   const gdb_byte *info_ptr;
20249   ULONGEST str_offset;
20250   static const char form_name[] = "DW_FORM_GNU_str_index";
20251
20252   dwarf2_read_section (objfile, str_section);
20253   dwarf2_read_section (objfile, str_offsets_section);
20254   if (str_section->buffer == NULL)
20255     error (_("%s used without .debug_str.dwo section"
20256              " in CU at offset %s [in module %s]"),
20257            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20258   if (str_offsets_section->buffer == NULL)
20259     error (_("%s used without .debug_str_offsets.dwo section"
20260              " in CU at offset %s [in module %s]"),
20261            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20262   if (str_index * cu->header.offset_size >= str_offsets_section->size)
20263     error (_("%s pointing outside of .debug_str_offsets.dwo"
20264              " section in CU at offset %s [in module %s]"),
20265            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20266   info_ptr = (str_offsets_section->buffer
20267               + str_index * cu->header.offset_size);
20268   if (cu->header.offset_size == 4)
20269     str_offset = bfd_get_32 (abfd, info_ptr);
20270   else
20271     str_offset = bfd_get_64 (abfd, info_ptr);
20272   if (str_offset >= str_section->size)
20273     error (_("Offset from %s pointing outside of"
20274              " .debug_str.dwo section in CU at offset %s [in module %s]"),
20275            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20276   return (const char *) (str_section->buffer + str_offset);
20277 }
20278
20279 /* Return the length of an LEB128 number in BUF.  */
20280
20281 static int
20282 leb128_size (const gdb_byte *buf)
20283 {
20284   const gdb_byte *begin = buf;
20285   gdb_byte byte;
20286
20287   while (1)
20288     {
20289       byte = *buf++;
20290       if ((byte & 128) == 0)
20291         return buf - begin;
20292     }
20293 }
20294
20295 static void
20296 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
20297 {
20298   switch (lang)
20299     {
20300     case DW_LANG_C89:
20301     case DW_LANG_C99:
20302     case DW_LANG_C11:
20303     case DW_LANG_C:
20304     case DW_LANG_UPC:
20305       cu->language = language_c;
20306       break;
20307     case DW_LANG_Java:
20308     case DW_LANG_C_plus_plus:
20309     case DW_LANG_C_plus_plus_11:
20310     case DW_LANG_C_plus_plus_14:
20311       cu->language = language_cplus;
20312       break;
20313     case DW_LANG_D:
20314       cu->language = language_d;
20315       break;
20316     case DW_LANG_Fortran77:
20317     case DW_LANG_Fortran90:
20318     case DW_LANG_Fortran95:
20319     case DW_LANG_Fortran03:
20320     case DW_LANG_Fortran08:
20321       cu->language = language_fortran;
20322       break;
20323     case DW_LANG_Go:
20324       cu->language = language_go;
20325       break;
20326     case DW_LANG_Mips_Assembler:
20327       cu->language = language_asm;
20328       break;
20329     case DW_LANG_Ada83:
20330     case DW_LANG_Ada95:
20331       cu->language = language_ada;
20332       break;
20333     case DW_LANG_Modula2:
20334       cu->language = language_m2;
20335       break;
20336     case DW_LANG_Pascal83:
20337       cu->language = language_pascal;
20338       break;
20339     case DW_LANG_ObjC:
20340       cu->language = language_objc;
20341       break;
20342     case DW_LANG_Rust:
20343     case DW_LANG_Rust_old:
20344       cu->language = language_rust;
20345       break;
20346     case DW_LANG_Cobol74:
20347     case DW_LANG_Cobol85:
20348     default:
20349       cu->language = language_minimal;
20350       break;
20351     }
20352   cu->language_defn = language_def (cu->language);
20353 }
20354
20355 /* Return the named attribute or NULL if not there.  */
20356
20357 static struct attribute *
20358 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20359 {
20360   for (;;)
20361     {
20362       unsigned int i;
20363       struct attribute *spec = NULL;
20364
20365       for (i = 0; i < die->num_attrs; ++i)
20366         {
20367           if (die->attrs[i].name == name)
20368             return &die->attrs[i];
20369           if (die->attrs[i].name == DW_AT_specification
20370               || die->attrs[i].name == DW_AT_abstract_origin)
20371             spec = &die->attrs[i];
20372         }
20373
20374       if (!spec)
20375         break;
20376
20377       die = follow_die_ref (die, spec, &cu);
20378     }
20379
20380   return NULL;
20381 }
20382
20383 /* Return the named attribute or NULL if not there,
20384    but do not follow DW_AT_specification, etc.
20385    This is for use in contexts where we're reading .debug_types dies.
20386    Following DW_AT_specification, DW_AT_abstract_origin will take us
20387    back up the chain, and we want to go down.  */
20388
20389 static struct attribute *
20390 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20391 {
20392   unsigned int i;
20393
20394   for (i = 0; i < die->num_attrs; ++i)
20395     if (die->attrs[i].name == name)
20396       return &die->attrs[i];
20397
20398   return NULL;
20399 }
20400
20401 /* Return the string associated with a string-typed attribute, or NULL if it
20402    is either not found or is of an incorrect type.  */
20403
20404 static const char *
20405 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20406 {
20407   struct attribute *attr;
20408   const char *str = NULL;
20409
20410   attr = dwarf2_attr (die, name, cu);
20411
20412   if (attr != NULL)
20413     {
20414       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20415           || attr->form == DW_FORM_string
20416           || attr->form == DW_FORM_GNU_str_index
20417           || attr->form == DW_FORM_GNU_strp_alt)
20418         str = DW_STRING (attr);
20419       else
20420         complaint (&symfile_complaints,
20421                    _("string type expected for attribute %s for "
20422                      "DIE at %s in module %s"),
20423                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20424                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20425     }
20426
20427   return str;
20428 }
20429
20430 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20431    and holds a non-zero value.  This function should only be used for
20432    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20433
20434 static int
20435 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20436 {
20437   struct attribute *attr = dwarf2_attr (die, name, cu);
20438
20439   return (attr && DW_UNSND (attr));
20440 }
20441
20442 static int
20443 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20444 {
20445   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20446      which value is non-zero.  However, we have to be careful with
20447      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20448      (via dwarf2_flag_true_p) follows this attribute.  So we may
20449      end up accidently finding a declaration attribute that belongs
20450      to a different DIE referenced by the specification attribute,
20451      even though the given DIE does not have a declaration attribute.  */
20452   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20453           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20454 }
20455
20456 /* Return the die giving the specification for DIE, if there is
20457    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20458    containing the return value on output.  If there is no
20459    specification, but there is an abstract origin, that is
20460    returned.  */
20461
20462 static struct die_info *
20463 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20464 {
20465   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20466                                              *spec_cu);
20467
20468   if (spec_attr == NULL)
20469     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20470
20471   if (spec_attr == NULL)
20472     return NULL;
20473   else
20474     return follow_die_ref (die, spec_attr, spec_cu);
20475 }
20476
20477 /* Stub for free_line_header to match void * callback types.  */
20478
20479 static void
20480 free_line_header_voidp (void *arg)
20481 {
20482   struct line_header *lh = (struct line_header *) arg;
20483
20484   delete lh;
20485 }
20486
20487 void
20488 line_header::add_include_dir (const char *include_dir)
20489 {
20490   if (dwarf_line_debug >= 2)
20491     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20492                         include_dirs.size () + 1, include_dir);
20493
20494   include_dirs.push_back (include_dir);
20495 }
20496
20497 void
20498 line_header::add_file_name (const char *name,
20499                             dir_index d_index,
20500                             unsigned int mod_time,
20501                             unsigned int length)
20502 {
20503   if (dwarf_line_debug >= 2)
20504     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20505                         (unsigned) file_names.size () + 1, name);
20506
20507   file_names.emplace_back (name, d_index, mod_time, length);
20508 }
20509
20510 /* A convenience function to find the proper .debug_line section for a CU.  */
20511
20512 static struct dwarf2_section_info *
20513 get_debug_line_section (struct dwarf2_cu *cu)
20514 {
20515   struct dwarf2_section_info *section;
20516   struct dwarf2_per_objfile *dwarf2_per_objfile
20517     = cu->per_cu->dwarf2_per_objfile;
20518
20519   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20520      DWO file.  */
20521   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20522     section = &cu->dwo_unit->dwo_file->sections.line;
20523   else if (cu->per_cu->is_dwz)
20524     {
20525       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20526
20527       section = &dwz->line;
20528     }
20529   else
20530     section = &dwarf2_per_objfile->line;
20531
20532   return section;
20533 }
20534
20535 /* Read directory or file name entry format, starting with byte of
20536    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20537    entries count and the entries themselves in the described entry
20538    format.  */
20539
20540 static void
20541 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20542                         bfd *abfd, const gdb_byte **bufp,
20543                         struct line_header *lh,
20544                         const struct comp_unit_head *cu_header,
20545                         void (*callback) (struct line_header *lh,
20546                                           const char *name,
20547                                           dir_index d_index,
20548                                           unsigned int mod_time,
20549                                           unsigned int length))
20550 {
20551   gdb_byte format_count, formati;
20552   ULONGEST data_count, datai;
20553   const gdb_byte *buf = *bufp;
20554   const gdb_byte *format_header_data;
20555   unsigned int bytes_read;
20556
20557   format_count = read_1_byte (abfd, buf);
20558   buf += 1;
20559   format_header_data = buf;
20560   for (formati = 0; formati < format_count; formati++)
20561     {
20562       read_unsigned_leb128 (abfd, buf, &bytes_read);
20563       buf += bytes_read;
20564       read_unsigned_leb128 (abfd, buf, &bytes_read);
20565       buf += bytes_read;
20566     }
20567
20568   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20569   buf += bytes_read;
20570   for (datai = 0; datai < data_count; datai++)
20571     {
20572       const gdb_byte *format = format_header_data;
20573       struct file_entry fe;
20574
20575       for (formati = 0; formati < format_count; formati++)
20576         {
20577           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20578           format += bytes_read;
20579
20580           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20581           format += bytes_read;
20582
20583           gdb::optional<const char *> string;
20584           gdb::optional<unsigned int> uint;
20585
20586           switch (form)
20587             {
20588             case DW_FORM_string:
20589               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20590               buf += bytes_read;
20591               break;
20592
20593             case DW_FORM_line_strp:
20594               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20595                                                          abfd, buf,
20596                                                          cu_header,
20597                                                          &bytes_read));
20598               buf += bytes_read;
20599               break;
20600
20601             case DW_FORM_data1:
20602               uint.emplace (read_1_byte (abfd, buf));
20603               buf += 1;
20604               break;
20605
20606             case DW_FORM_data2:
20607               uint.emplace (read_2_bytes (abfd, buf));
20608               buf += 2;
20609               break;
20610
20611             case DW_FORM_data4:
20612               uint.emplace (read_4_bytes (abfd, buf));
20613               buf += 4;
20614               break;
20615
20616             case DW_FORM_data8:
20617               uint.emplace (read_8_bytes (abfd, buf));
20618               buf += 8;
20619               break;
20620
20621             case DW_FORM_udata:
20622               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20623               buf += bytes_read;
20624               break;
20625
20626             case DW_FORM_block:
20627               /* It is valid only for DW_LNCT_timestamp which is ignored by
20628                  current GDB.  */
20629               break;
20630             }
20631
20632           switch (content_type)
20633             {
20634             case DW_LNCT_path:
20635               if (string.has_value ())
20636                 fe.name = *string;
20637               break;
20638             case DW_LNCT_directory_index:
20639               if (uint.has_value ())
20640                 fe.d_index = (dir_index) *uint;
20641               break;
20642             case DW_LNCT_timestamp:
20643               if (uint.has_value ())
20644                 fe.mod_time = *uint;
20645               break;
20646             case DW_LNCT_size:
20647               if (uint.has_value ())
20648                 fe.length = *uint;
20649               break;
20650             case DW_LNCT_MD5:
20651               break;
20652             default:
20653               complaint (&symfile_complaints,
20654                          _("Unknown format content type %s"),
20655                          pulongest (content_type));
20656             }
20657         }
20658
20659       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20660     }
20661
20662   *bufp = buf;
20663 }
20664
20665 /* Read the statement program header starting at OFFSET in
20666    .debug_line, or .debug_line.dwo.  Return a pointer
20667    to a struct line_header, allocated using xmalloc.
20668    Returns NULL if there is a problem reading the header, e.g., if it
20669    has a version we don't understand.
20670
20671    NOTE: the strings in the include directory and file name tables of
20672    the returned object point into the dwarf line section buffer,
20673    and must not be freed.  */
20674
20675 static line_header_up
20676 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20677 {
20678   const gdb_byte *line_ptr;
20679   unsigned int bytes_read, offset_size;
20680   int i;
20681   const char *cur_dir, *cur_file;
20682   struct dwarf2_section_info *section;
20683   bfd *abfd;
20684   struct dwarf2_per_objfile *dwarf2_per_objfile
20685     = cu->per_cu->dwarf2_per_objfile;
20686
20687   section = get_debug_line_section (cu);
20688   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20689   if (section->buffer == NULL)
20690     {
20691       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20692         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20693       else
20694         complaint (&symfile_complaints, _("missing .debug_line section"));
20695       return 0;
20696     }
20697
20698   /* We can't do this until we know the section is non-empty.
20699      Only then do we know we have such a section.  */
20700   abfd = get_section_bfd_owner (section);
20701
20702   /* Make sure that at least there's room for the total_length field.
20703      That could be 12 bytes long, but we're just going to fudge that.  */
20704   if (to_underlying (sect_off) + 4 >= section->size)
20705     {
20706       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20707       return 0;
20708     }
20709
20710   line_header_up lh (new line_header ());
20711
20712   lh->sect_off = sect_off;
20713   lh->offset_in_dwz = cu->per_cu->is_dwz;
20714
20715   line_ptr = section->buffer + to_underlying (sect_off);
20716
20717   /* Read in the header.  */
20718   lh->total_length =
20719     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20720                                             &bytes_read, &offset_size);
20721   line_ptr += bytes_read;
20722   if (line_ptr + lh->total_length > (section->buffer + section->size))
20723     {
20724       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20725       return 0;
20726     }
20727   lh->statement_program_end = line_ptr + lh->total_length;
20728   lh->version = read_2_bytes (abfd, line_ptr);
20729   line_ptr += 2;
20730   if (lh->version > 5)
20731     {
20732       /* This is a version we don't understand.  The format could have
20733          changed in ways we don't handle properly so just punt.  */
20734       complaint (&symfile_complaints,
20735                  _("unsupported version in .debug_line section"));
20736       return NULL;
20737     }
20738   if (lh->version >= 5)
20739     {
20740       gdb_byte segment_selector_size;
20741
20742       /* Skip address size.  */
20743       read_1_byte (abfd, line_ptr);
20744       line_ptr += 1;
20745
20746       segment_selector_size = read_1_byte (abfd, line_ptr);
20747       line_ptr += 1;
20748       if (segment_selector_size != 0)
20749         {
20750           complaint (&symfile_complaints,
20751                      _("unsupported segment selector size %u "
20752                        "in .debug_line section"),
20753                      segment_selector_size);
20754           return NULL;
20755         }
20756     }
20757   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20758   line_ptr += offset_size;
20759   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20760   line_ptr += 1;
20761   if (lh->version >= 4)
20762     {
20763       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20764       line_ptr += 1;
20765     }
20766   else
20767     lh->maximum_ops_per_instruction = 1;
20768
20769   if (lh->maximum_ops_per_instruction == 0)
20770     {
20771       lh->maximum_ops_per_instruction = 1;
20772       complaint (&symfile_complaints,
20773                  _("invalid maximum_ops_per_instruction "
20774                    "in `.debug_line' section"));
20775     }
20776
20777   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20778   line_ptr += 1;
20779   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20780   line_ptr += 1;
20781   lh->line_range = read_1_byte (abfd, line_ptr);
20782   line_ptr += 1;
20783   lh->opcode_base = read_1_byte (abfd, line_ptr);
20784   line_ptr += 1;
20785   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20786
20787   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20788   for (i = 1; i < lh->opcode_base; ++i)
20789     {
20790       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20791       line_ptr += 1;
20792     }
20793
20794   if (lh->version >= 5)
20795     {
20796       /* Read directory table.  */
20797       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20798                               &cu->header,
20799                               [] (struct line_header *lh, const char *name,
20800                                   dir_index d_index, unsigned int mod_time,
20801                                   unsigned int length)
20802         {
20803           lh->add_include_dir (name);
20804         });
20805
20806       /* Read file name table.  */
20807       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20808                               &cu->header,
20809                               [] (struct line_header *lh, const char *name,
20810                                   dir_index d_index, unsigned int mod_time,
20811                                   unsigned int length)
20812         {
20813           lh->add_file_name (name, d_index, mod_time, length);
20814         });
20815     }
20816   else
20817     {
20818       /* Read directory table.  */
20819       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20820         {
20821           line_ptr += bytes_read;
20822           lh->add_include_dir (cur_dir);
20823         }
20824       line_ptr += bytes_read;
20825
20826       /* Read file name table.  */
20827       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20828         {
20829           unsigned int mod_time, length;
20830           dir_index d_index;
20831
20832           line_ptr += bytes_read;
20833           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20834           line_ptr += bytes_read;
20835           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20836           line_ptr += bytes_read;
20837           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20838           line_ptr += bytes_read;
20839
20840           lh->add_file_name (cur_file, d_index, mod_time, length);
20841         }
20842       line_ptr += bytes_read;
20843     }
20844   lh->statement_program_start = line_ptr;
20845
20846   if (line_ptr > (section->buffer + section->size))
20847     complaint (&symfile_complaints,
20848                _("line number info header doesn't "
20849                  "fit in `.debug_line' section"));
20850
20851   return lh;
20852 }
20853
20854 /* Subroutine of dwarf_decode_lines to simplify it.
20855    Return the file name of the psymtab for included file FILE_INDEX
20856    in line header LH of PST.
20857    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20858    If space for the result is malloc'd, *NAME_HOLDER will be set.
20859    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20860
20861 static const char *
20862 psymtab_include_file_name (const struct line_header *lh, int file_index,
20863                            const struct partial_symtab *pst,
20864                            const char *comp_dir,
20865                            gdb::unique_xmalloc_ptr<char> *name_holder)
20866 {
20867   const file_entry &fe = lh->file_names[file_index];
20868   const char *include_name = fe.name;
20869   const char *include_name_to_compare = include_name;
20870   const char *pst_filename;
20871   int file_is_pst;
20872
20873   const char *dir_name = fe.include_dir (lh);
20874
20875   gdb::unique_xmalloc_ptr<char> hold_compare;
20876   if (!IS_ABSOLUTE_PATH (include_name)
20877       && (dir_name != NULL || comp_dir != NULL))
20878     {
20879       /* Avoid creating a duplicate psymtab for PST.
20880          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20881          Before we do the comparison, however, we need to account
20882          for DIR_NAME and COMP_DIR.
20883          First prepend dir_name (if non-NULL).  If we still don't
20884          have an absolute path prepend comp_dir (if non-NULL).
20885          However, the directory we record in the include-file's
20886          psymtab does not contain COMP_DIR (to match the
20887          corresponding symtab(s)).
20888
20889          Example:
20890
20891          bash$ cd /tmp
20892          bash$ gcc -g ./hello.c
20893          include_name = "hello.c"
20894          dir_name = "."
20895          DW_AT_comp_dir = comp_dir = "/tmp"
20896          DW_AT_name = "./hello.c"
20897
20898       */
20899
20900       if (dir_name != NULL)
20901         {
20902           name_holder->reset (concat (dir_name, SLASH_STRING,
20903                                       include_name, (char *) NULL));
20904           include_name = name_holder->get ();
20905           include_name_to_compare = include_name;
20906         }
20907       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20908         {
20909           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20910                                       include_name, (char *) NULL));
20911           include_name_to_compare = hold_compare.get ();
20912         }
20913     }
20914
20915   pst_filename = pst->filename;
20916   gdb::unique_xmalloc_ptr<char> copied_name;
20917   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20918     {
20919       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20920                                  pst_filename, (char *) NULL));
20921       pst_filename = copied_name.get ();
20922     }
20923
20924   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20925
20926   if (file_is_pst)
20927     return NULL;
20928   return include_name;
20929 }
20930
20931 /* State machine to track the state of the line number program.  */
20932
20933 class lnp_state_machine
20934 {
20935 public:
20936   /* Initialize a machine state for the start of a line number
20937      program.  */
20938   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20939
20940   file_entry *current_file ()
20941   {
20942     /* lh->file_names is 0-based, but the file name numbers in the
20943        statement program are 1-based.  */
20944     return m_line_header->file_name_at (m_file);
20945   }
20946
20947   /* Record the line in the state machine.  END_SEQUENCE is true if
20948      we're processing the end of a sequence.  */
20949   void record_line (bool end_sequence);
20950
20951   /* Check address and if invalid nop-out the rest of the lines in this
20952      sequence.  */
20953   void check_line_address (struct dwarf2_cu *cu,
20954                            const gdb_byte *line_ptr,
20955                            CORE_ADDR lowpc, CORE_ADDR address);
20956
20957   void handle_set_discriminator (unsigned int discriminator)
20958   {
20959     m_discriminator = discriminator;
20960     m_line_has_non_zero_discriminator |= discriminator != 0;
20961   }
20962
20963   /* Handle DW_LNE_set_address.  */
20964   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20965   {
20966     m_op_index = 0;
20967     address += baseaddr;
20968     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20969   }
20970
20971   /* Handle DW_LNS_advance_pc.  */
20972   void handle_advance_pc (CORE_ADDR adjust);
20973
20974   /* Handle a special opcode.  */
20975   void handle_special_opcode (unsigned char op_code);
20976
20977   /* Handle DW_LNS_advance_line.  */
20978   void handle_advance_line (int line_delta)
20979   {
20980     advance_line (line_delta);
20981   }
20982
20983   /* Handle DW_LNS_set_file.  */
20984   void handle_set_file (file_name_index file);
20985
20986   /* Handle DW_LNS_negate_stmt.  */
20987   void handle_negate_stmt ()
20988   {
20989     m_is_stmt = !m_is_stmt;
20990   }
20991
20992   /* Handle DW_LNS_const_add_pc.  */
20993   void handle_const_add_pc ();
20994
20995   /* Handle DW_LNS_fixed_advance_pc.  */
20996   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20997   {
20998     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20999     m_op_index = 0;
21000   }
21001
21002   /* Handle DW_LNS_copy.  */
21003   void handle_copy ()
21004   {
21005     record_line (false);
21006     m_discriminator = 0;
21007   }
21008
21009   /* Handle DW_LNE_end_sequence.  */
21010   void handle_end_sequence ()
21011   {
21012     m_record_line_callback = ::record_line;
21013   }
21014
21015 private:
21016   /* Advance the line by LINE_DELTA.  */
21017   void advance_line (int line_delta)
21018   {
21019     m_line += line_delta;
21020
21021     if (line_delta != 0)
21022       m_line_has_non_zero_discriminator = m_discriminator != 0;
21023   }
21024
21025   gdbarch *m_gdbarch;
21026
21027   /* True if we're recording lines.
21028      Otherwise we're building partial symtabs and are just interested in
21029      finding include files mentioned by the line number program.  */
21030   bool m_record_lines_p;
21031
21032   /* The line number header.  */
21033   line_header *m_line_header;
21034
21035   /* These are part of the standard DWARF line number state machine,
21036      and initialized according to the DWARF spec.  */
21037
21038   unsigned char m_op_index = 0;
21039   /* The line table index (1-based) of the current file.  */
21040   file_name_index m_file = (file_name_index) 1;
21041   unsigned int m_line = 1;
21042
21043   /* These are initialized in the constructor.  */
21044
21045   CORE_ADDR m_address;
21046   bool m_is_stmt;
21047   unsigned int m_discriminator;
21048
21049   /* Additional bits of state we need to track.  */
21050
21051   /* The last file that we called dwarf2_start_subfile for.
21052      This is only used for TLLs.  */
21053   unsigned int m_last_file = 0;
21054   /* The last file a line number was recorded for.  */
21055   struct subfile *m_last_subfile = NULL;
21056
21057   /* The function to call to record a line.  */
21058   record_line_ftype *m_record_line_callback = NULL;
21059
21060   /* The last line number that was recorded, used to coalesce
21061      consecutive entries for the same line.  This can happen, for
21062      example, when discriminators are present.  PR 17276.  */
21063   unsigned int m_last_line = 0;
21064   bool m_line_has_non_zero_discriminator = false;
21065 };
21066
21067 void
21068 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
21069 {
21070   CORE_ADDR addr_adj = (((m_op_index + adjust)
21071                          / m_line_header->maximum_ops_per_instruction)
21072                         * m_line_header->minimum_instruction_length);
21073   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21074   m_op_index = ((m_op_index + adjust)
21075                 % m_line_header->maximum_ops_per_instruction);
21076 }
21077
21078 void
21079 lnp_state_machine::handle_special_opcode (unsigned char op_code)
21080 {
21081   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
21082   CORE_ADDR addr_adj = (((m_op_index
21083                           + (adj_opcode / m_line_header->line_range))
21084                          / m_line_header->maximum_ops_per_instruction)
21085                         * m_line_header->minimum_instruction_length);
21086   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21087   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
21088                 % m_line_header->maximum_ops_per_instruction);
21089
21090   int line_delta = (m_line_header->line_base
21091                     + (adj_opcode % m_line_header->line_range));
21092   advance_line (line_delta);
21093   record_line (false);
21094   m_discriminator = 0;
21095 }
21096
21097 void
21098 lnp_state_machine::handle_set_file (file_name_index file)
21099 {
21100   m_file = file;
21101
21102   const file_entry *fe = current_file ();
21103   if (fe == NULL)
21104     dwarf2_debug_line_missing_file_complaint ();
21105   else if (m_record_lines_p)
21106     {
21107       const char *dir = fe->include_dir (m_line_header);
21108
21109       m_last_subfile = current_subfile;
21110       m_line_has_non_zero_discriminator = m_discriminator != 0;
21111       dwarf2_start_subfile (fe->name, dir);
21112     }
21113 }
21114
21115 void
21116 lnp_state_machine::handle_const_add_pc ()
21117 {
21118   CORE_ADDR adjust
21119     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
21120
21121   CORE_ADDR addr_adj
21122     = (((m_op_index + adjust)
21123         / m_line_header->maximum_ops_per_instruction)
21124        * m_line_header->minimum_instruction_length);
21125
21126   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
21127   m_op_index = ((m_op_index + adjust)
21128                 % m_line_header->maximum_ops_per_instruction);
21129 }
21130
21131 /* Ignore this record_line request.  */
21132
21133 static void
21134 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
21135 {
21136   return;
21137 }
21138
21139 /* Return non-zero if we should add LINE to the line number table.
21140    LINE is the line to add, LAST_LINE is the last line that was added,
21141    LAST_SUBFILE is the subfile for LAST_LINE.
21142    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
21143    had a non-zero discriminator.
21144
21145    We have to be careful in the presence of discriminators.
21146    E.g., for this line:
21147
21148      for (i = 0; i < 100000; i++);
21149
21150    clang can emit four line number entries for that one line,
21151    each with a different discriminator.
21152    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
21153
21154    However, we want gdb to coalesce all four entries into one.
21155    Otherwise the user could stepi into the middle of the line and
21156    gdb would get confused about whether the pc really was in the
21157    middle of the line.
21158
21159    Things are further complicated by the fact that two consecutive
21160    line number entries for the same line is a heuristic used by gcc
21161    to denote the end of the prologue.  So we can't just discard duplicate
21162    entries, we have to be selective about it.  The heuristic we use is
21163    that we only collapse consecutive entries for the same line if at least
21164    one of those entries has a non-zero discriminator.  PR 17276.
21165
21166    Note: Addresses in the line number state machine can never go backwards
21167    within one sequence, thus this coalescing is ok.  */
21168
21169 static int
21170 dwarf_record_line_p (unsigned int line, unsigned int last_line,
21171                      int line_has_non_zero_discriminator,
21172                      struct subfile *last_subfile)
21173 {
21174   if (current_subfile != last_subfile)
21175     return 1;
21176   if (line != last_line)
21177     return 1;
21178   /* Same line for the same file that we've seen already.
21179      As a last check, for pr 17276, only record the line if the line
21180      has never had a non-zero discriminator.  */
21181   if (!line_has_non_zero_discriminator)
21182     return 1;
21183   return 0;
21184 }
21185
21186 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
21187    in the line table of subfile SUBFILE.  */
21188
21189 static void
21190 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
21191                      unsigned int line, CORE_ADDR address,
21192                      record_line_ftype p_record_line)
21193 {
21194   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
21195
21196   if (dwarf_line_debug)
21197     {
21198       fprintf_unfiltered (gdb_stdlog,
21199                           "Recording line %u, file %s, address %s\n",
21200                           line, lbasename (subfile->name),
21201                           paddress (gdbarch, address));
21202     }
21203
21204   (*p_record_line) (subfile, line, addr);
21205 }
21206
21207 /* Subroutine of dwarf_decode_lines_1 to simplify it.
21208    Mark the end of a set of line number records.
21209    The arguments are the same as for dwarf_record_line_1.
21210    If SUBFILE is NULL the request is ignored.  */
21211
21212 static void
21213 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
21214                    CORE_ADDR address, record_line_ftype p_record_line)
21215 {
21216   if (subfile == NULL)
21217     return;
21218
21219   if (dwarf_line_debug)
21220     {
21221       fprintf_unfiltered (gdb_stdlog,
21222                           "Finishing current line, file %s, address %s\n",
21223                           lbasename (subfile->name),
21224                           paddress (gdbarch, address));
21225     }
21226
21227   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
21228 }
21229
21230 void
21231 lnp_state_machine::record_line (bool end_sequence)
21232 {
21233   if (dwarf_line_debug)
21234     {
21235       fprintf_unfiltered (gdb_stdlog,
21236                           "Processing actual line %u: file %u,"
21237                           " address %s, is_stmt %u, discrim %u\n",
21238                           m_line, to_underlying (m_file),
21239                           paddress (m_gdbarch, m_address),
21240                           m_is_stmt, m_discriminator);
21241     }
21242
21243   file_entry *fe = current_file ();
21244
21245   if (fe == NULL)
21246     dwarf2_debug_line_missing_file_complaint ();
21247   /* For now we ignore lines not starting on an instruction boundary.
21248      But not when processing end_sequence for compatibility with the
21249      previous version of the code.  */
21250   else if (m_op_index == 0 || end_sequence)
21251     {
21252       fe->included_p = 1;
21253       if (m_record_lines_p && m_is_stmt)
21254         {
21255           if (m_last_subfile != current_subfile || end_sequence)
21256             {
21257               dwarf_finish_line (m_gdbarch, m_last_subfile,
21258                                  m_address, m_record_line_callback);
21259             }
21260
21261           if (!end_sequence)
21262             {
21263               if (dwarf_record_line_p (m_line, m_last_line,
21264                                        m_line_has_non_zero_discriminator,
21265                                        m_last_subfile))
21266                 {
21267                   dwarf_record_line_1 (m_gdbarch, current_subfile,
21268                                        m_line, m_address,
21269                                        m_record_line_callback);
21270                 }
21271               m_last_subfile = current_subfile;
21272               m_last_line = m_line;
21273             }
21274         }
21275     }
21276 }
21277
21278 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
21279                                       bool record_lines_p)
21280 {
21281   m_gdbarch = arch;
21282   m_record_lines_p = record_lines_p;
21283   m_line_header = lh;
21284
21285   m_record_line_callback = ::record_line;
21286
21287   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21288      was a line entry for it so that the backend has a chance to adjust it
21289      and also record it in case it needs it.  This is currently used by MIPS
21290      code, cf. `mips_adjust_dwarf2_line'.  */
21291   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21292   m_is_stmt = lh->default_is_stmt;
21293   m_discriminator = 0;
21294 }
21295
21296 void
21297 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21298                                        const gdb_byte *line_ptr,
21299                                        CORE_ADDR lowpc, CORE_ADDR address)
21300 {
21301   /* If address < lowpc then it's not a usable value, it's outside the
21302      pc range of the CU.  However, we restrict the test to only address
21303      values of zero to preserve GDB's previous behaviour which is to
21304      handle the specific case of a function being GC'd by the linker.  */
21305
21306   if (address == 0 && address < lowpc)
21307     {
21308       /* This line table is for a function which has been
21309          GCd by the linker.  Ignore it.  PR gdb/12528 */
21310
21311       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21312       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21313
21314       complaint (&symfile_complaints,
21315                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21316                  line_offset, objfile_name (objfile));
21317       m_record_line_callback = noop_record_line;
21318       /* Note: record_line_callback is left as noop_record_line until
21319          we see DW_LNE_end_sequence.  */
21320     }
21321 }
21322
21323 /* Subroutine of dwarf_decode_lines to simplify it.
21324    Process the line number information in LH.
21325    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21326    program in order to set included_p for every referenced header.  */
21327
21328 static void
21329 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21330                       const int decode_for_pst_p, CORE_ADDR lowpc)
21331 {
21332   const gdb_byte *line_ptr, *extended_end;
21333   const gdb_byte *line_end;
21334   unsigned int bytes_read, extended_len;
21335   unsigned char op_code, extended_op;
21336   CORE_ADDR baseaddr;
21337   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21338   bfd *abfd = objfile->obfd;
21339   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21340   /* True if we're recording line info (as opposed to building partial
21341      symtabs and just interested in finding include files mentioned by
21342      the line number program).  */
21343   bool record_lines_p = !decode_for_pst_p;
21344
21345   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21346
21347   line_ptr = lh->statement_program_start;
21348   line_end = lh->statement_program_end;
21349
21350   /* Read the statement sequences until there's nothing left.  */
21351   while (line_ptr < line_end)
21352     {
21353       /* The DWARF line number program state machine.  Reset the state
21354          machine at the start of each sequence.  */
21355       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
21356       bool end_sequence = false;
21357
21358       if (record_lines_p)
21359         {
21360           /* Start a subfile for the current file of the state
21361              machine.  */
21362           const file_entry *fe = state_machine.current_file ();
21363
21364           if (fe != NULL)
21365             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
21366         }
21367
21368       /* Decode the table.  */
21369       while (line_ptr < line_end && !end_sequence)
21370         {
21371           op_code = read_1_byte (abfd, line_ptr);
21372           line_ptr += 1;
21373
21374           if (op_code >= lh->opcode_base)
21375             {
21376               /* Special opcode.  */
21377               state_machine.handle_special_opcode (op_code);
21378             }
21379           else switch (op_code)
21380             {
21381             case DW_LNS_extended_op:
21382               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21383                                                    &bytes_read);
21384               line_ptr += bytes_read;
21385               extended_end = line_ptr + extended_len;
21386               extended_op = read_1_byte (abfd, line_ptr);
21387               line_ptr += 1;
21388               switch (extended_op)
21389                 {
21390                 case DW_LNE_end_sequence:
21391                   state_machine.handle_end_sequence ();
21392                   end_sequence = true;
21393                   break;
21394                 case DW_LNE_set_address:
21395                   {
21396                     CORE_ADDR address
21397                       = read_address (abfd, line_ptr, cu, &bytes_read);
21398                     line_ptr += bytes_read;
21399
21400                     state_machine.check_line_address (cu, line_ptr,
21401                                                       lowpc, address);
21402                     state_machine.handle_set_address (baseaddr, address);
21403                   }
21404                   break;
21405                 case DW_LNE_define_file:
21406                   {
21407                     const char *cur_file;
21408                     unsigned int mod_time, length;
21409                     dir_index dindex;
21410
21411                     cur_file = read_direct_string (abfd, line_ptr,
21412                                                    &bytes_read);
21413                     line_ptr += bytes_read;
21414                     dindex = (dir_index)
21415                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21416                     line_ptr += bytes_read;
21417                     mod_time =
21418                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21419                     line_ptr += bytes_read;
21420                     length =
21421                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21422                     line_ptr += bytes_read;
21423                     lh->add_file_name (cur_file, dindex, mod_time, length);
21424                   }
21425                   break;
21426                 case DW_LNE_set_discriminator:
21427                   {
21428                     /* The discriminator is not interesting to the
21429                        debugger; just ignore it.  We still need to
21430                        check its value though:
21431                        if there are consecutive entries for the same
21432                        (non-prologue) line we want to coalesce them.
21433                        PR 17276.  */
21434                     unsigned int discr
21435                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21436                     line_ptr += bytes_read;
21437
21438                     state_machine.handle_set_discriminator (discr);
21439                   }
21440                   break;
21441                 default:
21442                   complaint (&symfile_complaints,
21443                              _("mangled .debug_line section"));
21444                   return;
21445                 }
21446               /* Make sure that we parsed the extended op correctly.  If e.g.
21447                  we expected a different address size than the producer used,
21448                  we may have read the wrong number of bytes.  */
21449               if (line_ptr != extended_end)
21450                 {
21451                   complaint (&symfile_complaints,
21452                              _("mangled .debug_line section"));
21453                   return;
21454                 }
21455               break;
21456             case DW_LNS_copy:
21457               state_machine.handle_copy ();
21458               break;
21459             case DW_LNS_advance_pc:
21460               {
21461                 CORE_ADDR adjust
21462                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21463                 line_ptr += bytes_read;
21464
21465                 state_machine.handle_advance_pc (adjust);
21466               }
21467               break;
21468             case DW_LNS_advance_line:
21469               {
21470                 int line_delta
21471                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21472                 line_ptr += bytes_read;
21473
21474                 state_machine.handle_advance_line (line_delta);
21475               }
21476               break;
21477             case DW_LNS_set_file:
21478               {
21479                 file_name_index file
21480                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21481                                                             &bytes_read);
21482                 line_ptr += bytes_read;
21483
21484                 state_machine.handle_set_file (file);
21485               }
21486               break;
21487             case DW_LNS_set_column:
21488               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21489               line_ptr += bytes_read;
21490               break;
21491             case DW_LNS_negate_stmt:
21492               state_machine.handle_negate_stmt ();
21493               break;
21494             case DW_LNS_set_basic_block:
21495               break;
21496             /* Add to the address register of the state machine the
21497                address increment value corresponding to special opcode
21498                255.  I.e., this value is scaled by the minimum
21499                instruction length since special opcode 255 would have
21500                scaled the increment.  */
21501             case DW_LNS_const_add_pc:
21502               state_machine.handle_const_add_pc ();
21503               break;
21504             case DW_LNS_fixed_advance_pc:
21505               {
21506                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21507                 line_ptr += 2;
21508
21509                 state_machine.handle_fixed_advance_pc (addr_adj);
21510               }
21511               break;
21512             default:
21513               {
21514                 /* Unknown standard opcode, ignore it.  */
21515                 int i;
21516
21517                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21518                   {
21519                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21520                     line_ptr += bytes_read;
21521                   }
21522               }
21523             }
21524         }
21525
21526       if (!end_sequence)
21527         dwarf2_debug_line_missing_end_sequence_complaint ();
21528
21529       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21530          in which case we still finish recording the last line).  */
21531       state_machine.record_line (true);
21532     }
21533 }
21534
21535 /* Decode the Line Number Program (LNP) for the given line_header
21536    structure and CU.  The actual information extracted and the type
21537    of structures created from the LNP depends on the value of PST.
21538
21539    1. If PST is NULL, then this procedure uses the data from the program
21540       to create all necessary symbol tables, and their linetables.
21541
21542    2. If PST is not NULL, this procedure reads the program to determine
21543       the list of files included by the unit represented by PST, and
21544       builds all the associated partial symbol tables.
21545
21546    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21547    It is used for relative paths in the line table.
21548    NOTE: When processing partial symtabs (pst != NULL),
21549    comp_dir == pst->dirname.
21550
21551    NOTE: It is important that psymtabs have the same file name (via strcmp)
21552    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21553    symtab we don't use it in the name of the psymtabs we create.
21554    E.g. expand_line_sal requires this when finding psymtabs to expand.
21555    A good testcase for this is mb-inline.exp.
21556
21557    LOWPC is the lowest address in CU (or 0 if not known).
21558
21559    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21560    for its PC<->lines mapping information.  Otherwise only the filename
21561    table is read in.  */
21562
21563 static void
21564 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21565                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21566                     CORE_ADDR lowpc, int decode_mapping)
21567 {
21568   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21569   const int decode_for_pst_p = (pst != NULL);
21570
21571   if (decode_mapping)
21572     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21573
21574   if (decode_for_pst_p)
21575     {
21576       int file_index;
21577
21578       /* Now that we're done scanning the Line Header Program, we can
21579          create the psymtab of each included file.  */
21580       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21581         if (lh->file_names[file_index].included_p == 1)
21582           {
21583             gdb::unique_xmalloc_ptr<char> name_holder;
21584             const char *include_name =
21585               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21586                                          &name_holder);
21587             if (include_name != NULL)
21588               dwarf2_create_include_psymtab (include_name, pst, objfile);
21589           }
21590     }
21591   else
21592     {
21593       /* Make sure a symtab is created for every file, even files
21594          which contain only variables (i.e. no code with associated
21595          line numbers).  */
21596       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21597       int i;
21598
21599       for (i = 0; i < lh->file_names.size (); i++)
21600         {
21601           file_entry &fe = lh->file_names[i];
21602
21603           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21604
21605           if (current_subfile->symtab == NULL)
21606             {
21607               current_subfile->symtab
21608                 = allocate_symtab (cust, current_subfile->name);
21609             }
21610           fe.symtab = current_subfile->symtab;
21611         }
21612     }
21613 }
21614
21615 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21616    DIRNAME the name of the source directory which contains FILENAME
21617    or NULL if not known.
21618    This routine tries to keep line numbers from identical absolute and
21619    relative file names in a common subfile.
21620
21621    Using the `list' example from the GDB testsuite, which resides in
21622    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21623    of /srcdir/list0.c yields the following debugging information for list0.c:
21624
21625    DW_AT_name:          /srcdir/list0.c
21626    DW_AT_comp_dir:      /compdir
21627    files.files[0].name: list0.h
21628    files.files[0].dir:  /srcdir
21629    files.files[1].name: list0.c
21630    files.files[1].dir:  /srcdir
21631
21632    The line number information for list0.c has to end up in a single
21633    subfile, so that `break /srcdir/list0.c:1' works as expected.
21634    start_subfile will ensure that this happens provided that we pass the
21635    concatenation of files.files[1].dir and files.files[1].name as the
21636    subfile's name.  */
21637
21638 static void
21639 dwarf2_start_subfile (const char *filename, const char *dirname)
21640 {
21641   char *copy = NULL;
21642
21643   /* In order not to lose the line information directory,
21644      we concatenate it to the filename when it makes sense.
21645      Note that the Dwarf3 standard says (speaking of filenames in line
21646      information): ``The directory index is ignored for file names
21647      that represent full path names''.  Thus ignoring dirname in the
21648      `else' branch below isn't an issue.  */
21649
21650   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21651     {
21652       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21653       filename = copy;
21654     }
21655
21656   start_subfile (filename);
21657
21658   if (copy != NULL)
21659     xfree (copy);
21660 }
21661
21662 /* Start a symtab for DWARF.
21663    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21664
21665 static struct compunit_symtab *
21666 dwarf2_start_symtab (struct dwarf2_cu *cu,
21667                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21668 {
21669   struct compunit_symtab *cust
21670     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21671                     low_pc, cu->language);
21672
21673   record_debugformat ("DWARF 2");
21674   record_producer (cu->producer);
21675
21676   /* We assume that we're processing GCC output.  */
21677   processing_gcc_compilation = 2;
21678
21679   cu->processing_has_namespace_info = 0;
21680
21681   return cust;
21682 }
21683
21684 static void
21685 var_decode_location (struct attribute *attr, struct symbol *sym,
21686                      struct dwarf2_cu *cu)
21687 {
21688   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21689   struct comp_unit_head *cu_header = &cu->header;
21690
21691   /* NOTE drow/2003-01-30: There used to be a comment and some special
21692      code here to turn a symbol with DW_AT_external and a
21693      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21694      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21695      with some versions of binutils) where shared libraries could have
21696      relocations against symbols in their debug information - the
21697      minimal symbol would have the right address, but the debug info
21698      would not.  It's no longer necessary, because we will explicitly
21699      apply relocations when we read in the debug information now.  */
21700
21701   /* A DW_AT_location attribute with no contents indicates that a
21702      variable has been optimized away.  */
21703   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21704     {
21705       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21706       return;
21707     }
21708
21709   /* Handle one degenerate form of location expression specially, to
21710      preserve GDB's previous behavior when section offsets are
21711      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21712      then mark this symbol as LOC_STATIC.  */
21713
21714   if (attr_form_is_block (attr)
21715       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21716            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21717           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21718               && (DW_BLOCK (attr)->size
21719                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21720     {
21721       unsigned int dummy;
21722
21723       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21724         SYMBOL_VALUE_ADDRESS (sym) =
21725           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21726       else
21727         SYMBOL_VALUE_ADDRESS (sym) =
21728           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21729       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21730       fixup_symbol_section (sym, objfile);
21731       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21732                                               SYMBOL_SECTION (sym));
21733       return;
21734     }
21735
21736   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21737      expression evaluator, and use LOC_COMPUTED only when necessary
21738      (i.e. when the value of a register or memory location is
21739      referenced, or a thread-local block, etc.).  Then again, it might
21740      not be worthwhile.  I'm assuming that it isn't unless performance
21741      or memory numbers show me otherwise.  */
21742
21743   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21744
21745   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21746     cu->has_loclist = 1;
21747 }
21748
21749 /* Given a pointer to a DWARF information entry, figure out if we need
21750    to make a symbol table entry for it, and if so, create a new entry
21751    and return a pointer to it.
21752    If TYPE is NULL, determine symbol type from the die, otherwise
21753    used the passed type.
21754    If SPACE is not NULL, use it to hold the new symbol.  If it is
21755    NULL, allocate a new symbol on the objfile's obstack.  */
21756
21757 static struct symbol *
21758 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21759             struct symbol *space)
21760 {
21761   struct dwarf2_per_objfile *dwarf2_per_objfile
21762     = cu->per_cu->dwarf2_per_objfile;
21763   struct objfile *objfile = dwarf2_per_objfile->objfile;
21764   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21765   struct symbol *sym = NULL;
21766   const char *name;
21767   struct attribute *attr = NULL;
21768   struct attribute *attr2 = NULL;
21769   CORE_ADDR baseaddr;
21770   struct pending **list_to_add = NULL;
21771
21772   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21773
21774   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21775
21776   name = dwarf2_name (die, cu);
21777   if (name)
21778     {
21779       const char *linkagename;
21780       int suppress_add = 0;
21781
21782       if (space)
21783         sym = space;
21784       else
21785         sym = allocate_symbol (objfile);
21786       OBJSTAT (objfile, n_syms++);
21787
21788       /* Cache this symbol's name and the name's demangled form (if any).  */
21789       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21790       linkagename = dwarf2_physname (name, die, cu);
21791       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21792
21793       /* Fortran does not have mangling standard and the mangling does differ
21794          between gfortran, iFort etc.  */
21795       if (cu->language == language_fortran
21796           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21797         symbol_set_demangled_name (&(sym->ginfo),
21798                                    dwarf2_full_name (name, die, cu),
21799                                    NULL);
21800
21801       /* Default assumptions.
21802          Use the passed type or decode it from the die.  */
21803       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21804       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21805       if (type != NULL)
21806         SYMBOL_TYPE (sym) = type;
21807       else
21808         SYMBOL_TYPE (sym) = die_type (die, cu);
21809       attr = dwarf2_attr (die,
21810                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21811                           cu);
21812       if (attr)
21813         {
21814           SYMBOL_LINE (sym) = DW_UNSND (attr);
21815         }
21816
21817       attr = dwarf2_attr (die,
21818                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21819                           cu);
21820       if (attr)
21821         {
21822           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21823           struct file_entry *fe;
21824
21825           if (cu->line_header != NULL)
21826             fe = cu->line_header->file_name_at (file_index);
21827           else
21828             fe = NULL;
21829
21830           if (fe == NULL)
21831             complaint (&symfile_complaints,
21832                        _("file index out of range"));
21833           else
21834             symbol_set_symtab (sym, fe->symtab);
21835         }
21836
21837       switch (die->tag)
21838         {
21839         case DW_TAG_label:
21840           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21841           if (attr)
21842             {
21843               CORE_ADDR addr;
21844
21845               addr = attr_value_as_address (attr);
21846               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21847               SYMBOL_VALUE_ADDRESS (sym) = addr;
21848             }
21849           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21850           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21851           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21852           add_symbol_to_list (sym, cu->list_in_scope);
21853           break;
21854         case DW_TAG_subprogram:
21855           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21856              finish_block.  */
21857           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21858           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21859           if ((attr2 && (DW_UNSND (attr2) != 0))
21860               || cu->language == language_ada)
21861             {
21862               /* Subprograms marked external are stored as a global symbol.
21863                  Ada subprograms, whether marked external or not, are always
21864                  stored as a global symbol, because we want to be able to
21865                  access them globally.  For instance, we want to be able
21866                  to break on a nested subprogram without having to
21867                  specify the context.  */
21868               list_to_add = &global_symbols;
21869             }
21870           else
21871             {
21872               list_to_add = cu->list_in_scope;
21873             }
21874           break;
21875         case DW_TAG_inlined_subroutine:
21876           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21877              finish_block.  */
21878           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21879           SYMBOL_INLINED (sym) = 1;
21880           list_to_add = cu->list_in_scope;
21881           break;
21882         case DW_TAG_template_value_param:
21883           suppress_add = 1;
21884           /* Fall through.  */
21885         case DW_TAG_constant:
21886         case DW_TAG_variable:
21887         case DW_TAG_member:
21888           /* Compilation with minimal debug info may result in
21889              variables with missing type entries.  Change the
21890              misleading `void' type to something sensible.  */
21891           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21892             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21893
21894           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21895           /* In the case of DW_TAG_member, we should only be called for
21896              static const members.  */
21897           if (die->tag == DW_TAG_member)
21898             {
21899               /* dwarf2_add_field uses die_is_declaration,
21900                  so we do the same.  */
21901               gdb_assert (die_is_declaration (die, cu));
21902               gdb_assert (attr);
21903             }
21904           if (attr)
21905             {
21906               dwarf2_const_value (attr, sym, cu);
21907               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21908               if (!suppress_add)
21909                 {
21910                   if (attr2 && (DW_UNSND (attr2) != 0))
21911                     list_to_add = &global_symbols;
21912                   else
21913                     list_to_add = cu->list_in_scope;
21914                 }
21915               break;
21916             }
21917           attr = dwarf2_attr (die, DW_AT_location, cu);
21918           if (attr)
21919             {
21920               var_decode_location (attr, sym, cu);
21921               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21922
21923               /* Fortran explicitly imports any global symbols to the local
21924                  scope by DW_TAG_common_block.  */
21925               if (cu->language == language_fortran && die->parent
21926                   && die->parent->tag == DW_TAG_common_block)
21927                 attr2 = NULL;
21928
21929               if (SYMBOL_CLASS (sym) == LOC_STATIC
21930                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21931                   && !dwarf2_per_objfile->has_section_at_zero)
21932                 {
21933                   /* When a static variable is eliminated by the linker,
21934                      the corresponding debug information is not stripped
21935                      out, but the variable address is set to null;
21936                      do not add such variables into symbol table.  */
21937                 }
21938               else if (attr2 && (DW_UNSND (attr2) != 0))
21939                 {
21940                   /* Workaround gfortran PR debug/40040 - it uses
21941                      DW_AT_location for variables in -fPIC libraries which may
21942                      get overriden by other libraries/executable and get
21943                      a different address.  Resolve it by the minimal symbol
21944                      which may come from inferior's executable using copy
21945                      relocation.  Make this workaround only for gfortran as for
21946                      other compilers GDB cannot guess the minimal symbol
21947                      Fortran mangling kind.  */
21948                   if (cu->language == language_fortran && die->parent
21949                       && die->parent->tag == DW_TAG_module
21950                       && cu->producer
21951                       && startswith (cu->producer, "GNU Fortran"))
21952                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21953
21954                   /* A variable with DW_AT_external is never static,
21955                      but it may be block-scoped.  */
21956                   list_to_add = (cu->list_in_scope == &file_symbols
21957                                  ? &global_symbols : cu->list_in_scope);
21958                 }
21959               else
21960                 list_to_add = cu->list_in_scope;
21961             }
21962           else
21963             {
21964               /* We do not know the address of this symbol.
21965                  If it is an external symbol and we have type information
21966                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21967                  The address of the variable will then be determined from
21968                  the minimal symbol table whenever the variable is
21969                  referenced.  */
21970               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21971
21972               /* Fortran explicitly imports any global symbols to the local
21973                  scope by DW_TAG_common_block.  */
21974               if (cu->language == language_fortran && die->parent
21975                   && die->parent->tag == DW_TAG_common_block)
21976                 {
21977                   /* SYMBOL_CLASS doesn't matter here because
21978                      read_common_block is going to reset it.  */
21979                   if (!suppress_add)
21980                     list_to_add = cu->list_in_scope;
21981                 }
21982               else if (attr2 && (DW_UNSND (attr2) != 0)
21983                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21984                 {
21985                   /* A variable with DW_AT_external is never static, but it
21986                      may be block-scoped.  */
21987                   list_to_add = (cu->list_in_scope == &file_symbols
21988                                  ? &global_symbols : cu->list_in_scope);
21989
21990                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21991                 }
21992               else if (!die_is_declaration (die, cu))
21993                 {
21994                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21995                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21996                   if (!suppress_add)
21997                     list_to_add = cu->list_in_scope;
21998                 }
21999             }
22000           break;
22001         case DW_TAG_formal_parameter:
22002           /* If we are inside a function, mark this as an argument.  If
22003              not, we might be looking at an argument to an inlined function
22004              when we do not have enough information to show inlined frames;
22005              pretend it's a local variable in that case so that the user can
22006              still see it.  */
22007           if (context_stack_depth > 0
22008               && context_stack[context_stack_depth - 1].name != NULL)
22009             SYMBOL_IS_ARGUMENT (sym) = 1;
22010           attr = dwarf2_attr (die, DW_AT_location, cu);
22011           if (attr)
22012             {
22013               var_decode_location (attr, sym, cu);
22014             }
22015           attr = dwarf2_attr (die, DW_AT_const_value, cu);
22016           if (attr)
22017             {
22018               dwarf2_const_value (attr, sym, cu);
22019             }
22020
22021           list_to_add = cu->list_in_scope;
22022           break;
22023         case DW_TAG_unspecified_parameters:
22024           /* From varargs functions; gdb doesn't seem to have any
22025              interest in this information, so just ignore it for now.
22026              (FIXME?) */
22027           break;
22028         case DW_TAG_template_type_param:
22029           suppress_add = 1;
22030           /* Fall through.  */
22031         case DW_TAG_class_type:
22032         case DW_TAG_interface_type:
22033         case DW_TAG_structure_type:
22034         case DW_TAG_union_type:
22035         case DW_TAG_set_type:
22036         case DW_TAG_enumeration_type:
22037           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22038           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
22039
22040           {
22041             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
22042                really ever be static objects: otherwise, if you try
22043                to, say, break of a class's method and you're in a file
22044                which doesn't mention that class, it won't work unless
22045                the check for all static symbols in lookup_symbol_aux
22046                saves you.  See the OtherFileClass tests in
22047                gdb.c++/namespace.exp.  */
22048
22049             if (!suppress_add)
22050               {
22051                 list_to_add = (cu->list_in_scope == &file_symbols
22052                                && cu->language == language_cplus
22053                                ? &global_symbols : cu->list_in_scope);
22054
22055                 /* The semantics of C++ state that "struct foo {
22056                    ... }" also defines a typedef for "foo".  */
22057                 if (cu->language == language_cplus
22058                     || cu->language == language_ada
22059                     || cu->language == language_d
22060                     || cu->language == language_rust)
22061                   {
22062                     /* The symbol's name is already allocated along
22063                        with this objfile, so we don't need to
22064                        duplicate it for the type.  */
22065                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
22066                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
22067                   }
22068               }
22069           }
22070           break;
22071         case DW_TAG_typedef:
22072           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22073           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
22074           list_to_add = cu->list_in_scope;
22075           break;
22076         case DW_TAG_base_type:
22077         case DW_TAG_subrange_type:
22078           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22079           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
22080           list_to_add = cu->list_in_scope;
22081           break;
22082         case DW_TAG_enumerator:
22083           attr = dwarf2_attr (die, DW_AT_const_value, cu);
22084           if (attr)
22085             {
22086               dwarf2_const_value (attr, sym, cu);
22087             }
22088           {
22089             /* NOTE: carlton/2003-11-10: See comment above in the
22090                DW_TAG_class_type, etc. block.  */
22091
22092             list_to_add = (cu->list_in_scope == &file_symbols
22093                            && cu->language == language_cplus
22094                            ? &global_symbols : cu->list_in_scope);
22095           }
22096           break;
22097         case DW_TAG_imported_declaration:
22098         case DW_TAG_namespace:
22099           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22100           list_to_add = &global_symbols;
22101           break;
22102         case DW_TAG_module:
22103           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
22104           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
22105           list_to_add = &global_symbols;
22106           break;
22107         case DW_TAG_common_block:
22108           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
22109           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
22110           add_symbol_to_list (sym, cu->list_in_scope);
22111           break;
22112         default:
22113           /* Not a tag we recognize.  Hopefully we aren't processing
22114              trash data, but since we must specifically ignore things
22115              we don't recognize, there is nothing else we should do at
22116              this point.  */
22117           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
22118                      dwarf_tag_name (die->tag));
22119           break;
22120         }
22121
22122       if (suppress_add)
22123         {
22124           sym->hash_next = objfile->template_symbols;
22125           objfile->template_symbols = sym;
22126           list_to_add = NULL;
22127         }
22128
22129       if (list_to_add != NULL)
22130         add_symbol_to_list (sym, list_to_add);
22131
22132       /* For the benefit of old versions of GCC, check for anonymous
22133          namespaces based on the demangled name.  */
22134       if (!cu->processing_has_namespace_info
22135           && cu->language == language_cplus)
22136         cp_scan_for_anonymous_namespaces (sym, objfile);
22137     }
22138   return (sym);
22139 }
22140
22141 /* Given an attr with a DW_FORM_dataN value in host byte order,
22142    zero-extend it as appropriate for the symbol's type.  The DWARF
22143    standard (v4) is not entirely clear about the meaning of using
22144    DW_FORM_dataN for a constant with a signed type, where the type is
22145    wider than the data.  The conclusion of a discussion on the DWARF
22146    list was that this is unspecified.  We choose to always zero-extend
22147    because that is the interpretation long in use by GCC.  */
22148
22149 static gdb_byte *
22150 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
22151                          struct dwarf2_cu *cu, LONGEST *value, int bits)
22152 {
22153   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22154   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
22155                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
22156   LONGEST l = DW_UNSND (attr);
22157
22158   if (bits < sizeof (*value) * 8)
22159     {
22160       l &= ((LONGEST) 1 << bits) - 1;
22161       *value = l;
22162     }
22163   else if (bits == sizeof (*value) * 8)
22164     *value = l;
22165   else
22166     {
22167       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
22168       store_unsigned_integer (bytes, bits / 8, byte_order, l);
22169       return bytes;
22170     }
22171
22172   return NULL;
22173 }
22174
22175 /* Read a constant value from an attribute.  Either set *VALUE, or if
22176    the value does not fit in *VALUE, set *BYTES - either already
22177    allocated on the objfile obstack, or newly allocated on OBSTACK,
22178    or, set *BATON, if we translated the constant to a location
22179    expression.  */
22180
22181 static void
22182 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
22183                          const char *name, struct obstack *obstack,
22184                          struct dwarf2_cu *cu,
22185                          LONGEST *value, const gdb_byte **bytes,
22186                          struct dwarf2_locexpr_baton **baton)
22187 {
22188   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22189   struct comp_unit_head *cu_header = &cu->header;
22190   struct dwarf_block *blk;
22191   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
22192                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22193
22194   *value = 0;
22195   *bytes = NULL;
22196   *baton = NULL;
22197
22198   switch (attr->form)
22199     {
22200     case DW_FORM_addr:
22201     case DW_FORM_GNU_addr_index:
22202       {
22203         gdb_byte *data;
22204
22205         if (TYPE_LENGTH (type) != cu_header->addr_size)
22206           dwarf2_const_value_length_mismatch_complaint (name,
22207                                                         cu_header->addr_size,
22208                                                         TYPE_LENGTH (type));
22209         /* Symbols of this form are reasonably rare, so we just
22210            piggyback on the existing location code rather than writing
22211            a new implementation of symbol_computed_ops.  */
22212         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
22213         (*baton)->per_cu = cu->per_cu;
22214         gdb_assert ((*baton)->per_cu);
22215
22216         (*baton)->size = 2 + cu_header->addr_size;
22217         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
22218         (*baton)->data = data;
22219
22220         data[0] = DW_OP_addr;
22221         store_unsigned_integer (&data[1], cu_header->addr_size,
22222                                 byte_order, DW_ADDR (attr));
22223         data[cu_header->addr_size + 1] = DW_OP_stack_value;
22224       }
22225       break;
22226     case DW_FORM_string:
22227     case DW_FORM_strp:
22228     case DW_FORM_GNU_str_index:
22229     case DW_FORM_GNU_strp_alt:
22230       /* DW_STRING is already allocated on the objfile obstack, point
22231          directly to it.  */
22232       *bytes = (const gdb_byte *) DW_STRING (attr);
22233       break;
22234     case DW_FORM_block1:
22235     case DW_FORM_block2:
22236     case DW_FORM_block4:
22237     case DW_FORM_block:
22238     case DW_FORM_exprloc:
22239     case DW_FORM_data16:
22240       blk = DW_BLOCK (attr);
22241       if (TYPE_LENGTH (type) != blk->size)
22242         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
22243                                                       TYPE_LENGTH (type));
22244       *bytes = blk->data;
22245       break;
22246
22247       /* The DW_AT_const_value attributes are supposed to carry the
22248          symbol's value "represented as it would be on the target
22249          architecture."  By the time we get here, it's already been
22250          converted to host endianness, so we just need to sign- or
22251          zero-extend it as appropriate.  */
22252     case DW_FORM_data1:
22253       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
22254       break;
22255     case DW_FORM_data2:
22256       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
22257       break;
22258     case DW_FORM_data4:
22259       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
22260       break;
22261     case DW_FORM_data8:
22262       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22263       break;
22264
22265     case DW_FORM_sdata:
22266     case DW_FORM_implicit_const:
22267       *value = DW_SND (attr);
22268       break;
22269
22270     case DW_FORM_udata:
22271       *value = DW_UNSND (attr);
22272       break;
22273
22274     default:
22275       complaint (&symfile_complaints,
22276                  _("unsupported const value attribute form: '%s'"),
22277                  dwarf_form_name (attr->form));
22278       *value = 0;
22279       break;
22280     }
22281 }
22282
22283
22284 /* Copy constant value from an attribute to a symbol.  */
22285
22286 static void
22287 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22288                     struct dwarf2_cu *cu)
22289 {
22290   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22291   LONGEST value;
22292   const gdb_byte *bytes;
22293   struct dwarf2_locexpr_baton *baton;
22294
22295   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22296                            SYMBOL_PRINT_NAME (sym),
22297                            &objfile->objfile_obstack, cu,
22298                            &value, &bytes, &baton);
22299
22300   if (baton != NULL)
22301     {
22302       SYMBOL_LOCATION_BATON (sym) = baton;
22303       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22304     }
22305   else if (bytes != NULL)
22306      {
22307       SYMBOL_VALUE_BYTES (sym) = bytes;
22308       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22309     }
22310   else
22311     {
22312       SYMBOL_VALUE (sym) = value;
22313       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22314     }
22315 }
22316
22317 /* Return the type of the die in question using its DW_AT_type attribute.  */
22318
22319 static struct type *
22320 die_type (struct die_info *die, struct dwarf2_cu *cu)
22321 {
22322   struct attribute *type_attr;
22323
22324   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22325   if (!type_attr)
22326     {
22327       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22328       /* A missing DW_AT_type represents a void type.  */
22329       return objfile_type (objfile)->builtin_void;
22330     }
22331
22332   return lookup_die_type (die, type_attr, cu);
22333 }
22334
22335 /* True iff CU's producer generates GNAT Ada auxiliary information
22336    that allows to find parallel types through that information instead
22337    of having to do expensive parallel lookups by type name.  */
22338
22339 static int
22340 need_gnat_info (struct dwarf2_cu *cu)
22341 {
22342   /* Assume that the Ada compiler was GNAT, which always produces
22343      the auxiliary information.  */
22344   return (cu->language == language_ada);
22345 }
22346
22347 /* Return the auxiliary type of the die in question using its
22348    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22349    attribute is not present.  */
22350
22351 static struct type *
22352 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22353 {
22354   struct attribute *type_attr;
22355
22356   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22357   if (!type_attr)
22358     return NULL;
22359
22360   return lookup_die_type (die, type_attr, cu);
22361 }
22362
22363 /* If DIE has a descriptive_type attribute, then set the TYPE's
22364    descriptive type accordingly.  */
22365
22366 static void
22367 set_descriptive_type (struct type *type, struct die_info *die,
22368                       struct dwarf2_cu *cu)
22369 {
22370   struct type *descriptive_type = die_descriptive_type (die, cu);
22371
22372   if (descriptive_type)
22373     {
22374       ALLOCATE_GNAT_AUX_TYPE (type);
22375       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22376     }
22377 }
22378
22379 /* Return the containing type of the die in question using its
22380    DW_AT_containing_type attribute.  */
22381
22382 static struct type *
22383 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22384 {
22385   struct attribute *type_attr;
22386   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22387
22388   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22389   if (!type_attr)
22390     error (_("Dwarf Error: Problem turning containing type into gdb type "
22391              "[in module %s]"), objfile_name (objfile));
22392
22393   return lookup_die_type (die, type_attr, cu);
22394 }
22395
22396 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22397
22398 static struct type *
22399 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22400 {
22401   struct dwarf2_per_objfile *dwarf2_per_objfile
22402     = cu->per_cu->dwarf2_per_objfile;
22403   struct objfile *objfile = dwarf2_per_objfile->objfile;
22404   char *message, *saved;
22405
22406   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
22407                         objfile_name (objfile),
22408                         sect_offset_str (cu->header.sect_off),
22409                         sect_offset_str (die->sect_off));
22410   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22411                                   message, strlen (message));
22412   xfree (message);
22413
22414   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22415 }
22416
22417 /* Look up the type of DIE in CU using its type attribute ATTR.
22418    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22419    DW_AT_containing_type.
22420    If there is no type substitute an error marker.  */
22421
22422 static struct type *
22423 lookup_die_type (struct die_info *die, const struct attribute *attr,
22424                  struct dwarf2_cu *cu)
22425 {
22426   struct dwarf2_per_objfile *dwarf2_per_objfile
22427     = cu->per_cu->dwarf2_per_objfile;
22428   struct objfile *objfile = dwarf2_per_objfile->objfile;
22429   struct type *this_type;
22430
22431   gdb_assert (attr->name == DW_AT_type
22432               || attr->name == DW_AT_GNAT_descriptive_type
22433               || attr->name == DW_AT_containing_type);
22434
22435   /* First see if we have it cached.  */
22436
22437   if (attr->form == DW_FORM_GNU_ref_alt)
22438     {
22439       struct dwarf2_per_cu_data *per_cu;
22440       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22441
22442       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22443                                                  dwarf2_per_objfile);
22444       this_type = get_die_type_at_offset (sect_off, per_cu);
22445     }
22446   else if (attr_form_is_ref (attr))
22447     {
22448       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22449
22450       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22451     }
22452   else if (attr->form == DW_FORM_ref_sig8)
22453     {
22454       ULONGEST signature = DW_SIGNATURE (attr);
22455
22456       return get_signatured_type (die, signature, cu);
22457     }
22458   else
22459     {
22460       complaint (&symfile_complaints,
22461                  _("Dwarf Error: Bad type attribute %s in DIE"
22462                    " at %s [in module %s]"),
22463                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22464                  objfile_name (objfile));
22465       return build_error_marker_type (cu, die);
22466     }
22467
22468   /* If not cached we need to read it in.  */
22469
22470   if (this_type == NULL)
22471     {
22472       struct die_info *type_die = NULL;
22473       struct dwarf2_cu *type_cu = cu;
22474
22475       if (attr_form_is_ref (attr))
22476         type_die = follow_die_ref (die, attr, &type_cu);
22477       if (type_die == NULL)
22478         return build_error_marker_type (cu, die);
22479       /* If we find the type now, it's probably because the type came
22480          from an inter-CU reference and the type's CU got expanded before
22481          ours.  */
22482       this_type = read_type_die (type_die, type_cu);
22483     }
22484
22485   /* If we still don't have a type use an error marker.  */
22486
22487   if (this_type == NULL)
22488     return build_error_marker_type (cu, die);
22489
22490   return this_type;
22491 }
22492
22493 /* Return the type in DIE, CU.
22494    Returns NULL for invalid types.
22495
22496    This first does a lookup in die_type_hash,
22497    and only reads the die in if necessary.
22498
22499    NOTE: This can be called when reading in partial or full symbols.  */
22500
22501 static struct type *
22502 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22503 {
22504   struct type *this_type;
22505
22506   this_type = get_die_type (die, cu);
22507   if (this_type)
22508     return this_type;
22509
22510   return read_type_die_1 (die, cu);
22511 }
22512
22513 /* Read the type in DIE, CU.
22514    Returns NULL for invalid types.  */
22515
22516 static struct type *
22517 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22518 {
22519   struct type *this_type = NULL;
22520
22521   switch (die->tag)
22522     {
22523     case DW_TAG_class_type:
22524     case DW_TAG_interface_type:
22525     case DW_TAG_structure_type:
22526     case DW_TAG_union_type:
22527       this_type = read_structure_type (die, cu);
22528       break;
22529     case DW_TAG_enumeration_type:
22530       this_type = read_enumeration_type (die, cu);
22531       break;
22532     case DW_TAG_subprogram:
22533     case DW_TAG_subroutine_type:
22534     case DW_TAG_inlined_subroutine:
22535       this_type = read_subroutine_type (die, cu);
22536       break;
22537     case DW_TAG_array_type:
22538       this_type = read_array_type (die, cu);
22539       break;
22540     case DW_TAG_set_type:
22541       this_type = read_set_type (die, cu);
22542       break;
22543     case DW_TAG_pointer_type:
22544       this_type = read_tag_pointer_type (die, cu);
22545       break;
22546     case DW_TAG_ptr_to_member_type:
22547       this_type = read_tag_ptr_to_member_type (die, cu);
22548       break;
22549     case DW_TAG_reference_type:
22550       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22551       break;
22552     case DW_TAG_rvalue_reference_type:
22553       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22554       break;
22555     case DW_TAG_const_type:
22556       this_type = read_tag_const_type (die, cu);
22557       break;
22558     case DW_TAG_volatile_type:
22559       this_type = read_tag_volatile_type (die, cu);
22560       break;
22561     case DW_TAG_restrict_type:
22562       this_type = read_tag_restrict_type (die, cu);
22563       break;
22564     case DW_TAG_string_type:
22565       this_type = read_tag_string_type (die, cu);
22566       break;
22567     case DW_TAG_typedef:
22568       this_type = read_typedef (die, cu);
22569       break;
22570     case DW_TAG_subrange_type:
22571       this_type = read_subrange_type (die, cu);
22572       break;
22573     case DW_TAG_base_type:
22574       this_type = read_base_type (die, cu);
22575       break;
22576     case DW_TAG_unspecified_type:
22577       this_type = read_unspecified_type (die, cu);
22578       break;
22579     case DW_TAG_namespace:
22580       this_type = read_namespace_type (die, cu);
22581       break;
22582     case DW_TAG_module:
22583       this_type = read_module_type (die, cu);
22584       break;
22585     case DW_TAG_atomic_type:
22586       this_type = read_tag_atomic_type (die, cu);
22587       break;
22588     default:
22589       complaint (&symfile_complaints,
22590                  _("unexpected tag in read_type_die: '%s'"),
22591                  dwarf_tag_name (die->tag));
22592       break;
22593     }
22594
22595   return this_type;
22596 }
22597
22598 /* See if we can figure out if the class lives in a namespace.  We do
22599    this by looking for a member function; its demangled name will
22600    contain namespace info, if there is any.
22601    Return the computed name or NULL.
22602    Space for the result is allocated on the objfile's obstack.
22603    This is the full-die version of guess_partial_die_structure_name.
22604    In this case we know DIE has no useful parent.  */
22605
22606 static char *
22607 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22608 {
22609   struct die_info *spec_die;
22610   struct dwarf2_cu *spec_cu;
22611   struct die_info *child;
22612   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22613
22614   spec_cu = cu;
22615   spec_die = die_specification (die, &spec_cu);
22616   if (spec_die != NULL)
22617     {
22618       die = spec_die;
22619       cu = spec_cu;
22620     }
22621
22622   for (child = die->child;
22623        child != NULL;
22624        child = child->sibling)
22625     {
22626       if (child->tag == DW_TAG_subprogram)
22627         {
22628           const char *linkage_name = dw2_linkage_name (child, cu);
22629
22630           if (linkage_name != NULL)
22631             {
22632               char *actual_name
22633                 = language_class_name_from_physname (cu->language_defn,
22634                                                      linkage_name);
22635               char *name = NULL;
22636
22637               if (actual_name != NULL)
22638                 {
22639                   const char *die_name = dwarf2_name (die, cu);
22640
22641                   if (die_name != NULL
22642                       && strcmp (die_name, actual_name) != 0)
22643                     {
22644                       /* Strip off the class name from the full name.
22645                          We want the prefix.  */
22646                       int die_name_len = strlen (die_name);
22647                       int actual_name_len = strlen (actual_name);
22648
22649                       /* Test for '::' as a sanity check.  */
22650                       if (actual_name_len > die_name_len + 2
22651                           && actual_name[actual_name_len
22652                                          - die_name_len - 1] == ':')
22653                         name = (char *) obstack_copy0 (
22654                           &objfile->per_bfd->storage_obstack,
22655                           actual_name, actual_name_len - die_name_len - 2);
22656                     }
22657                 }
22658               xfree (actual_name);
22659               return name;
22660             }
22661         }
22662     }
22663
22664   return NULL;
22665 }
22666
22667 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22668    prefix part in such case.  See
22669    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22670
22671 static const char *
22672 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22673 {
22674   struct attribute *attr;
22675   const char *base;
22676
22677   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22678       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22679     return NULL;
22680
22681   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22682     return NULL;
22683
22684   attr = dw2_linkage_name_attr (die, cu);
22685   if (attr == NULL || DW_STRING (attr) == NULL)
22686     return NULL;
22687
22688   /* dwarf2_name had to be already called.  */
22689   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22690
22691   /* Strip the base name, keep any leading namespaces/classes.  */
22692   base = strrchr (DW_STRING (attr), ':');
22693   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22694     return "";
22695
22696   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22697   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22698                                  DW_STRING (attr),
22699                                  &base[-1] - DW_STRING (attr));
22700 }
22701
22702 /* Return the name of the namespace/class that DIE is defined within,
22703    or "" if we can't tell.  The caller should not xfree the result.
22704
22705    For example, if we're within the method foo() in the following
22706    code:
22707
22708    namespace N {
22709      class C {
22710        void foo () {
22711        }
22712      };
22713    }
22714
22715    then determine_prefix on foo's die will return "N::C".  */
22716
22717 static const char *
22718 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22719 {
22720   struct dwarf2_per_objfile *dwarf2_per_objfile
22721     = cu->per_cu->dwarf2_per_objfile;
22722   struct die_info *parent, *spec_die;
22723   struct dwarf2_cu *spec_cu;
22724   struct type *parent_type;
22725   const char *retval;
22726
22727   if (cu->language != language_cplus
22728       && cu->language != language_fortran && cu->language != language_d
22729       && cu->language != language_rust)
22730     return "";
22731
22732   retval = anonymous_struct_prefix (die, cu);
22733   if (retval)
22734     return retval;
22735
22736   /* We have to be careful in the presence of DW_AT_specification.
22737      For example, with GCC 3.4, given the code
22738
22739      namespace N {
22740        void foo() {
22741          // Definition of N::foo.
22742        }
22743      }
22744
22745      then we'll have a tree of DIEs like this:
22746
22747      1: DW_TAG_compile_unit
22748        2: DW_TAG_namespace        // N
22749          3: DW_TAG_subprogram     // declaration of N::foo
22750        4: DW_TAG_subprogram       // definition of N::foo
22751             DW_AT_specification   // refers to die #3
22752
22753      Thus, when processing die #4, we have to pretend that we're in
22754      the context of its DW_AT_specification, namely the contex of die
22755      #3.  */
22756   spec_cu = cu;
22757   spec_die = die_specification (die, &spec_cu);
22758   if (spec_die == NULL)
22759     parent = die->parent;
22760   else
22761     {
22762       parent = spec_die->parent;
22763       cu = spec_cu;
22764     }
22765
22766   if (parent == NULL)
22767     return "";
22768   else if (parent->building_fullname)
22769     {
22770       const char *name;
22771       const char *parent_name;
22772
22773       /* It has been seen on RealView 2.2 built binaries,
22774          DW_TAG_template_type_param types actually _defined_ as
22775          children of the parent class:
22776
22777          enum E {};
22778          template class <class Enum> Class{};
22779          Class<enum E> class_e;
22780
22781          1: DW_TAG_class_type (Class)
22782            2: DW_TAG_enumeration_type (E)
22783              3: DW_TAG_enumerator (enum1:0)
22784              3: DW_TAG_enumerator (enum2:1)
22785              ...
22786            2: DW_TAG_template_type_param
22787               DW_AT_type  DW_FORM_ref_udata (E)
22788
22789          Besides being broken debug info, it can put GDB into an
22790          infinite loop.  Consider:
22791
22792          When we're building the full name for Class<E>, we'll start
22793          at Class, and go look over its template type parameters,
22794          finding E.  We'll then try to build the full name of E, and
22795          reach here.  We're now trying to build the full name of E,
22796          and look over the parent DIE for containing scope.  In the
22797          broken case, if we followed the parent DIE of E, we'd again
22798          find Class, and once again go look at its template type
22799          arguments, etc., etc.  Simply don't consider such parent die
22800          as source-level parent of this die (it can't be, the language
22801          doesn't allow it), and break the loop here.  */
22802       name = dwarf2_name (die, cu);
22803       parent_name = dwarf2_name (parent, cu);
22804       complaint (&symfile_complaints,
22805                  _("template param type '%s' defined within parent '%s'"),
22806                  name ? name : "<unknown>",
22807                  parent_name ? parent_name : "<unknown>");
22808       return "";
22809     }
22810   else
22811     switch (parent->tag)
22812       {
22813       case DW_TAG_namespace:
22814         parent_type = read_type_die (parent, cu);
22815         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22816            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22817            Work around this problem here.  */
22818         if (cu->language == language_cplus
22819             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22820           return "";
22821         /* We give a name to even anonymous namespaces.  */
22822         return TYPE_TAG_NAME (parent_type);
22823       case DW_TAG_class_type:
22824       case DW_TAG_interface_type:
22825       case DW_TAG_structure_type:
22826       case DW_TAG_union_type:
22827       case DW_TAG_module:
22828         parent_type = read_type_die (parent, cu);
22829         if (TYPE_TAG_NAME (parent_type) != NULL)
22830           return TYPE_TAG_NAME (parent_type);
22831         else
22832           /* An anonymous structure is only allowed non-static data
22833              members; no typedefs, no member functions, et cetera.
22834              So it does not need a prefix.  */
22835           return "";
22836       case DW_TAG_compile_unit:
22837       case DW_TAG_partial_unit:
22838         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22839         if (cu->language == language_cplus
22840             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22841             && die->child != NULL
22842             && (die->tag == DW_TAG_class_type
22843                 || die->tag == DW_TAG_structure_type
22844                 || die->tag == DW_TAG_union_type))
22845           {
22846             char *name = guess_full_die_structure_name (die, cu);
22847             if (name != NULL)
22848               return name;
22849           }
22850         return "";
22851       case DW_TAG_enumeration_type:
22852         parent_type = read_type_die (parent, cu);
22853         if (TYPE_DECLARED_CLASS (parent_type))
22854           {
22855             if (TYPE_TAG_NAME (parent_type) != NULL)
22856               return TYPE_TAG_NAME (parent_type);
22857             return "";
22858           }
22859         /* Fall through.  */
22860       default:
22861         return determine_prefix (parent, cu);
22862       }
22863 }
22864
22865 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22866    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22867    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22868    an obconcat, otherwise allocate storage for the result.  The CU argument is
22869    used to determine the language and hence, the appropriate separator.  */
22870
22871 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22872
22873 static char *
22874 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22875                  int physname, struct dwarf2_cu *cu)
22876 {
22877   const char *lead = "";
22878   const char *sep;
22879
22880   if (suffix == NULL || suffix[0] == '\0'
22881       || prefix == NULL || prefix[0] == '\0')
22882     sep = "";
22883   else if (cu->language == language_d)
22884     {
22885       /* For D, the 'main' function could be defined in any module, but it
22886          should never be prefixed.  */
22887       if (strcmp (suffix, "D main") == 0)
22888         {
22889           prefix = "";
22890           sep = "";
22891         }
22892       else
22893         sep = ".";
22894     }
22895   else if (cu->language == language_fortran && physname)
22896     {
22897       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22898          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22899
22900       lead = "__";
22901       sep = "_MOD_";
22902     }
22903   else
22904     sep = "::";
22905
22906   if (prefix == NULL)
22907     prefix = "";
22908   if (suffix == NULL)
22909     suffix = "";
22910
22911   if (obs == NULL)
22912     {
22913       char *retval
22914         = ((char *)
22915            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22916
22917       strcpy (retval, lead);
22918       strcat (retval, prefix);
22919       strcat (retval, sep);
22920       strcat (retval, suffix);
22921       return retval;
22922     }
22923   else
22924     {
22925       /* We have an obstack.  */
22926       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22927     }
22928 }
22929
22930 /* Return sibling of die, NULL if no sibling.  */
22931
22932 static struct die_info *
22933 sibling_die (struct die_info *die)
22934 {
22935   return die->sibling;
22936 }
22937
22938 /* Get name of a die, return NULL if not found.  */
22939
22940 static const char *
22941 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22942                           struct obstack *obstack)
22943 {
22944   if (name && cu->language == language_cplus)
22945     {
22946       std::string canon_name = cp_canonicalize_string (name);
22947
22948       if (!canon_name.empty ())
22949         {
22950           if (canon_name != name)
22951             name = (const char *) obstack_copy0 (obstack,
22952                                                  canon_name.c_str (),
22953                                                  canon_name.length ());
22954         }
22955     }
22956
22957   return name;
22958 }
22959
22960 /* Get name of a die, return NULL if not found.
22961    Anonymous namespaces are converted to their magic string.  */
22962
22963 static const char *
22964 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22965 {
22966   struct attribute *attr;
22967   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22968
22969   attr = dwarf2_attr (die, DW_AT_name, cu);
22970   if ((!attr || !DW_STRING (attr))
22971       && die->tag != DW_TAG_namespace
22972       && die->tag != DW_TAG_class_type
22973       && die->tag != DW_TAG_interface_type
22974       && die->tag != DW_TAG_structure_type
22975       && die->tag != DW_TAG_union_type)
22976     return NULL;
22977
22978   switch (die->tag)
22979     {
22980     case DW_TAG_compile_unit:
22981     case DW_TAG_partial_unit:
22982       /* Compilation units have a DW_AT_name that is a filename, not
22983          a source language identifier.  */
22984     case DW_TAG_enumeration_type:
22985     case DW_TAG_enumerator:
22986       /* These tags always have simple identifiers already; no need
22987          to canonicalize them.  */
22988       return DW_STRING (attr);
22989
22990     case DW_TAG_namespace:
22991       if (attr != NULL && DW_STRING (attr) != NULL)
22992         return DW_STRING (attr);
22993       return CP_ANONYMOUS_NAMESPACE_STR;
22994
22995     case DW_TAG_class_type:
22996     case DW_TAG_interface_type:
22997     case DW_TAG_structure_type:
22998     case DW_TAG_union_type:
22999       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
23000          structures or unions.  These were of the form "._%d" in GCC 4.1,
23001          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
23002          and GCC 4.4.  We work around this problem by ignoring these.  */
23003       if (attr && DW_STRING (attr)
23004           && (startswith (DW_STRING (attr), "._")
23005               || startswith (DW_STRING (attr), "<anonymous")))
23006         return NULL;
23007
23008       /* GCC might emit a nameless typedef that has a linkage name.  See
23009          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
23010       if (!attr || DW_STRING (attr) == NULL)
23011         {
23012           char *demangled = NULL;
23013
23014           attr = dw2_linkage_name_attr (die, cu);
23015           if (attr == NULL || DW_STRING (attr) == NULL)
23016             return NULL;
23017
23018           /* Avoid demangling DW_STRING (attr) the second time on a second
23019              call for the same DIE.  */
23020           if (!DW_STRING_IS_CANONICAL (attr))
23021             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
23022
23023           if (demangled)
23024             {
23025               const char *base;
23026
23027               /* FIXME: we already did this for the partial symbol... */
23028               DW_STRING (attr)
23029                 = ((const char *)
23030                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
23031                                   demangled, strlen (demangled)));
23032               DW_STRING_IS_CANONICAL (attr) = 1;
23033               xfree (demangled);
23034
23035               /* Strip any leading namespaces/classes, keep only the base name.
23036                  DW_AT_name for named DIEs does not contain the prefixes.  */
23037               base = strrchr (DW_STRING (attr), ':');
23038               if (base && base > DW_STRING (attr) && base[-1] == ':')
23039                 return &base[1];
23040               else
23041                 return DW_STRING (attr);
23042             }
23043         }
23044       break;
23045
23046     default:
23047       break;
23048     }
23049
23050   if (!DW_STRING_IS_CANONICAL (attr))
23051     {
23052       DW_STRING (attr)
23053         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
23054                                     &objfile->per_bfd->storage_obstack);
23055       DW_STRING_IS_CANONICAL (attr) = 1;
23056     }
23057   return DW_STRING (attr);
23058 }
23059
23060 /* Return the die that this die in an extension of, or NULL if there
23061    is none.  *EXT_CU is the CU containing DIE on input, and the CU
23062    containing the return value on output.  */
23063
23064 static struct die_info *
23065 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
23066 {
23067   struct attribute *attr;
23068
23069   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
23070   if (attr == NULL)
23071     return NULL;
23072
23073   return follow_die_ref (die, attr, ext_cu);
23074 }
23075
23076 /* Convert a DIE tag into its string name.  */
23077
23078 static const char *
23079 dwarf_tag_name (unsigned tag)
23080 {
23081   const char *name = get_DW_TAG_name (tag);
23082
23083   if (name == NULL)
23084     return "DW_TAG_<unknown>";
23085
23086   return name;
23087 }
23088
23089 /* Convert a DWARF attribute code into its string name.  */
23090
23091 static const char *
23092 dwarf_attr_name (unsigned attr)
23093 {
23094   const char *name;
23095
23096 #ifdef MIPS /* collides with DW_AT_HP_block_index */
23097   if (attr == DW_AT_MIPS_fde)
23098     return "DW_AT_MIPS_fde";
23099 #else
23100   if (attr == DW_AT_HP_block_index)
23101     return "DW_AT_HP_block_index";
23102 #endif
23103
23104   name = get_DW_AT_name (attr);
23105
23106   if (name == NULL)
23107     return "DW_AT_<unknown>";
23108
23109   return name;
23110 }
23111
23112 /* Convert a DWARF value form code into its string name.  */
23113
23114 static const char *
23115 dwarf_form_name (unsigned form)
23116 {
23117   const char *name = get_DW_FORM_name (form);
23118
23119   if (name == NULL)
23120     return "DW_FORM_<unknown>";
23121
23122   return name;
23123 }
23124
23125 static const char *
23126 dwarf_bool_name (unsigned mybool)
23127 {
23128   if (mybool)
23129     return "TRUE";
23130   else
23131     return "FALSE";
23132 }
23133
23134 /* Convert a DWARF type code into its string name.  */
23135
23136 static const char *
23137 dwarf_type_encoding_name (unsigned enc)
23138 {
23139   const char *name = get_DW_ATE_name (enc);
23140
23141   if (name == NULL)
23142     return "DW_ATE_<unknown>";
23143
23144   return name;
23145 }
23146
23147 static void
23148 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
23149 {
23150   unsigned int i;
23151
23152   print_spaces (indent, f);
23153   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
23154                       dwarf_tag_name (die->tag), die->abbrev,
23155                       sect_offset_str (die->sect_off));
23156
23157   if (die->parent != NULL)
23158     {
23159       print_spaces (indent, f);
23160       fprintf_unfiltered (f, "  parent at offset: %s\n",
23161                           sect_offset_str (die->parent->sect_off));
23162     }
23163
23164   print_spaces (indent, f);
23165   fprintf_unfiltered (f, "  has children: %s\n",
23166            dwarf_bool_name (die->child != NULL));
23167
23168   print_spaces (indent, f);
23169   fprintf_unfiltered (f, "  attributes:\n");
23170
23171   for (i = 0; i < die->num_attrs; ++i)
23172     {
23173       print_spaces (indent, f);
23174       fprintf_unfiltered (f, "    %s (%s) ",
23175                dwarf_attr_name (die->attrs[i].name),
23176                dwarf_form_name (die->attrs[i].form));
23177
23178       switch (die->attrs[i].form)
23179         {
23180         case DW_FORM_addr:
23181         case DW_FORM_GNU_addr_index:
23182           fprintf_unfiltered (f, "address: ");
23183           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
23184           break;
23185         case DW_FORM_block2:
23186         case DW_FORM_block4:
23187         case DW_FORM_block:
23188         case DW_FORM_block1:
23189           fprintf_unfiltered (f, "block: size %s",
23190                               pulongest (DW_BLOCK (&die->attrs[i])->size));
23191           break;
23192         case DW_FORM_exprloc:
23193           fprintf_unfiltered (f, "expression: size %s",
23194                               pulongest (DW_BLOCK (&die->attrs[i])->size));
23195           break;
23196         case DW_FORM_data16:
23197           fprintf_unfiltered (f, "constant of 16 bytes");
23198           break;
23199         case DW_FORM_ref_addr:
23200           fprintf_unfiltered (f, "ref address: ");
23201           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
23202           break;
23203         case DW_FORM_GNU_ref_alt:
23204           fprintf_unfiltered (f, "alt ref address: ");
23205           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
23206           break;
23207         case DW_FORM_ref1:
23208         case DW_FORM_ref2:
23209         case DW_FORM_ref4:
23210         case DW_FORM_ref8:
23211         case DW_FORM_ref_udata:
23212           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
23213                               (long) (DW_UNSND (&die->attrs[i])));
23214           break;
23215         case DW_FORM_data1:
23216         case DW_FORM_data2:
23217         case DW_FORM_data4:
23218         case DW_FORM_data8:
23219         case DW_FORM_udata:
23220         case DW_FORM_sdata:
23221           fprintf_unfiltered (f, "constant: %s",
23222                               pulongest (DW_UNSND (&die->attrs[i])));
23223           break;
23224         case DW_FORM_sec_offset:
23225           fprintf_unfiltered (f, "section offset: %s",
23226                               pulongest (DW_UNSND (&die->attrs[i])));
23227           break;
23228         case DW_FORM_ref_sig8:
23229           fprintf_unfiltered (f, "signature: %s",
23230                               hex_string (DW_SIGNATURE (&die->attrs[i])));
23231           break;
23232         case DW_FORM_string:
23233         case DW_FORM_strp:
23234         case DW_FORM_line_strp:
23235         case DW_FORM_GNU_str_index:
23236         case DW_FORM_GNU_strp_alt:
23237           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
23238                    DW_STRING (&die->attrs[i])
23239                    ? DW_STRING (&die->attrs[i]) : "",
23240                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
23241           break;
23242         case DW_FORM_flag:
23243           if (DW_UNSND (&die->attrs[i]))
23244             fprintf_unfiltered (f, "flag: TRUE");
23245           else
23246             fprintf_unfiltered (f, "flag: FALSE");
23247           break;
23248         case DW_FORM_flag_present:
23249           fprintf_unfiltered (f, "flag: TRUE");
23250           break;
23251         case DW_FORM_indirect:
23252           /* The reader will have reduced the indirect form to
23253              the "base form" so this form should not occur.  */
23254           fprintf_unfiltered (f, 
23255                               "unexpected attribute form: DW_FORM_indirect");
23256           break;
23257         case DW_FORM_implicit_const:
23258           fprintf_unfiltered (f, "constant: %s",
23259                               plongest (DW_SND (&die->attrs[i])));
23260           break;
23261         default:
23262           fprintf_unfiltered (f, "unsupported attribute form: %d.",
23263                    die->attrs[i].form);
23264           break;
23265         }
23266       fprintf_unfiltered (f, "\n");
23267     }
23268 }
23269
23270 static void
23271 dump_die_for_error (struct die_info *die)
23272 {
23273   dump_die_shallow (gdb_stderr, 0, die);
23274 }
23275
23276 static void
23277 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23278 {
23279   int indent = level * 4;
23280
23281   gdb_assert (die != NULL);
23282
23283   if (level >= max_level)
23284     return;
23285
23286   dump_die_shallow (f, indent, die);
23287
23288   if (die->child != NULL)
23289     {
23290       print_spaces (indent, f);
23291       fprintf_unfiltered (f, "  Children:");
23292       if (level + 1 < max_level)
23293         {
23294           fprintf_unfiltered (f, "\n");
23295           dump_die_1 (f, level + 1, max_level, die->child);
23296         }
23297       else
23298         {
23299           fprintf_unfiltered (f,
23300                               " [not printed, max nesting level reached]\n");
23301         }
23302     }
23303
23304   if (die->sibling != NULL && level > 0)
23305     {
23306       dump_die_1 (f, level, max_level, die->sibling);
23307     }
23308 }
23309
23310 /* This is called from the pdie macro in gdbinit.in.
23311    It's not static so gcc will keep a copy callable from gdb.  */
23312
23313 void
23314 dump_die (struct die_info *die, int max_level)
23315 {
23316   dump_die_1 (gdb_stdlog, 0, max_level, die);
23317 }
23318
23319 static void
23320 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23321 {
23322   void **slot;
23323
23324   slot = htab_find_slot_with_hash (cu->die_hash, die,
23325                                    to_underlying (die->sect_off),
23326                                    INSERT);
23327
23328   *slot = die;
23329 }
23330
23331 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
23332    required kind.  */
23333
23334 static sect_offset
23335 dwarf2_get_ref_die_offset (const struct attribute *attr)
23336 {
23337   if (attr_form_is_ref (attr))
23338     return (sect_offset) DW_UNSND (attr);
23339
23340   complaint (&symfile_complaints,
23341              _("unsupported die ref attribute form: '%s'"),
23342              dwarf_form_name (attr->form));
23343   return {};
23344 }
23345
23346 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
23347  * the value held by the attribute is not constant.  */
23348
23349 static LONGEST
23350 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
23351 {
23352   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
23353     return DW_SND (attr);
23354   else if (attr->form == DW_FORM_udata
23355            || attr->form == DW_FORM_data1
23356            || attr->form == DW_FORM_data2
23357            || attr->form == DW_FORM_data4
23358            || attr->form == DW_FORM_data8)
23359     return DW_UNSND (attr);
23360   else
23361     {
23362       /* For DW_FORM_data16 see attr_form_is_constant.  */
23363       complaint (&symfile_complaints,
23364                  _("Attribute value is not a constant (%s)"),
23365                  dwarf_form_name (attr->form));
23366       return default_value;
23367     }
23368 }
23369
23370 /* Follow reference or signature attribute ATTR of SRC_DIE.
23371    On entry *REF_CU is the CU of SRC_DIE.
23372    On exit *REF_CU is the CU of the result.  */
23373
23374 static struct die_info *
23375 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23376                        struct dwarf2_cu **ref_cu)
23377 {
23378   struct die_info *die;
23379
23380   if (attr_form_is_ref (attr))
23381     die = follow_die_ref (src_die, attr, ref_cu);
23382   else if (attr->form == DW_FORM_ref_sig8)
23383     die = follow_die_sig (src_die, attr, ref_cu);
23384   else
23385     {
23386       dump_die_for_error (src_die);
23387       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23388              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23389     }
23390
23391   return die;
23392 }
23393
23394 /* Follow reference OFFSET.
23395    On entry *REF_CU is the CU of the source die referencing OFFSET.
23396    On exit *REF_CU is the CU of the result.
23397    Returns NULL if OFFSET is invalid.  */
23398
23399 static struct die_info *
23400 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23401                    struct dwarf2_cu **ref_cu)
23402 {
23403   struct die_info temp_die;
23404   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23405   struct dwarf2_per_objfile *dwarf2_per_objfile
23406     = cu->per_cu->dwarf2_per_objfile;
23407   struct objfile *objfile = dwarf2_per_objfile->objfile;
23408
23409   gdb_assert (cu->per_cu != NULL);
23410
23411   target_cu = cu;
23412
23413   if (cu->per_cu->is_debug_types)
23414     {
23415       /* .debug_types CUs cannot reference anything outside their CU.
23416          If they need to, they have to reference a signatured type via
23417          DW_FORM_ref_sig8.  */
23418       if (!offset_in_cu_p (&cu->header, sect_off))
23419         return NULL;
23420     }
23421   else if (offset_in_dwz != cu->per_cu->is_dwz
23422            || !offset_in_cu_p (&cu->header, sect_off))
23423     {
23424       struct dwarf2_per_cu_data *per_cu;
23425
23426       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23427                                                  dwarf2_per_objfile);
23428
23429       /* If necessary, add it to the queue and load its DIEs.  */
23430       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23431         load_full_comp_unit (per_cu, cu->language);
23432
23433       target_cu = per_cu->cu;
23434     }
23435   else if (cu->dies == NULL)
23436     {
23437       /* We're loading full DIEs during partial symbol reading.  */
23438       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23439       load_full_comp_unit (cu->per_cu, language_minimal);
23440     }
23441
23442   *ref_cu = target_cu;
23443   temp_die.sect_off = sect_off;
23444   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23445                                                   &temp_die,
23446                                                   to_underlying (sect_off));
23447 }
23448
23449 /* Follow reference attribute ATTR of SRC_DIE.
23450    On entry *REF_CU is the CU of SRC_DIE.
23451    On exit *REF_CU is the CU of the result.  */
23452
23453 static struct die_info *
23454 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23455                 struct dwarf2_cu **ref_cu)
23456 {
23457   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23458   struct dwarf2_cu *cu = *ref_cu;
23459   struct die_info *die;
23460
23461   die = follow_die_offset (sect_off,
23462                            (attr->form == DW_FORM_GNU_ref_alt
23463                             || cu->per_cu->is_dwz),
23464                            ref_cu);
23465   if (!die)
23466     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23467            "at %s [in module %s]"),
23468            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23469            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23470
23471   return die;
23472 }
23473
23474 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23475    Returned value is intended for DW_OP_call*.  Returned
23476    dwarf2_locexpr_baton->data has lifetime of
23477    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23478
23479 struct dwarf2_locexpr_baton
23480 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23481                                struct dwarf2_per_cu_data *per_cu,
23482                                CORE_ADDR (*get_frame_pc) (void *baton),
23483                                void *baton)
23484 {
23485   struct dwarf2_cu *cu;
23486   struct die_info *die;
23487   struct attribute *attr;
23488   struct dwarf2_locexpr_baton retval;
23489   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23490   struct dwarf2_per_objfile *dwarf2_per_objfile
23491     = get_dwarf2_per_objfile (objfile);
23492
23493   if (per_cu->cu == NULL)
23494     load_cu (per_cu);
23495   cu = per_cu->cu;
23496   if (cu == NULL)
23497     {
23498       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23499          Instead just throw an error, not much else we can do.  */
23500       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23501              sect_offset_str (sect_off), objfile_name (objfile));
23502     }
23503
23504   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23505   if (!die)
23506     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23507            sect_offset_str (sect_off), objfile_name (objfile));
23508
23509   attr = dwarf2_attr (die, DW_AT_location, cu);
23510   if (!attr)
23511     {
23512       /* DWARF: "If there is no such attribute, then there is no effect.".
23513          DATA is ignored if SIZE is 0.  */
23514
23515       retval.data = NULL;
23516       retval.size = 0;
23517     }
23518   else if (attr_form_is_section_offset (attr))
23519     {
23520       struct dwarf2_loclist_baton loclist_baton;
23521       CORE_ADDR pc = (*get_frame_pc) (baton);
23522       size_t size;
23523
23524       fill_in_loclist_baton (cu, &loclist_baton, attr);
23525
23526       retval.data = dwarf2_find_location_expression (&loclist_baton,
23527                                                      &size, pc);
23528       retval.size = size;
23529     }
23530   else
23531     {
23532       if (!attr_form_is_block (attr))
23533         error (_("Dwarf Error: DIE at %s referenced in module %s "
23534                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23535                sect_offset_str (sect_off), objfile_name (objfile));
23536
23537       retval.data = DW_BLOCK (attr)->data;
23538       retval.size = DW_BLOCK (attr)->size;
23539     }
23540   retval.per_cu = cu->per_cu;
23541
23542   age_cached_comp_units (dwarf2_per_objfile);
23543
23544   return retval;
23545 }
23546
23547 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23548    offset.  */
23549
23550 struct dwarf2_locexpr_baton
23551 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23552                              struct dwarf2_per_cu_data *per_cu,
23553                              CORE_ADDR (*get_frame_pc) (void *baton),
23554                              void *baton)
23555 {
23556   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23557
23558   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23559 }
23560
23561 /* Write a constant of a given type as target-ordered bytes into
23562    OBSTACK.  */
23563
23564 static const gdb_byte *
23565 write_constant_as_bytes (struct obstack *obstack,
23566                          enum bfd_endian byte_order,
23567                          struct type *type,
23568                          ULONGEST value,
23569                          LONGEST *len)
23570 {
23571   gdb_byte *result;
23572
23573   *len = TYPE_LENGTH (type);
23574   result = (gdb_byte *) obstack_alloc (obstack, *len);
23575   store_unsigned_integer (result, *len, byte_order, value);
23576
23577   return result;
23578 }
23579
23580 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23581    pointer to the constant bytes and set LEN to the length of the
23582    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23583    does not have a DW_AT_const_value, return NULL.  */
23584
23585 const gdb_byte *
23586 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23587                              struct dwarf2_per_cu_data *per_cu,
23588                              struct obstack *obstack,
23589                              LONGEST *len)
23590 {
23591   struct dwarf2_cu *cu;
23592   struct die_info *die;
23593   struct attribute *attr;
23594   const gdb_byte *result = NULL;
23595   struct type *type;
23596   LONGEST value;
23597   enum bfd_endian byte_order;
23598   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23599
23600   if (per_cu->cu == NULL)
23601     load_cu (per_cu);
23602   cu = per_cu->cu;
23603   if (cu == NULL)
23604     {
23605       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23606          Instead just throw an error, not much else we can do.  */
23607       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23608              sect_offset_str (sect_off), objfile_name (objfile));
23609     }
23610
23611   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23612   if (!die)
23613     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23614            sect_offset_str (sect_off), objfile_name (objfile));
23615
23616   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23617   if (attr == NULL)
23618     return NULL;
23619
23620   byte_order = (bfd_big_endian (objfile->obfd)
23621                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23622
23623   switch (attr->form)
23624     {
23625     case DW_FORM_addr:
23626     case DW_FORM_GNU_addr_index:
23627       {
23628         gdb_byte *tem;
23629
23630         *len = cu->header.addr_size;
23631         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23632         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23633         result = tem;
23634       }
23635       break;
23636     case DW_FORM_string:
23637     case DW_FORM_strp:
23638     case DW_FORM_GNU_str_index:
23639     case DW_FORM_GNU_strp_alt:
23640       /* DW_STRING is already allocated on the objfile obstack, point
23641          directly to it.  */
23642       result = (const gdb_byte *) DW_STRING (attr);
23643       *len = strlen (DW_STRING (attr));
23644       break;
23645     case DW_FORM_block1:
23646     case DW_FORM_block2:
23647     case DW_FORM_block4:
23648     case DW_FORM_block:
23649     case DW_FORM_exprloc:
23650     case DW_FORM_data16:
23651       result = DW_BLOCK (attr)->data;
23652       *len = DW_BLOCK (attr)->size;
23653       break;
23654
23655       /* The DW_AT_const_value attributes are supposed to carry the
23656          symbol's value "represented as it would be on the target
23657          architecture."  By the time we get here, it's already been
23658          converted to host endianness, so we just need to sign- or
23659          zero-extend it as appropriate.  */
23660     case DW_FORM_data1:
23661       type = die_type (die, cu);
23662       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23663       if (result == NULL)
23664         result = write_constant_as_bytes (obstack, byte_order,
23665                                           type, value, len);
23666       break;
23667     case DW_FORM_data2:
23668       type = die_type (die, cu);
23669       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23670       if (result == NULL)
23671         result = write_constant_as_bytes (obstack, byte_order,
23672                                           type, value, len);
23673       break;
23674     case DW_FORM_data4:
23675       type = die_type (die, cu);
23676       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23677       if (result == NULL)
23678         result = write_constant_as_bytes (obstack, byte_order,
23679                                           type, value, len);
23680       break;
23681     case DW_FORM_data8:
23682       type = die_type (die, cu);
23683       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23684       if (result == NULL)
23685         result = write_constant_as_bytes (obstack, byte_order,
23686                                           type, value, len);
23687       break;
23688
23689     case DW_FORM_sdata:
23690     case DW_FORM_implicit_const:
23691       type = die_type (die, cu);
23692       result = write_constant_as_bytes (obstack, byte_order,
23693                                         type, DW_SND (attr), len);
23694       break;
23695
23696     case DW_FORM_udata:
23697       type = die_type (die, cu);
23698       result = write_constant_as_bytes (obstack, byte_order,
23699                                         type, DW_UNSND (attr), len);
23700       break;
23701
23702     default:
23703       complaint (&symfile_complaints,
23704                  _("unsupported const value attribute form: '%s'"),
23705                  dwarf_form_name (attr->form));
23706       break;
23707     }
23708
23709   return result;
23710 }
23711
23712 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23713    valid type for this die is found.  */
23714
23715 struct type *
23716 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23717                                 struct dwarf2_per_cu_data *per_cu)
23718 {
23719   struct dwarf2_cu *cu;
23720   struct die_info *die;
23721
23722   if (per_cu->cu == NULL)
23723     load_cu (per_cu);
23724   cu = per_cu->cu;
23725   if (!cu)
23726     return NULL;
23727
23728   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23729   if (!die)
23730     return NULL;
23731
23732   return die_type (die, cu);
23733 }
23734
23735 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23736    PER_CU.  */
23737
23738 struct type *
23739 dwarf2_get_die_type (cu_offset die_offset,
23740                      struct dwarf2_per_cu_data *per_cu)
23741 {
23742   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23743   return get_die_type_at_offset (die_offset_sect, per_cu);
23744 }
23745
23746 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23747    On entry *REF_CU is the CU of SRC_DIE.
23748    On exit *REF_CU is the CU of the result.
23749    Returns NULL if the referenced DIE isn't found.  */
23750
23751 static struct die_info *
23752 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23753                   struct dwarf2_cu **ref_cu)
23754 {
23755   struct die_info temp_die;
23756   struct dwarf2_cu *sig_cu;
23757   struct die_info *die;
23758
23759   /* While it might be nice to assert sig_type->type == NULL here,
23760      we can get here for DW_AT_imported_declaration where we need
23761      the DIE not the type.  */
23762
23763   /* If necessary, add it to the queue and load its DIEs.  */
23764
23765   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23766     read_signatured_type (sig_type);
23767
23768   sig_cu = sig_type->per_cu.cu;
23769   gdb_assert (sig_cu != NULL);
23770   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23771   temp_die.sect_off = sig_type->type_offset_in_section;
23772   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23773                                                  to_underlying (temp_die.sect_off));
23774   if (die)
23775     {
23776       struct dwarf2_per_objfile *dwarf2_per_objfile
23777         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23778
23779       /* For .gdb_index version 7 keep track of included TUs.
23780          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23781       if (dwarf2_per_objfile->index_table != NULL
23782           && dwarf2_per_objfile->index_table->version <= 7)
23783         {
23784           VEC_safe_push (dwarf2_per_cu_ptr,
23785                          (*ref_cu)->per_cu->imported_symtabs,
23786                          sig_cu->per_cu);
23787         }
23788
23789       *ref_cu = sig_cu;
23790       return die;
23791     }
23792
23793   return NULL;
23794 }
23795
23796 /* Follow signatured type referenced by ATTR in SRC_DIE.
23797    On entry *REF_CU is the CU of SRC_DIE.
23798    On exit *REF_CU is the CU of the result.
23799    The result is the DIE of the type.
23800    If the referenced type cannot be found an error is thrown.  */
23801
23802 static struct die_info *
23803 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23804                 struct dwarf2_cu **ref_cu)
23805 {
23806   ULONGEST signature = DW_SIGNATURE (attr);
23807   struct signatured_type *sig_type;
23808   struct die_info *die;
23809
23810   gdb_assert (attr->form == DW_FORM_ref_sig8);
23811
23812   sig_type = lookup_signatured_type (*ref_cu, signature);
23813   /* sig_type will be NULL if the signatured type is missing from
23814      the debug info.  */
23815   if (sig_type == NULL)
23816     {
23817       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23818                " from DIE at %s [in module %s]"),
23819              hex_string (signature), sect_offset_str (src_die->sect_off),
23820              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23821     }
23822
23823   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23824   if (die == NULL)
23825     {
23826       dump_die_for_error (src_die);
23827       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23828                " from DIE at %s [in module %s]"),
23829              hex_string (signature), sect_offset_str (src_die->sect_off),
23830              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23831     }
23832
23833   return die;
23834 }
23835
23836 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23837    reading in and processing the type unit if necessary.  */
23838
23839 static struct type *
23840 get_signatured_type (struct die_info *die, ULONGEST signature,
23841                      struct dwarf2_cu *cu)
23842 {
23843   struct dwarf2_per_objfile *dwarf2_per_objfile
23844     = cu->per_cu->dwarf2_per_objfile;
23845   struct signatured_type *sig_type;
23846   struct dwarf2_cu *type_cu;
23847   struct die_info *type_die;
23848   struct type *type;
23849
23850   sig_type = lookup_signatured_type (cu, signature);
23851   /* sig_type will be NULL if the signatured type is missing from
23852      the debug info.  */
23853   if (sig_type == NULL)
23854     {
23855       complaint (&symfile_complaints,
23856                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23857                    " from DIE at %s [in module %s]"),
23858                  hex_string (signature), sect_offset_str (die->sect_off),
23859                  objfile_name (dwarf2_per_objfile->objfile));
23860       return build_error_marker_type (cu, die);
23861     }
23862
23863   /* If we already know the type we're done.  */
23864   if (sig_type->type != NULL)
23865     return sig_type->type;
23866
23867   type_cu = cu;
23868   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23869   if (type_die != NULL)
23870     {
23871       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23872          is created.  This is important, for example, because for c++ classes
23873          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23874       type = read_type_die (type_die, type_cu);
23875       if (type == NULL)
23876         {
23877           complaint (&symfile_complaints,
23878                      _("Dwarf Error: Cannot build signatured type %s"
23879                        " referenced from DIE at %s [in module %s]"),
23880                      hex_string (signature), sect_offset_str (die->sect_off),
23881                      objfile_name (dwarf2_per_objfile->objfile));
23882           type = build_error_marker_type (cu, die);
23883         }
23884     }
23885   else
23886     {
23887       complaint (&symfile_complaints,
23888                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23889                    " from DIE at %s [in module %s]"),
23890                  hex_string (signature), sect_offset_str (die->sect_off),
23891                  objfile_name (dwarf2_per_objfile->objfile));
23892       type = build_error_marker_type (cu, die);
23893     }
23894   sig_type->type = type;
23895
23896   return type;
23897 }
23898
23899 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23900    reading in and processing the type unit if necessary.  */
23901
23902 static struct type *
23903 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23904                           struct dwarf2_cu *cu) /* ARI: editCase function */
23905 {
23906   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23907   if (attr_form_is_ref (attr))
23908     {
23909       struct dwarf2_cu *type_cu = cu;
23910       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23911
23912       return read_type_die (type_die, type_cu);
23913     }
23914   else if (attr->form == DW_FORM_ref_sig8)
23915     {
23916       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23917     }
23918   else
23919     {
23920       struct dwarf2_per_objfile *dwarf2_per_objfile
23921         = cu->per_cu->dwarf2_per_objfile;
23922
23923       complaint (&symfile_complaints,
23924                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23925                    " at %s [in module %s]"),
23926                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23927                  objfile_name (dwarf2_per_objfile->objfile));
23928       return build_error_marker_type (cu, die);
23929     }
23930 }
23931
23932 /* Load the DIEs associated with type unit PER_CU into memory.  */
23933
23934 static void
23935 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23936 {
23937   struct signatured_type *sig_type;
23938
23939   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23940   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23941
23942   /* We have the per_cu, but we need the signatured_type.
23943      Fortunately this is an easy translation.  */
23944   gdb_assert (per_cu->is_debug_types);
23945   sig_type = (struct signatured_type *) per_cu;
23946
23947   gdb_assert (per_cu->cu == NULL);
23948
23949   read_signatured_type (sig_type);
23950
23951   gdb_assert (per_cu->cu != NULL);
23952 }
23953
23954 /* die_reader_func for read_signatured_type.
23955    This is identical to load_full_comp_unit_reader,
23956    but is kept separate for now.  */
23957
23958 static void
23959 read_signatured_type_reader (const struct die_reader_specs *reader,
23960                              const gdb_byte *info_ptr,
23961                              struct die_info *comp_unit_die,
23962                              int has_children,
23963                              void *data)
23964 {
23965   struct dwarf2_cu *cu = reader->cu;
23966
23967   gdb_assert (cu->die_hash == NULL);
23968   cu->die_hash =
23969     htab_create_alloc_ex (cu->header.length / 12,
23970                           die_hash,
23971                           die_eq,
23972                           NULL,
23973                           &cu->comp_unit_obstack,
23974                           hashtab_obstack_allocate,
23975                           dummy_obstack_deallocate);
23976
23977   if (has_children)
23978     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23979                                                   &info_ptr, comp_unit_die);
23980   cu->dies = comp_unit_die;
23981   /* comp_unit_die is not stored in die_hash, no need.  */
23982
23983   /* We try not to read any attributes in this function, because not
23984      all CUs needed for references have been loaded yet, and symbol
23985      table processing isn't initialized.  But we have to set the CU language,
23986      or we won't be able to build types correctly.
23987      Similarly, if we do not read the producer, we can not apply
23988      producer-specific interpretation.  */
23989   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23990 }
23991
23992 /* Read in a signatured type and build its CU and DIEs.
23993    If the type is a stub for the real type in a DWO file,
23994    read in the real type from the DWO file as well.  */
23995
23996 static void
23997 read_signatured_type (struct signatured_type *sig_type)
23998 {
23999   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
24000
24001   gdb_assert (per_cu->is_debug_types);
24002   gdb_assert (per_cu->cu == NULL);
24003
24004   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
24005                            read_signatured_type_reader, NULL);
24006   sig_type->per_cu.tu_read = 1;
24007 }
24008
24009 /* Decode simple location descriptions.
24010    Given a pointer to a dwarf block that defines a location, compute
24011    the location and return the value.
24012
24013    NOTE drow/2003-11-18: This function is called in two situations
24014    now: for the address of static or global variables (partial symbols
24015    only) and for offsets into structures which are expected to be
24016    (more or less) constant.  The partial symbol case should go away,
24017    and only the constant case should remain.  That will let this
24018    function complain more accurately.  A few special modes are allowed
24019    without complaint for global variables (for instance, global
24020    register values and thread-local values).
24021
24022    A location description containing no operations indicates that the
24023    object is optimized out.  The return value is 0 for that case.
24024    FIXME drow/2003-11-16: No callers check for this case any more; soon all
24025    callers will only want a very basic result and this can become a
24026    complaint.
24027
24028    Note that stack[0] is unused except as a default error return.  */
24029
24030 static CORE_ADDR
24031 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
24032 {
24033   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
24034   size_t i;
24035   size_t size = blk->size;
24036   const gdb_byte *data = blk->data;
24037   CORE_ADDR stack[64];
24038   int stacki;
24039   unsigned int bytes_read, unsnd;
24040   gdb_byte op;
24041
24042   i = 0;
24043   stacki = 0;
24044   stack[stacki] = 0;
24045   stack[++stacki] = 0;
24046
24047   while (i < size)
24048     {
24049       op = data[i++];
24050       switch (op)
24051         {
24052         case DW_OP_lit0:
24053         case DW_OP_lit1:
24054         case DW_OP_lit2:
24055         case DW_OP_lit3:
24056         case DW_OP_lit4:
24057         case DW_OP_lit5:
24058         case DW_OP_lit6:
24059         case DW_OP_lit7:
24060         case DW_OP_lit8:
24061         case DW_OP_lit9:
24062         case DW_OP_lit10:
24063         case DW_OP_lit11:
24064         case DW_OP_lit12:
24065         case DW_OP_lit13:
24066         case DW_OP_lit14:
24067         case DW_OP_lit15:
24068         case DW_OP_lit16:
24069         case DW_OP_lit17:
24070         case DW_OP_lit18:
24071         case DW_OP_lit19:
24072         case DW_OP_lit20:
24073         case DW_OP_lit21:
24074         case DW_OP_lit22:
24075         case DW_OP_lit23:
24076         case DW_OP_lit24:
24077         case DW_OP_lit25:
24078         case DW_OP_lit26:
24079         case DW_OP_lit27:
24080         case DW_OP_lit28:
24081         case DW_OP_lit29:
24082         case DW_OP_lit30:
24083         case DW_OP_lit31:
24084           stack[++stacki] = op - DW_OP_lit0;
24085           break;
24086
24087         case DW_OP_reg0:
24088         case DW_OP_reg1:
24089         case DW_OP_reg2:
24090         case DW_OP_reg3:
24091         case DW_OP_reg4:
24092         case DW_OP_reg5:
24093         case DW_OP_reg6:
24094         case DW_OP_reg7:
24095         case DW_OP_reg8:
24096         case DW_OP_reg9:
24097         case DW_OP_reg10:
24098         case DW_OP_reg11:
24099         case DW_OP_reg12:
24100         case DW_OP_reg13:
24101         case DW_OP_reg14:
24102         case DW_OP_reg15:
24103         case DW_OP_reg16:
24104         case DW_OP_reg17:
24105         case DW_OP_reg18:
24106         case DW_OP_reg19:
24107         case DW_OP_reg20:
24108         case DW_OP_reg21:
24109         case DW_OP_reg22:
24110         case DW_OP_reg23:
24111         case DW_OP_reg24:
24112         case DW_OP_reg25:
24113         case DW_OP_reg26:
24114         case DW_OP_reg27:
24115         case DW_OP_reg28:
24116         case DW_OP_reg29:
24117         case DW_OP_reg30:
24118         case DW_OP_reg31:
24119           stack[++stacki] = op - DW_OP_reg0;
24120           if (i < size)
24121             dwarf2_complex_location_expr_complaint ();
24122           break;
24123
24124         case DW_OP_regx:
24125           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
24126           i += bytes_read;
24127           stack[++stacki] = unsnd;
24128           if (i < size)
24129             dwarf2_complex_location_expr_complaint ();
24130           break;
24131
24132         case DW_OP_addr:
24133           stack[++stacki] = read_address (objfile->obfd, &data[i],
24134                                           cu, &bytes_read);
24135           i += bytes_read;
24136           break;
24137
24138         case DW_OP_const1u:
24139           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
24140           i += 1;
24141           break;
24142
24143         case DW_OP_const1s:
24144           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
24145           i += 1;
24146           break;
24147
24148         case DW_OP_const2u:
24149           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
24150           i += 2;
24151           break;
24152
24153         case DW_OP_const2s:
24154           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
24155           i += 2;
24156           break;
24157
24158         case DW_OP_const4u:
24159           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
24160           i += 4;
24161           break;
24162
24163         case DW_OP_const4s:
24164           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
24165           i += 4;
24166           break;
24167
24168         case DW_OP_const8u:
24169           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
24170           i += 8;
24171           break;
24172
24173         case DW_OP_constu:
24174           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
24175                                                   &bytes_read);
24176           i += bytes_read;
24177           break;
24178
24179         case DW_OP_consts:
24180           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
24181           i += bytes_read;
24182           break;
24183
24184         case DW_OP_dup:
24185           stack[stacki + 1] = stack[stacki];
24186           stacki++;
24187           break;
24188
24189         case DW_OP_plus:
24190           stack[stacki - 1] += stack[stacki];
24191           stacki--;
24192           break;
24193
24194         case DW_OP_plus_uconst:
24195           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
24196                                                  &bytes_read);
24197           i += bytes_read;
24198           break;
24199
24200         case DW_OP_minus:
24201           stack[stacki - 1] -= stack[stacki];
24202           stacki--;
24203           break;
24204
24205         case DW_OP_deref:
24206           /* If we're not the last op, then we definitely can't encode
24207              this using GDB's address_class enum.  This is valid for partial
24208              global symbols, although the variable's address will be bogus
24209              in the psymtab.  */
24210           if (i < size)
24211             dwarf2_complex_location_expr_complaint ();
24212           break;
24213
24214         case DW_OP_GNU_push_tls_address:
24215         case DW_OP_form_tls_address:
24216           /* The top of the stack has the offset from the beginning
24217              of the thread control block at which the variable is located.  */
24218           /* Nothing should follow this operator, so the top of stack would
24219              be returned.  */
24220           /* This is valid for partial global symbols, but the variable's
24221              address will be bogus in the psymtab.  Make it always at least
24222              non-zero to not look as a variable garbage collected by linker
24223              which have DW_OP_addr 0.  */
24224           if (i < size)
24225             dwarf2_complex_location_expr_complaint ();
24226           stack[stacki]++;
24227           break;
24228
24229         case DW_OP_GNU_uninit:
24230           break;
24231
24232         case DW_OP_GNU_addr_index:
24233         case DW_OP_GNU_const_index:
24234           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
24235                                                          &bytes_read);
24236           i += bytes_read;
24237           break;
24238
24239         default:
24240           {
24241             const char *name = get_DW_OP_name (op);
24242
24243             if (name)
24244               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
24245                          name);
24246             else
24247               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
24248                          op);
24249           }
24250
24251           return (stack[stacki]);
24252         }
24253
24254       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24255          outside of the allocated space.  Also enforce minimum>0.  */
24256       if (stacki >= ARRAY_SIZE (stack) - 1)
24257         {
24258           complaint (&symfile_complaints,
24259                      _("location description stack overflow"));
24260           return 0;
24261         }
24262
24263       if (stacki <= 0)
24264         {
24265           complaint (&symfile_complaints,
24266                      _("location description stack underflow"));
24267           return 0;
24268         }
24269     }
24270   return (stack[stacki]);
24271 }
24272
24273 /* memory allocation interface */
24274
24275 static struct dwarf_block *
24276 dwarf_alloc_block (struct dwarf2_cu *cu)
24277 {
24278   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24279 }
24280
24281 static struct die_info *
24282 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24283 {
24284   struct die_info *die;
24285   size_t size = sizeof (struct die_info);
24286
24287   if (num_attrs > 1)
24288     size += (num_attrs - 1) * sizeof (struct attribute);
24289
24290   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24291   memset (die, 0, sizeof (struct die_info));
24292   return (die);
24293 }
24294
24295 \f
24296 /* Macro support.  */
24297
24298 /* Return file name relative to the compilation directory of file number I in
24299    *LH's file name table.  The result is allocated using xmalloc; the caller is
24300    responsible for freeing it.  */
24301
24302 static char *
24303 file_file_name (int file, struct line_header *lh)
24304 {
24305   /* Is the file number a valid index into the line header's file name
24306      table?  Remember that file numbers start with one, not zero.  */
24307   if (1 <= file && file <= lh->file_names.size ())
24308     {
24309       const file_entry &fe = lh->file_names[file - 1];
24310
24311       if (!IS_ABSOLUTE_PATH (fe.name))
24312         {
24313           const char *dir = fe.include_dir (lh);
24314           if (dir != NULL)
24315             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
24316         }
24317       return xstrdup (fe.name);
24318     }
24319   else
24320     {
24321       /* The compiler produced a bogus file number.  We can at least
24322          record the macro definitions made in the file, even if we
24323          won't be able to find the file by name.  */
24324       char fake_name[80];
24325
24326       xsnprintf (fake_name, sizeof (fake_name),
24327                  "<bad macro file number %d>", file);
24328
24329       complaint (&symfile_complaints,
24330                  _("bad file number in macro information (%d)"),
24331                  file);
24332
24333       return xstrdup (fake_name);
24334     }
24335 }
24336
24337 /* Return the full name of file number I in *LH's file name table.
24338    Use COMP_DIR as the name of the current directory of the
24339    compilation.  The result is allocated using xmalloc; the caller is
24340    responsible for freeing it.  */
24341 static char *
24342 file_full_name (int file, struct line_header *lh, const char *comp_dir)
24343 {
24344   /* Is the file number a valid index into the line header's file name
24345      table?  Remember that file numbers start with one, not zero.  */
24346   if (1 <= file && file <= lh->file_names.size ())
24347     {
24348       char *relative = file_file_name (file, lh);
24349
24350       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
24351         return relative;
24352       return reconcat (relative, comp_dir, SLASH_STRING,
24353                        relative, (char *) NULL);
24354     }
24355   else
24356     return file_file_name (file, lh);
24357 }
24358
24359
24360 static struct macro_source_file *
24361 macro_start_file (int file, int line,
24362                   struct macro_source_file *current_file,
24363                   struct line_header *lh)
24364 {
24365   /* File name relative to the compilation directory of this source file.  */
24366   char *file_name = file_file_name (file, lh);
24367
24368   if (! current_file)
24369     {
24370       /* Note: We don't create a macro table for this compilation unit
24371          at all until we actually get a filename.  */
24372       struct macro_table *macro_table = get_macro_table ();
24373
24374       /* If we have no current file, then this must be the start_file
24375          directive for the compilation unit's main source file.  */
24376       current_file = macro_set_main (macro_table, file_name);
24377       macro_define_special (macro_table);
24378     }
24379   else
24380     current_file = macro_include (current_file, line, file_name);
24381
24382   xfree (file_name);
24383
24384   return current_file;
24385 }
24386
24387 static const char *
24388 consume_improper_spaces (const char *p, const char *body)
24389 {
24390   if (*p == ' ')
24391     {
24392       complaint (&symfile_complaints,
24393                  _("macro definition contains spaces "
24394                    "in formal argument list:\n`%s'"),
24395                  body);
24396
24397       while (*p == ' ')
24398         p++;
24399     }
24400
24401   return p;
24402 }
24403
24404
24405 static void
24406 parse_macro_definition (struct macro_source_file *file, int line,
24407                         const char *body)
24408 {
24409   const char *p;
24410
24411   /* The body string takes one of two forms.  For object-like macro
24412      definitions, it should be:
24413
24414         <macro name> " " <definition>
24415
24416      For function-like macro definitions, it should be:
24417
24418         <macro name> "() " <definition>
24419      or
24420         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24421
24422      Spaces may appear only where explicitly indicated, and in the
24423      <definition>.
24424
24425      The Dwarf 2 spec says that an object-like macro's name is always
24426      followed by a space, but versions of GCC around March 2002 omit
24427      the space when the macro's definition is the empty string.
24428
24429      The Dwarf 2 spec says that there should be no spaces between the
24430      formal arguments in a function-like macro's formal argument list,
24431      but versions of GCC around March 2002 include spaces after the
24432      commas.  */
24433
24434
24435   /* Find the extent of the macro name.  The macro name is terminated
24436      by either a space or null character (for an object-like macro) or
24437      an opening paren (for a function-like macro).  */
24438   for (p = body; *p; p++)
24439     if (*p == ' ' || *p == '(')
24440       break;
24441
24442   if (*p == ' ' || *p == '\0')
24443     {
24444       /* It's an object-like macro.  */
24445       int name_len = p - body;
24446       char *name = savestring (body, name_len);
24447       const char *replacement;
24448
24449       if (*p == ' ')
24450         replacement = body + name_len + 1;
24451       else
24452         {
24453           dwarf2_macro_malformed_definition_complaint (body);
24454           replacement = body + name_len;
24455         }
24456
24457       macro_define_object (file, line, name, replacement);
24458
24459       xfree (name);
24460     }
24461   else if (*p == '(')
24462     {
24463       /* It's a function-like macro.  */
24464       char *name = savestring (body, p - body);
24465       int argc = 0;
24466       int argv_size = 1;
24467       char **argv = XNEWVEC (char *, argv_size);
24468
24469       p++;
24470
24471       p = consume_improper_spaces (p, body);
24472
24473       /* Parse the formal argument list.  */
24474       while (*p && *p != ')')
24475         {
24476           /* Find the extent of the current argument name.  */
24477           const char *arg_start = p;
24478
24479           while (*p && *p != ',' && *p != ')' && *p != ' ')
24480             p++;
24481
24482           if (! *p || p == arg_start)
24483             dwarf2_macro_malformed_definition_complaint (body);
24484           else
24485             {
24486               /* Make sure argv has room for the new argument.  */
24487               if (argc >= argv_size)
24488                 {
24489                   argv_size *= 2;
24490                   argv = XRESIZEVEC (char *, argv, argv_size);
24491                 }
24492
24493               argv[argc++] = savestring (arg_start, p - arg_start);
24494             }
24495
24496           p = consume_improper_spaces (p, body);
24497
24498           /* Consume the comma, if present.  */
24499           if (*p == ',')
24500             {
24501               p++;
24502
24503               p = consume_improper_spaces (p, body);
24504             }
24505         }
24506
24507       if (*p == ')')
24508         {
24509           p++;
24510
24511           if (*p == ' ')
24512             /* Perfectly formed definition, no complaints.  */
24513             macro_define_function (file, line, name,
24514                                    argc, (const char **) argv,
24515                                    p + 1);
24516           else if (*p == '\0')
24517             {
24518               /* Complain, but do define it.  */
24519               dwarf2_macro_malformed_definition_complaint (body);
24520               macro_define_function (file, line, name,
24521                                      argc, (const char **) argv,
24522                                      p);
24523             }
24524           else
24525             /* Just complain.  */
24526             dwarf2_macro_malformed_definition_complaint (body);
24527         }
24528       else
24529         /* Just complain.  */
24530         dwarf2_macro_malformed_definition_complaint (body);
24531
24532       xfree (name);
24533       {
24534         int i;
24535
24536         for (i = 0; i < argc; i++)
24537           xfree (argv[i]);
24538       }
24539       xfree (argv);
24540     }
24541   else
24542     dwarf2_macro_malformed_definition_complaint (body);
24543 }
24544
24545 /* Skip some bytes from BYTES according to the form given in FORM.
24546    Returns the new pointer.  */
24547
24548 static const gdb_byte *
24549 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24550                  enum dwarf_form form,
24551                  unsigned int offset_size,
24552                  struct dwarf2_section_info *section)
24553 {
24554   unsigned int bytes_read;
24555
24556   switch (form)
24557     {
24558     case DW_FORM_data1:
24559     case DW_FORM_flag:
24560       ++bytes;
24561       break;
24562
24563     case DW_FORM_data2:
24564       bytes += 2;
24565       break;
24566
24567     case DW_FORM_data4:
24568       bytes += 4;
24569       break;
24570
24571     case DW_FORM_data8:
24572       bytes += 8;
24573       break;
24574
24575     case DW_FORM_data16:
24576       bytes += 16;
24577       break;
24578
24579     case DW_FORM_string:
24580       read_direct_string (abfd, bytes, &bytes_read);
24581       bytes += bytes_read;
24582       break;
24583
24584     case DW_FORM_sec_offset:
24585     case DW_FORM_strp:
24586     case DW_FORM_GNU_strp_alt:
24587       bytes += offset_size;
24588       break;
24589
24590     case DW_FORM_block:
24591       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24592       bytes += bytes_read;
24593       break;
24594
24595     case DW_FORM_block1:
24596       bytes += 1 + read_1_byte (abfd, bytes);
24597       break;
24598     case DW_FORM_block2:
24599       bytes += 2 + read_2_bytes (abfd, bytes);
24600       break;
24601     case DW_FORM_block4:
24602       bytes += 4 + read_4_bytes (abfd, bytes);
24603       break;
24604
24605     case DW_FORM_sdata:
24606     case DW_FORM_udata:
24607     case DW_FORM_GNU_addr_index:
24608     case DW_FORM_GNU_str_index:
24609       bytes = gdb_skip_leb128 (bytes, buffer_end);
24610       if (bytes == NULL)
24611         {
24612           dwarf2_section_buffer_overflow_complaint (section);
24613           return NULL;
24614         }
24615       break;
24616
24617     case DW_FORM_implicit_const:
24618       break;
24619
24620     default:
24621       {
24622         complaint (&symfile_complaints,
24623                    _("invalid form 0x%x in `%s'"),
24624                    form, get_section_name (section));
24625         return NULL;
24626       }
24627     }
24628
24629   return bytes;
24630 }
24631
24632 /* A helper for dwarf_decode_macros that handles skipping an unknown
24633    opcode.  Returns an updated pointer to the macro data buffer; or,
24634    on error, issues a complaint and returns NULL.  */
24635
24636 static const gdb_byte *
24637 skip_unknown_opcode (unsigned int opcode,
24638                      const gdb_byte **opcode_definitions,
24639                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24640                      bfd *abfd,
24641                      unsigned int offset_size,
24642                      struct dwarf2_section_info *section)
24643 {
24644   unsigned int bytes_read, i;
24645   unsigned long arg;
24646   const gdb_byte *defn;
24647
24648   if (opcode_definitions[opcode] == NULL)
24649     {
24650       complaint (&symfile_complaints,
24651                  _("unrecognized DW_MACFINO opcode 0x%x"),
24652                  opcode);
24653       return NULL;
24654     }
24655
24656   defn = opcode_definitions[opcode];
24657   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24658   defn += bytes_read;
24659
24660   for (i = 0; i < arg; ++i)
24661     {
24662       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24663                                  (enum dwarf_form) defn[i], offset_size,
24664                                  section);
24665       if (mac_ptr == NULL)
24666         {
24667           /* skip_form_bytes already issued the complaint.  */
24668           return NULL;
24669         }
24670     }
24671
24672   return mac_ptr;
24673 }
24674
24675 /* A helper function which parses the header of a macro section.
24676    If the macro section is the extended (for now called "GNU") type,
24677    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24678    the header, or issues a complaint and returns NULL on error.  */
24679
24680 static const gdb_byte *
24681 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24682                           bfd *abfd,
24683                           const gdb_byte *mac_ptr,
24684                           unsigned int *offset_size,
24685                           int section_is_gnu)
24686 {
24687   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24688
24689   if (section_is_gnu)
24690     {
24691       unsigned int version, flags;
24692
24693       version = read_2_bytes (abfd, mac_ptr);
24694       if (version != 4 && version != 5)
24695         {
24696           complaint (&symfile_complaints,
24697                      _("unrecognized version `%d' in .debug_macro section"),
24698                      version);
24699           return NULL;
24700         }
24701       mac_ptr += 2;
24702
24703       flags = read_1_byte (abfd, mac_ptr);
24704       ++mac_ptr;
24705       *offset_size = (flags & 1) ? 8 : 4;
24706
24707       if ((flags & 2) != 0)
24708         /* We don't need the line table offset.  */
24709         mac_ptr += *offset_size;
24710
24711       /* Vendor opcode descriptions.  */
24712       if ((flags & 4) != 0)
24713         {
24714           unsigned int i, count;
24715
24716           count = read_1_byte (abfd, mac_ptr);
24717           ++mac_ptr;
24718           for (i = 0; i < count; ++i)
24719             {
24720               unsigned int opcode, bytes_read;
24721               unsigned long arg;
24722
24723               opcode = read_1_byte (abfd, mac_ptr);
24724               ++mac_ptr;
24725               opcode_definitions[opcode] = mac_ptr;
24726               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24727               mac_ptr += bytes_read;
24728               mac_ptr += arg;
24729             }
24730         }
24731     }
24732
24733   return mac_ptr;
24734 }
24735
24736 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24737    including DW_MACRO_import.  */
24738
24739 static void
24740 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24741                           bfd *abfd,
24742                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24743                           struct macro_source_file *current_file,
24744                           struct line_header *lh,
24745                           struct dwarf2_section_info *section,
24746                           int section_is_gnu, int section_is_dwz,
24747                           unsigned int offset_size,
24748                           htab_t include_hash)
24749 {
24750   struct objfile *objfile = dwarf2_per_objfile->objfile;
24751   enum dwarf_macro_record_type macinfo_type;
24752   int at_commandline;
24753   const gdb_byte *opcode_definitions[256];
24754
24755   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24756                                       &offset_size, section_is_gnu);
24757   if (mac_ptr == NULL)
24758     {
24759       /* We already issued a complaint.  */
24760       return;
24761     }
24762
24763   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24764      GDB is still reading the definitions from command line.  First
24765      DW_MACINFO_start_file will need to be ignored as it was already executed
24766      to create CURRENT_FILE for the main source holding also the command line
24767      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24768      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24769
24770   at_commandline = 1;
24771
24772   do
24773     {
24774       /* Do we at least have room for a macinfo type byte?  */
24775       if (mac_ptr >= mac_end)
24776         {
24777           dwarf2_section_buffer_overflow_complaint (section);
24778           break;
24779         }
24780
24781       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24782       mac_ptr++;
24783
24784       /* Note that we rely on the fact that the corresponding GNU and
24785          DWARF constants are the same.  */
24786       DIAGNOSTIC_PUSH
24787       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24788       switch (macinfo_type)
24789         {
24790           /* A zero macinfo type indicates the end of the macro
24791              information.  */
24792         case 0:
24793           break;
24794
24795         case DW_MACRO_define:
24796         case DW_MACRO_undef:
24797         case DW_MACRO_define_strp:
24798         case DW_MACRO_undef_strp:
24799         case DW_MACRO_define_sup:
24800         case DW_MACRO_undef_sup:
24801           {
24802             unsigned int bytes_read;
24803             int line;
24804             const char *body;
24805             int is_define;
24806
24807             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24808             mac_ptr += bytes_read;
24809
24810             if (macinfo_type == DW_MACRO_define
24811                 || macinfo_type == DW_MACRO_undef)
24812               {
24813                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24814                 mac_ptr += bytes_read;
24815               }
24816             else
24817               {
24818                 LONGEST str_offset;
24819
24820                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24821                 mac_ptr += offset_size;
24822
24823                 if (macinfo_type == DW_MACRO_define_sup
24824                     || macinfo_type == DW_MACRO_undef_sup
24825                     || section_is_dwz)
24826                   {
24827                     struct dwz_file *dwz
24828                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24829
24830                     body = read_indirect_string_from_dwz (objfile,
24831                                                           dwz, str_offset);
24832                   }
24833                 else
24834                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24835                                                          abfd, str_offset);
24836               }
24837
24838             is_define = (macinfo_type == DW_MACRO_define
24839                          || macinfo_type == DW_MACRO_define_strp
24840                          || macinfo_type == DW_MACRO_define_sup);
24841             if (! current_file)
24842               {
24843                 /* DWARF violation as no main source is present.  */
24844                 complaint (&symfile_complaints,
24845                            _("debug info with no main source gives macro %s "
24846                              "on line %d: %s"),
24847                            is_define ? _("definition") : _("undefinition"),
24848                            line, body);
24849                 break;
24850               }
24851             if ((line == 0 && !at_commandline)
24852                 || (line != 0 && at_commandline))
24853               complaint (&symfile_complaints,
24854                          _("debug info gives %s macro %s with %s line %d: %s"),
24855                          at_commandline ? _("command-line") : _("in-file"),
24856                          is_define ? _("definition") : _("undefinition"),
24857                          line == 0 ? _("zero") : _("non-zero"), line, body);
24858
24859             if (is_define)
24860               parse_macro_definition (current_file, line, body);
24861             else
24862               {
24863                 gdb_assert (macinfo_type == DW_MACRO_undef
24864                             || macinfo_type == DW_MACRO_undef_strp
24865                             || macinfo_type == DW_MACRO_undef_sup);
24866                 macro_undef (current_file, line, body);
24867               }
24868           }
24869           break;
24870
24871         case DW_MACRO_start_file:
24872           {
24873             unsigned int bytes_read;
24874             int line, file;
24875
24876             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24877             mac_ptr += bytes_read;
24878             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24879             mac_ptr += bytes_read;
24880
24881             if ((line == 0 && !at_commandline)
24882                 || (line != 0 && at_commandline))
24883               complaint (&symfile_complaints,
24884                          _("debug info gives source %d included "
24885                            "from %s at %s line %d"),
24886                          file, at_commandline ? _("command-line") : _("file"),
24887                          line == 0 ? _("zero") : _("non-zero"), line);
24888
24889             if (at_commandline)
24890               {
24891                 /* This DW_MACRO_start_file was executed in the
24892                    pass one.  */
24893                 at_commandline = 0;
24894               }
24895             else
24896               current_file = macro_start_file (file, line, current_file, lh);
24897           }
24898           break;
24899
24900         case DW_MACRO_end_file:
24901           if (! current_file)
24902             complaint (&symfile_complaints,
24903                        _("macro debug info has an unmatched "
24904                          "`close_file' directive"));
24905           else
24906             {
24907               current_file = current_file->included_by;
24908               if (! current_file)
24909                 {
24910                   enum dwarf_macro_record_type next_type;
24911
24912                   /* GCC circa March 2002 doesn't produce the zero
24913                      type byte marking the end of the compilation
24914                      unit.  Complain if it's not there, but exit no
24915                      matter what.  */
24916
24917                   /* Do we at least have room for a macinfo type byte?  */
24918                   if (mac_ptr >= mac_end)
24919                     {
24920                       dwarf2_section_buffer_overflow_complaint (section);
24921                       return;
24922                     }
24923
24924                   /* We don't increment mac_ptr here, so this is just
24925                      a look-ahead.  */
24926                   next_type
24927                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24928                                                                   mac_ptr);
24929                   if (next_type != 0)
24930                     complaint (&symfile_complaints,
24931                                _("no terminating 0-type entry for "
24932                                  "macros in `.debug_macinfo' section"));
24933
24934                   return;
24935                 }
24936             }
24937           break;
24938
24939         case DW_MACRO_import:
24940         case DW_MACRO_import_sup:
24941           {
24942             LONGEST offset;
24943             void **slot;
24944             bfd *include_bfd = abfd;
24945             struct dwarf2_section_info *include_section = section;
24946             const gdb_byte *include_mac_end = mac_end;
24947             int is_dwz = section_is_dwz;
24948             const gdb_byte *new_mac_ptr;
24949
24950             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24951             mac_ptr += offset_size;
24952
24953             if (macinfo_type == DW_MACRO_import_sup)
24954               {
24955                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24956
24957                 dwarf2_read_section (objfile, &dwz->macro);
24958
24959                 include_section = &dwz->macro;
24960                 include_bfd = get_section_bfd_owner (include_section);
24961                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24962                 is_dwz = 1;
24963               }
24964
24965             new_mac_ptr = include_section->buffer + offset;
24966             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24967
24968             if (*slot != NULL)
24969               {
24970                 /* This has actually happened; see
24971                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24972                 complaint (&symfile_complaints,
24973                            _("recursive DW_MACRO_import in "
24974                              ".debug_macro section"));
24975               }
24976             else
24977               {
24978                 *slot = (void *) new_mac_ptr;
24979
24980                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24981                                           include_bfd, new_mac_ptr,
24982                                           include_mac_end, current_file, lh,
24983                                           section, section_is_gnu, is_dwz,
24984                                           offset_size, include_hash);
24985
24986                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24987               }
24988           }
24989           break;
24990
24991         case DW_MACINFO_vendor_ext:
24992           if (!section_is_gnu)
24993             {
24994               unsigned int bytes_read;
24995
24996               /* This reads the constant, but since we don't recognize
24997                  any vendor extensions, we ignore it.  */
24998               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24999               mac_ptr += bytes_read;
25000               read_direct_string (abfd, mac_ptr, &bytes_read);
25001               mac_ptr += bytes_read;
25002
25003               /* We don't recognize any vendor extensions.  */
25004               break;
25005             }
25006           /* FALLTHROUGH */
25007
25008         default:
25009           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
25010                                          mac_ptr, mac_end, abfd, offset_size,
25011                                          section);
25012           if (mac_ptr == NULL)
25013             return;
25014           break;
25015         }
25016       DIAGNOSTIC_POP
25017     } while (macinfo_type != 0);
25018 }
25019
25020 static void
25021 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
25022                      int section_is_gnu)
25023 {
25024   struct dwarf2_per_objfile *dwarf2_per_objfile
25025     = cu->per_cu->dwarf2_per_objfile;
25026   struct objfile *objfile = dwarf2_per_objfile->objfile;
25027   struct line_header *lh = cu->line_header;
25028   bfd *abfd;
25029   const gdb_byte *mac_ptr, *mac_end;
25030   struct macro_source_file *current_file = 0;
25031   enum dwarf_macro_record_type macinfo_type;
25032   unsigned int offset_size = cu->header.offset_size;
25033   const gdb_byte *opcode_definitions[256];
25034   void **slot;
25035   struct dwarf2_section_info *section;
25036   const char *section_name;
25037
25038   if (cu->dwo_unit != NULL)
25039     {
25040       if (section_is_gnu)
25041         {
25042           section = &cu->dwo_unit->dwo_file->sections.macro;
25043           section_name = ".debug_macro.dwo";
25044         }
25045       else
25046         {
25047           section = &cu->dwo_unit->dwo_file->sections.macinfo;
25048           section_name = ".debug_macinfo.dwo";
25049         }
25050     }
25051   else
25052     {
25053       if (section_is_gnu)
25054         {
25055           section = &dwarf2_per_objfile->macro;
25056           section_name = ".debug_macro";
25057         }
25058       else
25059         {
25060           section = &dwarf2_per_objfile->macinfo;
25061           section_name = ".debug_macinfo";
25062         }
25063     }
25064
25065   dwarf2_read_section (objfile, section);
25066   if (section->buffer == NULL)
25067     {
25068       complaint (&symfile_complaints, _("missing %s section"), section_name);
25069       return;
25070     }
25071   abfd = get_section_bfd_owner (section);
25072
25073   /* First pass: Find the name of the base filename.
25074      This filename is needed in order to process all macros whose definition
25075      (or undefinition) comes from the command line.  These macros are defined
25076      before the first DW_MACINFO_start_file entry, and yet still need to be
25077      associated to the base file.
25078
25079      To determine the base file name, we scan the macro definitions until we
25080      reach the first DW_MACINFO_start_file entry.  We then initialize
25081      CURRENT_FILE accordingly so that any macro definition found before the
25082      first DW_MACINFO_start_file can still be associated to the base file.  */
25083
25084   mac_ptr = section->buffer + offset;
25085   mac_end = section->buffer + section->size;
25086
25087   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
25088                                       &offset_size, section_is_gnu);
25089   if (mac_ptr == NULL)
25090     {
25091       /* We already issued a complaint.  */
25092       return;
25093     }
25094
25095   do
25096     {
25097       /* Do we at least have room for a macinfo type byte?  */
25098       if (mac_ptr >= mac_end)
25099         {
25100           /* Complaint is printed during the second pass as GDB will probably
25101              stop the first pass earlier upon finding
25102              DW_MACINFO_start_file.  */
25103           break;
25104         }
25105
25106       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
25107       mac_ptr++;
25108
25109       /* Note that we rely on the fact that the corresponding GNU and
25110          DWARF constants are the same.  */
25111       DIAGNOSTIC_PUSH
25112       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
25113       switch (macinfo_type)
25114         {
25115           /* A zero macinfo type indicates the end of the macro
25116              information.  */
25117         case 0:
25118           break;
25119
25120         case DW_MACRO_define:
25121         case DW_MACRO_undef:
25122           /* Only skip the data by MAC_PTR.  */
25123           {
25124             unsigned int bytes_read;
25125
25126             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25127             mac_ptr += bytes_read;
25128             read_direct_string (abfd, mac_ptr, &bytes_read);
25129             mac_ptr += bytes_read;
25130           }
25131           break;
25132
25133         case DW_MACRO_start_file:
25134           {
25135             unsigned int bytes_read;
25136             int line, file;
25137
25138             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25139             mac_ptr += bytes_read;
25140             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25141             mac_ptr += bytes_read;
25142
25143             current_file = macro_start_file (file, line, current_file, lh);
25144           }
25145           break;
25146
25147         case DW_MACRO_end_file:
25148           /* No data to skip by MAC_PTR.  */
25149           break;
25150
25151         case DW_MACRO_define_strp:
25152         case DW_MACRO_undef_strp:
25153         case DW_MACRO_define_sup:
25154         case DW_MACRO_undef_sup:
25155           {
25156             unsigned int bytes_read;
25157
25158             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25159             mac_ptr += bytes_read;
25160             mac_ptr += offset_size;
25161           }
25162           break;
25163
25164         case DW_MACRO_import:
25165         case DW_MACRO_import_sup:
25166           /* Note that, according to the spec, a transparent include
25167              chain cannot call DW_MACRO_start_file.  So, we can just
25168              skip this opcode.  */
25169           mac_ptr += offset_size;
25170           break;
25171
25172         case DW_MACINFO_vendor_ext:
25173           /* Only skip the data by MAC_PTR.  */
25174           if (!section_is_gnu)
25175             {
25176               unsigned int bytes_read;
25177
25178               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25179               mac_ptr += bytes_read;
25180               read_direct_string (abfd, mac_ptr, &bytes_read);
25181               mac_ptr += bytes_read;
25182             }
25183           /* FALLTHROUGH */
25184
25185         default:
25186           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
25187                                          mac_ptr, mac_end, abfd, offset_size,
25188                                          section);
25189           if (mac_ptr == NULL)
25190             return;
25191           break;
25192         }
25193       DIAGNOSTIC_POP
25194     } while (macinfo_type != 0 && current_file == NULL);
25195
25196   /* Second pass: Process all entries.
25197
25198      Use the AT_COMMAND_LINE flag to determine whether we are still processing
25199      command-line macro definitions/undefinitions.  This flag is unset when we
25200      reach the first DW_MACINFO_start_file entry.  */
25201
25202   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
25203                                            htab_eq_pointer,
25204                                            NULL, xcalloc, xfree));
25205   mac_ptr = section->buffer + offset;
25206   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
25207   *slot = (void *) mac_ptr;
25208   dwarf_decode_macro_bytes (dwarf2_per_objfile,
25209                             abfd, mac_ptr, mac_end,
25210                             current_file, lh, section,
25211                             section_is_gnu, 0, offset_size,
25212                             include_hash.get ());
25213 }
25214
25215 /* Check if the attribute's form is a DW_FORM_block*
25216    if so return true else false.  */
25217
25218 static int
25219 attr_form_is_block (const struct attribute *attr)
25220 {
25221   return (attr == NULL ? 0 :
25222       attr->form == DW_FORM_block1
25223       || attr->form == DW_FORM_block2
25224       || attr->form == DW_FORM_block4
25225       || attr->form == DW_FORM_block
25226       || attr->form == DW_FORM_exprloc);
25227 }
25228
25229 /* Return non-zero if ATTR's value is a section offset --- classes
25230    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
25231    You may use DW_UNSND (attr) to retrieve such offsets.
25232
25233    Section 7.5.4, "Attribute Encodings", explains that no attribute
25234    may have a value that belongs to more than one of these classes; it
25235    would be ambiguous if we did, because we use the same forms for all
25236    of them.  */
25237
25238 static int
25239 attr_form_is_section_offset (const struct attribute *attr)
25240 {
25241   return (attr->form == DW_FORM_data4
25242           || attr->form == DW_FORM_data8
25243           || attr->form == DW_FORM_sec_offset);
25244 }
25245
25246 /* Return non-zero if ATTR's value falls in the 'constant' class, or
25247    zero otherwise.  When this function returns true, you can apply
25248    dwarf2_get_attr_constant_value to it.
25249
25250    However, note that for some attributes you must check
25251    attr_form_is_section_offset before using this test.  DW_FORM_data4
25252    and DW_FORM_data8 are members of both the constant class, and of
25253    the classes that contain offsets into other debug sections
25254    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
25255    that, if an attribute's can be either a constant or one of the
25256    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
25257    taken as section offsets, not constants.
25258
25259    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
25260    cannot handle that.  */
25261
25262 static int
25263 attr_form_is_constant (const struct attribute *attr)
25264 {
25265   switch (attr->form)
25266     {
25267     case DW_FORM_sdata:
25268     case DW_FORM_udata:
25269     case DW_FORM_data1:
25270     case DW_FORM_data2:
25271     case DW_FORM_data4:
25272     case DW_FORM_data8:
25273     case DW_FORM_implicit_const:
25274       return 1;
25275     default:
25276       return 0;
25277     }
25278 }
25279
25280
25281 /* DW_ADDR is always stored already as sect_offset; despite for the forms
25282    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
25283
25284 static int
25285 attr_form_is_ref (const struct attribute *attr)
25286 {
25287   switch (attr->form)
25288     {
25289     case DW_FORM_ref_addr:
25290     case DW_FORM_ref1:
25291     case DW_FORM_ref2:
25292     case DW_FORM_ref4:
25293     case DW_FORM_ref8:
25294     case DW_FORM_ref_udata:
25295     case DW_FORM_GNU_ref_alt:
25296       return 1;
25297     default:
25298       return 0;
25299     }
25300 }
25301
25302 /* Return the .debug_loc section to use for CU.
25303    For DWO files use .debug_loc.dwo.  */
25304
25305 static struct dwarf2_section_info *
25306 cu_debug_loc_section (struct dwarf2_cu *cu)
25307 {
25308   struct dwarf2_per_objfile *dwarf2_per_objfile
25309     = cu->per_cu->dwarf2_per_objfile;
25310
25311   if (cu->dwo_unit)
25312     {
25313       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
25314       
25315       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
25316     }
25317   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
25318                                   : &dwarf2_per_objfile->loc);
25319 }
25320
25321 /* A helper function that fills in a dwarf2_loclist_baton.  */
25322
25323 static void
25324 fill_in_loclist_baton (struct dwarf2_cu *cu,
25325                        struct dwarf2_loclist_baton *baton,
25326                        const struct attribute *attr)
25327 {
25328   struct dwarf2_per_objfile *dwarf2_per_objfile
25329     = cu->per_cu->dwarf2_per_objfile;
25330   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25331
25332   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
25333
25334   baton->per_cu = cu->per_cu;
25335   gdb_assert (baton->per_cu);
25336   /* We don't know how long the location list is, but make sure we
25337      don't run off the edge of the section.  */
25338   baton->size = section->size - DW_UNSND (attr);
25339   baton->data = section->buffer + DW_UNSND (attr);
25340   baton->base_address = cu->base_address;
25341   baton->from_dwo = cu->dwo_unit != NULL;
25342 }
25343
25344 static void
25345 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
25346                              struct dwarf2_cu *cu, int is_block)
25347 {
25348   struct dwarf2_per_objfile *dwarf2_per_objfile
25349     = cu->per_cu->dwarf2_per_objfile;
25350   struct objfile *objfile = dwarf2_per_objfile->objfile;
25351   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25352
25353   if (attr_form_is_section_offset (attr)
25354       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
25355          the section.  If so, fall through to the complaint in the
25356          other branch.  */
25357       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
25358     {
25359       struct dwarf2_loclist_baton *baton;
25360
25361       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
25362
25363       fill_in_loclist_baton (cu, baton, attr);
25364
25365       if (cu->base_known == 0)
25366         complaint (&symfile_complaints,
25367                    _("Location list used without "
25368                      "specifying the CU base address."));
25369
25370       SYMBOL_ACLASS_INDEX (sym) = (is_block
25371                                    ? dwarf2_loclist_block_index
25372                                    : dwarf2_loclist_index);
25373       SYMBOL_LOCATION_BATON (sym) = baton;
25374     }
25375   else
25376     {
25377       struct dwarf2_locexpr_baton *baton;
25378
25379       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25380       baton->per_cu = cu->per_cu;
25381       gdb_assert (baton->per_cu);
25382
25383       if (attr_form_is_block (attr))
25384         {
25385           /* Note that we're just copying the block's data pointer
25386              here, not the actual data.  We're still pointing into the
25387              info_buffer for SYM's objfile; right now we never release
25388              that buffer, but when we do clean up properly this may
25389              need to change.  */
25390           baton->size = DW_BLOCK (attr)->size;
25391           baton->data = DW_BLOCK (attr)->data;
25392         }
25393       else
25394         {
25395           dwarf2_invalid_attrib_class_complaint ("location description",
25396                                                  SYMBOL_NATURAL_NAME (sym));
25397           baton->size = 0;
25398         }
25399
25400       SYMBOL_ACLASS_INDEX (sym) = (is_block
25401                                    ? dwarf2_locexpr_block_index
25402                                    : dwarf2_locexpr_index);
25403       SYMBOL_LOCATION_BATON (sym) = baton;
25404     }
25405 }
25406
25407 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25408    came from a separate debuginfo file, then the master objfile is
25409    returned.  */
25410
25411 struct objfile *
25412 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25413 {
25414   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25415
25416   /* Return the master objfile, so that we can report and look up the
25417      correct file containing this variable.  */
25418   if (objfile->separate_debug_objfile_backlink)
25419     objfile = objfile->separate_debug_objfile_backlink;
25420
25421   return objfile;
25422 }
25423
25424 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25425    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25426    CU_HEADERP first.  */
25427
25428 static const struct comp_unit_head *
25429 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25430                        struct dwarf2_per_cu_data *per_cu)
25431 {
25432   const gdb_byte *info_ptr;
25433
25434   if (per_cu->cu)
25435     return &per_cu->cu->header;
25436
25437   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25438
25439   memset (cu_headerp, 0, sizeof (*cu_headerp));
25440   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25441                        rcuh_kind::COMPILE);
25442
25443   return cu_headerp;
25444 }
25445
25446 /* Return the address size given in the compilation unit header for CU.  */
25447
25448 int
25449 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25450 {
25451   struct comp_unit_head cu_header_local;
25452   const struct comp_unit_head *cu_headerp;
25453
25454   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25455
25456   return cu_headerp->addr_size;
25457 }
25458
25459 /* Return the offset size given in the compilation unit header for CU.  */
25460
25461 int
25462 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25463 {
25464   struct comp_unit_head cu_header_local;
25465   const struct comp_unit_head *cu_headerp;
25466
25467   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25468
25469   return cu_headerp->offset_size;
25470 }
25471
25472 /* See its dwarf2loc.h declaration.  */
25473
25474 int
25475 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25476 {
25477   struct comp_unit_head cu_header_local;
25478   const struct comp_unit_head *cu_headerp;
25479
25480   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25481
25482   if (cu_headerp->version == 2)
25483     return cu_headerp->addr_size;
25484   else
25485     return cu_headerp->offset_size;
25486 }
25487
25488 /* Return the text offset of the CU.  The returned offset comes from
25489    this CU's objfile.  If this objfile came from a separate debuginfo
25490    file, then the offset may be different from the corresponding
25491    offset in the parent objfile.  */
25492
25493 CORE_ADDR
25494 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25495 {
25496   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25497
25498   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25499 }
25500
25501 /* Return DWARF version number of PER_CU.  */
25502
25503 short
25504 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25505 {
25506   return per_cu->dwarf_version;
25507 }
25508
25509 /* Locate the .debug_info compilation unit from CU's objfile which contains
25510    the DIE at OFFSET.  Raises an error on failure.  */
25511
25512 static struct dwarf2_per_cu_data *
25513 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25514                                   unsigned int offset_in_dwz,
25515                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25516 {
25517   struct dwarf2_per_cu_data *this_cu;
25518   int low, high;
25519   const sect_offset *cu_off;
25520
25521   low = 0;
25522   high = dwarf2_per_objfile->n_comp_units - 1;
25523   while (high > low)
25524     {
25525       struct dwarf2_per_cu_data *mid_cu;
25526       int mid = low + (high - low) / 2;
25527
25528       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25529       cu_off = &mid_cu->sect_off;
25530       if (mid_cu->is_dwz > offset_in_dwz
25531           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25532         high = mid;
25533       else
25534         low = mid + 1;
25535     }
25536   gdb_assert (low == high);
25537   this_cu = dwarf2_per_objfile->all_comp_units[low];
25538   cu_off = &this_cu->sect_off;
25539   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25540     {
25541       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25542         error (_("Dwarf Error: could not find partial DIE containing "
25543                "offset %s [in module %s]"),
25544                sect_offset_str (sect_off),
25545                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25546
25547       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25548                   <= sect_off);
25549       return dwarf2_per_objfile->all_comp_units[low-1];
25550     }
25551   else
25552     {
25553       this_cu = dwarf2_per_objfile->all_comp_units[low];
25554       if (low == dwarf2_per_objfile->n_comp_units - 1
25555           && sect_off >= this_cu->sect_off + this_cu->length)
25556         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25557       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25558       return this_cu;
25559     }
25560 }
25561
25562 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25563
25564 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25565   : per_cu (per_cu_),
25566     mark (0),
25567     has_loclist (0),
25568     checked_producer (0),
25569     producer_is_gxx_lt_4_6 (0),
25570     producer_is_gcc_lt_4_3 (0),
25571     producer_is_icc_lt_14 (0),
25572     processing_has_namespace_info (0)
25573 {
25574   per_cu->cu = this;
25575 }
25576
25577 /* Destroy a dwarf2_cu.  */
25578
25579 dwarf2_cu::~dwarf2_cu ()
25580 {
25581   per_cu->cu = NULL;
25582 }
25583
25584 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25585
25586 static void
25587 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25588                        enum language pretend_language)
25589 {
25590   struct attribute *attr;
25591
25592   /* Set the language we're debugging.  */
25593   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25594   if (attr)
25595     set_cu_language (DW_UNSND (attr), cu);
25596   else
25597     {
25598       cu->language = pretend_language;
25599       cu->language_defn = language_def (cu->language);
25600     }
25601
25602   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25603 }
25604
25605 /* Free all cached compilation units.  */
25606
25607 static void
25608 free_cached_comp_units (void *data)
25609 {
25610   struct dwarf2_per_objfile *dwarf2_per_objfile
25611     = (struct dwarf2_per_objfile *) data;
25612
25613   dwarf2_per_objfile->free_cached_comp_units ();
25614 }
25615
25616 /* Increase the age counter on each cached compilation unit, and free
25617    any that are too old.  */
25618
25619 static void
25620 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25621 {
25622   struct dwarf2_per_cu_data *per_cu, **last_chain;
25623
25624   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25625   per_cu = dwarf2_per_objfile->read_in_chain;
25626   while (per_cu != NULL)
25627     {
25628       per_cu->cu->last_used ++;
25629       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25630         dwarf2_mark (per_cu->cu);
25631       per_cu = per_cu->cu->read_in_chain;
25632     }
25633
25634   per_cu = dwarf2_per_objfile->read_in_chain;
25635   last_chain = &dwarf2_per_objfile->read_in_chain;
25636   while (per_cu != NULL)
25637     {
25638       struct dwarf2_per_cu_data *next_cu;
25639
25640       next_cu = per_cu->cu->read_in_chain;
25641
25642       if (!per_cu->cu->mark)
25643         {
25644           delete per_cu->cu;
25645           *last_chain = next_cu;
25646         }
25647       else
25648         last_chain = &per_cu->cu->read_in_chain;
25649
25650       per_cu = next_cu;
25651     }
25652 }
25653
25654 /* Remove a single compilation unit from the cache.  */
25655
25656 static void
25657 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25658 {
25659   struct dwarf2_per_cu_data *per_cu, **last_chain;
25660   struct dwarf2_per_objfile *dwarf2_per_objfile
25661     = target_per_cu->dwarf2_per_objfile;
25662
25663   per_cu = dwarf2_per_objfile->read_in_chain;
25664   last_chain = &dwarf2_per_objfile->read_in_chain;
25665   while (per_cu != NULL)
25666     {
25667       struct dwarf2_per_cu_data *next_cu;
25668
25669       next_cu = per_cu->cu->read_in_chain;
25670
25671       if (per_cu == target_per_cu)
25672         {
25673           delete per_cu->cu;
25674           per_cu->cu = NULL;
25675           *last_chain = next_cu;
25676           break;
25677         }
25678       else
25679         last_chain = &per_cu->cu->read_in_chain;
25680
25681       per_cu = next_cu;
25682     }
25683 }
25684
25685 /* Release all extra memory associated with OBJFILE.  */
25686
25687 void
25688 dwarf2_free_objfile (struct objfile *objfile)
25689 {
25690   struct dwarf2_per_objfile *dwarf2_per_objfile
25691     = get_dwarf2_per_objfile (objfile);
25692
25693   delete dwarf2_per_objfile;
25694 }
25695
25696 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25697    We store these in a hash table separate from the DIEs, and preserve them
25698    when the DIEs are flushed out of cache.
25699
25700    The CU "per_cu" pointer is needed because offset alone is not enough to
25701    uniquely identify the type.  A file may have multiple .debug_types sections,
25702    or the type may come from a DWO file.  Furthermore, while it's more logical
25703    to use per_cu->section+offset, with Fission the section with the data is in
25704    the DWO file but we don't know that section at the point we need it.
25705    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25706    because we can enter the lookup routine, get_die_type_at_offset, from
25707    outside this file, and thus won't necessarily have PER_CU->cu.
25708    Fortunately, PER_CU is stable for the life of the objfile.  */
25709
25710 struct dwarf2_per_cu_offset_and_type
25711 {
25712   const struct dwarf2_per_cu_data *per_cu;
25713   sect_offset sect_off;
25714   struct type *type;
25715 };
25716
25717 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25718
25719 static hashval_t
25720 per_cu_offset_and_type_hash (const void *item)
25721 {
25722   const struct dwarf2_per_cu_offset_and_type *ofs
25723     = (const struct dwarf2_per_cu_offset_and_type *) item;
25724
25725   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25726 }
25727
25728 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25729
25730 static int
25731 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25732 {
25733   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25734     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25735   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25736     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25737
25738   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25739           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25740 }
25741
25742 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25743    table if necessary.  For convenience, return TYPE.
25744
25745    The DIEs reading must have careful ordering to:
25746     * Not cause infite loops trying to read in DIEs as a prerequisite for
25747       reading current DIE.
25748     * Not trying to dereference contents of still incompletely read in types
25749       while reading in other DIEs.
25750     * Enable referencing still incompletely read in types just by a pointer to
25751       the type without accessing its fields.
25752
25753    Therefore caller should follow these rules:
25754      * Try to fetch any prerequisite types we may need to build this DIE type
25755        before building the type and calling set_die_type.
25756      * After building type call set_die_type for current DIE as soon as
25757        possible before fetching more types to complete the current type.
25758      * Make the type as complete as possible before fetching more types.  */
25759
25760 static struct type *
25761 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25762 {
25763   struct dwarf2_per_objfile *dwarf2_per_objfile
25764     = cu->per_cu->dwarf2_per_objfile;
25765   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25766   struct objfile *objfile = dwarf2_per_objfile->objfile;
25767   struct attribute *attr;
25768   struct dynamic_prop prop;
25769
25770   /* For Ada types, make sure that the gnat-specific data is always
25771      initialized (if not already set).  There are a few types where
25772      we should not be doing so, because the type-specific area is
25773      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25774      where the type-specific area is used to store the floatformat).
25775      But this is not a problem, because the gnat-specific information
25776      is actually not needed for these types.  */
25777   if (need_gnat_info (cu)
25778       && TYPE_CODE (type) != TYPE_CODE_FUNC
25779       && TYPE_CODE (type) != TYPE_CODE_FLT
25780       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25781       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25782       && TYPE_CODE (type) != TYPE_CODE_METHOD
25783       && !HAVE_GNAT_AUX_INFO (type))
25784     INIT_GNAT_SPECIFIC (type);
25785
25786   /* Read DW_AT_allocated and set in type.  */
25787   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25788   if (attr_form_is_block (attr))
25789     {
25790       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25791         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25792     }
25793   else if (attr != NULL)
25794     {
25795       complaint (&symfile_complaints,
25796                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25797                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25798                  sect_offset_str (die->sect_off));
25799     }
25800
25801   /* Read DW_AT_associated and set in type.  */
25802   attr = dwarf2_attr (die, DW_AT_associated, cu);
25803   if (attr_form_is_block (attr))
25804     {
25805       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25806         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25807     }
25808   else if (attr != NULL)
25809     {
25810       complaint (&symfile_complaints,
25811                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25812                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25813                  sect_offset_str (die->sect_off));
25814     }
25815
25816   /* Read DW_AT_data_location and set in type.  */
25817   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25818   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25819     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25820
25821   if (dwarf2_per_objfile->die_type_hash == NULL)
25822     {
25823       dwarf2_per_objfile->die_type_hash =
25824         htab_create_alloc_ex (127,
25825                               per_cu_offset_and_type_hash,
25826                               per_cu_offset_and_type_eq,
25827                               NULL,
25828                               &objfile->objfile_obstack,
25829                               hashtab_obstack_allocate,
25830                               dummy_obstack_deallocate);
25831     }
25832
25833   ofs.per_cu = cu->per_cu;
25834   ofs.sect_off = die->sect_off;
25835   ofs.type = type;
25836   slot = (struct dwarf2_per_cu_offset_and_type **)
25837     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25838   if (*slot)
25839     complaint (&symfile_complaints,
25840                _("A problem internal to GDB: DIE %s has type already set"),
25841                sect_offset_str (die->sect_off));
25842   *slot = XOBNEW (&objfile->objfile_obstack,
25843                   struct dwarf2_per_cu_offset_and_type);
25844   **slot = ofs;
25845   return type;
25846 }
25847
25848 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25849    or return NULL if the die does not have a saved type.  */
25850
25851 static struct type *
25852 get_die_type_at_offset (sect_offset sect_off,
25853                         struct dwarf2_per_cu_data *per_cu)
25854 {
25855   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25856   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25857
25858   if (dwarf2_per_objfile->die_type_hash == NULL)
25859     return NULL;
25860
25861   ofs.per_cu = per_cu;
25862   ofs.sect_off = sect_off;
25863   slot = ((struct dwarf2_per_cu_offset_and_type *)
25864           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25865   if (slot)
25866     return slot->type;
25867   else
25868     return NULL;
25869 }
25870
25871 /* Look up the type for DIE in CU in die_type_hash,
25872    or return NULL if DIE does not have a saved type.  */
25873
25874 static struct type *
25875 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25876 {
25877   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25878 }
25879
25880 /* Add a dependence relationship from CU to REF_PER_CU.  */
25881
25882 static void
25883 dwarf2_add_dependence (struct dwarf2_cu *cu,
25884                        struct dwarf2_per_cu_data *ref_per_cu)
25885 {
25886   void **slot;
25887
25888   if (cu->dependencies == NULL)
25889     cu->dependencies
25890       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25891                               NULL, &cu->comp_unit_obstack,
25892                               hashtab_obstack_allocate,
25893                               dummy_obstack_deallocate);
25894
25895   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25896   if (*slot == NULL)
25897     *slot = ref_per_cu;
25898 }
25899
25900 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25901    Set the mark field in every compilation unit in the
25902    cache that we must keep because we are keeping CU.  */
25903
25904 static int
25905 dwarf2_mark_helper (void **slot, void *data)
25906 {
25907   struct dwarf2_per_cu_data *per_cu;
25908
25909   per_cu = (struct dwarf2_per_cu_data *) *slot;
25910
25911   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25912      reading of the chain.  As such dependencies remain valid it is not much
25913      useful to track and undo them during QUIT cleanups.  */
25914   if (per_cu->cu == NULL)
25915     return 1;
25916
25917   if (per_cu->cu->mark)
25918     return 1;
25919   per_cu->cu->mark = 1;
25920
25921   if (per_cu->cu->dependencies != NULL)
25922     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25923
25924   return 1;
25925 }
25926
25927 /* Set the mark field in CU and in every other compilation unit in the
25928    cache that we must keep because we are keeping CU.  */
25929
25930 static void
25931 dwarf2_mark (struct dwarf2_cu *cu)
25932 {
25933   if (cu->mark)
25934     return;
25935   cu->mark = 1;
25936   if (cu->dependencies != NULL)
25937     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25938 }
25939
25940 static void
25941 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25942 {
25943   while (per_cu)
25944     {
25945       per_cu->cu->mark = 0;
25946       per_cu = per_cu->cu->read_in_chain;
25947     }
25948 }
25949
25950 /* Trivial hash function for partial_die_info: the hash value of a DIE
25951    is its offset in .debug_info for this objfile.  */
25952
25953 static hashval_t
25954 partial_die_hash (const void *item)
25955 {
25956   const struct partial_die_info *part_die
25957     = (const struct partial_die_info *) item;
25958
25959   return to_underlying (part_die->sect_off);
25960 }
25961
25962 /* Trivial comparison function for partial_die_info structures: two DIEs
25963    are equal if they have the same offset.  */
25964
25965 static int
25966 partial_die_eq (const void *item_lhs, const void *item_rhs)
25967 {
25968   const struct partial_die_info *part_die_lhs
25969     = (const struct partial_die_info *) item_lhs;
25970   const struct partial_die_info *part_die_rhs
25971     = (const struct partial_die_info *) item_rhs;
25972
25973   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25974 }
25975
25976 static struct cmd_list_element *set_dwarf_cmdlist;
25977 static struct cmd_list_element *show_dwarf_cmdlist;
25978
25979 static void
25980 set_dwarf_cmd (const char *args, int from_tty)
25981 {
25982   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25983              gdb_stdout);
25984 }
25985
25986 static void
25987 show_dwarf_cmd (const char *args, int from_tty)
25988 {
25989   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25990 }
25991
25992 /* The "save gdb-index" command.  */
25993
25994 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25995    error checking.  */
25996
25997 static void
25998 file_write (FILE *file, const void *data, size_t size)
25999 {
26000   if (fwrite (data, 1, size, file) != size)
26001     error (_("couldn't data write to file"));
26002 }
26003
26004 /* Write the contents of VEC to FILE, with error checking.  */
26005
26006 template<typename Elem, typename Alloc>
26007 static void
26008 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
26009 {
26010   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
26011 }
26012
26013 /* In-memory buffer to prepare data to be written later to a file.  */
26014 class data_buf
26015 {
26016 public:
26017   /* Copy DATA to the end of the buffer.  */
26018   template<typename T>
26019   void append_data (const T &data)
26020   {
26021     std::copy (reinterpret_cast<const gdb_byte *> (&data),
26022                reinterpret_cast<const gdb_byte *> (&data + 1),
26023                grow (sizeof (data)));
26024   }
26025
26026   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
26027      terminating zero is appended too.  */
26028   void append_cstr0 (const char *cstr)
26029   {
26030     const size_t size = strlen (cstr) + 1;
26031     std::copy (cstr, cstr + size, grow (size));
26032   }
26033
26034   /* Store INPUT as ULEB128 to the end of buffer.  */
26035   void append_unsigned_leb128 (ULONGEST input)
26036   {
26037     for (;;)
26038       {
26039         gdb_byte output = input & 0x7f;
26040         input >>= 7;
26041         if (input)
26042           output |= 0x80;
26043         append_data (output);
26044         if (input == 0)
26045           break;
26046       }
26047   }
26048
26049   /* Accept a host-format integer in VAL and append it to the buffer
26050      as a target-format integer which is LEN bytes long.  */
26051   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
26052   {
26053     ::store_unsigned_integer (grow (len), len, byte_order, val);
26054   }
26055
26056   /* Return the size of the buffer.  */
26057   size_t size () const
26058   {
26059     return m_vec.size ();
26060   }
26061
26062   /* Return true iff the buffer is empty.  */
26063   bool empty () const
26064   {
26065     return m_vec.empty ();
26066   }
26067
26068   /* Write the buffer to FILE.  */
26069   void file_write (FILE *file) const
26070   {
26071     ::file_write (file, m_vec);
26072   }
26073
26074 private:
26075   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
26076      the start of the new block.  */
26077   gdb_byte *grow (size_t size)
26078   {
26079     m_vec.resize (m_vec.size () + size);
26080     return &*m_vec.end () - size;
26081   }
26082
26083   gdb::byte_vector m_vec;
26084 };
26085
26086 /* An entry in the symbol table.  */
26087 struct symtab_index_entry
26088 {
26089   /* The name of the symbol.  */
26090   const char *name;
26091   /* The offset of the name in the constant pool.  */
26092   offset_type index_offset;
26093   /* A sorted vector of the indices of all the CUs that hold an object
26094      of this name.  */
26095   std::vector<offset_type> cu_indices;
26096 };
26097
26098 /* The symbol table.  This is a power-of-2-sized hash table.  */
26099 struct mapped_symtab
26100 {
26101   mapped_symtab ()
26102   {
26103     data.resize (1024);
26104   }
26105
26106   offset_type n_elements = 0;
26107   std::vector<symtab_index_entry> data;
26108 };
26109
26110 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
26111    the slot.
26112    
26113    Function is used only during write_hash_table so no index format backward
26114    compatibility is needed.  */
26115
26116 static symtab_index_entry &
26117 find_slot (struct mapped_symtab *symtab, const char *name)
26118 {
26119   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
26120
26121   index = hash & (symtab->data.size () - 1);
26122   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
26123
26124   for (;;)
26125     {
26126       if (symtab->data[index].name == NULL
26127           || strcmp (name, symtab->data[index].name) == 0)
26128         return symtab->data[index];
26129       index = (index + step) & (symtab->data.size () - 1);
26130     }
26131 }
26132
26133 /* Expand SYMTAB's hash table.  */
26134
26135 static void
26136 hash_expand (struct mapped_symtab *symtab)
26137 {
26138   auto old_entries = std::move (symtab->data);
26139
26140   symtab->data.clear ();
26141   symtab->data.resize (old_entries.size () * 2);
26142
26143   for (auto &it : old_entries)
26144     if (it.name != NULL)
26145       {
26146         auto &ref = find_slot (symtab, it.name);
26147         ref = std::move (it);
26148       }
26149 }
26150
26151 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
26152    CU_INDEX is the index of the CU in which the symbol appears.
26153    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
26154
26155 static void
26156 add_index_entry (struct mapped_symtab *symtab, const char *name,
26157                  int is_static, gdb_index_symbol_kind kind,
26158                  offset_type cu_index)
26159 {
26160   offset_type cu_index_and_attrs;
26161
26162   ++symtab->n_elements;
26163   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
26164     hash_expand (symtab);
26165
26166   symtab_index_entry &slot = find_slot (symtab, name);
26167   if (slot.name == NULL)
26168     {
26169       slot.name = name;
26170       /* index_offset is set later.  */
26171     }
26172
26173   cu_index_and_attrs = 0;
26174   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
26175   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
26176   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
26177
26178   /* We don't want to record an index value twice as we want to avoid the
26179      duplication.
26180      We process all global symbols and then all static symbols
26181      (which would allow us to avoid the duplication by only having to check
26182      the last entry pushed), but a symbol could have multiple kinds in one CU.
26183      To keep things simple we don't worry about the duplication here and
26184      sort and uniqufy the list after we've processed all symbols.  */
26185   slot.cu_indices.push_back (cu_index_and_attrs);
26186 }
26187
26188 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
26189
26190 static void
26191 uniquify_cu_indices (struct mapped_symtab *symtab)
26192 {
26193   for (auto &entry : symtab->data)
26194     {
26195       if (entry.name != NULL && !entry.cu_indices.empty ())
26196         {
26197           auto &cu_indices = entry.cu_indices;
26198           std::sort (cu_indices.begin (), cu_indices.end ());
26199           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
26200           cu_indices.erase (from, cu_indices.end ());
26201         }
26202     }
26203 }
26204
26205 /* A form of 'const char *' suitable for container keys.  Only the
26206    pointer is stored.  The strings themselves are compared, not the
26207    pointers.  */
26208 class c_str_view
26209 {
26210 public:
26211   c_str_view (const char *cstr)
26212     : m_cstr (cstr)
26213   {}
26214
26215   bool operator== (const c_str_view &other) const
26216   {
26217     return strcmp (m_cstr, other.m_cstr) == 0;
26218   }
26219
26220   /* Return the underlying C string.  Note, the returned string is
26221      only a reference with lifetime of this object.  */
26222   const char *c_str () const
26223   {
26224     return m_cstr;
26225   }
26226
26227 private:
26228   friend class c_str_view_hasher;
26229   const char *const m_cstr;
26230 };
26231
26232 /* A std::unordered_map::hasher for c_str_view that uses the right
26233    hash function for strings in a mapped index.  */
26234 class c_str_view_hasher
26235 {
26236 public:
26237   size_t operator () (const c_str_view &x) const
26238   {
26239     return mapped_index_string_hash (INT_MAX, x.m_cstr);
26240   }
26241 };
26242
26243 /* A std::unordered_map::hasher for std::vector<>.  */
26244 template<typename T>
26245 class vector_hasher
26246 {
26247 public:
26248   size_t operator () (const std::vector<T> &key) const
26249   {
26250     return iterative_hash (key.data (),
26251                            sizeof (key.front ()) * key.size (), 0);
26252   }
26253 };
26254
26255 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
26256    constant pool entries going into the data buffer CPOOL.  */
26257
26258 static void
26259 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
26260 {
26261   {
26262     /* Elements are sorted vectors of the indices of all the CUs that
26263        hold an object of this name.  */
26264     std::unordered_map<std::vector<offset_type>, offset_type,
26265                        vector_hasher<offset_type>>
26266       symbol_hash_table;
26267
26268     /* We add all the index vectors to the constant pool first, to
26269        ensure alignment is ok.  */
26270     for (symtab_index_entry &entry : symtab->data)
26271       {
26272         if (entry.name == NULL)
26273           continue;
26274         gdb_assert (entry.index_offset == 0);
26275
26276         /* Finding before inserting is faster than always trying to
26277            insert, because inserting always allocates a node, does the
26278            lookup, and then destroys the new node if another node
26279            already had the same key.  C++17 try_emplace will avoid
26280            this.  */
26281         const auto found
26282           = symbol_hash_table.find (entry.cu_indices);
26283         if (found != symbol_hash_table.end ())
26284           {
26285             entry.index_offset = found->second;
26286             continue;
26287           }
26288
26289         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
26290         entry.index_offset = cpool.size ();
26291         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
26292         for (const auto index : entry.cu_indices)
26293           cpool.append_data (MAYBE_SWAP (index));
26294       }
26295   }
26296
26297   /* Now write out the hash table.  */
26298   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
26299   for (const auto &entry : symtab->data)
26300     {
26301       offset_type str_off, vec_off;
26302
26303       if (entry.name != NULL)
26304         {
26305           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
26306           if (insertpair.second)
26307             cpool.append_cstr0 (entry.name);
26308           str_off = insertpair.first->second;
26309           vec_off = entry.index_offset;
26310         }
26311       else
26312         {
26313           /* While 0 is a valid constant pool index, it is not valid
26314              to have 0 for both offsets.  */
26315           str_off = 0;
26316           vec_off = 0;
26317         }
26318
26319       output.append_data (MAYBE_SWAP (str_off));
26320       output.append_data (MAYBE_SWAP (vec_off));
26321     }
26322 }
26323
26324 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
26325
26326 /* Helper struct for building the address table.  */
26327 struct addrmap_index_data
26328 {
26329   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
26330     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
26331   {}
26332
26333   struct objfile *objfile;
26334   data_buf &addr_vec;
26335   psym_index_map &cu_index_htab;
26336
26337   /* Non-zero if the previous_* fields are valid.
26338      We can't write an entry until we see the next entry (since it is only then
26339      that we know the end of the entry).  */
26340   int previous_valid;
26341   /* Index of the CU in the table of all CUs in the index file.  */
26342   unsigned int previous_cu_index;
26343   /* Start address of the CU.  */
26344   CORE_ADDR previous_cu_start;
26345 };
26346
26347 /* Write an address entry to ADDR_VEC.  */
26348
26349 static void
26350 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
26351                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
26352 {
26353   CORE_ADDR baseaddr;
26354
26355   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
26356
26357   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
26358   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
26359   addr_vec.append_data (MAYBE_SWAP (cu_index));
26360 }
26361
26362 /* Worker function for traversing an addrmap to build the address table.  */
26363
26364 static int
26365 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
26366 {
26367   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
26368   struct partial_symtab *pst = (struct partial_symtab *) obj;
26369
26370   if (data->previous_valid)
26371     add_address_entry (data->objfile, data->addr_vec,
26372                        data->previous_cu_start, start_addr,
26373                        data->previous_cu_index);
26374
26375   data->previous_cu_start = start_addr;
26376   if (pst != NULL)
26377     {
26378       const auto it = data->cu_index_htab.find (pst);
26379       gdb_assert (it != data->cu_index_htab.cend ());
26380       data->previous_cu_index = it->second;
26381       data->previous_valid = 1;
26382     }
26383   else
26384     data->previous_valid = 0;
26385
26386   return 0;
26387 }
26388
26389 /* Write OBJFILE's address map to ADDR_VEC.
26390    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
26391    in the index file.  */
26392
26393 static void
26394 write_address_map (struct objfile *objfile, data_buf &addr_vec,
26395                    psym_index_map &cu_index_htab)
26396 {
26397   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
26398
26399   /* When writing the address table, we have to cope with the fact that
26400      the addrmap iterator only provides the start of a region; we have to
26401      wait until the next invocation to get the start of the next region.  */
26402
26403   addrmap_index_data.objfile = objfile;
26404   addrmap_index_data.previous_valid = 0;
26405
26406   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
26407                    &addrmap_index_data);
26408
26409   /* It's highly unlikely the last entry (end address = 0xff...ff)
26410      is valid, but we should still handle it.
26411      The end address is recorded as the start of the next region, but that
26412      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
26413      anyway.  */
26414   if (addrmap_index_data.previous_valid)
26415     add_address_entry (objfile, addr_vec,
26416                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
26417                        addrmap_index_data.previous_cu_index);
26418 }
26419
26420 /* Return the symbol kind of PSYM.  */
26421
26422 static gdb_index_symbol_kind
26423 symbol_kind (struct partial_symbol *psym)
26424 {
26425   domain_enum domain = PSYMBOL_DOMAIN (psym);
26426   enum address_class aclass = PSYMBOL_CLASS (psym);
26427
26428   switch (domain)
26429     {
26430     case VAR_DOMAIN:
26431       switch (aclass)
26432         {
26433         case LOC_BLOCK:
26434           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
26435         case LOC_TYPEDEF:
26436           return GDB_INDEX_SYMBOL_KIND_TYPE;
26437         case LOC_COMPUTED:
26438         case LOC_CONST_BYTES:
26439         case LOC_OPTIMIZED_OUT:
26440         case LOC_STATIC:
26441           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26442         case LOC_CONST:
26443           /* Note: It's currently impossible to recognize psyms as enum values
26444              short of reading the type info.  For now punt.  */
26445           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26446         default:
26447           /* There are other LOC_FOO values that one might want to classify
26448              as variables, but dwarf2read.c doesn't currently use them.  */
26449           return GDB_INDEX_SYMBOL_KIND_OTHER;
26450         }
26451     case STRUCT_DOMAIN:
26452       return GDB_INDEX_SYMBOL_KIND_TYPE;
26453     default:
26454       return GDB_INDEX_SYMBOL_KIND_OTHER;
26455     }
26456 }
26457
26458 /* Add a list of partial symbols to SYMTAB.  */
26459
26460 static void
26461 write_psymbols (struct mapped_symtab *symtab,
26462                 std::unordered_set<partial_symbol *> &psyms_seen,
26463                 struct partial_symbol **psymp,
26464                 int count,
26465                 offset_type cu_index,
26466                 int is_static)
26467 {
26468   for (; count-- > 0; ++psymp)
26469     {
26470       struct partial_symbol *psym = *psymp;
26471
26472       if (SYMBOL_LANGUAGE (psym) == language_ada)
26473         error (_("Ada is not currently supported by the index"));
26474
26475       /* Only add a given psymbol once.  */
26476       if (psyms_seen.insert (psym).second)
26477         {
26478           gdb_index_symbol_kind kind = symbol_kind (psym);
26479
26480           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26481                            is_static, kind, cu_index);
26482         }
26483     }
26484 }
26485
26486 /* A helper struct used when iterating over debug_types.  */
26487 struct signatured_type_index_data
26488 {
26489   signatured_type_index_data (data_buf &types_list_,
26490                               std::unordered_set<partial_symbol *> &psyms_seen_)
26491     : types_list (types_list_), psyms_seen (psyms_seen_)
26492   {}
26493
26494   struct objfile *objfile;
26495   struct mapped_symtab *symtab;
26496   data_buf &types_list;
26497   std::unordered_set<partial_symbol *> &psyms_seen;
26498   int cu_index;
26499 };
26500
26501 /* A helper function that writes a single signatured_type to an
26502    obstack.  */
26503
26504 static int
26505 write_one_signatured_type (void **slot, void *d)
26506 {
26507   struct signatured_type_index_data *info
26508     = (struct signatured_type_index_data *) d;
26509   struct signatured_type *entry = (struct signatured_type *) *slot;
26510   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26511
26512   write_psymbols (info->symtab,
26513                   info->psyms_seen,
26514                   &info->objfile->global_psymbols[psymtab->globals_offset],
26515                   psymtab->n_global_syms, info->cu_index,
26516                   0);
26517   write_psymbols (info->symtab,
26518                   info->psyms_seen,
26519                   &info->objfile->static_psymbols[psymtab->statics_offset],
26520                   psymtab->n_static_syms, info->cu_index,
26521                   1);
26522
26523   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26524                                 to_underlying (entry->per_cu.sect_off));
26525   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26526                                 to_underlying (entry->type_offset_in_tu));
26527   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26528
26529   ++info->cu_index;
26530
26531   return 1;
26532 }
26533
26534 /* Recurse into all "included" dependencies and count their symbols as
26535    if they appeared in this psymtab.  */
26536
26537 static void
26538 recursively_count_psymbols (struct partial_symtab *psymtab,
26539                             size_t &psyms_seen)
26540 {
26541   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26542     if (psymtab->dependencies[i]->user != NULL)
26543       recursively_count_psymbols (psymtab->dependencies[i],
26544                                   psyms_seen);
26545
26546   psyms_seen += psymtab->n_global_syms;
26547   psyms_seen += psymtab->n_static_syms;
26548 }
26549
26550 /* Recurse into all "included" dependencies and write their symbols as
26551    if they appeared in this psymtab.  */
26552
26553 static void
26554 recursively_write_psymbols (struct objfile *objfile,
26555                             struct partial_symtab *psymtab,
26556                             struct mapped_symtab *symtab,
26557                             std::unordered_set<partial_symbol *> &psyms_seen,
26558                             offset_type cu_index)
26559 {
26560   int i;
26561
26562   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26563     if (psymtab->dependencies[i]->user != NULL)
26564       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26565                                   symtab, psyms_seen, cu_index);
26566
26567   write_psymbols (symtab,
26568                   psyms_seen,
26569                   &objfile->global_psymbols[psymtab->globals_offset],
26570                   psymtab->n_global_syms, cu_index,
26571                   0);
26572   write_psymbols (symtab,
26573                   psyms_seen,
26574                   &objfile->static_psymbols[psymtab->statics_offset],
26575                   psymtab->n_static_syms, cu_index,
26576                   1);
26577 }
26578
26579 /* DWARF-5 .debug_names builder.  */
26580 class debug_names
26581 {
26582 public:
26583   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26584                bfd_endian dwarf5_byte_order)
26585     : m_dwarf5_byte_order (dwarf5_byte_order),
26586       m_dwarf32 (dwarf5_byte_order),
26587       m_dwarf64 (dwarf5_byte_order),
26588       m_dwarf (is_dwarf64
26589                ? static_cast<dwarf &> (m_dwarf64)
26590                : static_cast<dwarf &> (m_dwarf32)),
26591       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26592       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26593       m_debugstrlookup (dwarf2_per_objfile)
26594   {}
26595
26596   int dwarf5_offset_size () const
26597   {
26598     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26599     return dwarf5_is_dwarf64 ? 8 : 4;
26600   }
26601
26602   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26603   enum class unit_kind { cu, tu };
26604
26605   /* Insert one symbol.  */
26606   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26607                unit_kind kind)
26608   {
26609     const int dwarf_tag = psymbol_tag (psym);
26610     if (dwarf_tag == 0)
26611       return;
26612     const char *const name = SYMBOL_SEARCH_NAME (psym);
26613     const auto insertpair
26614       = m_name_to_value_set.emplace (c_str_view (name),
26615                                      std::set<symbol_value> ());
26616     std::set<symbol_value> &value_set = insertpair.first->second;
26617     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26618   }
26619
26620   /* Build all the tables.  All symbols must be already inserted.
26621      This function does not call file_write, caller has to do it
26622      afterwards.  */
26623   void build ()
26624   {
26625     /* Verify the build method has not be called twice.  */
26626     gdb_assert (m_abbrev_table.empty ());
26627     const size_t name_count = m_name_to_value_set.size ();
26628     m_bucket_table.resize
26629       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26630     m_hash_table.reserve (name_count);
26631     m_name_table_string_offs.reserve (name_count);
26632     m_name_table_entry_offs.reserve (name_count);
26633
26634     /* Map each hash of symbol to its name and value.  */
26635     struct hash_it_pair
26636     {
26637       uint32_t hash;
26638       decltype (m_name_to_value_set)::const_iterator it;
26639     };
26640     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26641     bucket_hash.resize (m_bucket_table.size ());
26642     for (decltype (m_name_to_value_set)::const_iterator it
26643            = m_name_to_value_set.cbegin ();
26644          it != m_name_to_value_set.cend ();
26645          ++it)
26646       {
26647         const char *const name = it->first.c_str ();
26648         const uint32_t hash = dwarf5_djb_hash (name);
26649         hash_it_pair hashitpair;
26650         hashitpair.hash = hash;
26651         hashitpair.it = it;
26652         auto &slot = bucket_hash[hash % bucket_hash.size()];
26653         slot.push_front (std::move (hashitpair));
26654       }
26655     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26656       {
26657         const std::forward_list<hash_it_pair> &hashitlist
26658           = bucket_hash[bucket_ix];
26659         if (hashitlist.empty ())
26660           continue;
26661         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26662         /* The hashes array is indexed starting at 1.  */
26663         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26664                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26665                                 m_hash_table.size () + 1);
26666         for (const hash_it_pair &hashitpair : hashitlist)
26667           {
26668             m_hash_table.push_back (0);
26669             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26670                                                         (&m_hash_table.back ()),
26671                                     sizeof (m_hash_table.back ()),
26672                                     m_dwarf5_byte_order, hashitpair.hash);
26673             const c_str_view &name = hashitpair.it->first;
26674             const std::set<symbol_value> &value_set = hashitpair.it->second;
26675             m_name_table_string_offs.push_back_reorder
26676               (m_debugstrlookup.lookup (name.c_str ()));
26677             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26678             gdb_assert (!value_set.empty ());
26679             for (const symbol_value &value : value_set)
26680               {
26681                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26682                                                         value.is_static,
26683                                                         value.kind)];
26684                 if (idx == 0)
26685                   {
26686                     idx = m_idx_next++;
26687                     m_abbrev_table.append_unsigned_leb128 (idx);
26688                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26689                     m_abbrev_table.append_unsigned_leb128
26690                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26691                                                            : DW_IDX_type_unit);
26692                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26693                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26694                                                            ? DW_IDX_GNU_internal
26695                                                            : DW_IDX_GNU_external);
26696                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26697
26698                     /* Terminate attributes list.  */
26699                     m_abbrev_table.append_unsigned_leb128 (0);
26700                     m_abbrev_table.append_unsigned_leb128 (0);
26701                   }
26702
26703                 m_entry_pool.append_unsigned_leb128 (idx);
26704                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26705               }
26706
26707             /* Terminate the list of CUs.  */
26708             m_entry_pool.append_unsigned_leb128 (0);
26709           }
26710       }
26711     gdb_assert (m_hash_table.size () == name_count);
26712
26713     /* Terminate tags list.  */
26714     m_abbrev_table.append_unsigned_leb128 (0);
26715   }
26716
26717   /* Return .debug_names bucket count.  This must be called only after
26718      calling the build method.  */
26719   uint32_t bucket_count () const
26720   {
26721     /* Verify the build method has been already called.  */
26722     gdb_assert (!m_abbrev_table.empty ());
26723     const uint32_t retval = m_bucket_table.size ();
26724
26725     /* Check for overflow.  */
26726     gdb_assert (retval == m_bucket_table.size ());
26727     return retval;
26728   }
26729
26730   /* Return .debug_names names count.  This must be called only after
26731      calling the build method.  */
26732   uint32_t name_count () const
26733   {
26734     /* Verify the build method has been already called.  */
26735     gdb_assert (!m_abbrev_table.empty ());
26736     const uint32_t retval = m_hash_table.size ();
26737
26738     /* Check for overflow.  */
26739     gdb_assert (retval == m_hash_table.size ());
26740     return retval;
26741   }
26742
26743   /* Return number of bytes of .debug_names abbreviation table.  This
26744      must be called only after calling the build method.  */
26745   uint32_t abbrev_table_bytes () const
26746   {
26747     gdb_assert (!m_abbrev_table.empty ());
26748     return m_abbrev_table.size ();
26749   }
26750
26751   /* Recurse into all "included" dependencies and store their symbols
26752      as if they appeared in this psymtab.  */
26753   void recursively_write_psymbols
26754     (struct objfile *objfile,
26755      struct partial_symtab *psymtab,
26756      std::unordered_set<partial_symbol *> &psyms_seen,
26757      int cu_index)
26758   {
26759     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26760       if (psymtab->dependencies[i]->user != NULL)
26761         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26762                                     psyms_seen, cu_index);
26763
26764     write_psymbols (psyms_seen,
26765                     &objfile->global_psymbols[psymtab->globals_offset],
26766                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26767     write_psymbols (psyms_seen,
26768                     &objfile->static_psymbols[psymtab->statics_offset],
26769                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26770   }
26771
26772   /* Return number of bytes the .debug_names section will have.  This
26773      must be called only after calling the build method.  */
26774   size_t bytes () const
26775   {
26776     /* Verify the build method has been already called.  */
26777     gdb_assert (!m_abbrev_table.empty ());
26778     size_t expected_bytes = 0;
26779     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26780     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26781     expected_bytes += m_name_table_string_offs.bytes ();
26782     expected_bytes += m_name_table_entry_offs.bytes ();
26783     expected_bytes += m_abbrev_table.size ();
26784     expected_bytes += m_entry_pool.size ();
26785     return expected_bytes;
26786   }
26787
26788   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26789      FILE_STR.  This must be called only after calling the build
26790      method.  */
26791   void file_write (FILE *file_names, FILE *file_str) const
26792   {
26793     /* Verify the build method has been already called.  */
26794     gdb_assert (!m_abbrev_table.empty ());
26795     ::file_write (file_names, m_bucket_table);
26796     ::file_write (file_names, m_hash_table);
26797     m_name_table_string_offs.file_write (file_names);
26798     m_name_table_entry_offs.file_write (file_names);
26799     m_abbrev_table.file_write (file_names);
26800     m_entry_pool.file_write (file_names);
26801     m_debugstrlookup.file_write (file_str);
26802   }
26803
26804   /* A helper user data for write_one_signatured_type.  */
26805   class write_one_signatured_type_data
26806   {
26807   public:
26808     write_one_signatured_type_data (debug_names &nametable_,
26809                                     signatured_type_index_data &&info_)
26810     : nametable (nametable_), info (std::move (info_))
26811     {}
26812     debug_names &nametable;
26813     struct signatured_type_index_data info;
26814   };
26815
26816   /* A helper function to pass write_one_signatured_type to
26817      htab_traverse_noresize.  */
26818   static int
26819   write_one_signatured_type (void **slot, void *d)
26820   {
26821     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26822     struct signatured_type_index_data *info = &data->info;
26823     struct signatured_type *entry = (struct signatured_type *) *slot;
26824
26825     data->nametable.write_one_signatured_type (entry, info);
26826
26827     return 1;
26828   }
26829
26830 private:
26831
26832   /* Storage for symbol names mapping them to their .debug_str section
26833      offsets.  */
26834   class debug_str_lookup
26835   {
26836   public:
26837
26838     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26839        All .debug_str section strings are automatically stored.  */
26840     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26841       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26842         m_dwarf2_per_objfile (dwarf2_per_objfile)
26843     {
26844       dwarf2_read_section (dwarf2_per_objfile->objfile,
26845                            &dwarf2_per_objfile->str);
26846       if (dwarf2_per_objfile->str.buffer == NULL)
26847         return;
26848       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26849            data < (dwarf2_per_objfile->str.buffer
26850                    + dwarf2_per_objfile->str.size);)
26851         {
26852           const char *const s = reinterpret_cast<const char *> (data);
26853           const auto insertpair
26854             = m_str_table.emplace (c_str_view (s),
26855                                    data - dwarf2_per_objfile->str.buffer);
26856           if (!insertpair.second)
26857             complaint (&symfile_complaints,
26858                        _("Duplicate string \"%s\" in "
26859                          ".debug_str section [in module %s]"),
26860                        s, bfd_get_filename (m_abfd));
26861           data += strlen (s) + 1;
26862         }
26863     }
26864
26865     /* Return offset of symbol name S in the .debug_str section.  Add
26866        such symbol to the section's end if it does not exist there
26867        yet.  */
26868     size_t lookup (const char *s)
26869     {
26870       const auto it = m_str_table.find (c_str_view (s));
26871       if (it != m_str_table.end ())
26872         return it->second;
26873       const size_t offset = (m_dwarf2_per_objfile->str.size
26874                              + m_str_add_buf.size ());
26875       m_str_table.emplace (c_str_view (s), offset);
26876       m_str_add_buf.append_cstr0 (s);
26877       return offset;
26878     }
26879
26880     /* Append the end of the .debug_str section to FILE.  */
26881     void file_write (FILE *file) const
26882     {
26883       m_str_add_buf.file_write (file);
26884     }
26885
26886   private:
26887     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26888     bfd *const m_abfd;
26889     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26890
26891     /* Data to add at the end of .debug_str for new needed symbol names.  */
26892     data_buf m_str_add_buf;
26893   };
26894
26895   /* Container to map used DWARF tags to their .debug_names abbreviation
26896      tags.  */
26897   class index_key
26898   {
26899   public:
26900     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26901       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26902     {
26903     }
26904
26905     bool
26906     operator== (const index_key &other) const
26907     {
26908       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26909               && kind == other.kind);
26910     }
26911
26912     const int dwarf_tag;
26913     const bool is_static;
26914     const unit_kind kind;
26915   };
26916
26917   /* Provide std::unordered_map::hasher for index_key.  */
26918   class index_key_hasher
26919   {
26920   public:
26921     size_t
26922     operator () (const index_key &key) const
26923     {
26924       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26925     }
26926   };
26927
26928   /* Parameters of one symbol entry.  */
26929   class symbol_value
26930   {
26931   public:
26932     const int dwarf_tag, cu_index;
26933     const bool is_static;
26934     const unit_kind kind;
26935
26936     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26937                   unit_kind kind_)
26938       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26939         kind (kind_)
26940     {}
26941
26942     bool
26943     operator< (const symbol_value &other) const
26944     {
26945 #define X(n) \
26946   do \
26947     { \
26948       if (n < other.n) \
26949         return true; \
26950       if (n > other.n) \
26951         return false; \
26952     } \
26953   while (0)
26954       X (dwarf_tag);
26955       X (is_static);
26956       X (kind);
26957       X (cu_index);
26958 #undef X
26959       return false;
26960     }
26961   };
26962
26963   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26964      output.  */
26965   class offset_vec
26966   {
26967   protected:
26968     const bfd_endian dwarf5_byte_order;
26969   public:
26970     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26971       : dwarf5_byte_order (dwarf5_byte_order_)
26972     {}
26973
26974     /* Call std::vector::reserve for NELEM elements.  */
26975     virtual void reserve (size_t nelem) = 0;
26976
26977     /* Call std::vector::push_back with store_unsigned_integer byte
26978        reordering for ELEM.  */
26979     virtual void push_back_reorder (size_t elem) = 0;
26980
26981     /* Return expected output size in bytes.  */
26982     virtual size_t bytes () const = 0;
26983
26984     /* Write name table to FILE.  */
26985     virtual void file_write (FILE *file) const = 0;
26986   };
26987
26988   /* Template to unify DWARF-32 and DWARF-64 output.  */
26989   template<typename OffsetSize>
26990   class offset_vec_tmpl : public offset_vec
26991   {
26992   public:
26993     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26994       : offset_vec (dwarf5_byte_order_)
26995     {}
26996
26997     /* Implement offset_vec::reserve.  */
26998     void reserve (size_t nelem) override
26999     {
27000       m_vec.reserve (nelem);
27001     }
27002
27003     /* Implement offset_vec::push_back_reorder.  */
27004     void push_back_reorder (size_t elem) override
27005     {
27006       m_vec.push_back (elem);
27007       /* Check for overflow.  */
27008       gdb_assert (m_vec.back () == elem);
27009       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
27010                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
27011     }
27012
27013     /* Implement offset_vec::bytes.  */
27014     size_t bytes () const override
27015     {
27016       return m_vec.size () * sizeof (m_vec[0]);
27017     }
27018
27019     /* Implement offset_vec::file_write.  */
27020     void file_write (FILE *file) const override
27021     {
27022       ::file_write (file, m_vec);
27023     }
27024
27025   private:
27026     std::vector<OffsetSize> m_vec;
27027   };
27028
27029   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
27030      respecting name table width.  */
27031   class dwarf
27032   {
27033   public:
27034     offset_vec &name_table_string_offs, &name_table_entry_offs;
27035
27036     dwarf (offset_vec &name_table_string_offs_,
27037            offset_vec &name_table_entry_offs_)
27038       : name_table_string_offs (name_table_string_offs_),
27039         name_table_entry_offs (name_table_entry_offs_)
27040     {
27041     }
27042   };
27043
27044   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
27045      respecting name table width.  */
27046   template<typename OffsetSize>
27047   class dwarf_tmpl : public dwarf
27048   {
27049   public:
27050     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
27051       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
27052         m_name_table_string_offs (dwarf5_byte_order_),
27053         m_name_table_entry_offs (dwarf5_byte_order_)
27054     {}
27055
27056   private:
27057     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
27058     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
27059   };
27060
27061   /* Try to reconstruct original DWARF tag for given partial_symbol.
27062      This function is not DWARF-5 compliant but it is sufficient for
27063      GDB as a DWARF-5 index consumer.  */
27064   static int psymbol_tag (const struct partial_symbol *psym)
27065   {
27066     domain_enum domain = PSYMBOL_DOMAIN (psym);
27067     enum address_class aclass = PSYMBOL_CLASS (psym);
27068
27069     switch (domain)
27070       {
27071       case VAR_DOMAIN:
27072         switch (aclass)
27073           {
27074           case LOC_BLOCK:
27075             return DW_TAG_subprogram;
27076           case LOC_TYPEDEF:
27077             return DW_TAG_typedef;
27078           case LOC_COMPUTED:
27079           case LOC_CONST_BYTES:
27080           case LOC_OPTIMIZED_OUT:
27081           case LOC_STATIC:
27082             return DW_TAG_variable;
27083           case LOC_CONST:
27084             /* Note: It's currently impossible to recognize psyms as enum values
27085                short of reading the type info.  For now punt.  */
27086             return DW_TAG_variable;
27087           default:
27088             /* There are other LOC_FOO values that one might want to classify
27089                as variables, but dwarf2read.c doesn't currently use them.  */
27090             return DW_TAG_variable;
27091           }
27092       case STRUCT_DOMAIN:
27093         return DW_TAG_structure_type;
27094       default:
27095         return 0;
27096       }
27097   }
27098
27099   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
27100   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
27101                        struct partial_symbol **psymp, int count, int cu_index,
27102                        bool is_static, unit_kind kind)
27103   {
27104     for (; count-- > 0; ++psymp)
27105       {
27106         struct partial_symbol *psym = *psymp;
27107
27108         if (SYMBOL_LANGUAGE (psym) == language_ada)
27109           error (_("Ada is not currently supported by the index"));
27110
27111         /* Only add a given psymbol once.  */
27112         if (psyms_seen.insert (psym).second)
27113           insert (psym, cu_index, is_static, kind);
27114       }
27115   }
27116
27117   /* A helper function that writes a single signatured_type
27118      to a debug_names.  */
27119   void
27120   write_one_signatured_type (struct signatured_type *entry,
27121                              struct signatured_type_index_data *info)
27122   {
27123     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
27124
27125     write_psymbols (info->psyms_seen,
27126                     &info->objfile->global_psymbols[psymtab->globals_offset],
27127                     psymtab->n_global_syms, info->cu_index, false,
27128                     unit_kind::tu);
27129     write_psymbols (info->psyms_seen,
27130                     &info->objfile->static_psymbols[psymtab->statics_offset],
27131                     psymtab->n_static_syms, info->cu_index, true,
27132                     unit_kind::tu);
27133
27134     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
27135                                   to_underlying (entry->per_cu.sect_off));
27136
27137     ++info->cu_index;
27138   }
27139
27140   /* Store value of each symbol.  */
27141   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
27142     m_name_to_value_set;
27143
27144   /* Tables of DWARF-5 .debug_names.  They are in object file byte
27145      order.  */
27146   std::vector<uint32_t> m_bucket_table;
27147   std::vector<uint32_t> m_hash_table;
27148
27149   const bfd_endian m_dwarf5_byte_order;
27150   dwarf_tmpl<uint32_t> m_dwarf32;
27151   dwarf_tmpl<uint64_t> m_dwarf64;
27152   dwarf &m_dwarf;
27153   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
27154   debug_str_lookup m_debugstrlookup;
27155
27156   /* Map each used .debug_names abbreviation tag parameter to its
27157      index value.  */
27158   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
27159
27160   /* Next unused .debug_names abbreviation tag for
27161      m_indexkey_to_idx.  */
27162   int m_idx_next = 1;
27163
27164   /* .debug_names abbreviation table.  */
27165   data_buf m_abbrev_table;
27166
27167   /* .debug_names entry pool.  */
27168   data_buf m_entry_pool;
27169 };
27170
27171 /* Return iff any of the needed offsets does not fit into 32-bit
27172    .debug_names section.  */
27173
27174 static bool
27175 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
27176 {
27177   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27178     {
27179       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
27180
27181       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
27182         return true;
27183     }
27184   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
27185     {
27186       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
27187       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
27188
27189       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
27190         return true;
27191     }
27192   return false;
27193 }
27194
27195 /* The psyms_seen set is potentially going to be largish (~40k
27196    elements when indexing a -g3 build of GDB itself).  Estimate the
27197    number of elements in order to avoid too many rehashes, which
27198    require rebuilding buckets and thus many trips to
27199    malloc/free.  */
27200
27201 static size_t
27202 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
27203 {
27204   size_t psyms_count = 0;
27205   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27206     {
27207       struct dwarf2_per_cu_data *per_cu
27208         = dwarf2_per_objfile->all_comp_units[i];
27209       struct partial_symtab *psymtab = per_cu->v.psymtab;
27210
27211       if (psymtab != NULL && psymtab->user == NULL)
27212         recursively_count_psymbols (psymtab, psyms_count);
27213     }
27214   /* Generating an index for gdb itself shows a ratio of
27215      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
27216   return psyms_count / 4;
27217 }
27218
27219 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
27220    Return how many bytes were expected to be written into OUT_FILE.  */
27221
27222 static size_t
27223 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
27224 {
27225   struct objfile *objfile = dwarf2_per_objfile->objfile;
27226   mapped_symtab symtab;
27227   data_buf cu_list;
27228
27229   /* While we're scanning CU's create a table that maps a psymtab pointer
27230      (which is what addrmap records) to its index (which is what is recorded
27231      in the index file).  This will later be needed to write the address
27232      table.  */
27233   psym_index_map cu_index_htab;
27234   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
27235
27236   /* The CU list is already sorted, so we don't need to do additional
27237      work here.  Also, the debug_types entries do not appear in
27238      all_comp_units, but only in their own hash table.  */
27239
27240   std::unordered_set<partial_symbol *> psyms_seen
27241     (psyms_seen_size (dwarf2_per_objfile));
27242   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27243     {
27244       struct dwarf2_per_cu_data *per_cu
27245         = dwarf2_per_objfile->all_comp_units[i];
27246       struct partial_symtab *psymtab = per_cu->v.psymtab;
27247
27248       /* CU of a shared file from 'dwz -m' may be unused by this main file.
27249          It may be referenced from a local scope but in such case it does not
27250          need to be present in .gdb_index.  */
27251       if (psymtab == NULL)
27252         continue;
27253
27254       if (psymtab->user == NULL)
27255         recursively_write_psymbols (objfile, psymtab, &symtab,
27256                                     psyms_seen, i);
27257
27258       const auto insertpair = cu_index_htab.emplace (psymtab, i);
27259       gdb_assert (insertpair.second);
27260
27261       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
27262                            to_underlying (per_cu->sect_off));
27263       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
27264     }
27265
27266   /* Dump the address map.  */
27267   data_buf addr_vec;
27268   write_address_map (objfile, addr_vec, cu_index_htab);
27269
27270   /* Write out the .debug_type entries, if any.  */
27271   data_buf types_cu_list;
27272   if (dwarf2_per_objfile->signatured_types)
27273     {
27274       signatured_type_index_data sig_data (types_cu_list,
27275                                            psyms_seen);
27276
27277       sig_data.objfile = objfile;
27278       sig_data.symtab = &symtab;
27279       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
27280       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27281                               write_one_signatured_type, &sig_data);
27282     }
27283
27284   /* Now that we've processed all symbols we can shrink their cu_indices
27285      lists.  */
27286   uniquify_cu_indices (&symtab);
27287
27288   data_buf symtab_vec, constant_pool;
27289   write_hash_table (&symtab, symtab_vec, constant_pool);
27290
27291   data_buf contents;
27292   const offset_type size_of_contents = 6 * sizeof (offset_type);
27293   offset_type total_len = size_of_contents;
27294
27295   /* The version number.  */
27296   contents.append_data (MAYBE_SWAP (8));
27297
27298   /* The offset of the CU list from the start of the file.  */
27299   contents.append_data (MAYBE_SWAP (total_len));
27300   total_len += cu_list.size ();
27301
27302   /* The offset of the types CU list from the start of the file.  */
27303   contents.append_data (MAYBE_SWAP (total_len));
27304   total_len += types_cu_list.size ();
27305
27306   /* The offset of the address table from the start of the file.  */
27307   contents.append_data (MAYBE_SWAP (total_len));
27308   total_len += addr_vec.size ();
27309
27310   /* The offset of the symbol table from the start of the file.  */
27311   contents.append_data (MAYBE_SWAP (total_len));
27312   total_len += symtab_vec.size ();
27313
27314   /* The offset of the constant pool from the start of the file.  */
27315   contents.append_data (MAYBE_SWAP (total_len));
27316   total_len += constant_pool.size ();
27317
27318   gdb_assert (contents.size () == size_of_contents);
27319
27320   contents.file_write (out_file);
27321   cu_list.file_write (out_file);
27322   types_cu_list.file_write (out_file);
27323   addr_vec.file_write (out_file);
27324   symtab_vec.file_write (out_file);
27325   constant_pool.file_write (out_file);
27326
27327   return total_len;
27328 }
27329
27330 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
27331 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
27332
27333 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
27334    needed addition to .debug_str section to OUT_FILE_STR.  Return how
27335    many bytes were expected to be written into OUT_FILE.  */
27336
27337 static size_t
27338 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
27339                    FILE *out_file, FILE *out_file_str)
27340 {
27341   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
27342   struct objfile *objfile = dwarf2_per_objfile->objfile;
27343   const enum bfd_endian dwarf5_byte_order
27344     = gdbarch_byte_order (get_objfile_arch (objfile));
27345
27346   /* The CU list is already sorted, so we don't need to do additional
27347      work here.  Also, the debug_types entries do not appear in
27348      all_comp_units, but only in their own hash table.  */
27349   data_buf cu_list;
27350   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
27351                          dwarf5_byte_order);
27352   std::unordered_set<partial_symbol *>
27353     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
27354   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27355     {
27356       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
27357       partial_symtab *psymtab = per_cu->v.psymtab;
27358
27359       /* CU of a shared file from 'dwz -m' may be unused by this main
27360          file.  It may be referenced from a local scope but in such
27361          case it does not need to be present in .debug_names.  */
27362       if (psymtab == NULL)
27363         continue;
27364
27365       if (psymtab->user == NULL)
27366         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
27367
27368       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
27369                            to_underlying (per_cu->sect_off));
27370     }
27371
27372   /* Write out the .debug_type entries, if any.  */
27373   data_buf types_cu_list;
27374   if (dwarf2_per_objfile->signatured_types)
27375     {
27376       debug_names::write_one_signatured_type_data sig_data (nametable,
27377                         signatured_type_index_data (types_cu_list, psyms_seen));
27378
27379       sig_data.info.objfile = objfile;
27380       /* It is used only for gdb_index.  */
27381       sig_data.info.symtab = nullptr;
27382       sig_data.info.cu_index = 0;
27383       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27384                               debug_names::write_one_signatured_type,
27385                               &sig_data);
27386     }
27387
27388   nametable.build ();
27389
27390   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
27391
27392   const offset_type bytes_of_header
27393     = ((dwarf5_is_dwarf64 ? 12 : 4)
27394        + 2 + 2 + 7 * 4
27395        + sizeof (dwarf5_gdb_augmentation));
27396   size_t expected_bytes = 0;
27397   expected_bytes += bytes_of_header;
27398   expected_bytes += cu_list.size ();
27399   expected_bytes += types_cu_list.size ();
27400   expected_bytes += nametable.bytes ();
27401   data_buf header;
27402
27403   if (!dwarf5_is_dwarf64)
27404     {
27405       const uint64_t size64 = expected_bytes - 4;
27406       gdb_assert (size64 < 0xfffffff0);
27407       header.append_uint (4, dwarf5_byte_order, size64);
27408     }
27409   else
27410     {
27411       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
27412       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
27413     }
27414
27415   /* The version number.  */
27416   header.append_uint (2, dwarf5_byte_order, 5);
27417
27418   /* Padding.  */
27419   header.append_uint (2, dwarf5_byte_order, 0);
27420
27421   /* comp_unit_count - The number of CUs in the CU list.  */
27422   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
27423
27424   /* local_type_unit_count - The number of TUs in the local TU
27425      list.  */
27426   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
27427
27428   /* foreign_type_unit_count - The number of TUs in the foreign TU
27429      list.  */
27430   header.append_uint (4, dwarf5_byte_order, 0);
27431
27432   /* bucket_count - The number of hash buckets in the hash lookup
27433      table.  */
27434   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
27435
27436   /* name_count - The number of unique names in the index.  */
27437   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
27438
27439   /* abbrev_table_size - The size in bytes of the abbreviations
27440      table.  */
27441   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
27442
27443   /* augmentation_string_size - The size in bytes of the augmentation
27444      string.  This value is rounded up to a multiple of 4.  */
27445   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
27446   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
27447   header.append_data (dwarf5_gdb_augmentation);
27448
27449   gdb_assert (header.size () == bytes_of_header);
27450
27451   header.file_write (out_file);
27452   cu_list.file_write (out_file);
27453   types_cu_list.file_write (out_file);
27454   nametable.file_write (out_file, out_file_str);
27455
27456   return expected_bytes;
27457 }
27458
27459 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
27460    position is at the end of the file.  */
27461
27462 static void
27463 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27464 {
27465   const auto file_size = ftell (file);
27466   if (file_size == -1)
27467     error (_("Can't get `%s' size"), filename);
27468   gdb_assert (file_size == expected_size);
27469 }
27470
27471 /* Create an index file for OBJFILE in the directory DIR.  */
27472
27473 static void
27474 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27475                          const char *dir,
27476                          dw_index_kind index_kind)
27477 {
27478   struct objfile *objfile = dwarf2_per_objfile->objfile;
27479
27480   if (dwarf2_per_objfile->using_index)
27481     error (_("Cannot use an index to create the index"));
27482
27483   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27484     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27485
27486   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27487     return;
27488
27489   struct stat st;
27490   if (stat (objfile_name (objfile), &st) < 0)
27491     perror_with_name (objfile_name (objfile));
27492
27493   std::string filename (std::string (dir) + SLASH_STRING
27494                         + lbasename (objfile_name (objfile))
27495                         + (index_kind == dw_index_kind::DEBUG_NAMES
27496                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27497
27498   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27499   if (!out_file)
27500     error (_("Can't open `%s' for writing"), filename.c_str ());
27501
27502   /* Order matters here; we want FILE to be closed before FILENAME is
27503      unlinked, because on MS-Windows one cannot delete a file that is
27504      still open.  (Don't call anything here that might throw until
27505      file_closer is created.)  */
27506   gdb::unlinker unlink_file (filename.c_str ());
27507   gdb_file_up close_out_file (out_file);
27508
27509   if (index_kind == dw_index_kind::DEBUG_NAMES)
27510     {
27511       std::string filename_str (std::string (dir) + SLASH_STRING
27512                                 + lbasename (objfile_name (objfile))
27513                                 + DEBUG_STR_SUFFIX);
27514       FILE *out_file_str
27515         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27516       if (!out_file_str)
27517         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27518       gdb::unlinker unlink_file_str (filename_str.c_str ());
27519       gdb_file_up close_out_file_str (out_file_str);
27520
27521       const size_t total_len
27522         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27523       assert_file_size (out_file, filename.c_str (), total_len);
27524
27525       /* We want to keep the file .debug_str file too.  */
27526       unlink_file_str.keep ();
27527     }
27528   else
27529     {
27530       const size_t total_len
27531         = write_gdbindex (dwarf2_per_objfile, out_file);
27532       assert_file_size (out_file, filename.c_str (), total_len);
27533     }
27534
27535   /* We want to keep the file.  */
27536   unlink_file.keep ();
27537 }
27538
27539 /* Implementation of the `save gdb-index' command.
27540    
27541    Note that the .gdb_index file format used by this command is
27542    documented in the GDB manual.  Any changes here must be documented
27543    there.  */
27544
27545 static void
27546 save_gdb_index_command (const char *arg, int from_tty)
27547 {
27548   struct objfile *objfile;
27549   const char dwarf5space[] = "-dwarf-5 ";
27550   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27551
27552   if (!arg)
27553     arg = "";
27554
27555   arg = skip_spaces (arg);
27556   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27557     {
27558       index_kind = dw_index_kind::DEBUG_NAMES;
27559       arg += strlen (dwarf5space);
27560       arg = skip_spaces (arg);
27561     }
27562
27563   if (!*arg)
27564     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27565
27566   ALL_OBJFILES (objfile)
27567   {
27568     struct stat st;
27569
27570     /* If the objfile does not correspond to an actual file, skip it.  */
27571     if (stat (objfile_name (objfile), &st) < 0)
27572       continue;
27573
27574     struct dwarf2_per_objfile *dwarf2_per_objfile
27575       = get_dwarf2_per_objfile (objfile);
27576
27577     if (dwarf2_per_objfile != NULL)
27578       {
27579         TRY
27580           {
27581             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27582           }
27583         CATCH (except, RETURN_MASK_ERROR)
27584           {
27585             exception_fprintf (gdb_stderr, except,
27586                                _("Error while writing index for `%s': "),
27587                                objfile_name (objfile));
27588           }
27589         END_CATCH
27590       }
27591
27592   }
27593 }
27594
27595 \f
27596
27597 int dwarf_always_disassemble;
27598
27599 static void
27600 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27601                                struct cmd_list_element *c, const char *value)
27602 {
27603   fprintf_filtered (file,
27604                     _("Whether to always disassemble "
27605                       "DWARF expressions is %s.\n"),
27606                     value);
27607 }
27608
27609 static void
27610 show_check_physname (struct ui_file *file, int from_tty,
27611                      struct cmd_list_element *c, const char *value)
27612 {
27613   fprintf_filtered (file,
27614                     _("Whether to check \"physname\" is %s.\n"),
27615                     value);
27616 }
27617
27618 void
27619 _initialize_dwarf2_read (void)
27620 {
27621   struct cmd_list_element *c;
27622
27623   dwarf2_objfile_data_key = register_objfile_data ();
27624
27625   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27626 Set DWARF specific variables.\n\
27627 Configure DWARF variables such as the cache size"),
27628                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27629                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27630
27631   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27632 Show DWARF specific variables\n\
27633 Show DWARF variables such as the cache size"),
27634                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27635                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27636
27637   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27638                             &dwarf_max_cache_age, _("\
27639 Set the upper bound on the age of cached DWARF compilation units."), _("\
27640 Show the upper bound on the age of cached DWARF compilation units."), _("\
27641 A higher limit means that cached compilation units will be stored\n\
27642 in memory longer, and more total memory will be used.  Zero disables\n\
27643 caching, which can slow down startup."),
27644                             NULL,
27645                             show_dwarf_max_cache_age,
27646                             &set_dwarf_cmdlist,
27647                             &show_dwarf_cmdlist);
27648
27649   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27650                            &dwarf_always_disassemble, _("\
27651 Set whether `info address' always disassembles DWARF expressions."), _("\
27652 Show whether `info address' always disassembles DWARF expressions."), _("\
27653 When enabled, DWARF expressions are always printed in an assembly-like\n\
27654 syntax.  When disabled, expressions will be printed in a more\n\
27655 conversational style, when possible."),
27656                            NULL,
27657                            show_dwarf_always_disassemble,
27658                            &set_dwarf_cmdlist,
27659                            &show_dwarf_cmdlist);
27660
27661   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27662 Set debugging of the DWARF reader."), _("\
27663 Show debugging of the DWARF reader."), _("\
27664 When enabled (non-zero), debugging messages are printed during DWARF\n\
27665 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27666 information.  A value greater than 1 provides more verbose information."),
27667                             NULL,
27668                             NULL,
27669                             &setdebuglist, &showdebuglist);
27670
27671   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27672 Set debugging of the DWARF DIE reader."), _("\
27673 Show debugging of the DWARF DIE reader."), _("\
27674 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27675 The value is the maximum depth to print."),
27676                              NULL,
27677                              NULL,
27678                              &setdebuglist, &showdebuglist);
27679
27680   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27681 Set debugging of the dwarf line reader."), _("\
27682 Show debugging of the dwarf line reader."), _("\
27683 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27684 A value of 1 (one) provides basic information.\n\
27685 A value greater than 1 provides more verbose information."),
27686                              NULL,
27687                              NULL,
27688                              &setdebuglist, &showdebuglist);
27689
27690   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27691 Set cross-checking of \"physname\" code against demangler."), _("\
27692 Show cross-checking of \"physname\" code against demangler."), _("\
27693 When enabled, GDB's internal \"physname\" code is checked against\n\
27694 the demangler."),
27695                            NULL, show_check_physname,
27696                            &setdebuglist, &showdebuglist);
27697
27698   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27699                            no_class, &use_deprecated_index_sections, _("\
27700 Set whether to use deprecated gdb_index sections."), _("\
27701 Show whether to use deprecated gdb_index sections."), _("\
27702 When enabled, deprecated .gdb_index sections are used anyway.\n\
27703 Normally they are ignored either because of a missing feature or\n\
27704 performance issue.\n\
27705 Warning: This option must be enabled before gdb reads the file."),
27706                            NULL,
27707                            NULL,
27708                            &setlist, &showlist);
27709
27710   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27711                _("\
27712 Save a gdb-index file.\n\
27713 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27714 \n\
27715 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27716 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27717 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27718                &save_cmdlist);
27719   set_cmd_completer (c, filename_completer);
27720
27721   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27722                                                         &dwarf2_locexpr_funcs);
27723   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27724                                                         &dwarf2_loclist_funcs);
27725
27726   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27727                                         &dwarf2_block_frame_base_locexpr_funcs);
27728   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27729                                         &dwarf2_block_frame_base_loclist_funcs);
27730
27731 #if GDB_SELF_TEST
27732   selftests::register_test ("dw2_expand_symtabs_matching",
27733                             selftests::dw2_expand_symtabs_matching::run_test);
27734 #endif
27735 }