Remove symbolp typedef
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 /* When == 1, print basic high level tracing messages.
91    When > 1, be more verbose.
92    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
93 static unsigned int dwarf_read_debug = 0;
94
95 /* When non-zero, dump DIEs after they are read in.  */
96 static unsigned int dwarf_die_debug = 0;
97
98 /* When non-zero, dump line number entries as they are read in.  */
99 static unsigned int dwarf_line_debug = 0;
100
101 /* When non-zero, cross-check physname against demangler.  */
102 static int check_physname = 0;
103
104 /* When non-zero, do not reject deprecated .gdb_index sections.  */
105 static int use_deprecated_index_sections = 0;
106
107 static const struct objfile_data *dwarf2_objfile_data_key;
108
109 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
110
111 static int dwarf2_locexpr_index;
112 static int dwarf2_loclist_index;
113 static int dwarf2_locexpr_block_index;
114 static int dwarf2_loclist_block_index;
115
116 /* A descriptor for dwarf sections.
117
118    S.ASECTION, SIZE are typically initialized when the objfile is first
119    scanned.  BUFFER, READIN are filled in later when the section is read.
120    If the section contained compressed data then SIZE is updated to record
121    the uncompressed size of the section.
122
123    DWP file format V2 introduces a wrinkle that is easiest to handle by
124    creating the concept of virtual sections contained within a real section.
125    In DWP V2 the sections of the input DWO files are concatenated together
126    into one section, but section offsets are kept relative to the original
127    input section.
128    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
129    the real section this "virtual" section is contained in, and BUFFER,SIZE
130    describe the virtual section.  */
131
132 struct dwarf2_section_info
133 {
134   union
135   {
136     /* If this is a real section, the bfd section.  */
137     asection *section;
138     /* If this is a virtual section, pointer to the containing ("real")
139        section.  */
140     struct dwarf2_section_info *containing_section;
141   } s;
142   /* Pointer to section data, only valid if readin.  */
143   const gdb_byte *buffer;
144   /* The size of the section, real or virtual.  */
145   bfd_size_type size;
146   /* If this is a virtual section, the offset in the real section.
147      Only valid if is_virtual.  */
148   bfd_size_type virtual_offset;
149   /* True if we have tried to read this section.  */
150   char readin;
151   /* True if this is a virtual section, False otherwise.
152      This specifies which of s.section and s.containing_section to use.  */
153   char is_virtual;
154 };
155
156 typedef struct dwarf2_section_info dwarf2_section_info_def;
157 DEF_VEC_O (dwarf2_section_info_def);
158
159 /* All offsets in the index are of this type.  It must be
160    architecture-independent.  */
161 typedef uint32_t offset_type;
162
163 DEF_VEC_I (offset_type);
164
165 /* Ensure only legit values are used.  */
166 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
167   do { \
168     gdb_assert ((unsigned int) (value) <= 1); \
169     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
170   } while (0)
171
172 /* Ensure only legit values are used.  */
173 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
174   do { \
175     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
176                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
177     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
178   } while (0)
179
180 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
181 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
182   do { \
183     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
184     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
185   } while (0)
186
187 #if WORDS_BIGENDIAN
188
189 /* Convert VALUE between big- and little-endian.  */
190
191 static offset_type
192 byte_swap (offset_type value)
193 {
194   offset_type result;
195
196   result = (value & 0xff) << 24;
197   result |= (value & 0xff00) << 8;
198   result |= (value & 0xff0000) >> 8;
199   result |= (value & 0xff000000) >> 24;
200   return result;
201 }
202
203 #define MAYBE_SWAP(V)  byte_swap (V)
204
205 #else
206 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
207 #endif /* WORDS_BIGENDIAN */
208
209 /* An index into a (C++) symbol name component in a symbol name as
210    recorded in the mapped_index's symbol table.  For each C++ symbol
211    in the symbol table, we record one entry for the start of each
212    component in the symbol in a table of name components, and then
213    sort the table, in order to be able to binary search symbol names,
214    ignoring leading namespaces, both completion and regular look up.
215    For example, for symbol "A::B::C", we'll have an entry that points
216    to "A::B::C", another that points to "B::C", and another for "C".
217    Note that function symbols in GDB index have no parameter
218    information, just the function/method names.  You can convert a
219    name_component to a "const char *" using the
220    'mapped_index::symbol_name_at(offset_type)' method.  */
221
222 struct name_component
223 {
224   /* Offset in the symbol name where the component starts.  Stored as
225      a (32-bit) offset instead of a pointer to save memory and improve
226      locality on 64-bit architectures.  */
227   offset_type name_offset;
228
229   /* The symbol's index in the symbol and constant pool tables of a
230      mapped_index.  */
231   offset_type idx;
232 };
233
234 /* Base class containing bits shared by both .gdb_index and
235    .debug_name indexes.  */
236
237 struct mapped_index_base
238 {
239   /* The name_component table (a sorted vector).  See name_component's
240      description above.  */
241   std::vector<name_component> name_components;
242
243   /* How NAME_COMPONENTS is sorted.  */
244   enum case_sensitivity name_components_casing;
245
246   /* Return the number of names in the symbol table.  */
247   virtual size_t symbol_name_count () const = 0;
248
249   /* Get the name of the symbol at IDX in the symbol table.  */
250   virtual const char *symbol_name_at (offset_type idx) const = 0;
251
252   /* Return whether the name at IDX in the symbol table should be
253      ignored.  */
254   virtual bool symbol_name_slot_invalid (offset_type idx) const
255   {
256     return false;
257   }
258
259   /* Build the symbol name component sorted vector, if we haven't
260      yet.  */
261   void build_name_components ();
262
263   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
264      possible matches for LN_NO_PARAMS in the name component
265      vector.  */
266   std::pair<std::vector<name_component>::const_iterator,
267             std::vector<name_component>::const_iterator>
268     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
269
270   /* Prevent deleting/destroying via a base class pointer.  */
271 protected:
272   ~mapped_index_base() = default;
273 };
274
275 /* A description of the mapped index.  The file format is described in
276    a comment by the code that writes the index.  */
277 struct mapped_index final : public mapped_index_base
278 {
279   /* A slot/bucket in the symbol table hash.  */
280   struct symbol_table_slot
281   {
282     const offset_type name;
283     const offset_type vec;
284   };
285
286   /* Index data format version.  */
287   int version;
288
289   /* The total length of the buffer.  */
290   off_t total_size;
291
292   /* The address table data.  */
293   gdb::array_view<const gdb_byte> address_table;
294
295   /* The symbol table, implemented as a hash table.  */
296   gdb::array_view<symbol_table_slot> symbol_table;
297
298   /* A pointer to the constant pool.  */
299   const char *constant_pool;
300
301   bool symbol_name_slot_invalid (offset_type idx) const override
302   {
303     const auto &bucket = this->symbol_table[idx];
304     return bucket.name == 0 && bucket.vec;
305   }
306
307   /* Convenience method to get at the name of the symbol at IDX in the
308      symbol table.  */
309   const char *symbol_name_at (offset_type idx) const override
310   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
311
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size (); }
314 };
315
316 /* A description of the mapped .debug_names.
317    Uninitialized map has CU_COUNT 0.  */
318 struct mapped_debug_names final : public mapped_index_base
319 {
320   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
321   : dwarf2_per_objfile (dwarf2_per_objfile_)
322   {}
323
324   struct dwarf2_per_objfile *dwarf2_per_objfile;
325   bfd_endian dwarf5_byte_order;
326   bool dwarf5_is_dwarf64;
327   bool augmentation_is_gdb;
328   uint8_t offset_size;
329   uint32_t cu_count = 0;
330   uint32_t tu_count, bucket_count, name_count;
331   const gdb_byte *cu_table_reordered, *tu_table_reordered;
332   const uint32_t *bucket_table_reordered, *hash_table_reordered;
333   const gdb_byte *name_table_string_offs_reordered;
334   const gdb_byte *name_table_entry_offs_reordered;
335   const gdb_byte *entry_pool;
336
337   struct index_val
338   {
339     ULONGEST dwarf_tag;
340     struct attr
341     {
342       /* Attribute name DW_IDX_*.  */
343       ULONGEST dw_idx;
344
345       /* Attribute form DW_FORM_*.  */
346       ULONGEST form;
347
348       /* Value if FORM is DW_FORM_implicit_const.  */
349       LONGEST implicit_const;
350     };
351     std::vector<attr> attr_vec;
352   };
353
354   std::unordered_map<ULONGEST, index_val> abbrev_map;
355
356   const char *namei_to_name (uint32_t namei) const;
357
358   /* Implementation of the mapped_index_base virtual interface, for
359      the name_components cache.  */
360
361   const char *symbol_name_at (offset_type idx) const override
362   { return namei_to_name (idx); }
363
364   size_t symbol_name_count () const override
365   { return this->name_count; }
366 };
367
368 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
369 DEF_VEC_P (dwarf2_per_cu_ptr);
370
371 struct tu_stats
372 {
373   int nr_uniq_abbrev_tables;
374   int nr_symtabs;
375   int nr_symtab_sharers;
376   int nr_stmt_less_type_units;
377   int nr_all_type_units_reallocs;
378 };
379
380 /* Collection of data recorded per objfile.
381    This hangs off of dwarf2_objfile_data_key.  */
382
383 struct dwarf2_per_objfile
384 {
385   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
386      dwarf2 section names, or is NULL if the standard ELF names are
387      used.  */
388   dwarf2_per_objfile (struct objfile *objfile,
389                       const dwarf2_debug_sections *names);
390
391   ~dwarf2_per_objfile ();
392
393   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
394
395   /* Free all cached compilation units.  */
396   void free_cached_comp_units ();
397 private:
398   /* This function is mapped across the sections and remembers the
399      offset and size of each of the debugging sections we are
400      interested in.  */
401   void locate_sections (bfd *abfd, asection *sectp,
402                         const dwarf2_debug_sections &names);
403
404 public:
405   dwarf2_section_info info {};
406   dwarf2_section_info abbrev {};
407   dwarf2_section_info line {};
408   dwarf2_section_info loc {};
409   dwarf2_section_info loclists {};
410   dwarf2_section_info macinfo {};
411   dwarf2_section_info macro {};
412   dwarf2_section_info str {};
413   dwarf2_section_info line_str {};
414   dwarf2_section_info ranges {};
415   dwarf2_section_info rnglists {};
416   dwarf2_section_info addr {};
417   dwarf2_section_info frame {};
418   dwarf2_section_info eh_frame {};
419   dwarf2_section_info gdb_index {};
420   dwarf2_section_info debug_names {};
421   dwarf2_section_info debug_aranges {};
422
423   VEC (dwarf2_section_info_def) *types = NULL;
424
425   /* Back link.  */
426   struct objfile *objfile = NULL;
427
428   /* Table of all the compilation units.  This is used to locate
429      the target compilation unit of a particular reference.  */
430   struct dwarf2_per_cu_data **all_comp_units = NULL;
431
432   /* The number of compilation units in ALL_COMP_UNITS.  */
433   int n_comp_units = 0;
434
435   /* The number of .debug_types-related CUs.  */
436   int n_type_units = 0;
437
438   /* The number of elements allocated in all_type_units.
439      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
440   int n_allocated_type_units = 0;
441
442   /* The .debug_types-related CUs (TUs).
443      This is stored in malloc space because we may realloc it.  */
444   struct signatured_type **all_type_units = NULL;
445
446   /* Table of struct type_unit_group objects.
447      The hash key is the DW_AT_stmt_list value.  */
448   htab_t type_unit_groups {};
449
450   /* A table mapping .debug_types signatures to its signatured_type entry.
451      This is NULL if the .debug_types section hasn't been read in yet.  */
452   htab_t signatured_types {};
453
454   /* Type unit statistics, to see how well the scaling improvements
455      are doing.  */
456   struct tu_stats tu_stats {};
457
458   /* A chain of compilation units that are currently read in, so that
459      they can be freed later.  */
460   dwarf2_per_cu_data *read_in_chain = NULL;
461
462   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
463      This is NULL if the table hasn't been allocated yet.  */
464   htab_t dwo_files {};
465
466   /* True if we've checked for whether there is a DWP file.  */
467   bool dwp_checked = false;
468
469   /* The DWP file if there is one, or NULL.  */
470   struct dwp_file *dwp_file = NULL;
471
472   /* The shared '.dwz' file, if one exists.  This is used when the
473      original data was compressed using 'dwz -m'.  */
474   struct dwz_file *dwz_file = NULL;
475
476   /* A flag indicating whether this objfile has a section loaded at a
477      VMA of 0.  */
478   bool has_section_at_zero = false;
479
480   /* True if we are using the mapped index,
481      or we are faking it for OBJF_READNOW's sake.  */
482   bool using_index = false;
483
484   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
485   mapped_index *index_table = NULL;
486
487   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
488   std::unique_ptr<mapped_debug_names> debug_names_table;
489
490   /* When using index_table, this keeps track of all quick_file_names entries.
491      TUs typically share line table entries with a CU, so we maintain a
492      separate table of all line table entries to support the sharing.
493      Note that while there can be way more TUs than CUs, we've already
494      sorted all the TUs into "type unit groups", grouped by their
495      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
496      CU and its associated TU group if there is one.  */
497   htab_t quick_file_names_table {};
498
499   /* Set during partial symbol reading, to prevent queueing of full
500      symbols.  */
501   bool reading_partial_symbols = false;
502
503   /* Table mapping type DIEs to their struct type *.
504      This is NULL if not allocated yet.
505      The mapping is done via (CU/TU + DIE offset) -> type.  */
506   htab_t die_type_hash {};
507
508   /* The CUs we recently read.  */
509   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
510
511   /* Table containing line_header indexed by offset and offset_in_dwz.  */
512   htab_t line_header_hash {};
513
514   /* Table containing all filenames.  This is an optional because the
515      table is lazily constructed on first access.  */
516   gdb::optional<filename_seen_cache> filenames_cache;
517 };
518
519 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
520
521 struct dwarf2_per_objfile *
522 get_dwarf2_per_objfile (struct objfile *objfile)
523 {
524   return ((struct dwarf2_per_objfile *)
525           objfile_data (objfile, dwarf2_objfile_data_key));
526 }
527
528 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
529
530 void
531 set_dwarf2_per_objfile (struct objfile *objfile,
532                         struct dwarf2_per_objfile *dwarf2_per_objfile)
533 {
534   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
535   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
536 }
537
538 /* Default names of the debugging sections.  */
539
540 /* Note that if the debugging section has been compressed, it might
541    have a name like .zdebug_info.  */
542
543 static const struct dwarf2_debug_sections dwarf2_elf_names =
544 {
545   { ".debug_info", ".zdebug_info" },
546   { ".debug_abbrev", ".zdebug_abbrev" },
547   { ".debug_line", ".zdebug_line" },
548   { ".debug_loc", ".zdebug_loc" },
549   { ".debug_loclists", ".zdebug_loclists" },
550   { ".debug_macinfo", ".zdebug_macinfo" },
551   { ".debug_macro", ".zdebug_macro" },
552   { ".debug_str", ".zdebug_str" },
553   { ".debug_line_str", ".zdebug_line_str" },
554   { ".debug_ranges", ".zdebug_ranges" },
555   { ".debug_rnglists", ".zdebug_rnglists" },
556   { ".debug_types", ".zdebug_types" },
557   { ".debug_addr", ".zdebug_addr" },
558   { ".debug_frame", ".zdebug_frame" },
559   { ".eh_frame", NULL },
560   { ".gdb_index", ".zgdb_index" },
561   { ".debug_names", ".zdebug_names" },
562   { ".debug_aranges", ".zdebug_aranges" },
563   23
564 };
565
566 /* List of DWO/DWP sections.  */
567
568 static const struct dwop_section_names
569 {
570   struct dwarf2_section_names abbrev_dwo;
571   struct dwarf2_section_names info_dwo;
572   struct dwarf2_section_names line_dwo;
573   struct dwarf2_section_names loc_dwo;
574   struct dwarf2_section_names loclists_dwo;
575   struct dwarf2_section_names macinfo_dwo;
576   struct dwarf2_section_names macro_dwo;
577   struct dwarf2_section_names str_dwo;
578   struct dwarf2_section_names str_offsets_dwo;
579   struct dwarf2_section_names types_dwo;
580   struct dwarf2_section_names cu_index;
581   struct dwarf2_section_names tu_index;
582 }
583 dwop_section_names =
584 {
585   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
586   { ".debug_info.dwo", ".zdebug_info.dwo" },
587   { ".debug_line.dwo", ".zdebug_line.dwo" },
588   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
589   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
590   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
591   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
592   { ".debug_str.dwo", ".zdebug_str.dwo" },
593   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
594   { ".debug_types.dwo", ".zdebug_types.dwo" },
595   { ".debug_cu_index", ".zdebug_cu_index" },
596   { ".debug_tu_index", ".zdebug_tu_index" },
597 };
598
599 /* local data types */
600
601 /* The data in a compilation unit header, after target2host
602    translation, looks like this.  */
603 struct comp_unit_head
604 {
605   unsigned int length;
606   short version;
607   unsigned char addr_size;
608   unsigned char signed_addr_p;
609   sect_offset abbrev_sect_off;
610
611   /* Size of file offsets; either 4 or 8.  */
612   unsigned int offset_size;
613
614   /* Size of the length field; either 4 or 12.  */
615   unsigned int initial_length_size;
616
617   enum dwarf_unit_type unit_type;
618
619   /* Offset to the first byte of this compilation unit header in the
620      .debug_info section, for resolving relative reference dies.  */
621   sect_offset sect_off;
622
623   /* Offset to first die in this cu from the start of the cu.
624      This will be the first byte following the compilation unit header.  */
625   cu_offset first_die_cu_offset;
626
627   /* 64-bit signature of this type unit - it is valid only for
628      UNIT_TYPE DW_UT_type.  */
629   ULONGEST signature;
630
631   /* For types, offset in the type's DIE of the type defined by this TU.  */
632   cu_offset type_cu_offset_in_tu;
633 };
634
635 /* Type used for delaying computation of method physnames.
636    See comments for compute_delayed_physnames.  */
637 struct delayed_method_info
638 {
639   /* The type to which the method is attached, i.e., its parent class.  */
640   struct type *type;
641
642   /* The index of the method in the type's function fieldlists.  */
643   int fnfield_index;
644
645   /* The index of the method in the fieldlist.  */
646   int index;
647
648   /* The name of the DIE.  */
649   const char *name;
650
651   /*  The DIE associated with this method.  */
652   struct die_info *die;
653 };
654
655 /* Internal state when decoding a particular compilation unit.  */
656 struct dwarf2_cu
657 {
658   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
659   ~dwarf2_cu ();
660
661   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
662
663   /* The header of the compilation unit.  */
664   struct comp_unit_head header {};
665
666   /* Base address of this compilation unit.  */
667   CORE_ADDR base_address = 0;
668
669   /* Non-zero if base_address has been set.  */
670   int base_known = 0;
671
672   /* The language we are debugging.  */
673   enum language language = language_unknown;
674   const struct language_defn *language_defn = nullptr;
675
676   const char *producer = nullptr;
677
678   /* The generic symbol table building routines have separate lists for
679      file scope symbols and all all other scopes (local scopes).  So
680      we need to select the right one to pass to add_symbol_to_list().
681      We do it by keeping a pointer to the correct list in list_in_scope.
682
683      FIXME: The original dwarf code just treated the file scope as the
684      first local scope, and all other local scopes as nested local
685      scopes, and worked fine.  Check to see if we really need to
686      distinguish these in buildsym.c.  */
687   struct pending **list_in_scope = nullptr;
688
689   /* Hash table holding all the loaded partial DIEs
690      with partial_die->offset.SECT_OFF as hash.  */
691   htab_t partial_dies = nullptr;
692
693   /* Storage for things with the same lifetime as this read-in compilation
694      unit, including partial DIEs.  */
695   auto_obstack comp_unit_obstack;
696
697   /* When multiple dwarf2_cu structures are living in memory, this field
698      chains them all together, so that they can be released efficiently.
699      We will probably also want a generation counter so that most-recently-used
700      compilation units are cached...  */
701   struct dwarf2_per_cu_data *read_in_chain = nullptr;
702
703   /* Backlink to our per_cu entry.  */
704   struct dwarf2_per_cu_data *per_cu;
705
706   /* How many compilation units ago was this CU last referenced?  */
707   int last_used = 0;
708
709   /* A hash table of DIE cu_offset for following references with
710      die_info->offset.sect_off as hash.  */
711   htab_t die_hash = nullptr;
712
713   /* Full DIEs if read in.  */
714   struct die_info *dies = nullptr;
715
716   /* A set of pointers to dwarf2_per_cu_data objects for compilation
717      units referenced by this one.  Only set during full symbol processing;
718      partial symbol tables do not have dependencies.  */
719   htab_t dependencies = nullptr;
720
721   /* Header data from the line table, during full symbol processing.  */
722   struct line_header *line_header = nullptr;
723   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
724      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
725      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
726      to the line header as long as this DIE is being processed.  See
727      process_die_scope.  */
728   die_info *line_header_die_owner = nullptr;
729
730   /* A list of methods which need to have physnames computed
731      after all type information has been read.  */
732   std::vector<delayed_method_info> method_list;
733
734   /* To be copied to symtab->call_site_htab.  */
735   htab_t call_site_htab = nullptr;
736
737   /* Non-NULL if this CU came from a DWO file.
738      There is an invariant here that is important to remember:
739      Except for attributes copied from the top level DIE in the "main"
740      (or "stub") file in preparation for reading the DWO file
741      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
742      Either there isn't a DWO file (in which case this is NULL and the point
743      is moot), or there is and either we're not going to read it (in which
744      case this is NULL) or there is and we are reading it (in which case this
745      is non-NULL).  */
746   struct dwo_unit *dwo_unit = nullptr;
747
748   /* The DW_AT_addr_base attribute if present, zero otherwise
749      (zero is a valid value though).
750      Note this value comes from the Fission stub CU/TU's DIE.  */
751   ULONGEST addr_base = 0;
752
753   /* The DW_AT_ranges_base attribute if present, zero otherwise
754      (zero is a valid value though).
755      Note this value comes from the Fission stub CU/TU's DIE.
756      Also note that the value is zero in the non-DWO case so this value can
757      be used without needing to know whether DWO files are in use or not.
758      N.B. This does not apply to DW_AT_ranges appearing in
759      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
760      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
761      DW_AT_ranges_base *would* have to be applied, and we'd have to care
762      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
763   ULONGEST ranges_base = 0;
764
765   /* Mark used when releasing cached dies.  */
766   unsigned int mark : 1;
767
768   /* This CU references .debug_loc.  See the symtab->locations_valid field.
769      This test is imperfect as there may exist optimized debug code not using
770      any location list and still facing inlining issues if handled as
771      unoptimized code.  For a future better test see GCC PR other/32998.  */
772   unsigned int has_loclist : 1;
773
774   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
775      if all the producer_is_* fields are valid.  This information is cached
776      because profiling CU expansion showed excessive time spent in
777      producer_is_gxx_lt_4_6.  */
778   unsigned int checked_producer : 1;
779   unsigned int producer_is_gxx_lt_4_6 : 1;
780   unsigned int producer_is_gcc_lt_4_3 : 1;
781   unsigned int producer_is_icc_lt_14 : 1;
782
783   /* When set, the file that we're processing is known to have
784      debugging info for C++ namespaces.  GCC 3.3.x did not produce
785      this information, but later versions do.  */
786
787   unsigned int processing_has_namespace_info : 1;
788 };
789
790 /* Persistent data held for a compilation unit, even when not
791    processing it.  We put a pointer to this structure in the
792    read_symtab_private field of the psymtab.  */
793
794 struct dwarf2_per_cu_data
795 {
796   /* The start offset and length of this compilation unit.
797      NOTE: Unlike comp_unit_head.length, this length includes
798      initial_length_size.
799      If the DIE refers to a DWO file, this is always of the original die,
800      not the DWO file.  */
801   sect_offset sect_off;
802   unsigned int length;
803
804   /* DWARF standard version this data has been read from (such as 4 or 5).  */
805   short dwarf_version;
806
807   /* Flag indicating this compilation unit will be read in before
808      any of the current compilation units are processed.  */
809   unsigned int queued : 1;
810
811   /* This flag will be set when reading partial DIEs if we need to load
812      absolutely all DIEs for this compilation unit, instead of just the ones
813      we think are interesting.  It gets set if we look for a DIE in the
814      hash table and don't find it.  */
815   unsigned int load_all_dies : 1;
816
817   /* Non-zero if this CU is from .debug_types.
818      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
819      this is non-zero.  */
820   unsigned int is_debug_types : 1;
821
822   /* Non-zero if this CU is from the .dwz file.  */
823   unsigned int is_dwz : 1;
824
825   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
826      This flag is only valid if is_debug_types is true.
827      We can't read a CU directly from a DWO file: There are required
828      attributes in the stub.  */
829   unsigned int reading_dwo_directly : 1;
830
831   /* Non-zero if the TU has been read.
832      This is used to assist the "Stay in DWO Optimization" for Fission:
833      When reading a DWO, it's faster to read TUs from the DWO instead of
834      fetching them from random other DWOs (due to comdat folding).
835      If the TU has already been read, the optimization is unnecessary
836      (and unwise - we don't want to change where gdb thinks the TU lives
837      "midflight").
838      This flag is only valid if is_debug_types is true.  */
839   unsigned int tu_read : 1;
840
841   /* The section this CU/TU lives in.
842      If the DIE refers to a DWO file, this is always the original die,
843      not the DWO file.  */
844   struct dwarf2_section_info *section;
845
846   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
847      of the CU cache it gets reset to NULL again.  This is left as NULL for
848      dummy CUs (a CU header, but nothing else).  */
849   struct dwarf2_cu *cu;
850
851   /* The corresponding dwarf2_per_objfile.  */
852   struct dwarf2_per_objfile *dwarf2_per_objfile;
853
854   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
855      is active.  Otherwise, the 'psymtab' field is active.  */
856   union
857   {
858     /* The partial symbol table associated with this compilation unit,
859        or NULL for unread partial units.  */
860     struct partial_symtab *psymtab;
861
862     /* Data needed by the "quick" functions.  */
863     struct dwarf2_per_cu_quick_data *quick;
864   } v;
865
866   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
867      while reading psymtabs, used to compute the psymtab dependencies,
868      and then cleared.  Then it is filled in again while reading full
869      symbols, and only deleted when the objfile is destroyed.
870
871      This is also used to work around a difference between the way gold
872      generates .gdb_index version <=7 and the way gdb does.  Arguably this
873      is a gold bug.  For symbols coming from TUs, gold records in the index
874      the CU that includes the TU instead of the TU itself.  This breaks
875      dw2_lookup_symbol: It assumes that if the index says symbol X lives
876      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
877      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
878      we need to look in TU Z to find X.  Fortunately, this is akin to
879      DW_TAG_imported_unit, so we just use the same mechanism: For
880      .gdb_index version <=7 this also records the TUs that the CU referred
881      to.  Concurrently with this change gdb was modified to emit version 8
882      indices so we only pay a price for gold generated indices.
883      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
884   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
885 };
886
887 /* Entry in the signatured_types hash table.  */
888
889 struct signatured_type
890 {
891   /* The "per_cu" object of this type.
892      This struct is used iff per_cu.is_debug_types.
893      N.B.: This is the first member so that it's easy to convert pointers
894      between them.  */
895   struct dwarf2_per_cu_data per_cu;
896
897   /* The type's signature.  */
898   ULONGEST signature;
899
900   /* Offset in the TU of the type's DIE, as read from the TU header.
901      If this TU is a DWO stub and the definition lives in a DWO file
902      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
903   cu_offset type_offset_in_tu;
904
905   /* Offset in the section of the type's DIE.
906      If the definition lives in a DWO file, this is the offset in the
907      .debug_types.dwo section.
908      The value is zero until the actual value is known.
909      Zero is otherwise not a valid section offset.  */
910   sect_offset type_offset_in_section;
911
912   /* Type units are grouped by their DW_AT_stmt_list entry so that they
913      can share them.  This points to the containing symtab.  */
914   struct type_unit_group *type_unit_group;
915
916   /* The type.
917      The first time we encounter this type we fully read it in and install it
918      in the symbol tables.  Subsequent times we only need the type.  */
919   struct type *type;
920
921   /* Containing DWO unit.
922      This field is valid iff per_cu.reading_dwo_directly.  */
923   struct dwo_unit *dwo_unit;
924 };
925
926 typedef struct signatured_type *sig_type_ptr;
927 DEF_VEC_P (sig_type_ptr);
928
929 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
930    This includes type_unit_group and quick_file_names.  */
931
932 struct stmt_list_hash
933 {
934   /* The DWO unit this table is from or NULL if there is none.  */
935   struct dwo_unit *dwo_unit;
936
937   /* Offset in .debug_line or .debug_line.dwo.  */
938   sect_offset line_sect_off;
939 };
940
941 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
942    an object of this type.  */
943
944 struct type_unit_group
945 {
946   /* dwarf2read.c's main "handle" on a TU symtab.
947      To simplify things we create an artificial CU that "includes" all the
948      type units using this stmt_list so that the rest of the code still has
949      a "per_cu" handle on the symtab.
950      This PER_CU is recognized by having no section.  */
951 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
952   struct dwarf2_per_cu_data per_cu;
953
954   /* The TUs that share this DW_AT_stmt_list entry.
955      This is added to while parsing type units to build partial symtabs,
956      and is deleted afterwards and not used again.  */
957   VEC (sig_type_ptr) *tus;
958
959   /* The compunit symtab.
960      Type units in a group needn't all be defined in the same source file,
961      so we create an essentially anonymous symtab as the compunit symtab.  */
962   struct compunit_symtab *compunit_symtab;
963
964   /* The data used to construct the hash key.  */
965   struct stmt_list_hash hash;
966
967   /* The number of symtabs from the line header.
968      The value here must match line_header.num_file_names.  */
969   unsigned int num_symtabs;
970
971   /* The symbol tables for this TU (obtained from the files listed in
972      DW_AT_stmt_list).
973      WARNING: The order of entries here must match the order of entries
974      in the line header.  After the first TU using this type_unit_group, the
975      line header for the subsequent TUs is recreated from this.  This is done
976      because we need to use the same symtabs for each TU using the same
977      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
978      there's no guarantee the line header doesn't have duplicate entries.  */
979   struct symtab **symtabs;
980 };
981
982 /* These sections are what may appear in a (real or virtual) DWO file.  */
983
984 struct dwo_sections
985 {
986   struct dwarf2_section_info abbrev;
987   struct dwarf2_section_info line;
988   struct dwarf2_section_info loc;
989   struct dwarf2_section_info loclists;
990   struct dwarf2_section_info macinfo;
991   struct dwarf2_section_info macro;
992   struct dwarf2_section_info str;
993   struct dwarf2_section_info str_offsets;
994   /* In the case of a virtual DWO file, these two are unused.  */
995   struct dwarf2_section_info info;
996   VEC (dwarf2_section_info_def) *types;
997 };
998
999 /* CUs/TUs in DWP/DWO files.  */
1000
1001 struct dwo_unit
1002 {
1003   /* Backlink to the containing struct dwo_file.  */
1004   struct dwo_file *dwo_file;
1005
1006   /* The "id" that distinguishes this CU/TU.
1007      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1008      Since signatures came first, we stick with it for consistency.  */
1009   ULONGEST signature;
1010
1011   /* The section this CU/TU lives in, in the DWO file.  */
1012   struct dwarf2_section_info *section;
1013
1014   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1015   sect_offset sect_off;
1016   unsigned int length;
1017
1018   /* For types, offset in the type's DIE of the type defined by this TU.  */
1019   cu_offset type_offset_in_tu;
1020 };
1021
1022 /* include/dwarf2.h defines the DWP section codes.
1023    It defines a max value but it doesn't define a min value, which we
1024    use for error checking, so provide one.  */
1025
1026 enum dwp_v2_section_ids
1027 {
1028   DW_SECT_MIN = 1
1029 };
1030
1031 /* Data for one DWO file.
1032
1033    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1034    appears in a DWP file).  DWP files don't really have DWO files per se -
1035    comdat folding of types "loses" the DWO file they came from, and from
1036    a high level view DWP files appear to contain a mass of random types.
1037    However, to maintain consistency with the non-DWP case we pretend DWP
1038    files contain virtual DWO files, and we assign each TU with one virtual
1039    DWO file (generally based on the line and abbrev section offsets -
1040    a heuristic that seems to work in practice).  */
1041
1042 struct dwo_file
1043 {
1044   /* The DW_AT_GNU_dwo_name attribute.
1045      For virtual DWO files the name is constructed from the section offsets
1046      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1047      from related CU+TUs.  */
1048   const char *dwo_name;
1049
1050   /* The DW_AT_comp_dir attribute.  */
1051   const char *comp_dir;
1052
1053   /* The bfd, when the file is open.  Otherwise this is NULL.
1054      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1055   bfd *dbfd;
1056
1057   /* The sections that make up this DWO file.
1058      Remember that for virtual DWO files in DWP V2, these are virtual
1059      sections (for lack of a better name).  */
1060   struct dwo_sections sections;
1061
1062   /* The CUs in the file.
1063      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1064      an extension to handle LLVM's Link Time Optimization output (where
1065      multiple source files may be compiled into a single object/dwo pair). */
1066   htab_t cus;
1067
1068   /* Table of TUs in the file.
1069      Each element is a struct dwo_unit.  */
1070   htab_t tus;
1071 };
1072
1073 /* These sections are what may appear in a DWP file.  */
1074
1075 struct dwp_sections
1076 {
1077   /* These are used by both DWP version 1 and 2.  */
1078   struct dwarf2_section_info str;
1079   struct dwarf2_section_info cu_index;
1080   struct dwarf2_section_info tu_index;
1081
1082   /* These are only used by DWP version 2 files.
1083      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1084      sections are referenced by section number, and are not recorded here.
1085      In DWP version 2 there is at most one copy of all these sections, each
1086      section being (effectively) comprised of the concatenation of all of the
1087      individual sections that exist in the version 1 format.
1088      To keep the code simple we treat each of these concatenated pieces as a
1089      section itself (a virtual section?).  */
1090   struct dwarf2_section_info abbrev;
1091   struct dwarf2_section_info info;
1092   struct dwarf2_section_info line;
1093   struct dwarf2_section_info loc;
1094   struct dwarf2_section_info macinfo;
1095   struct dwarf2_section_info macro;
1096   struct dwarf2_section_info str_offsets;
1097   struct dwarf2_section_info types;
1098 };
1099
1100 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1101    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1102
1103 struct virtual_v1_dwo_sections
1104 {
1105   struct dwarf2_section_info abbrev;
1106   struct dwarf2_section_info line;
1107   struct dwarf2_section_info loc;
1108   struct dwarf2_section_info macinfo;
1109   struct dwarf2_section_info macro;
1110   struct dwarf2_section_info str_offsets;
1111   /* Each DWP hash table entry records one CU or one TU.
1112      That is recorded here, and copied to dwo_unit.section.  */
1113   struct dwarf2_section_info info_or_types;
1114 };
1115
1116 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1117    In version 2, the sections of the DWO files are concatenated together
1118    and stored in one section of that name.  Thus each ELF section contains
1119    several "virtual" sections.  */
1120
1121 struct virtual_v2_dwo_sections
1122 {
1123   bfd_size_type abbrev_offset;
1124   bfd_size_type abbrev_size;
1125
1126   bfd_size_type line_offset;
1127   bfd_size_type line_size;
1128
1129   bfd_size_type loc_offset;
1130   bfd_size_type loc_size;
1131
1132   bfd_size_type macinfo_offset;
1133   bfd_size_type macinfo_size;
1134
1135   bfd_size_type macro_offset;
1136   bfd_size_type macro_size;
1137
1138   bfd_size_type str_offsets_offset;
1139   bfd_size_type str_offsets_size;
1140
1141   /* Each DWP hash table entry records one CU or one TU.
1142      That is recorded here, and copied to dwo_unit.section.  */
1143   bfd_size_type info_or_types_offset;
1144   bfd_size_type info_or_types_size;
1145 };
1146
1147 /* Contents of DWP hash tables.  */
1148
1149 struct dwp_hash_table
1150 {
1151   uint32_t version, nr_columns;
1152   uint32_t nr_units, nr_slots;
1153   const gdb_byte *hash_table, *unit_table;
1154   union
1155   {
1156     struct
1157     {
1158       const gdb_byte *indices;
1159     } v1;
1160     struct
1161     {
1162       /* This is indexed by column number and gives the id of the section
1163          in that column.  */
1164 #define MAX_NR_V2_DWO_SECTIONS \
1165   (1 /* .debug_info or .debug_types */ \
1166    + 1 /* .debug_abbrev */ \
1167    + 1 /* .debug_line */ \
1168    + 1 /* .debug_loc */ \
1169    + 1 /* .debug_str_offsets */ \
1170    + 1 /* .debug_macro or .debug_macinfo */)
1171       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1172       const gdb_byte *offsets;
1173       const gdb_byte *sizes;
1174     } v2;
1175   } section_pool;
1176 };
1177
1178 /* Data for one DWP file.  */
1179
1180 struct dwp_file
1181 {
1182   /* Name of the file.  */
1183   const char *name;
1184
1185   /* File format version.  */
1186   int version;
1187
1188   /* The bfd.  */
1189   bfd *dbfd;
1190
1191   /* Section info for this file.  */
1192   struct dwp_sections sections;
1193
1194   /* Table of CUs in the file.  */
1195   const struct dwp_hash_table *cus;
1196
1197   /* Table of TUs in the file.  */
1198   const struct dwp_hash_table *tus;
1199
1200   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1201   htab_t loaded_cus;
1202   htab_t loaded_tus;
1203
1204   /* Table to map ELF section numbers to their sections.
1205      This is only needed for the DWP V1 file format.  */
1206   unsigned int num_sections;
1207   asection **elf_sections;
1208 };
1209
1210 /* This represents a '.dwz' file.  */
1211
1212 struct dwz_file
1213 {
1214   /* A dwz file can only contain a few sections.  */
1215   struct dwarf2_section_info abbrev;
1216   struct dwarf2_section_info info;
1217   struct dwarf2_section_info str;
1218   struct dwarf2_section_info line;
1219   struct dwarf2_section_info macro;
1220   struct dwarf2_section_info gdb_index;
1221   struct dwarf2_section_info debug_names;
1222
1223   /* The dwz's BFD.  */
1224   bfd *dwz_bfd;
1225 };
1226
1227 /* Struct used to pass misc. parameters to read_die_and_children, et
1228    al.  which are used for both .debug_info and .debug_types dies.
1229    All parameters here are unchanging for the life of the call.  This
1230    struct exists to abstract away the constant parameters of die reading.  */
1231
1232 struct die_reader_specs
1233 {
1234   /* The bfd of die_section.  */
1235   bfd* abfd;
1236
1237   /* The CU of the DIE we are parsing.  */
1238   struct dwarf2_cu *cu;
1239
1240   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1241   struct dwo_file *dwo_file;
1242
1243   /* The section the die comes from.
1244      This is either .debug_info or .debug_types, or the .dwo variants.  */
1245   struct dwarf2_section_info *die_section;
1246
1247   /* die_section->buffer.  */
1248   const gdb_byte *buffer;
1249
1250   /* The end of the buffer.  */
1251   const gdb_byte *buffer_end;
1252
1253   /* The value of the DW_AT_comp_dir attribute.  */
1254   const char *comp_dir;
1255
1256   /* The abbreviation table to use when reading the DIEs.  */
1257   struct abbrev_table *abbrev_table;
1258 };
1259
1260 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1261 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1262                                       const gdb_byte *info_ptr,
1263                                       struct die_info *comp_unit_die,
1264                                       int has_children,
1265                                       void *data);
1266
1267 /* A 1-based directory index.  This is a strong typedef to prevent
1268    accidentally using a directory index as a 0-based index into an
1269    array/vector.  */
1270 enum class dir_index : unsigned int {};
1271
1272 /* Likewise, a 1-based file name index.  */
1273 enum class file_name_index : unsigned int {};
1274
1275 struct file_entry
1276 {
1277   file_entry () = default;
1278
1279   file_entry (const char *name_, dir_index d_index_,
1280               unsigned int mod_time_, unsigned int length_)
1281     : name (name_),
1282       d_index (d_index_),
1283       mod_time (mod_time_),
1284       length (length_)
1285   {}
1286
1287   /* Return the include directory at D_INDEX stored in LH.  Returns
1288      NULL if D_INDEX is out of bounds.  */
1289   const char *include_dir (const line_header *lh) const;
1290
1291   /* The file name.  Note this is an observing pointer.  The memory is
1292      owned by debug_line_buffer.  */
1293   const char *name {};
1294
1295   /* The directory index (1-based).  */
1296   dir_index d_index {};
1297
1298   unsigned int mod_time {};
1299
1300   unsigned int length {};
1301
1302   /* True if referenced by the Line Number Program.  */
1303   bool included_p {};
1304
1305   /* The associated symbol table, if any.  */
1306   struct symtab *symtab {};
1307 };
1308
1309 /* The line number information for a compilation unit (found in the
1310    .debug_line section) begins with a "statement program header",
1311    which contains the following information.  */
1312 struct line_header
1313 {
1314   line_header ()
1315     : offset_in_dwz {}
1316   {}
1317
1318   /* Add an entry to the include directory table.  */
1319   void add_include_dir (const char *include_dir);
1320
1321   /* Add an entry to the file name table.  */
1322   void add_file_name (const char *name, dir_index d_index,
1323                       unsigned int mod_time, unsigned int length);
1324
1325   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1326      is out of bounds.  */
1327   const char *include_dir_at (dir_index index) const
1328   {
1329     /* Convert directory index number (1-based) to vector index
1330        (0-based).  */
1331     size_t vec_index = to_underlying (index) - 1;
1332
1333     if (vec_index >= include_dirs.size ())
1334       return NULL;
1335     return include_dirs[vec_index];
1336   }
1337
1338   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1339      is out of bounds.  */
1340   file_entry *file_name_at (file_name_index index)
1341   {
1342     /* Convert file name index number (1-based) to vector index
1343        (0-based).  */
1344     size_t vec_index = to_underlying (index) - 1;
1345
1346     if (vec_index >= file_names.size ())
1347       return NULL;
1348     return &file_names[vec_index];
1349   }
1350
1351   /* Const version of the above.  */
1352   const file_entry *file_name_at (unsigned int index) const
1353   {
1354     if (index >= file_names.size ())
1355       return NULL;
1356     return &file_names[index];
1357   }
1358
1359   /* Offset of line number information in .debug_line section.  */
1360   sect_offset sect_off {};
1361
1362   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1363   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1364
1365   unsigned int total_length {};
1366   unsigned short version {};
1367   unsigned int header_length {};
1368   unsigned char minimum_instruction_length {};
1369   unsigned char maximum_ops_per_instruction {};
1370   unsigned char default_is_stmt {};
1371   int line_base {};
1372   unsigned char line_range {};
1373   unsigned char opcode_base {};
1374
1375   /* standard_opcode_lengths[i] is the number of operands for the
1376      standard opcode whose value is i.  This means that
1377      standard_opcode_lengths[0] is unused, and the last meaningful
1378      element is standard_opcode_lengths[opcode_base - 1].  */
1379   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1380
1381   /* The include_directories table.  Note these are observing
1382      pointers.  The memory is owned by debug_line_buffer.  */
1383   std::vector<const char *> include_dirs;
1384
1385   /* The file_names table.  */
1386   std::vector<file_entry> file_names;
1387
1388   /* The start and end of the statement program following this
1389      header.  These point into dwarf2_per_objfile->line_buffer.  */
1390   const gdb_byte *statement_program_start {}, *statement_program_end {};
1391 };
1392
1393 typedef std::unique_ptr<line_header> line_header_up;
1394
1395 const char *
1396 file_entry::include_dir (const line_header *lh) const
1397 {
1398   return lh->include_dir_at (d_index);
1399 }
1400
1401 /* When we construct a partial symbol table entry we only
1402    need this much information.  */
1403 struct partial_die_info
1404   {
1405     /* Offset of this DIE.  */
1406     sect_offset sect_off;
1407
1408     /* DWARF-2 tag for this DIE.  */
1409     ENUM_BITFIELD(dwarf_tag) tag : 16;
1410
1411     /* Assorted flags describing the data found in this DIE.  */
1412     unsigned int has_children : 1;
1413     unsigned int is_external : 1;
1414     unsigned int is_declaration : 1;
1415     unsigned int has_type : 1;
1416     unsigned int has_specification : 1;
1417     unsigned int has_pc_info : 1;
1418     unsigned int may_be_inlined : 1;
1419
1420     /* This DIE has been marked DW_AT_main_subprogram.  */
1421     unsigned int main_subprogram : 1;
1422
1423     /* Flag set if the SCOPE field of this structure has been
1424        computed.  */
1425     unsigned int scope_set : 1;
1426
1427     /* Flag set if the DIE has a byte_size attribute.  */
1428     unsigned int has_byte_size : 1;
1429
1430     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1431     unsigned int has_const_value : 1;
1432
1433     /* Flag set if any of the DIE's children are template arguments.  */
1434     unsigned int has_template_arguments : 1;
1435
1436     /* Flag set if fixup_partial_die has been called on this die.  */
1437     unsigned int fixup_called : 1;
1438
1439     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1440     unsigned int is_dwz : 1;
1441
1442     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1443     unsigned int spec_is_dwz : 1;
1444
1445     /* The name of this DIE.  Normally the value of DW_AT_name, but
1446        sometimes a default name for unnamed DIEs.  */
1447     const char *name;
1448
1449     /* The linkage name, if present.  */
1450     const char *linkage_name;
1451
1452     /* The scope to prepend to our children.  This is generally
1453        allocated on the comp_unit_obstack, so will disappear
1454        when this compilation unit leaves the cache.  */
1455     const char *scope;
1456
1457     /* Some data associated with the partial DIE.  The tag determines
1458        which field is live.  */
1459     union
1460     {
1461       /* The location description associated with this DIE, if any.  */
1462       struct dwarf_block *locdesc;
1463       /* The offset of an import, for DW_TAG_imported_unit.  */
1464       sect_offset sect_off;
1465     } d;
1466
1467     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1468     CORE_ADDR lowpc;
1469     CORE_ADDR highpc;
1470
1471     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1472        DW_AT_sibling, if any.  */
1473     /* NOTE: This member isn't strictly necessary, read_partial_die could
1474        return DW_AT_sibling values to its caller load_partial_dies.  */
1475     const gdb_byte *sibling;
1476
1477     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1478        DW_AT_specification (or DW_AT_abstract_origin or
1479        DW_AT_extension).  */
1480     sect_offset spec_offset;
1481
1482     /* Pointers to this DIE's parent, first child, and next sibling,
1483        if any.  */
1484     struct partial_die_info *die_parent, *die_child, *die_sibling;
1485   };
1486
1487 /* This data structure holds the information of an abbrev.  */
1488 struct abbrev_info
1489   {
1490     unsigned int number;        /* number identifying abbrev */
1491     enum dwarf_tag tag;         /* dwarf tag */
1492     unsigned short has_children;                /* boolean */
1493     unsigned short num_attrs;   /* number of attributes */
1494     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1495     struct abbrev_info *next;   /* next in chain */
1496   };
1497
1498 struct attr_abbrev
1499   {
1500     ENUM_BITFIELD(dwarf_attribute) name : 16;
1501     ENUM_BITFIELD(dwarf_form) form : 16;
1502
1503     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1504     LONGEST implicit_const;
1505   };
1506
1507 /* Size of abbrev_table.abbrev_hash_table.  */
1508 #define ABBREV_HASH_SIZE 121
1509
1510 /* Top level data structure to contain an abbreviation table.  */
1511
1512 struct abbrev_table
1513 {
1514   explicit abbrev_table (sect_offset off)
1515     : sect_off (off)
1516   {
1517     abbrevs =
1518       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1519     memset (abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1520   }
1521
1522   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1523
1524   /* Allocate space for a struct abbrev_info object in
1525      ABBREV_TABLE.  */
1526   struct abbrev_info *alloc_abbrev ();
1527
1528   /* Add an abbreviation to the table.  */
1529   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1530
1531   /* Look up an abbrev in the table.
1532      Returns NULL if the abbrev is not found.  */
1533
1534   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1535
1536
1537   /* Where the abbrev table came from.
1538      This is used as a sanity check when the table is used.  */
1539   const sect_offset sect_off;
1540
1541   /* Storage for the abbrev table.  */
1542   auto_obstack abbrev_obstack;
1543
1544   /* Hash table of abbrevs.
1545      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1546      It could be statically allocated, but the previous code didn't so we
1547      don't either.  */
1548   struct abbrev_info **abbrevs;
1549 };
1550
1551 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1552
1553 /* Attributes have a name and a value.  */
1554 struct attribute
1555   {
1556     ENUM_BITFIELD(dwarf_attribute) name : 16;
1557     ENUM_BITFIELD(dwarf_form) form : 15;
1558
1559     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1560        field should be in u.str (existing only for DW_STRING) but it is kept
1561        here for better struct attribute alignment.  */
1562     unsigned int string_is_canonical : 1;
1563
1564     union
1565       {
1566         const char *str;
1567         struct dwarf_block *blk;
1568         ULONGEST unsnd;
1569         LONGEST snd;
1570         CORE_ADDR addr;
1571         ULONGEST signature;
1572       }
1573     u;
1574   };
1575
1576 /* This data structure holds a complete die structure.  */
1577 struct die_info
1578   {
1579     /* DWARF-2 tag for this DIE.  */
1580     ENUM_BITFIELD(dwarf_tag) tag : 16;
1581
1582     /* Number of attributes */
1583     unsigned char num_attrs;
1584
1585     /* True if we're presently building the full type name for the
1586        type derived from this DIE.  */
1587     unsigned char building_fullname : 1;
1588
1589     /* True if this die is in process.  PR 16581.  */
1590     unsigned char in_process : 1;
1591
1592     /* Abbrev number */
1593     unsigned int abbrev;
1594
1595     /* Offset in .debug_info or .debug_types section.  */
1596     sect_offset sect_off;
1597
1598     /* The dies in a compilation unit form an n-ary tree.  PARENT
1599        points to this die's parent; CHILD points to the first child of
1600        this node; and all the children of a given node are chained
1601        together via their SIBLING fields.  */
1602     struct die_info *child;     /* Its first child, if any.  */
1603     struct die_info *sibling;   /* Its next sibling, if any.  */
1604     struct die_info *parent;    /* Its parent, if any.  */
1605
1606     /* An array of attributes, with NUM_ATTRS elements.  There may be
1607        zero, but it's not common and zero-sized arrays are not
1608        sufficiently portable C.  */
1609     struct attribute attrs[1];
1610   };
1611
1612 /* Get at parts of an attribute structure.  */
1613
1614 #define DW_STRING(attr)    ((attr)->u.str)
1615 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1616 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1617 #define DW_BLOCK(attr)     ((attr)->u.blk)
1618 #define DW_SND(attr)       ((attr)->u.snd)
1619 #define DW_ADDR(attr)      ((attr)->u.addr)
1620 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1621
1622 /* Blocks are a bunch of untyped bytes.  */
1623 struct dwarf_block
1624   {
1625     size_t size;
1626
1627     /* Valid only if SIZE is not zero.  */
1628     const gdb_byte *data;
1629   };
1630
1631 #ifndef ATTR_ALLOC_CHUNK
1632 #define ATTR_ALLOC_CHUNK 4
1633 #endif
1634
1635 /* Allocate fields for structs, unions and enums in this size.  */
1636 #ifndef DW_FIELD_ALLOC_CHUNK
1637 #define DW_FIELD_ALLOC_CHUNK 4
1638 #endif
1639
1640 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1641    but this would require a corresponding change in unpack_field_as_long
1642    and friends.  */
1643 static int bits_per_byte = 8;
1644
1645 struct nextfield
1646 {
1647   struct nextfield *next;
1648   int accessibility;
1649   int virtuality;
1650   struct field field;
1651 };
1652
1653 struct nextfnfield
1654 {
1655   struct nextfnfield *next;
1656   struct fn_field fnfield;
1657 };
1658
1659 struct fnfieldlist
1660 {
1661   const char *name;
1662   int length;
1663   struct nextfnfield *head;
1664 };
1665
1666 struct decl_field_list
1667 {
1668   struct decl_field field;
1669   struct decl_field_list *next;
1670 };
1671
1672 /* The routines that read and process dies for a C struct or C++ class
1673    pass lists of data member fields and lists of member function fields
1674    in an instance of a field_info structure, as defined below.  */
1675 struct field_info
1676   {
1677     /* List of data member and baseclasses fields.  */
1678     struct nextfield *fields, *baseclasses;
1679
1680     /* Number of fields (including baseclasses).  */
1681     int nfields;
1682
1683     /* Number of baseclasses.  */
1684     int nbaseclasses;
1685
1686     /* Set if the accesibility of one of the fields is not public.  */
1687     int non_public_fields;
1688
1689     /* Member function fieldlist array, contains name of possibly overloaded
1690        member function, number of overloaded member functions and a pointer
1691        to the head of the member function field chain.  */
1692     struct fnfieldlist *fnfieldlists;
1693
1694     /* Number of entries in the fnfieldlists array.  */
1695     int nfnfields;
1696
1697     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1698        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1699     struct decl_field_list *typedef_field_list;
1700     unsigned typedef_field_list_count;
1701
1702     /* Nested types defined by this class and the number of elements in this
1703        list.  */
1704     struct decl_field_list *nested_types_list;
1705     unsigned nested_types_list_count;
1706   };
1707
1708 /* One item on the queue of compilation units to read in full symbols
1709    for.  */
1710 struct dwarf2_queue_item
1711 {
1712   struct dwarf2_per_cu_data *per_cu;
1713   enum language pretend_language;
1714   struct dwarf2_queue_item *next;
1715 };
1716
1717 /* The current queue.  */
1718 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1719
1720 /* Loaded secondary compilation units are kept in memory until they
1721    have not been referenced for the processing of this many
1722    compilation units.  Set this to zero to disable caching.  Cache
1723    sizes of up to at least twenty will improve startup time for
1724    typical inter-CU-reference binaries, at an obvious memory cost.  */
1725 static int dwarf_max_cache_age = 5;
1726 static void
1727 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1728                           struct cmd_list_element *c, const char *value)
1729 {
1730   fprintf_filtered (file, _("The upper bound on the age of cached "
1731                             "DWARF compilation units is %s.\n"),
1732                     value);
1733 }
1734 \f
1735 /* local function prototypes */
1736
1737 static const char *get_section_name (const struct dwarf2_section_info *);
1738
1739 static const char *get_section_file_name (const struct dwarf2_section_info *);
1740
1741 static void dwarf2_find_base_address (struct die_info *die,
1742                                       struct dwarf2_cu *cu);
1743
1744 static struct partial_symtab *create_partial_symtab
1745   (struct dwarf2_per_cu_data *per_cu, const char *name);
1746
1747 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1748                                         const gdb_byte *info_ptr,
1749                                         struct die_info *type_unit_die,
1750                                         int has_children, void *data);
1751
1752 static void dwarf2_build_psymtabs_hard
1753   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1754
1755 static void scan_partial_symbols (struct partial_die_info *,
1756                                   CORE_ADDR *, CORE_ADDR *,
1757                                   int, struct dwarf2_cu *);
1758
1759 static void add_partial_symbol (struct partial_die_info *,
1760                                 struct dwarf2_cu *);
1761
1762 static void add_partial_namespace (struct partial_die_info *pdi,
1763                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1764                                    int set_addrmap, struct dwarf2_cu *cu);
1765
1766 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1767                                 CORE_ADDR *highpc, int set_addrmap,
1768                                 struct dwarf2_cu *cu);
1769
1770 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1771                                      struct dwarf2_cu *cu);
1772
1773 static void add_partial_subprogram (struct partial_die_info *pdi,
1774                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1775                                     int need_pc, struct dwarf2_cu *cu);
1776
1777 static void dwarf2_read_symtab (struct partial_symtab *,
1778                                 struct objfile *);
1779
1780 static void psymtab_to_symtab_1 (struct partial_symtab *);
1781
1782 static abbrev_table_up abbrev_table_read_table
1783   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1784    sect_offset);
1785
1786 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1787
1788 static struct partial_die_info *load_partial_dies
1789   (const struct die_reader_specs *, const gdb_byte *, int);
1790
1791 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1792                                          struct partial_die_info *,
1793                                          struct abbrev_info *,
1794                                          unsigned int,
1795                                          const gdb_byte *);
1796
1797 static struct partial_die_info *find_partial_die (sect_offset, int,
1798                                                   struct dwarf2_cu *);
1799
1800 static void fixup_partial_die (struct partial_die_info *,
1801                                struct dwarf2_cu *);
1802
1803 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1804                                        struct attribute *, struct attr_abbrev *,
1805                                        const gdb_byte *);
1806
1807 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1808
1809 static int read_1_signed_byte (bfd *, const gdb_byte *);
1810
1811 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1812
1813 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1814
1815 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1816
1817 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1818                                unsigned int *);
1819
1820 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1821
1822 static LONGEST read_checked_initial_length_and_offset
1823   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1824    unsigned int *, unsigned int *);
1825
1826 static LONGEST read_offset (bfd *, const gdb_byte *,
1827                             const struct comp_unit_head *,
1828                             unsigned int *);
1829
1830 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1831
1832 static sect_offset read_abbrev_offset
1833   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1834    struct dwarf2_section_info *, sect_offset);
1835
1836 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1837
1838 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1839
1840 static const char *read_indirect_string
1841   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1842    const struct comp_unit_head *, unsigned int *);
1843
1844 static const char *read_indirect_line_string
1845   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1846    const struct comp_unit_head *, unsigned int *);
1847
1848 static const char *read_indirect_string_at_offset
1849   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1850    LONGEST str_offset);
1851
1852 static const char *read_indirect_string_from_dwz
1853   (struct objfile *objfile, struct dwz_file *, LONGEST);
1854
1855 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1856
1857 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1858                                               const gdb_byte *,
1859                                               unsigned int *);
1860
1861 static const char *read_str_index (const struct die_reader_specs *reader,
1862                                    ULONGEST str_index);
1863
1864 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1865
1866 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1867                                       struct dwarf2_cu *);
1868
1869 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1870                                                 unsigned int);
1871
1872 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1873                                        struct dwarf2_cu *cu);
1874
1875 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1876                                struct dwarf2_cu *cu);
1877
1878 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1879
1880 static struct die_info *die_specification (struct die_info *die,
1881                                            struct dwarf2_cu **);
1882
1883 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1884                                                 struct dwarf2_cu *cu);
1885
1886 static void dwarf_decode_lines (struct line_header *, const char *,
1887                                 struct dwarf2_cu *, struct partial_symtab *,
1888                                 CORE_ADDR, int decode_mapping);
1889
1890 static void dwarf2_start_subfile (const char *, const char *);
1891
1892 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1893                                                     const char *, const char *,
1894                                                     CORE_ADDR);
1895
1896 static struct symbol *new_symbol (struct die_info *, struct type *,
1897                                   struct dwarf2_cu *, struct symbol * = NULL);
1898
1899 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1900                                 struct dwarf2_cu *);
1901
1902 static void dwarf2_const_value_attr (const struct attribute *attr,
1903                                      struct type *type,
1904                                      const char *name,
1905                                      struct obstack *obstack,
1906                                      struct dwarf2_cu *cu, LONGEST *value,
1907                                      const gdb_byte **bytes,
1908                                      struct dwarf2_locexpr_baton **baton);
1909
1910 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1911
1912 static int need_gnat_info (struct dwarf2_cu *);
1913
1914 static struct type *die_descriptive_type (struct die_info *,
1915                                           struct dwarf2_cu *);
1916
1917 static void set_descriptive_type (struct type *, struct die_info *,
1918                                   struct dwarf2_cu *);
1919
1920 static struct type *die_containing_type (struct die_info *,
1921                                          struct dwarf2_cu *);
1922
1923 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1924                                      struct dwarf2_cu *);
1925
1926 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1927
1928 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1929
1930 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1931
1932 static char *typename_concat (struct obstack *obs, const char *prefix,
1933                               const char *suffix, int physname,
1934                               struct dwarf2_cu *cu);
1935
1936 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1937
1938 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1939
1940 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1941
1942 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1943
1944 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1945
1946 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1947
1948 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1949                                struct dwarf2_cu *, struct partial_symtab *);
1950
1951 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1952    values.  Keep the items ordered with increasing constraints compliance.  */
1953 enum pc_bounds_kind
1954 {
1955   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1956   PC_BOUNDS_NOT_PRESENT,
1957
1958   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1959      were present but they do not form a valid range of PC addresses.  */
1960   PC_BOUNDS_INVALID,
1961
1962   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1963   PC_BOUNDS_RANGES,
1964
1965   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1966   PC_BOUNDS_HIGH_LOW,
1967 };
1968
1969 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1970                                                  CORE_ADDR *, CORE_ADDR *,
1971                                                  struct dwarf2_cu *,
1972                                                  struct partial_symtab *);
1973
1974 static void get_scope_pc_bounds (struct die_info *,
1975                                  CORE_ADDR *, CORE_ADDR *,
1976                                  struct dwarf2_cu *);
1977
1978 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1979                                         CORE_ADDR, struct dwarf2_cu *);
1980
1981 static void dwarf2_add_field (struct field_info *, struct die_info *,
1982                               struct dwarf2_cu *);
1983
1984 static void dwarf2_attach_fields_to_type (struct field_info *,
1985                                           struct type *, struct dwarf2_cu *);
1986
1987 static void dwarf2_add_member_fn (struct field_info *,
1988                                   struct die_info *, struct type *,
1989                                   struct dwarf2_cu *);
1990
1991 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1992                                              struct type *,
1993                                              struct dwarf2_cu *);
1994
1995 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1996
1997 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1998
1999 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2000
2001 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2002
2003 static struct using_direct **using_directives (enum language);
2004
2005 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2006
2007 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2008
2009 static struct type *read_module_type (struct die_info *die,
2010                                       struct dwarf2_cu *cu);
2011
2012 static const char *namespace_name (struct die_info *die,
2013                                    int *is_anonymous, struct dwarf2_cu *);
2014
2015 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2016
2017 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2018
2019 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2020                                                        struct dwarf2_cu *);
2021
2022 static struct die_info *read_die_and_siblings_1
2023   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2024    struct die_info *);
2025
2026 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2027                                                const gdb_byte *info_ptr,
2028                                                const gdb_byte **new_info_ptr,
2029                                                struct die_info *parent);
2030
2031 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2032                                         struct die_info **, const gdb_byte *,
2033                                         int *, int);
2034
2035 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2036                                       struct die_info **, const gdb_byte *,
2037                                       int *);
2038
2039 static void process_die (struct die_info *, struct dwarf2_cu *);
2040
2041 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2042                                              struct obstack *);
2043
2044 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2045
2046 static const char *dwarf2_full_name (const char *name,
2047                                      struct die_info *die,
2048                                      struct dwarf2_cu *cu);
2049
2050 static const char *dwarf2_physname (const char *name, struct die_info *die,
2051                                     struct dwarf2_cu *cu);
2052
2053 static struct die_info *dwarf2_extension (struct die_info *die,
2054                                           struct dwarf2_cu **);
2055
2056 static const char *dwarf_tag_name (unsigned int);
2057
2058 static const char *dwarf_attr_name (unsigned int);
2059
2060 static const char *dwarf_form_name (unsigned int);
2061
2062 static const char *dwarf_bool_name (unsigned int);
2063
2064 static const char *dwarf_type_encoding_name (unsigned int);
2065
2066 static struct die_info *sibling_die (struct die_info *);
2067
2068 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2069
2070 static void dump_die_for_error (struct die_info *);
2071
2072 static void dump_die_1 (struct ui_file *, int level, int max_level,
2073                         struct die_info *);
2074
2075 /*static*/ void dump_die (struct die_info *, int max_level);
2076
2077 static void store_in_ref_table (struct die_info *,
2078                                 struct dwarf2_cu *);
2079
2080 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2081
2082 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2083
2084 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2085                                                const struct attribute *,
2086                                                struct dwarf2_cu **);
2087
2088 static struct die_info *follow_die_ref (struct die_info *,
2089                                         const struct attribute *,
2090                                         struct dwarf2_cu **);
2091
2092 static struct die_info *follow_die_sig (struct die_info *,
2093                                         const struct attribute *,
2094                                         struct dwarf2_cu **);
2095
2096 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2097                                          struct dwarf2_cu *);
2098
2099 static struct type *get_DW_AT_signature_type (struct die_info *,
2100                                               const struct attribute *,
2101                                               struct dwarf2_cu *);
2102
2103 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2104
2105 static void read_signatured_type (struct signatured_type *);
2106
2107 static int attr_to_dynamic_prop (const struct attribute *attr,
2108                                  struct die_info *die, struct dwarf2_cu *cu,
2109                                  struct dynamic_prop *prop);
2110
2111 /* memory allocation interface */
2112
2113 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2114
2115 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2116
2117 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2118
2119 static int attr_form_is_block (const struct attribute *);
2120
2121 static int attr_form_is_section_offset (const struct attribute *);
2122
2123 static int attr_form_is_constant (const struct attribute *);
2124
2125 static int attr_form_is_ref (const struct attribute *);
2126
2127 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2128                                    struct dwarf2_loclist_baton *baton,
2129                                    const struct attribute *attr);
2130
2131 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2132                                          struct symbol *sym,
2133                                          struct dwarf2_cu *cu,
2134                                          int is_block);
2135
2136 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2137                                      const gdb_byte *info_ptr,
2138                                      struct abbrev_info *abbrev);
2139
2140 static hashval_t partial_die_hash (const void *item);
2141
2142 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2143
2144 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2145   (sect_offset sect_off, unsigned int offset_in_dwz,
2146    struct dwarf2_per_objfile *dwarf2_per_objfile);
2147
2148 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2149                                    struct die_info *comp_unit_die,
2150                                    enum language pretend_language);
2151
2152 static void free_cached_comp_units (void *);
2153
2154 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2155
2156 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2157
2158 static struct type *set_die_type (struct die_info *, struct type *,
2159                                   struct dwarf2_cu *);
2160
2161 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2162
2163 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2164
2165 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2166                                  enum language);
2167
2168 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2169                                     enum language);
2170
2171 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2172                                     enum language);
2173
2174 static void dwarf2_add_dependence (struct dwarf2_cu *,
2175                                    struct dwarf2_per_cu_data *);
2176
2177 static void dwarf2_mark (struct dwarf2_cu *);
2178
2179 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2180
2181 static struct type *get_die_type_at_offset (sect_offset,
2182                                             struct dwarf2_per_cu_data *);
2183
2184 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2185
2186 static void dwarf2_release_queue (void *dummy);
2187
2188 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2189                              enum language pretend_language);
2190
2191 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2192
2193 /* The return type of find_file_and_directory.  Note, the enclosed
2194    string pointers are only valid while this object is valid.  */
2195
2196 struct file_and_directory
2197 {
2198   /* The filename.  This is never NULL.  */
2199   const char *name;
2200
2201   /* The compilation directory.  NULL if not known.  If we needed to
2202      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2203      points directly to the DW_AT_comp_dir string attribute owned by
2204      the obstack that owns the DIE.  */
2205   const char *comp_dir;
2206
2207   /* If we needed to build a new string for comp_dir, this is what
2208      owns the storage.  */
2209   std::string comp_dir_storage;
2210 };
2211
2212 static file_and_directory find_file_and_directory (struct die_info *die,
2213                                                    struct dwarf2_cu *cu);
2214
2215 static char *file_full_name (int file, struct line_header *lh,
2216                              const char *comp_dir);
2217
2218 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2219 enum class rcuh_kind { COMPILE, TYPE };
2220
2221 static const gdb_byte *read_and_check_comp_unit_head
2222   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2223    struct comp_unit_head *header,
2224    struct dwarf2_section_info *section,
2225    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2226    rcuh_kind section_kind);
2227
2228 static void init_cutu_and_read_dies
2229   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2230    int use_existing_cu, int keep,
2231    die_reader_func_ftype *die_reader_func, void *data);
2232
2233 static void init_cutu_and_read_dies_simple
2234   (struct dwarf2_per_cu_data *this_cu,
2235    die_reader_func_ftype *die_reader_func, void *data);
2236
2237 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2238
2239 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2240
2241 static struct dwo_unit *lookup_dwo_unit_in_dwp
2242   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2243    struct dwp_file *dwp_file, const char *comp_dir,
2244    ULONGEST signature, int is_debug_types);
2245
2246 static struct dwp_file *get_dwp_file
2247   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2248
2249 static struct dwo_unit *lookup_dwo_comp_unit
2250   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2251
2252 static struct dwo_unit *lookup_dwo_type_unit
2253   (struct signatured_type *, const char *, const char *);
2254
2255 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2256
2257 static void free_dwo_file_cleanup (void *);
2258
2259 struct free_dwo_file_cleanup_data
2260 {
2261   struct dwo_file *dwo_file;
2262   struct dwarf2_per_objfile *dwarf2_per_objfile;
2263 };
2264
2265 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2266
2267 static void check_producer (struct dwarf2_cu *cu);
2268
2269 static void free_line_header_voidp (void *arg);
2270 \f
2271 /* Various complaints about symbol reading that don't abort the process.  */
2272
2273 static void
2274 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2275 {
2276   complaint (&symfile_complaints,
2277              _("statement list doesn't fit in .debug_line section"));
2278 }
2279
2280 static void
2281 dwarf2_debug_line_missing_file_complaint (void)
2282 {
2283   complaint (&symfile_complaints,
2284              _(".debug_line section has line data without a file"));
2285 }
2286
2287 static void
2288 dwarf2_debug_line_missing_end_sequence_complaint (void)
2289 {
2290   complaint (&symfile_complaints,
2291              _(".debug_line section has line "
2292                "program sequence without an end"));
2293 }
2294
2295 static void
2296 dwarf2_complex_location_expr_complaint (void)
2297 {
2298   complaint (&symfile_complaints, _("location expression too complex"));
2299 }
2300
2301 static void
2302 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2303                                               int arg3)
2304 {
2305   complaint (&symfile_complaints,
2306              _("const value length mismatch for '%s', got %d, expected %d"),
2307              arg1, arg2, arg3);
2308 }
2309
2310 static void
2311 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2312 {
2313   complaint (&symfile_complaints,
2314              _("debug info runs off end of %s section"
2315                " [in module %s]"),
2316              get_section_name (section),
2317              get_section_file_name (section));
2318 }
2319
2320 static void
2321 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2322 {
2323   complaint (&symfile_complaints,
2324              _("macro debug info contains a "
2325                "malformed macro definition:\n`%s'"),
2326              arg1);
2327 }
2328
2329 static void
2330 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2331 {
2332   complaint (&symfile_complaints,
2333              _("invalid attribute class or form for '%s' in '%s'"),
2334              arg1, arg2);
2335 }
2336
2337 /* Hash function for line_header_hash.  */
2338
2339 static hashval_t
2340 line_header_hash (const struct line_header *ofs)
2341 {
2342   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2343 }
2344
2345 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2346
2347 static hashval_t
2348 line_header_hash_voidp (const void *item)
2349 {
2350   const struct line_header *ofs = (const struct line_header *) item;
2351
2352   return line_header_hash (ofs);
2353 }
2354
2355 /* Equality function for line_header_hash.  */
2356
2357 static int
2358 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2359 {
2360   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2361   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2362
2363   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2364           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2365 }
2366
2367 \f
2368
2369 /* Read the given attribute value as an address, taking the attribute's
2370    form into account.  */
2371
2372 static CORE_ADDR
2373 attr_value_as_address (struct attribute *attr)
2374 {
2375   CORE_ADDR addr;
2376
2377   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2378     {
2379       /* Aside from a few clearly defined exceptions, attributes that
2380          contain an address must always be in DW_FORM_addr form.
2381          Unfortunately, some compilers happen to be violating this
2382          requirement by encoding addresses using other forms, such
2383          as DW_FORM_data4 for example.  For those broken compilers,
2384          we try to do our best, without any guarantee of success,
2385          to interpret the address correctly.  It would also be nice
2386          to generate a complaint, but that would require us to maintain
2387          a list of legitimate cases where a non-address form is allowed,
2388          as well as update callers to pass in at least the CU's DWARF
2389          version.  This is more overhead than what we're willing to
2390          expand for a pretty rare case.  */
2391       addr = DW_UNSND (attr);
2392     }
2393   else
2394     addr = DW_ADDR (attr);
2395
2396   return addr;
2397 }
2398
2399 /* The suffix for an index file.  */
2400 #define INDEX4_SUFFIX ".gdb-index"
2401 #define INDEX5_SUFFIX ".debug_names"
2402 #define DEBUG_STR_SUFFIX ".debug_str"
2403
2404 /* See declaration.  */
2405
2406 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2407                                         const dwarf2_debug_sections *names)
2408   : objfile (objfile_)
2409 {
2410   if (names == NULL)
2411     names = &dwarf2_elf_names;
2412
2413   bfd *obfd = objfile->obfd;
2414
2415   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2416     locate_sections (obfd, sec, *names);
2417 }
2418
2419 dwarf2_per_objfile::~dwarf2_per_objfile ()
2420 {
2421   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2422   free_cached_comp_units ();
2423
2424   if (quick_file_names_table)
2425     htab_delete (quick_file_names_table);
2426
2427   if (line_header_hash)
2428     htab_delete (line_header_hash);
2429
2430   /* Everything else should be on the objfile obstack.  */
2431 }
2432
2433 /* See declaration.  */
2434
2435 void
2436 dwarf2_per_objfile::free_cached_comp_units ()
2437 {
2438   dwarf2_per_cu_data *per_cu = read_in_chain;
2439   dwarf2_per_cu_data **last_chain = &read_in_chain;
2440   while (per_cu != NULL)
2441     {
2442       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2443
2444       delete per_cu->cu;
2445       *last_chain = next_cu;
2446       per_cu = next_cu;
2447     }
2448 }
2449
2450 /* Try to locate the sections we need for DWARF 2 debugging
2451    information and return true if we have enough to do something.
2452    NAMES points to the dwarf2 section names, or is NULL if the standard
2453    ELF names are used.  */
2454
2455 int
2456 dwarf2_has_info (struct objfile *objfile,
2457                  const struct dwarf2_debug_sections *names)
2458 {
2459   if (objfile->flags & OBJF_READNEVER)
2460     return 0;
2461
2462   struct dwarf2_per_objfile *dwarf2_per_objfile
2463     = get_dwarf2_per_objfile (objfile);
2464
2465   if (dwarf2_per_objfile == NULL)
2466     {
2467       /* Initialize per-objfile state.  */
2468       struct dwarf2_per_objfile *data
2469         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2470
2471       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2472       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2473     }
2474   return (!dwarf2_per_objfile->info.is_virtual
2475           && dwarf2_per_objfile->info.s.section != NULL
2476           && !dwarf2_per_objfile->abbrev.is_virtual
2477           && dwarf2_per_objfile->abbrev.s.section != NULL);
2478 }
2479
2480 /* Return the containing section of virtual section SECTION.  */
2481
2482 static struct dwarf2_section_info *
2483 get_containing_section (const struct dwarf2_section_info *section)
2484 {
2485   gdb_assert (section->is_virtual);
2486   return section->s.containing_section;
2487 }
2488
2489 /* Return the bfd owner of SECTION.  */
2490
2491 static struct bfd *
2492 get_section_bfd_owner (const struct dwarf2_section_info *section)
2493 {
2494   if (section->is_virtual)
2495     {
2496       section = get_containing_section (section);
2497       gdb_assert (!section->is_virtual);
2498     }
2499   return section->s.section->owner;
2500 }
2501
2502 /* Return the bfd section of SECTION.
2503    Returns NULL if the section is not present.  */
2504
2505 static asection *
2506 get_section_bfd_section (const struct dwarf2_section_info *section)
2507 {
2508   if (section->is_virtual)
2509     {
2510       section = get_containing_section (section);
2511       gdb_assert (!section->is_virtual);
2512     }
2513   return section->s.section;
2514 }
2515
2516 /* Return the name of SECTION.  */
2517
2518 static const char *
2519 get_section_name (const struct dwarf2_section_info *section)
2520 {
2521   asection *sectp = get_section_bfd_section (section);
2522
2523   gdb_assert (sectp != NULL);
2524   return bfd_section_name (get_section_bfd_owner (section), sectp);
2525 }
2526
2527 /* Return the name of the file SECTION is in.  */
2528
2529 static const char *
2530 get_section_file_name (const struct dwarf2_section_info *section)
2531 {
2532   bfd *abfd = get_section_bfd_owner (section);
2533
2534   return bfd_get_filename (abfd);
2535 }
2536
2537 /* Return the id of SECTION.
2538    Returns 0 if SECTION doesn't exist.  */
2539
2540 static int
2541 get_section_id (const struct dwarf2_section_info *section)
2542 {
2543   asection *sectp = get_section_bfd_section (section);
2544
2545   if (sectp == NULL)
2546     return 0;
2547   return sectp->id;
2548 }
2549
2550 /* Return the flags of SECTION.
2551    SECTION (or containing section if this is a virtual section) must exist.  */
2552
2553 static int
2554 get_section_flags (const struct dwarf2_section_info *section)
2555 {
2556   asection *sectp = get_section_bfd_section (section);
2557
2558   gdb_assert (sectp != NULL);
2559   return bfd_get_section_flags (sectp->owner, sectp);
2560 }
2561
2562 /* When loading sections, we look either for uncompressed section or for
2563    compressed section names.  */
2564
2565 static int
2566 section_is_p (const char *section_name,
2567               const struct dwarf2_section_names *names)
2568 {
2569   if (names->normal != NULL
2570       && strcmp (section_name, names->normal) == 0)
2571     return 1;
2572   if (names->compressed != NULL
2573       && strcmp (section_name, names->compressed) == 0)
2574     return 1;
2575   return 0;
2576 }
2577
2578 /* See declaration.  */
2579
2580 void
2581 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2582                                      const dwarf2_debug_sections &names)
2583 {
2584   flagword aflag = bfd_get_section_flags (abfd, sectp);
2585
2586   if ((aflag & SEC_HAS_CONTENTS) == 0)
2587     {
2588     }
2589   else if (section_is_p (sectp->name, &names.info))
2590     {
2591       this->info.s.section = sectp;
2592       this->info.size = bfd_get_section_size (sectp);
2593     }
2594   else if (section_is_p (sectp->name, &names.abbrev))
2595     {
2596       this->abbrev.s.section = sectp;
2597       this->abbrev.size = bfd_get_section_size (sectp);
2598     }
2599   else if (section_is_p (sectp->name, &names.line))
2600     {
2601       this->line.s.section = sectp;
2602       this->line.size = bfd_get_section_size (sectp);
2603     }
2604   else if (section_is_p (sectp->name, &names.loc))
2605     {
2606       this->loc.s.section = sectp;
2607       this->loc.size = bfd_get_section_size (sectp);
2608     }
2609   else if (section_is_p (sectp->name, &names.loclists))
2610     {
2611       this->loclists.s.section = sectp;
2612       this->loclists.size = bfd_get_section_size (sectp);
2613     }
2614   else if (section_is_p (sectp->name, &names.macinfo))
2615     {
2616       this->macinfo.s.section = sectp;
2617       this->macinfo.size = bfd_get_section_size (sectp);
2618     }
2619   else if (section_is_p (sectp->name, &names.macro))
2620     {
2621       this->macro.s.section = sectp;
2622       this->macro.size = bfd_get_section_size (sectp);
2623     }
2624   else if (section_is_p (sectp->name, &names.str))
2625     {
2626       this->str.s.section = sectp;
2627       this->str.size = bfd_get_section_size (sectp);
2628     }
2629   else if (section_is_p (sectp->name, &names.line_str))
2630     {
2631       this->line_str.s.section = sectp;
2632       this->line_str.size = bfd_get_section_size (sectp);
2633     }
2634   else if (section_is_p (sectp->name, &names.addr))
2635     {
2636       this->addr.s.section = sectp;
2637       this->addr.size = bfd_get_section_size (sectp);
2638     }
2639   else if (section_is_p (sectp->name, &names.frame))
2640     {
2641       this->frame.s.section = sectp;
2642       this->frame.size = bfd_get_section_size (sectp);
2643     }
2644   else if (section_is_p (sectp->name, &names.eh_frame))
2645     {
2646       this->eh_frame.s.section = sectp;
2647       this->eh_frame.size = bfd_get_section_size (sectp);
2648     }
2649   else if (section_is_p (sectp->name, &names.ranges))
2650     {
2651       this->ranges.s.section = sectp;
2652       this->ranges.size = bfd_get_section_size (sectp);
2653     }
2654   else if (section_is_p (sectp->name, &names.rnglists))
2655     {
2656       this->rnglists.s.section = sectp;
2657       this->rnglists.size = bfd_get_section_size (sectp);
2658     }
2659   else if (section_is_p (sectp->name, &names.types))
2660     {
2661       struct dwarf2_section_info type_section;
2662
2663       memset (&type_section, 0, sizeof (type_section));
2664       type_section.s.section = sectp;
2665       type_section.size = bfd_get_section_size (sectp);
2666
2667       VEC_safe_push (dwarf2_section_info_def, this->types,
2668                      &type_section);
2669     }
2670   else if (section_is_p (sectp->name, &names.gdb_index))
2671     {
2672       this->gdb_index.s.section = sectp;
2673       this->gdb_index.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &names.debug_names))
2676     {
2677       this->debug_names.s.section = sectp;
2678       this->debug_names.size = bfd_get_section_size (sectp);
2679     }
2680   else if (section_is_p (sectp->name, &names.debug_aranges))
2681     {
2682       this->debug_aranges.s.section = sectp;
2683       this->debug_aranges.size = bfd_get_section_size (sectp);
2684     }
2685
2686   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2687       && bfd_section_vma (abfd, sectp) == 0)
2688     this->has_section_at_zero = true;
2689 }
2690
2691 /* A helper function that decides whether a section is empty,
2692    or not present.  */
2693
2694 static int
2695 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2696 {
2697   if (section->is_virtual)
2698     return section->size == 0;
2699   return section->s.section == NULL || section->size == 0;
2700 }
2701
2702 /* Read the contents of the section INFO.
2703    OBJFILE is the main object file, but not necessarily the file where
2704    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2705    of the DWO file.
2706    If the section is compressed, uncompress it before returning.  */
2707
2708 static void
2709 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2710 {
2711   asection *sectp;
2712   bfd *abfd;
2713   gdb_byte *buf, *retbuf;
2714
2715   if (info->readin)
2716     return;
2717   info->buffer = NULL;
2718   info->readin = 1;
2719
2720   if (dwarf2_section_empty_p (info))
2721     return;
2722
2723   sectp = get_section_bfd_section (info);
2724
2725   /* If this is a virtual section we need to read in the real one first.  */
2726   if (info->is_virtual)
2727     {
2728       struct dwarf2_section_info *containing_section =
2729         get_containing_section (info);
2730
2731       gdb_assert (sectp != NULL);
2732       if ((sectp->flags & SEC_RELOC) != 0)
2733         {
2734           error (_("Dwarf Error: DWP format V2 with relocations is not"
2735                    " supported in section %s [in module %s]"),
2736                  get_section_name (info), get_section_file_name (info));
2737         }
2738       dwarf2_read_section (objfile, containing_section);
2739       /* Other code should have already caught virtual sections that don't
2740          fit.  */
2741       gdb_assert (info->virtual_offset + info->size
2742                   <= containing_section->size);
2743       /* If the real section is empty or there was a problem reading the
2744          section we shouldn't get here.  */
2745       gdb_assert (containing_section->buffer != NULL);
2746       info->buffer = containing_section->buffer + info->virtual_offset;
2747       return;
2748     }
2749
2750   /* If the section has relocations, we must read it ourselves.
2751      Otherwise we attach it to the BFD.  */
2752   if ((sectp->flags & SEC_RELOC) == 0)
2753     {
2754       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2755       return;
2756     }
2757
2758   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2759   info->buffer = buf;
2760
2761   /* When debugging .o files, we may need to apply relocations; see
2762      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2763      We never compress sections in .o files, so we only need to
2764      try this when the section is not compressed.  */
2765   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2766   if (retbuf != NULL)
2767     {
2768       info->buffer = retbuf;
2769       return;
2770     }
2771
2772   abfd = get_section_bfd_owner (info);
2773   gdb_assert (abfd != NULL);
2774
2775   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2776       || bfd_bread (buf, info->size, abfd) != info->size)
2777     {
2778       error (_("Dwarf Error: Can't read DWARF data"
2779                " in section %s [in module %s]"),
2780              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2781     }
2782 }
2783
2784 /* A helper function that returns the size of a section in a safe way.
2785    If you are positive that the section has been read before using the
2786    size, then it is safe to refer to the dwarf2_section_info object's
2787    "size" field directly.  In other cases, you must call this
2788    function, because for compressed sections the size field is not set
2789    correctly until the section has been read.  */
2790
2791 static bfd_size_type
2792 dwarf2_section_size (struct objfile *objfile,
2793                      struct dwarf2_section_info *info)
2794 {
2795   if (!info->readin)
2796     dwarf2_read_section (objfile, info);
2797   return info->size;
2798 }
2799
2800 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2801    SECTION_NAME.  */
2802
2803 void
2804 dwarf2_get_section_info (struct objfile *objfile,
2805                          enum dwarf2_section_enum sect,
2806                          asection **sectp, const gdb_byte **bufp,
2807                          bfd_size_type *sizep)
2808 {
2809   struct dwarf2_per_objfile *data
2810     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2811                                                   dwarf2_objfile_data_key);
2812   struct dwarf2_section_info *info;
2813
2814   /* We may see an objfile without any DWARF, in which case we just
2815      return nothing.  */
2816   if (data == NULL)
2817     {
2818       *sectp = NULL;
2819       *bufp = NULL;
2820       *sizep = 0;
2821       return;
2822     }
2823   switch (sect)
2824     {
2825     case DWARF2_DEBUG_FRAME:
2826       info = &data->frame;
2827       break;
2828     case DWARF2_EH_FRAME:
2829       info = &data->eh_frame;
2830       break;
2831     default:
2832       gdb_assert_not_reached ("unexpected section");
2833     }
2834
2835   dwarf2_read_section (objfile, info);
2836
2837   *sectp = get_section_bfd_section (info);
2838   *bufp = info->buffer;
2839   *sizep = info->size;
2840 }
2841
2842 /* A helper function to find the sections for a .dwz file.  */
2843
2844 static void
2845 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2846 {
2847   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2848
2849   /* Note that we only support the standard ELF names, because .dwz
2850      is ELF-only (at the time of writing).  */
2851   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2852     {
2853       dwz_file->abbrev.s.section = sectp;
2854       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2855     }
2856   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2857     {
2858       dwz_file->info.s.section = sectp;
2859       dwz_file->info.size = bfd_get_section_size (sectp);
2860     }
2861   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2862     {
2863       dwz_file->str.s.section = sectp;
2864       dwz_file->str.size = bfd_get_section_size (sectp);
2865     }
2866   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2867     {
2868       dwz_file->line.s.section = sectp;
2869       dwz_file->line.size = bfd_get_section_size (sectp);
2870     }
2871   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2872     {
2873       dwz_file->macro.s.section = sectp;
2874       dwz_file->macro.size = bfd_get_section_size (sectp);
2875     }
2876   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2877     {
2878       dwz_file->gdb_index.s.section = sectp;
2879       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2880     }
2881   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2882     {
2883       dwz_file->debug_names.s.section = sectp;
2884       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2885     }
2886 }
2887
2888 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2889    there is no .gnu_debugaltlink section in the file.  Error if there
2890    is such a section but the file cannot be found.  */
2891
2892 static struct dwz_file *
2893 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2894 {
2895   const char *filename;
2896   struct dwz_file *result;
2897   bfd_size_type buildid_len_arg;
2898   size_t buildid_len;
2899   bfd_byte *buildid;
2900
2901   if (dwarf2_per_objfile->dwz_file != NULL)
2902     return dwarf2_per_objfile->dwz_file;
2903
2904   bfd_set_error (bfd_error_no_error);
2905   gdb::unique_xmalloc_ptr<char> data
2906     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2907                                   &buildid_len_arg, &buildid));
2908   if (data == NULL)
2909     {
2910       if (bfd_get_error () == bfd_error_no_error)
2911         return NULL;
2912       error (_("could not read '.gnu_debugaltlink' section: %s"),
2913              bfd_errmsg (bfd_get_error ()));
2914     }
2915
2916   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2917
2918   buildid_len = (size_t) buildid_len_arg;
2919
2920   filename = data.get ();
2921
2922   std::string abs_storage;
2923   if (!IS_ABSOLUTE_PATH (filename))
2924     {
2925       gdb::unique_xmalloc_ptr<char> abs
2926         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2927
2928       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2929       filename = abs_storage.c_str ();
2930     }
2931
2932   /* First try the file name given in the section.  If that doesn't
2933      work, try to use the build-id instead.  */
2934   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2935   if (dwz_bfd != NULL)
2936     {
2937       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2938         dwz_bfd.release ();
2939     }
2940
2941   if (dwz_bfd == NULL)
2942     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2943
2944   if (dwz_bfd == NULL)
2945     error (_("could not find '.gnu_debugaltlink' file for %s"),
2946            objfile_name (dwarf2_per_objfile->objfile));
2947
2948   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2949                            struct dwz_file);
2950   result->dwz_bfd = dwz_bfd.release ();
2951
2952   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2953
2954   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2955   dwarf2_per_objfile->dwz_file = result;
2956   return result;
2957 }
2958 \f
2959 /* DWARF quick_symbols_functions support.  */
2960
2961 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2962    unique line tables, so we maintain a separate table of all .debug_line
2963    derived entries to support the sharing.
2964    All the quick functions need is the list of file names.  We discard the
2965    line_header when we're done and don't need to record it here.  */
2966 struct quick_file_names
2967 {
2968   /* The data used to construct the hash key.  */
2969   struct stmt_list_hash hash;
2970
2971   /* The number of entries in file_names, real_names.  */
2972   unsigned int num_file_names;
2973
2974   /* The file names from the line table, after being run through
2975      file_full_name.  */
2976   const char **file_names;
2977
2978   /* The file names from the line table after being run through
2979      gdb_realpath.  These are computed lazily.  */
2980   const char **real_names;
2981 };
2982
2983 /* When using the index (and thus not using psymtabs), each CU has an
2984    object of this type.  This is used to hold information needed by
2985    the various "quick" methods.  */
2986 struct dwarf2_per_cu_quick_data
2987 {
2988   /* The file table.  This can be NULL if there was no file table
2989      or it's currently not read in.
2990      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2991   struct quick_file_names *file_names;
2992
2993   /* The corresponding symbol table.  This is NULL if symbols for this
2994      CU have not yet been read.  */
2995   struct compunit_symtab *compunit_symtab;
2996
2997   /* A temporary mark bit used when iterating over all CUs in
2998      expand_symtabs_matching.  */
2999   unsigned int mark : 1;
3000
3001   /* True if we've tried to read the file table and found there isn't one.
3002      There will be no point in trying to read it again next time.  */
3003   unsigned int no_file_data : 1;
3004 };
3005
3006 /* Utility hash function for a stmt_list_hash.  */
3007
3008 static hashval_t
3009 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3010 {
3011   hashval_t v = 0;
3012
3013   if (stmt_list_hash->dwo_unit != NULL)
3014     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3015   v += to_underlying (stmt_list_hash->line_sect_off);
3016   return v;
3017 }
3018
3019 /* Utility equality function for a stmt_list_hash.  */
3020
3021 static int
3022 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3023                     const struct stmt_list_hash *rhs)
3024 {
3025   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3026     return 0;
3027   if (lhs->dwo_unit != NULL
3028       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3029     return 0;
3030
3031   return lhs->line_sect_off == rhs->line_sect_off;
3032 }
3033
3034 /* Hash function for a quick_file_names.  */
3035
3036 static hashval_t
3037 hash_file_name_entry (const void *e)
3038 {
3039   const struct quick_file_names *file_data
3040     = (const struct quick_file_names *) e;
3041
3042   return hash_stmt_list_entry (&file_data->hash);
3043 }
3044
3045 /* Equality function for a quick_file_names.  */
3046
3047 static int
3048 eq_file_name_entry (const void *a, const void *b)
3049 {
3050   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3051   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3052
3053   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3054 }
3055
3056 /* Delete function for a quick_file_names.  */
3057
3058 static void
3059 delete_file_name_entry (void *e)
3060 {
3061   struct quick_file_names *file_data = (struct quick_file_names *) e;
3062   int i;
3063
3064   for (i = 0; i < file_data->num_file_names; ++i)
3065     {
3066       xfree ((void*) file_data->file_names[i]);
3067       if (file_data->real_names)
3068         xfree ((void*) file_data->real_names[i]);
3069     }
3070
3071   /* The space for the struct itself lives on objfile_obstack,
3072      so we don't free it here.  */
3073 }
3074
3075 /* Create a quick_file_names hash table.  */
3076
3077 static htab_t
3078 create_quick_file_names_table (unsigned int nr_initial_entries)
3079 {
3080   return htab_create_alloc (nr_initial_entries,
3081                             hash_file_name_entry, eq_file_name_entry,
3082                             delete_file_name_entry, xcalloc, xfree);
3083 }
3084
3085 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3086    have to be created afterwards.  You should call age_cached_comp_units after
3087    processing PER_CU->CU.  dw2_setup must have been already called.  */
3088
3089 static void
3090 load_cu (struct dwarf2_per_cu_data *per_cu)
3091 {
3092   if (per_cu->is_debug_types)
3093     load_full_type_unit (per_cu);
3094   else
3095     load_full_comp_unit (per_cu, language_minimal);
3096
3097   if (per_cu->cu == NULL)
3098     return;  /* Dummy CU.  */
3099
3100   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3101 }
3102
3103 /* Read in the symbols for PER_CU.  */
3104
3105 static void
3106 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3107 {
3108   struct cleanup *back_to;
3109   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3110
3111   /* Skip type_unit_groups, reading the type units they contain
3112      is handled elsewhere.  */
3113   if (IS_TYPE_UNIT_GROUP (per_cu))
3114     return;
3115
3116   back_to = make_cleanup (dwarf2_release_queue, NULL);
3117
3118   if (dwarf2_per_objfile->using_index
3119       ? per_cu->v.quick->compunit_symtab == NULL
3120       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3121     {
3122       queue_comp_unit (per_cu, language_minimal);
3123       load_cu (per_cu);
3124
3125       /* If we just loaded a CU from a DWO, and we're working with an index
3126          that may badly handle TUs, load all the TUs in that DWO as well.
3127          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3128       if (!per_cu->is_debug_types
3129           && per_cu->cu != NULL
3130           && per_cu->cu->dwo_unit != NULL
3131           && dwarf2_per_objfile->index_table != NULL
3132           && dwarf2_per_objfile->index_table->version <= 7
3133           /* DWP files aren't supported yet.  */
3134           && get_dwp_file (dwarf2_per_objfile) == NULL)
3135         queue_and_load_all_dwo_tus (per_cu);
3136     }
3137
3138   process_queue (dwarf2_per_objfile);
3139
3140   /* Age the cache, releasing compilation units that have not
3141      been used recently.  */
3142   age_cached_comp_units (dwarf2_per_objfile);
3143
3144   do_cleanups (back_to);
3145 }
3146
3147 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3148    the objfile from which this CU came.  Returns the resulting symbol
3149    table.  */
3150
3151 static struct compunit_symtab *
3152 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3153 {
3154   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3155
3156   gdb_assert (dwarf2_per_objfile->using_index);
3157   if (!per_cu->v.quick->compunit_symtab)
3158     {
3159       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3160                                               dwarf2_per_objfile);
3161       scoped_restore decrementer = increment_reading_symtab ();
3162       dw2_do_instantiate_symtab (per_cu);
3163       process_cu_includes (dwarf2_per_objfile);
3164       do_cleanups (back_to);
3165     }
3166
3167   return per_cu->v.quick->compunit_symtab;
3168 }
3169
3170 /* Return the CU/TU given its index.
3171
3172    This is intended for loops like:
3173
3174    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3175                     + dwarf2_per_objfile->n_type_units); ++i)
3176      {
3177        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3178
3179        ...;
3180      }
3181 */
3182
3183 static struct dwarf2_per_cu_data *
3184 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3185               int index)
3186 {
3187   if (index >= dwarf2_per_objfile->n_comp_units)
3188     {
3189       index -= dwarf2_per_objfile->n_comp_units;
3190       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3191       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3192     }
3193
3194   return dwarf2_per_objfile->all_comp_units[index];
3195 }
3196
3197 /* Return the CU given its index.
3198    This differs from dw2_get_cutu in that it's for when you know INDEX
3199    refers to a CU.  */
3200
3201 static struct dwarf2_per_cu_data *
3202 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3203 {
3204   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3205
3206   return dwarf2_per_objfile->all_comp_units[index];
3207 }
3208
3209 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3210    objfile_obstack, and constructed with the specified field
3211    values.  */
3212
3213 static dwarf2_per_cu_data *
3214 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3215                           struct dwarf2_section_info *section,
3216                           int is_dwz,
3217                           sect_offset sect_off, ULONGEST length)
3218 {
3219   struct objfile *objfile = dwarf2_per_objfile->objfile;
3220   dwarf2_per_cu_data *the_cu
3221     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3222                      struct dwarf2_per_cu_data);
3223   the_cu->sect_off = sect_off;
3224   the_cu->length = length;
3225   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3226   the_cu->section = section;
3227   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3228                                    struct dwarf2_per_cu_quick_data);
3229   the_cu->is_dwz = is_dwz;
3230   return the_cu;
3231 }
3232
3233 /* A helper for create_cus_from_index that handles a given list of
3234    CUs.  */
3235
3236 static void
3237 create_cus_from_index_list (struct objfile *objfile,
3238                             const gdb_byte *cu_list, offset_type n_elements,
3239                             struct dwarf2_section_info *section,
3240                             int is_dwz,
3241                             int base_offset)
3242 {
3243   offset_type i;
3244   struct dwarf2_per_objfile *dwarf2_per_objfile
3245     = get_dwarf2_per_objfile (objfile);
3246
3247   for (i = 0; i < n_elements; i += 2)
3248     {
3249       gdb_static_assert (sizeof (ULONGEST) >= 8);
3250
3251       sect_offset sect_off
3252         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3253       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3254       cu_list += 2 * 8;
3255
3256       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3257         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3258                                      sect_off, length);
3259     }
3260 }
3261
3262 /* Read the CU list from the mapped index, and use it to create all
3263    the CU objects for this objfile.  */
3264
3265 static void
3266 create_cus_from_index (struct objfile *objfile,
3267                        const gdb_byte *cu_list, offset_type cu_list_elements,
3268                        const gdb_byte *dwz_list, offset_type dwz_elements)
3269 {
3270   struct dwz_file *dwz;
3271   struct dwarf2_per_objfile *dwarf2_per_objfile
3272     = get_dwarf2_per_objfile (objfile);
3273
3274   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3275   dwarf2_per_objfile->all_comp_units =
3276     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3277                dwarf2_per_objfile->n_comp_units);
3278
3279   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3280                               &dwarf2_per_objfile->info, 0, 0);
3281
3282   if (dwz_elements == 0)
3283     return;
3284
3285   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3286   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3287                               cu_list_elements / 2);
3288 }
3289
3290 /* Create the signatured type hash table from the index.  */
3291
3292 static void
3293 create_signatured_type_table_from_index (struct objfile *objfile,
3294                                          struct dwarf2_section_info *section,
3295                                          const gdb_byte *bytes,
3296                                          offset_type elements)
3297 {
3298   offset_type i;
3299   htab_t sig_types_hash;
3300   struct dwarf2_per_objfile *dwarf2_per_objfile
3301     = get_dwarf2_per_objfile (objfile);
3302
3303   dwarf2_per_objfile->n_type_units
3304     = dwarf2_per_objfile->n_allocated_type_units
3305     = elements / 3;
3306   dwarf2_per_objfile->all_type_units =
3307     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3308
3309   sig_types_hash = allocate_signatured_type_table (objfile);
3310
3311   for (i = 0; i < elements; i += 3)
3312     {
3313       struct signatured_type *sig_type;
3314       ULONGEST signature;
3315       void **slot;
3316       cu_offset type_offset_in_tu;
3317
3318       gdb_static_assert (sizeof (ULONGEST) >= 8);
3319       sect_offset sect_off
3320         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3321       type_offset_in_tu
3322         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3323                                                 BFD_ENDIAN_LITTLE);
3324       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3325       bytes += 3 * 8;
3326
3327       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3328                                  struct signatured_type);
3329       sig_type->signature = signature;
3330       sig_type->type_offset_in_tu = type_offset_in_tu;
3331       sig_type->per_cu.is_debug_types = 1;
3332       sig_type->per_cu.section = section;
3333       sig_type->per_cu.sect_off = sect_off;
3334       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3335       sig_type->per_cu.v.quick
3336         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3337                           struct dwarf2_per_cu_quick_data);
3338
3339       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3340       *slot = sig_type;
3341
3342       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3343     }
3344
3345   dwarf2_per_objfile->signatured_types = sig_types_hash;
3346 }
3347
3348 /* Create the signatured type hash table from .debug_names.  */
3349
3350 static void
3351 create_signatured_type_table_from_debug_names
3352   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3353    const mapped_debug_names &map,
3354    struct dwarf2_section_info *section,
3355    struct dwarf2_section_info *abbrev_section)
3356 {
3357   struct objfile *objfile = dwarf2_per_objfile->objfile;
3358
3359   dwarf2_read_section (objfile, section);
3360   dwarf2_read_section (objfile, abbrev_section);
3361
3362   dwarf2_per_objfile->n_type_units
3363     = dwarf2_per_objfile->n_allocated_type_units
3364     = map.tu_count;
3365   dwarf2_per_objfile->all_type_units
3366     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3367
3368   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3369
3370   for (uint32_t i = 0; i < map.tu_count; ++i)
3371     {
3372       struct signatured_type *sig_type;
3373       ULONGEST signature;
3374       void **slot;
3375       cu_offset type_offset_in_tu;
3376
3377       sect_offset sect_off
3378         = (sect_offset) (extract_unsigned_integer
3379                          (map.tu_table_reordered + i * map.offset_size,
3380                           map.offset_size,
3381                           map.dwarf5_byte_order));
3382
3383       comp_unit_head cu_header;
3384       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3385                                      abbrev_section,
3386                                      section->buffer + to_underlying (sect_off),
3387                                      rcuh_kind::TYPE);
3388
3389       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3390                                  struct signatured_type);
3391       sig_type->signature = cu_header.signature;
3392       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3393       sig_type->per_cu.is_debug_types = 1;
3394       sig_type->per_cu.section = section;
3395       sig_type->per_cu.sect_off = sect_off;
3396       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3397       sig_type->per_cu.v.quick
3398         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3399                           struct dwarf2_per_cu_quick_data);
3400
3401       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3402       *slot = sig_type;
3403
3404       dwarf2_per_objfile->all_type_units[i] = sig_type;
3405     }
3406
3407   dwarf2_per_objfile->signatured_types = sig_types_hash;
3408 }
3409
3410 /* Read the address map data from the mapped index, and use it to
3411    populate the objfile's psymtabs_addrmap.  */
3412
3413 static void
3414 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3415                            struct mapped_index *index)
3416 {
3417   struct objfile *objfile = dwarf2_per_objfile->objfile;
3418   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3419   const gdb_byte *iter, *end;
3420   struct addrmap *mutable_map;
3421   CORE_ADDR baseaddr;
3422
3423   auto_obstack temp_obstack;
3424
3425   mutable_map = addrmap_create_mutable (&temp_obstack);
3426
3427   iter = index->address_table.data ();
3428   end = iter + index->address_table.size ();
3429
3430   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3431
3432   while (iter < end)
3433     {
3434       ULONGEST hi, lo, cu_index;
3435       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3436       iter += 8;
3437       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3438       iter += 8;
3439       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3440       iter += 4;
3441
3442       if (lo > hi)
3443         {
3444           complaint (&symfile_complaints,
3445                      _(".gdb_index address table has invalid range (%s - %s)"),
3446                      hex_string (lo), hex_string (hi));
3447           continue;
3448         }
3449
3450       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3451         {
3452           complaint (&symfile_complaints,
3453                      _(".gdb_index address table has invalid CU number %u"),
3454                      (unsigned) cu_index);
3455           continue;
3456         }
3457
3458       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3459       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3460       addrmap_set_empty (mutable_map, lo, hi - 1,
3461                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3462     }
3463
3464   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3465                                                     &objfile->objfile_obstack);
3466 }
3467
3468 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3469    populate the objfile's psymtabs_addrmap.  */
3470
3471 static void
3472 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3473                              struct dwarf2_section_info *section)
3474 {
3475   struct objfile *objfile = dwarf2_per_objfile->objfile;
3476   bfd *abfd = objfile->obfd;
3477   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3478   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3479                                        SECT_OFF_TEXT (objfile));
3480
3481   auto_obstack temp_obstack;
3482   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3483
3484   std::unordered_map<sect_offset,
3485                      dwarf2_per_cu_data *,
3486                      gdb::hash_enum<sect_offset>>
3487     debug_info_offset_to_per_cu;
3488   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3489     {
3490       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3491       const auto insertpair
3492         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3493       if (!insertpair.second)
3494         {
3495           warning (_("Section .debug_aranges in %s has duplicate "
3496                      "debug_info_offset %u, ignoring .debug_aranges."),
3497                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3498           return;
3499         }
3500     }
3501
3502   dwarf2_read_section (objfile, section);
3503
3504   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3505
3506   const gdb_byte *addr = section->buffer;
3507
3508   while (addr < section->buffer + section->size)
3509     {
3510       const gdb_byte *const entry_addr = addr;
3511       unsigned int bytes_read;
3512
3513       const LONGEST entry_length = read_initial_length (abfd, addr,
3514                                                         &bytes_read);
3515       addr += bytes_read;
3516
3517       const gdb_byte *const entry_end = addr + entry_length;
3518       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3519       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3520       if (addr + entry_length > section->buffer + section->size)
3521         {
3522           warning (_("Section .debug_aranges in %s entry at offset %zu "
3523                      "length %s exceeds section length %s, "
3524                      "ignoring .debug_aranges."),
3525                    objfile_name (objfile), entry_addr - section->buffer,
3526                    plongest (bytes_read + entry_length),
3527                    pulongest (section->size));
3528           return;
3529         }
3530
3531       /* The version number.  */
3532       const uint16_t version = read_2_bytes (abfd, addr);
3533       addr += 2;
3534       if (version != 2)
3535         {
3536           warning (_("Section .debug_aranges in %s entry at offset %zu "
3537                      "has unsupported version %d, ignoring .debug_aranges."),
3538                    objfile_name (objfile), entry_addr - section->buffer,
3539                    version);
3540           return;
3541         }
3542
3543       const uint64_t debug_info_offset
3544         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3545       addr += offset_size;
3546       const auto per_cu_it
3547         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3548       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3549         {
3550           warning (_("Section .debug_aranges in %s entry at offset %zu "
3551                      "debug_info_offset %s does not exists, "
3552                      "ignoring .debug_aranges."),
3553                    objfile_name (objfile), entry_addr - section->buffer,
3554                    pulongest (debug_info_offset));
3555           return;
3556         }
3557       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3558
3559       const uint8_t address_size = *addr++;
3560       if (address_size < 1 || address_size > 8)
3561         {
3562           warning (_("Section .debug_aranges in %s entry at offset %zu "
3563                      "address_size %u is invalid, ignoring .debug_aranges."),
3564                    objfile_name (objfile), entry_addr - section->buffer,
3565                    address_size);
3566           return;
3567         }
3568
3569       const uint8_t segment_selector_size = *addr++;
3570       if (segment_selector_size != 0)
3571         {
3572           warning (_("Section .debug_aranges in %s entry at offset %zu "
3573                      "segment_selector_size %u is not supported, "
3574                      "ignoring .debug_aranges."),
3575                    objfile_name (objfile), entry_addr - section->buffer,
3576                    segment_selector_size);
3577           return;
3578         }
3579
3580       /* Must pad to an alignment boundary that is twice the address
3581          size.  It is undocumented by the DWARF standard but GCC does
3582          use it.  */
3583       for (size_t padding = ((-(addr - section->buffer))
3584                              & (2 * address_size - 1));
3585            padding > 0; padding--)
3586         if (*addr++ != 0)
3587           {
3588             warning (_("Section .debug_aranges in %s entry at offset %zu "
3589                        "padding is not zero, ignoring .debug_aranges."),
3590                      objfile_name (objfile), entry_addr - section->buffer);
3591             return;
3592           }
3593
3594       for (;;)
3595         {
3596           if (addr + 2 * address_size > entry_end)
3597             {
3598               warning (_("Section .debug_aranges in %s entry at offset %zu "
3599                          "address list is not properly terminated, "
3600                          "ignoring .debug_aranges."),
3601                        objfile_name (objfile), entry_addr - section->buffer);
3602               return;
3603             }
3604           ULONGEST start = extract_unsigned_integer (addr, address_size,
3605                                                      dwarf5_byte_order);
3606           addr += address_size;
3607           ULONGEST length = extract_unsigned_integer (addr, address_size,
3608                                                       dwarf5_byte_order);
3609           addr += address_size;
3610           if (start == 0 && length == 0)
3611             break;
3612           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3613             {
3614               /* Symbol was eliminated due to a COMDAT group.  */
3615               continue;
3616             }
3617           ULONGEST end = start + length;
3618           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3619           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3620           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3621         }
3622     }
3623
3624   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3625                                                     &objfile->objfile_obstack);
3626 }
3627
3628 /* The hash function for strings in the mapped index.  This is the same as
3629    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3630    implementation.  This is necessary because the hash function is tied to the
3631    format of the mapped index file.  The hash values do not have to match with
3632    SYMBOL_HASH_NEXT.
3633    
3634    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3635
3636 static hashval_t
3637 mapped_index_string_hash (int index_version, const void *p)
3638 {
3639   const unsigned char *str = (const unsigned char *) p;
3640   hashval_t r = 0;
3641   unsigned char c;
3642
3643   while ((c = *str++) != 0)
3644     {
3645       if (index_version >= 5)
3646         c = tolower (c);
3647       r = r * 67 + c - 113;
3648     }
3649
3650   return r;
3651 }
3652
3653 /* Find a slot in the mapped index INDEX for the object named NAME.
3654    If NAME is found, set *VEC_OUT to point to the CU vector in the
3655    constant pool and return true.  If NAME cannot be found, return
3656    false.  */
3657
3658 static bool
3659 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3660                           offset_type **vec_out)
3661 {
3662   offset_type hash;
3663   offset_type slot, step;
3664   int (*cmp) (const char *, const char *);
3665
3666   gdb::unique_xmalloc_ptr<char> without_params;
3667   if (current_language->la_language == language_cplus
3668       || current_language->la_language == language_fortran
3669       || current_language->la_language == language_d)
3670     {
3671       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3672          not contain any.  */
3673
3674       if (strchr (name, '(') != NULL)
3675         {
3676           without_params = cp_remove_params (name);
3677
3678           if (without_params != NULL)
3679             name = without_params.get ();
3680         }
3681     }
3682
3683   /* Index version 4 did not support case insensitive searches.  But the
3684      indices for case insensitive languages are built in lowercase, therefore
3685      simulate our NAME being searched is also lowercased.  */
3686   hash = mapped_index_string_hash ((index->version == 4
3687                                     && case_sensitivity == case_sensitive_off
3688                                     ? 5 : index->version),
3689                                    name);
3690
3691   slot = hash & (index->symbol_table.size () - 1);
3692   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3693   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3694
3695   for (;;)
3696     {
3697       const char *str;
3698
3699       const auto &bucket = index->symbol_table[slot];
3700       if (bucket.name == 0 && bucket.vec == 0)
3701         return false;
3702
3703       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3704       if (!cmp (name, str))
3705         {
3706           *vec_out = (offset_type *) (index->constant_pool
3707                                       + MAYBE_SWAP (bucket.vec));
3708           return true;
3709         }
3710
3711       slot = (slot + step) & (index->symbol_table.size () - 1);
3712     }
3713 }
3714
3715 /* A helper function that reads the .gdb_index from SECTION and fills
3716    in MAP.  FILENAME is the name of the file containing the section;
3717    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3718    ok to use deprecated sections.
3719
3720    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3721    out parameters that are filled in with information about the CU and
3722    TU lists in the section.
3723
3724    Returns 1 if all went well, 0 otherwise.  */
3725
3726 static int
3727 read_index_from_section (struct objfile *objfile,
3728                          const char *filename,
3729                          int deprecated_ok,
3730                          struct dwarf2_section_info *section,
3731                          struct mapped_index *map,
3732                          const gdb_byte **cu_list,
3733                          offset_type *cu_list_elements,
3734                          const gdb_byte **types_list,
3735                          offset_type *types_list_elements)
3736 {
3737   const gdb_byte *addr;
3738   offset_type version;
3739   offset_type *metadata;
3740   int i;
3741
3742   if (dwarf2_section_empty_p (section))
3743     return 0;
3744
3745   /* Older elfutils strip versions could keep the section in the main
3746      executable while splitting it for the separate debug info file.  */
3747   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3748     return 0;
3749
3750   dwarf2_read_section (objfile, section);
3751
3752   addr = section->buffer;
3753   /* Version check.  */
3754   version = MAYBE_SWAP (*(offset_type *) addr);
3755   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3756      causes the index to behave very poorly for certain requests.  Version 3
3757      contained incomplete addrmap.  So, it seems better to just ignore such
3758      indices.  */
3759   if (version < 4)
3760     {
3761       static int warning_printed = 0;
3762       if (!warning_printed)
3763         {
3764           warning (_("Skipping obsolete .gdb_index section in %s."),
3765                    filename);
3766           warning_printed = 1;
3767         }
3768       return 0;
3769     }
3770   /* Index version 4 uses a different hash function than index version
3771      5 and later.
3772
3773      Versions earlier than 6 did not emit psymbols for inlined
3774      functions.  Using these files will cause GDB not to be able to
3775      set breakpoints on inlined functions by name, so we ignore these
3776      indices unless the user has done
3777      "set use-deprecated-index-sections on".  */
3778   if (version < 6 && !deprecated_ok)
3779     {
3780       static int warning_printed = 0;
3781       if (!warning_printed)
3782         {
3783           warning (_("\
3784 Skipping deprecated .gdb_index section in %s.\n\
3785 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3786 to use the section anyway."),
3787                    filename);
3788           warning_printed = 1;
3789         }
3790       return 0;
3791     }
3792   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3793      of the TU (for symbols coming from TUs),
3794      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3795      Plus gold-generated indices can have duplicate entries for global symbols,
3796      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3797      These are just performance bugs, and we can't distinguish gdb-generated
3798      indices from gold-generated ones, so issue no warning here.  */
3799
3800   /* Indexes with higher version than the one supported by GDB may be no
3801      longer backward compatible.  */
3802   if (version > 8)
3803     return 0;
3804
3805   map->version = version;
3806   map->total_size = section->size;
3807
3808   metadata = (offset_type *) (addr + sizeof (offset_type));
3809
3810   i = 0;
3811   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3812   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3813                        / 8);
3814   ++i;
3815
3816   *types_list = addr + MAYBE_SWAP (metadata[i]);
3817   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3818                            - MAYBE_SWAP (metadata[i]))
3819                           / 8);
3820   ++i;
3821
3822   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3823   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3824   map->address_table
3825     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3826   ++i;
3827
3828   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3829   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3830   map->symbol_table
3831     = gdb::array_view<mapped_index::symbol_table_slot>
3832        ((mapped_index::symbol_table_slot *) symbol_table,
3833         (mapped_index::symbol_table_slot *) symbol_table_end);
3834
3835   ++i;
3836   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3837
3838   return 1;
3839 }
3840
3841 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3842    elements of all the CUs and return 1.  Otherwise, return 0.  */
3843
3844 static int
3845 dwarf2_read_index (struct objfile *objfile)
3846 {
3847   struct mapped_index local_map, *map;
3848   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3849   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3850   struct dwz_file *dwz;
3851   struct dwarf2_per_objfile *dwarf2_per_objfile
3852     = get_dwarf2_per_objfile (objfile);
3853
3854   if (!read_index_from_section (objfile, objfile_name (objfile),
3855                                 use_deprecated_index_sections,
3856                                 &dwarf2_per_objfile->gdb_index, &local_map,
3857                                 &cu_list, &cu_list_elements,
3858                                 &types_list, &types_list_elements))
3859     return 0;
3860
3861   /* Don't use the index if it's empty.  */
3862   if (local_map.symbol_table.empty ())
3863     return 0;
3864
3865   /* If there is a .dwz file, read it so we can get its CU list as
3866      well.  */
3867   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3868   if (dwz != NULL)
3869     {
3870       struct mapped_index dwz_map;
3871       const gdb_byte *dwz_types_ignore;
3872       offset_type dwz_types_elements_ignore;
3873
3874       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3875                                     1,
3876                                     &dwz->gdb_index, &dwz_map,
3877                                     &dwz_list, &dwz_list_elements,
3878                                     &dwz_types_ignore,
3879                                     &dwz_types_elements_ignore))
3880         {
3881           warning (_("could not read '.gdb_index' section from %s; skipping"),
3882                    bfd_get_filename (dwz->dwz_bfd));
3883           return 0;
3884         }
3885     }
3886
3887   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3888                          dwz_list_elements);
3889
3890   if (types_list_elements)
3891     {
3892       struct dwarf2_section_info *section;
3893
3894       /* We can only handle a single .debug_types when we have an
3895          index.  */
3896       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3897         return 0;
3898
3899       section = VEC_index (dwarf2_section_info_def,
3900                            dwarf2_per_objfile->types, 0);
3901
3902       create_signatured_type_table_from_index (objfile, section, types_list,
3903                                                types_list_elements);
3904     }
3905
3906   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3907
3908   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3909   map = new (map) mapped_index ();
3910   *map = local_map;
3911
3912   dwarf2_per_objfile->index_table = map;
3913   dwarf2_per_objfile->using_index = 1;
3914   dwarf2_per_objfile->quick_file_names_table =
3915     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3916
3917   return 1;
3918 }
3919
3920 /* die_reader_func for dw2_get_file_names.  */
3921
3922 static void
3923 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3924                            const gdb_byte *info_ptr,
3925                            struct die_info *comp_unit_die,
3926                            int has_children,
3927                            void *data)
3928 {
3929   struct dwarf2_cu *cu = reader->cu;
3930   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3931   struct dwarf2_per_objfile *dwarf2_per_objfile
3932     = cu->per_cu->dwarf2_per_objfile;
3933   struct objfile *objfile = dwarf2_per_objfile->objfile;
3934   struct dwarf2_per_cu_data *lh_cu;
3935   struct attribute *attr;
3936   int i;
3937   void **slot;
3938   struct quick_file_names *qfn;
3939
3940   gdb_assert (! this_cu->is_debug_types);
3941
3942   /* Our callers never want to match partial units -- instead they
3943      will match the enclosing full CU.  */
3944   if (comp_unit_die->tag == DW_TAG_partial_unit)
3945     {
3946       this_cu->v.quick->no_file_data = 1;
3947       return;
3948     }
3949
3950   lh_cu = this_cu;
3951   slot = NULL;
3952
3953   line_header_up lh;
3954   sect_offset line_offset {};
3955
3956   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3957   if (attr)
3958     {
3959       struct quick_file_names find_entry;
3960
3961       line_offset = (sect_offset) DW_UNSND (attr);
3962
3963       /* We may have already read in this line header (TU line header sharing).
3964          If we have we're done.  */
3965       find_entry.hash.dwo_unit = cu->dwo_unit;
3966       find_entry.hash.line_sect_off = line_offset;
3967       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3968                              &find_entry, INSERT);
3969       if (*slot != NULL)
3970         {
3971           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3972           return;
3973         }
3974
3975       lh = dwarf_decode_line_header (line_offset, cu);
3976     }
3977   if (lh == NULL)
3978     {
3979       lh_cu->v.quick->no_file_data = 1;
3980       return;
3981     }
3982
3983   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3984   qfn->hash.dwo_unit = cu->dwo_unit;
3985   qfn->hash.line_sect_off = line_offset;
3986   gdb_assert (slot != NULL);
3987   *slot = qfn;
3988
3989   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3990
3991   qfn->num_file_names = lh->file_names.size ();
3992   qfn->file_names =
3993     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3994   for (i = 0; i < lh->file_names.size (); ++i)
3995     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3996   qfn->real_names = NULL;
3997
3998   lh_cu->v.quick->file_names = qfn;
3999 }
4000
4001 /* A helper for the "quick" functions which attempts to read the line
4002    table for THIS_CU.  */
4003
4004 static struct quick_file_names *
4005 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4006 {
4007   /* This should never be called for TUs.  */
4008   gdb_assert (! this_cu->is_debug_types);
4009   /* Nor type unit groups.  */
4010   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4011
4012   if (this_cu->v.quick->file_names != NULL)
4013     return this_cu->v.quick->file_names;
4014   /* If we know there is no line data, no point in looking again.  */
4015   if (this_cu->v.quick->no_file_data)
4016     return NULL;
4017
4018   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4019
4020   if (this_cu->v.quick->no_file_data)
4021     return NULL;
4022   return this_cu->v.quick->file_names;
4023 }
4024
4025 /* A helper for the "quick" functions which computes and caches the
4026    real path for a given file name from the line table.  */
4027
4028 static const char *
4029 dw2_get_real_path (struct objfile *objfile,
4030                    struct quick_file_names *qfn, int index)
4031 {
4032   if (qfn->real_names == NULL)
4033     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4034                                       qfn->num_file_names, const char *);
4035
4036   if (qfn->real_names[index] == NULL)
4037     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4038
4039   return qfn->real_names[index];
4040 }
4041
4042 static struct symtab *
4043 dw2_find_last_source_symtab (struct objfile *objfile)
4044 {
4045   struct dwarf2_per_objfile *dwarf2_per_objfile
4046     = get_dwarf2_per_objfile (objfile);
4047   int index = dwarf2_per_objfile->n_comp_units - 1;
4048   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4049   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4050
4051   if (cust == NULL)
4052     return NULL;
4053
4054   return compunit_primary_filetab (cust);
4055 }
4056
4057 /* Traversal function for dw2_forget_cached_source_info.  */
4058
4059 static int
4060 dw2_free_cached_file_names (void **slot, void *info)
4061 {
4062   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4063
4064   if (file_data->real_names)
4065     {
4066       int i;
4067
4068       for (i = 0; i < file_data->num_file_names; ++i)
4069         {
4070           xfree ((void*) file_data->real_names[i]);
4071           file_data->real_names[i] = NULL;
4072         }
4073     }
4074
4075   return 1;
4076 }
4077
4078 static void
4079 dw2_forget_cached_source_info (struct objfile *objfile)
4080 {
4081   struct dwarf2_per_objfile *dwarf2_per_objfile
4082     = get_dwarf2_per_objfile (objfile);
4083
4084   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4085                           dw2_free_cached_file_names, NULL);
4086 }
4087
4088 /* Helper function for dw2_map_symtabs_matching_filename that expands
4089    the symtabs and calls the iterator.  */
4090
4091 static int
4092 dw2_map_expand_apply (struct objfile *objfile,
4093                       struct dwarf2_per_cu_data *per_cu,
4094                       const char *name, const char *real_path,
4095                       gdb::function_view<bool (symtab *)> callback)
4096 {
4097   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4098
4099   /* Don't visit already-expanded CUs.  */
4100   if (per_cu->v.quick->compunit_symtab)
4101     return 0;
4102
4103   /* This may expand more than one symtab, and we want to iterate over
4104      all of them.  */
4105   dw2_instantiate_symtab (per_cu);
4106
4107   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4108                                     last_made, callback);
4109 }
4110
4111 /* Implementation of the map_symtabs_matching_filename method.  */
4112
4113 static bool
4114 dw2_map_symtabs_matching_filename
4115   (struct objfile *objfile, const char *name, const char *real_path,
4116    gdb::function_view<bool (symtab *)> callback)
4117 {
4118   int i;
4119   const char *name_basename = lbasename (name);
4120   struct dwarf2_per_objfile *dwarf2_per_objfile
4121     = get_dwarf2_per_objfile (objfile);
4122
4123   /* The rule is CUs specify all the files, including those used by
4124      any TU, so there's no need to scan TUs here.  */
4125
4126   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4127     {
4128       int j;
4129       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4130       struct quick_file_names *file_data;
4131
4132       /* We only need to look at symtabs not already expanded.  */
4133       if (per_cu->v.quick->compunit_symtab)
4134         continue;
4135
4136       file_data = dw2_get_file_names (per_cu);
4137       if (file_data == NULL)
4138         continue;
4139
4140       for (j = 0; j < file_data->num_file_names; ++j)
4141         {
4142           const char *this_name = file_data->file_names[j];
4143           const char *this_real_name;
4144
4145           if (compare_filenames_for_search (this_name, name))
4146             {
4147               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4148                                         callback))
4149                 return true;
4150               continue;
4151             }
4152
4153           /* Before we invoke realpath, which can get expensive when many
4154              files are involved, do a quick comparison of the basenames.  */
4155           if (! basenames_may_differ
4156               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4157             continue;
4158
4159           this_real_name = dw2_get_real_path (objfile, file_data, j);
4160           if (compare_filenames_for_search (this_real_name, name))
4161             {
4162               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4163                                         callback))
4164                 return true;
4165               continue;
4166             }
4167
4168           if (real_path != NULL)
4169             {
4170               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4171               gdb_assert (IS_ABSOLUTE_PATH (name));
4172               if (this_real_name != NULL
4173                   && FILENAME_CMP (real_path, this_real_name) == 0)
4174                 {
4175                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4176                                             callback))
4177                     return true;
4178                   continue;
4179                 }
4180             }
4181         }
4182     }
4183
4184   return false;
4185 }
4186
4187 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4188
4189 struct dw2_symtab_iterator
4190 {
4191   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4192   struct dwarf2_per_objfile *dwarf2_per_objfile;
4193   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4194   int want_specific_block;
4195   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4196      Unused if !WANT_SPECIFIC_BLOCK.  */
4197   int block_index;
4198   /* The kind of symbol we're looking for.  */
4199   domain_enum domain;
4200   /* The list of CUs from the index entry of the symbol,
4201      or NULL if not found.  */
4202   offset_type *vec;
4203   /* The next element in VEC to look at.  */
4204   int next;
4205   /* The number of elements in VEC, or zero if there is no match.  */
4206   int length;
4207   /* Have we seen a global version of the symbol?
4208      If so we can ignore all further global instances.
4209      This is to work around gold/15646, inefficient gold-generated
4210      indices.  */
4211   int global_seen;
4212 };
4213
4214 /* Initialize the index symtab iterator ITER.
4215    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4216    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4217
4218 static void
4219 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4220                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4221                       int want_specific_block,
4222                       int block_index,
4223                       domain_enum domain,
4224                       const char *name)
4225 {
4226   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4227   iter->want_specific_block = want_specific_block;
4228   iter->block_index = block_index;
4229   iter->domain = domain;
4230   iter->next = 0;
4231   iter->global_seen = 0;
4232
4233   mapped_index *index = dwarf2_per_objfile->index_table;
4234
4235   /* index is NULL if OBJF_READNOW.  */
4236   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4237     iter->length = MAYBE_SWAP (*iter->vec);
4238   else
4239     {
4240       iter->vec = NULL;
4241       iter->length = 0;
4242     }
4243 }
4244
4245 /* Return the next matching CU or NULL if there are no more.  */
4246
4247 static struct dwarf2_per_cu_data *
4248 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4249 {
4250   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4251
4252   for ( ; iter->next < iter->length; ++iter->next)
4253     {
4254       offset_type cu_index_and_attrs =
4255         MAYBE_SWAP (iter->vec[iter->next + 1]);
4256       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4257       struct dwarf2_per_cu_data *per_cu;
4258       int want_static = iter->block_index != GLOBAL_BLOCK;
4259       /* This value is only valid for index versions >= 7.  */
4260       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4261       gdb_index_symbol_kind symbol_kind =
4262         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4263       /* Only check the symbol attributes if they're present.
4264          Indices prior to version 7 don't record them,
4265          and indices >= 7 may elide them for certain symbols
4266          (gold does this).  */
4267       int attrs_valid =
4268         (dwarf2_per_objfile->index_table->version >= 7
4269          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4270
4271       /* Don't crash on bad data.  */
4272       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4273                        + dwarf2_per_objfile->n_type_units))
4274         {
4275           complaint (&symfile_complaints,
4276                      _(".gdb_index entry has bad CU index"
4277                        " [in module %s]"),
4278                      objfile_name (dwarf2_per_objfile->objfile));
4279           continue;
4280         }
4281
4282       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4283
4284       /* Skip if already read in.  */
4285       if (per_cu->v.quick->compunit_symtab)
4286         continue;
4287
4288       /* Check static vs global.  */
4289       if (attrs_valid)
4290         {
4291           if (iter->want_specific_block
4292               && want_static != is_static)
4293             continue;
4294           /* Work around gold/15646.  */
4295           if (!is_static && iter->global_seen)
4296             continue;
4297           if (!is_static)
4298             iter->global_seen = 1;
4299         }
4300
4301       /* Only check the symbol's kind if it has one.  */
4302       if (attrs_valid)
4303         {
4304           switch (iter->domain)
4305             {
4306             case VAR_DOMAIN:
4307               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4308                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4309                   /* Some types are also in VAR_DOMAIN.  */
4310                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4311                 continue;
4312               break;
4313             case STRUCT_DOMAIN:
4314               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4315                 continue;
4316               break;
4317             case LABEL_DOMAIN:
4318               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4319                 continue;
4320               break;
4321             default:
4322               break;
4323             }
4324         }
4325
4326       ++iter->next;
4327       return per_cu;
4328     }
4329
4330   return NULL;
4331 }
4332
4333 static struct compunit_symtab *
4334 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4335                    const char *name, domain_enum domain)
4336 {
4337   struct compunit_symtab *stab_best = NULL;
4338   struct dwarf2_per_objfile *dwarf2_per_objfile
4339     = get_dwarf2_per_objfile (objfile);
4340
4341   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4342
4343   struct dw2_symtab_iterator iter;
4344   struct dwarf2_per_cu_data *per_cu;
4345
4346   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4347
4348   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4349     {
4350       struct symbol *sym, *with_opaque = NULL;
4351       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4352       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4353       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4354
4355       sym = block_find_symbol (block, name, domain,
4356                                block_find_non_opaque_type_preferred,
4357                                &with_opaque);
4358
4359       /* Some caution must be observed with overloaded functions
4360          and methods, since the index will not contain any overload
4361          information (but NAME might contain it).  */
4362
4363       if (sym != NULL
4364           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4365         return stab;
4366       if (with_opaque != NULL
4367           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4368         stab_best = stab;
4369
4370       /* Keep looking through other CUs.  */
4371     }
4372
4373   return stab_best;
4374 }
4375
4376 static void
4377 dw2_print_stats (struct objfile *objfile)
4378 {
4379   struct dwarf2_per_objfile *dwarf2_per_objfile
4380     = get_dwarf2_per_objfile (objfile);
4381   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4382   int count = 0;
4383
4384   for (int i = 0; i < total; ++i)
4385     {
4386       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4387
4388       if (!per_cu->v.quick->compunit_symtab)
4389         ++count;
4390     }
4391   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4392   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4393 }
4394
4395 /* This dumps minimal information about the index.
4396    It is called via "mt print objfiles".
4397    One use is to verify .gdb_index has been loaded by the
4398    gdb.dwarf2/gdb-index.exp testcase.  */
4399
4400 static void
4401 dw2_dump (struct objfile *objfile)
4402 {
4403   struct dwarf2_per_objfile *dwarf2_per_objfile
4404     = get_dwarf2_per_objfile (objfile);
4405
4406   gdb_assert (dwarf2_per_objfile->using_index);
4407   printf_filtered (".gdb_index:");
4408   if (dwarf2_per_objfile->index_table != NULL)
4409     {
4410       printf_filtered (" version %d\n",
4411                        dwarf2_per_objfile->index_table->version);
4412     }
4413   else
4414     printf_filtered (" faked for \"readnow\"\n");
4415   printf_filtered ("\n");
4416 }
4417
4418 static void
4419 dw2_relocate (struct objfile *objfile,
4420               const struct section_offsets *new_offsets,
4421               const struct section_offsets *delta)
4422 {
4423   /* There's nothing to relocate here.  */
4424 }
4425
4426 static void
4427 dw2_expand_symtabs_for_function (struct objfile *objfile,
4428                                  const char *func_name)
4429 {
4430   struct dwarf2_per_objfile *dwarf2_per_objfile
4431     = get_dwarf2_per_objfile (objfile);
4432
4433   struct dw2_symtab_iterator iter;
4434   struct dwarf2_per_cu_data *per_cu;
4435
4436   /* Note: It doesn't matter what we pass for block_index here.  */
4437   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4438                         func_name);
4439
4440   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4441     dw2_instantiate_symtab (per_cu);
4442
4443 }
4444
4445 static void
4446 dw2_expand_all_symtabs (struct objfile *objfile)
4447 {
4448   struct dwarf2_per_objfile *dwarf2_per_objfile
4449     = get_dwarf2_per_objfile (objfile);
4450   int total_units = (dwarf2_per_objfile->n_comp_units
4451                      + dwarf2_per_objfile->n_type_units);
4452
4453   for (int i = 0; i < total_units; ++i)
4454     {
4455       struct dwarf2_per_cu_data *per_cu
4456         = dw2_get_cutu (dwarf2_per_objfile, i);
4457
4458       dw2_instantiate_symtab (per_cu);
4459     }
4460 }
4461
4462 static void
4463 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4464                                   const char *fullname)
4465 {
4466   struct dwarf2_per_objfile *dwarf2_per_objfile
4467     = get_dwarf2_per_objfile (objfile);
4468
4469   /* We don't need to consider type units here.
4470      This is only called for examining code, e.g. expand_line_sal.
4471      There can be an order of magnitude (or more) more type units
4472      than comp units, and we avoid them if we can.  */
4473
4474   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4475     {
4476       int j;
4477       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4478       struct quick_file_names *file_data;
4479
4480       /* We only need to look at symtabs not already expanded.  */
4481       if (per_cu->v.quick->compunit_symtab)
4482         continue;
4483
4484       file_data = dw2_get_file_names (per_cu);
4485       if (file_data == NULL)
4486         continue;
4487
4488       for (j = 0; j < file_data->num_file_names; ++j)
4489         {
4490           const char *this_fullname = file_data->file_names[j];
4491
4492           if (filename_cmp (this_fullname, fullname) == 0)
4493             {
4494               dw2_instantiate_symtab (per_cu);
4495               break;
4496             }
4497         }
4498     }
4499 }
4500
4501 static void
4502 dw2_map_matching_symbols (struct objfile *objfile,
4503                           const char * name, domain_enum domain,
4504                           int global,
4505                           int (*callback) (struct block *,
4506                                            struct symbol *, void *),
4507                           void *data, symbol_name_match_type match,
4508                           symbol_compare_ftype *ordered_compare)
4509 {
4510   /* Currently unimplemented; used for Ada.  The function can be called if the
4511      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4512      does not look for non-Ada symbols this function should just return.  */
4513 }
4514
4515 /* Symbol name matcher for .gdb_index names.
4516
4517    Symbol names in .gdb_index have a few particularities:
4518
4519    - There's no indication of which is the language of each symbol.
4520
4521      Since each language has its own symbol name matching algorithm,
4522      and we don't know which language is the right one, we must match
4523      each symbol against all languages.  This would be a potential
4524      performance problem if it were not mitigated by the
4525      mapped_index::name_components lookup table, which significantly
4526      reduces the number of times we need to call into this matcher,
4527      making it a non-issue.
4528
4529    - Symbol names in the index have no overload (parameter)
4530      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4531      appear as "foo" in the index, for example.
4532
4533      This means that the lookup names passed to the symbol name
4534      matcher functions must have no parameter information either
4535      because (e.g.) symbol search name "foo" does not match
4536      lookup-name "foo(int)" [while swapping search name for lookup
4537      name would match].
4538 */
4539 class gdb_index_symbol_name_matcher
4540 {
4541 public:
4542   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4543   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4544
4545   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4546      Returns true if any matcher matches.  */
4547   bool matches (const char *symbol_name);
4548
4549 private:
4550   /* A reference to the lookup name we're matching against.  */
4551   const lookup_name_info &m_lookup_name;
4552
4553   /* A vector holding all the different symbol name matchers, for all
4554      languages.  */
4555   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4556 };
4557
4558 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4559   (const lookup_name_info &lookup_name)
4560     : m_lookup_name (lookup_name)
4561 {
4562   /* Prepare the vector of comparison functions upfront, to avoid
4563      doing the same work for each symbol.  Care is taken to avoid
4564      matching with the same matcher more than once if/when multiple
4565      languages use the same matcher function.  */
4566   auto &matchers = m_symbol_name_matcher_funcs;
4567   matchers.reserve (nr_languages);
4568
4569   matchers.push_back (default_symbol_name_matcher);
4570
4571   for (int i = 0; i < nr_languages; i++)
4572     {
4573       const language_defn *lang = language_def ((enum language) i);
4574       symbol_name_matcher_ftype *name_matcher
4575         = get_symbol_name_matcher (lang, m_lookup_name);
4576
4577       /* Don't insert the same comparison routine more than once.
4578          Note that we do this linear walk instead of a seemingly
4579          cheaper sorted insert, or use a std::set or something like
4580          that, because relative order of function addresses is not
4581          stable.  This is not a problem in practice because the number
4582          of supported languages is low, and the cost here is tiny
4583          compared to the number of searches we'll do afterwards using
4584          this object.  */
4585       if (name_matcher != default_symbol_name_matcher
4586           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4587               == matchers.end ()))
4588         matchers.push_back (name_matcher);
4589     }
4590 }
4591
4592 bool
4593 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4594 {
4595   for (auto matches_name : m_symbol_name_matcher_funcs)
4596     if (matches_name (symbol_name, m_lookup_name, NULL))
4597       return true;
4598
4599   return false;
4600 }
4601
4602 /* Starting from a search name, return the string that finds the upper
4603    bound of all strings that start with SEARCH_NAME in a sorted name
4604    list.  Returns the empty string to indicate that the upper bound is
4605    the end of the list.  */
4606
4607 static std::string
4608 make_sort_after_prefix_name (const char *search_name)
4609 {
4610   /* When looking to complete "func", we find the upper bound of all
4611      symbols that start with "func" by looking for where we'd insert
4612      the closest string that would follow "func" in lexicographical
4613      order.  Usually, that's "func"-with-last-character-incremented,
4614      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4615      will be UTF-8 multi-byte sequences, but we can't be certain.
4616      Especially mind the 0xff character, which is a valid character in
4617      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4618      rule out compilers allowing it in identifiers.  Note that
4619      conveniently, strcmp/strcasecmp are specified to compare
4620      characters interpreted as unsigned char.  So what we do is treat
4621      the whole string as a base 256 number composed of a sequence of
4622      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4623      to 0, and carries 1 to the following more-significant position.
4624      If the very first character in SEARCH_NAME ends up incremented
4625      and carries/overflows, then the upper bound is the end of the
4626      list.  The string after the empty string is also the empty
4627      string.
4628
4629      Some examples of this operation:
4630
4631        SEARCH_NAME  => "+1" RESULT
4632
4633        "abc"              => "abd"
4634        "ab\xff"           => "ac"
4635        "\xff" "a" "\xff"  => "\xff" "b"
4636        "\xff"             => ""
4637        "\xff\xff"         => ""
4638        ""                 => ""
4639
4640      Then, with these symbols for example:
4641
4642       func
4643       func1
4644       fund
4645
4646      completing "func" looks for symbols between "func" and
4647      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4648      which finds "func" and "func1", but not "fund".
4649
4650      And with:
4651
4652       funcÿ     (Latin1 'ÿ' [0xff])
4653       funcÿ1
4654       fund
4655
4656      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4657      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4658
4659      And with:
4660
4661       ÿÿ        (Latin1 'ÿ' [0xff])
4662       ÿÿ1
4663
4664      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4665      the end of the list.
4666   */
4667   std::string after = search_name;
4668   while (!after.empty () && (unsigned char) after.back () == 0xff)
4669     after.pop_back ();
4670   if (!after.empty ())
4671     after.back () = (unsigned char) after.back () + 1;
4672   return after;
4673 }
4674
4675 /* See declaration.  */
4676
4677 std::pair<std::vector<name_component>::const_iterator,
4678           std::vector<name_component>::const_iterator>
4679 mapped_index_base::find_name_components_bounds
4680   (const lookup_name_info &lookup_name_without_params) const
4681 {
4682   auto *name_cmp
4683     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4684
4685   const char *cplus
4686     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4687
4688   /* Comparison function object for lower_bound that matches against a
4689      given symbol name.  */
4690   auto lookup_compare_lower = [&] (const name_component &elem,
4691                                    const char *name)
4692     {
4693       const char *elem_qualified = this->symbol_name_at (elem.idx);
4694       const char *elem_name = elem_qualified + elem.name_offset;
4695       return name_cmp (elem_name, name) < 0;
4696     };
4697
4698   /* Comparison function object for upper_bound that matches against a
4699      given symbol name.  */
4700   auto lookup_compare_upper = [&] (const char *name,
4701                                    const name_component &elem)
4702     {
4703       const char *elem_qualified = this->symbol_name_at (elem.idx);
4704       const char *elem_name = elem_qualified + elem.name_offset;
4705       return name_cmp (name, elem_name) < 0;
4706     };
4707
4708   auto begin = this->name_components.begin ();
4709   auto end = this->name_components.end ();
4710
4711   /* Find the lower bound.  */
4712   auto lower = [&] ()
4713     {
4714       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4715         return begin;
4716       else
4717         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4718     } ();
4719
4720   /* Find the upper bound.  */
4721   auto upper = [&] ()
4722     {
4723       if (lookup_name_without_params.completion_mode ())
4724         {
4725           /* In completion mode, we want UPPER to point past all
4726              symbols names that have the same prefix.  I.e., with
4727              these symbols, and completing "func":
4728
4729               function        << lower bound
4730               function1
4731               other_function  << upper bound
4732
4733              We find the upper bound by looking for the insertion
4734              point of "func"-with-last-character-incremented,
4735              i.e. "fund".  */
4736           std::string after = make_sort_after_prefix_name (cplus);
4737           if (after.empty ())
4738             return end;
4739           return std::lower_bound (lower, end, after.c_str (),
4740                                    lookup_compare_lower);
4741         }
4742       else
4743         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4744     } ();
4745
4746   return {lower, upper};
4747 }
4748
4749 /* See declaration.  */
4750
4751 void
4752 mapped_index_base::build_name_components ()
4753 {
4754   if (!this->name_components.empty ())
4755     return;
4756
4757   this->name_components_casing = case_sensitivity;
4758   auto *name_cmp
4759     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4760
4761   /* The code below only knows how to break apart components of C++
4762      symbol names (and other languages that use '::' as
4763      namespace/module separator).  If we add support for wild matching
4764      to some language that uses some other operator (E.g., Ada, Go and
4765      D use '.'), then we'll need to try splitting the symbol name
4766      according to that language too.  Note that Ada does support wild
4767      matching, but doesn't currently support .gdb_index.  */
4768   auto count = this->symbol_name_count ();
4769   for (offset_type idx = 0; idx < count; idx++)
4770     {
4771       if (this->symbol_name_slot_invalid (idx))
4772         continue;
4773
4774       const char *name = this->symbol_name_at (idx);
4775
4776       /* Add each name component to the name component table.  */
4777       unsigned int previous_len = 0;
4778       for (unsigned int current_len = cp_find_first_component (name);
4779            name[current_len] != '\0';
4780            current_len += cp_find_first_component (name + current_len))
4781         {
4782           gdb_assert (name[current_len] == ':');
4783           this->name_components.push_back ({previous_len, idx});
4784           /* Skip the '::'.  */
4785           current_len += 2;
4786           previous_len = current_len;
4787         }
4788       this->name_components.push_back ({previous_len, idx});
4789     }
4790
4791   /* Sort name_components elements by name.  */
4792   auto name_comp_compare = [&] (const name_component &left,
4793                                 const name_component &right)
4794     {
4795       const char *left_qualified = this->symbol_name_at (left.idx);
4796       const char *right_qualified = this->symbol_name_at (right.idx);
4797
4798       const char *left_name = left_qualified + left.name_offset;
4799       const char *right_name = right_qualified + right.name_offset;
4800
4801       return name_cmp (left_name, right_name) < 0;
4802     };
4803
4804   std::sort (this->name_components.begin (),
4805              this->name_components.end (),
4806              name_comp_compare);
4807 }
4808
4809 /* Helper for dw2_expand_symtabs_matching that works with a
4810    mapped_index_base instead of the containing objfile.  This is split
4811    to a separate function in order to be able to unit test the
4812    name_components matching using a mock mapped_index_base.  For each
4813    symbol name that matches, calls MATCH_CALLBACK, passing it the
4814    symbol's index in the mapped_index_base symbol table.  */
4815
4816 static void
4817 dw2_expand_symtabs_matching_symbol
4818   (mapped_index_base &index,
4819    const lookup_name_info &lookup_name_in,
4820    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4821    enum search_domain kind,
4822    gdb::function_view<void (offset_type)> match_callback)
4823 {
4824   lookup_name_info lookup_name_without_params
4825     = lookup_name_in.make_ignore_params ();
4826   gdb_index_symbol_name_matcher lookup_name_matcher
4827     (lookup_name_without_params);
4828
4829   /* Build the symbol name component sorted vector, if we haven't
4830      yet.  */
4831   index.build_name_components ();
4832
4833   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4834
4835   /* Now for each symbol name in range, check to see if we have a name
4836      match, and if so, call the MATCH_CALLBACK callback.  */
4837
4838   /* The same symbol may appear more than once in the range though.
4839      E.g., if we're looking for symbols that complete "w", and we have
4840      a symbol named "w1::w2", we'll find the two name components for
4841      that same symbol in the range.  To be sure we only call the
4842      callback once per symbol, we first collect the symbol name
4843      indexes that matched in a temporary vector and ignore
4844      duplicates.  */
4845   std::vector<offset_type> matches;
4846   matches.reserve (std::distance (bounds.first, bounds.second));
4847
4848   for (; bounds.first != bounds.second; ++bounds.first)
4849     {
4850       const char *qualified = index.symbol_name_at (bounds.first->idx);
4851
4852       if (!lookup_name_matcher.matches (qualified)
4853           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4854         continue;
4855
4856       matches.push_back (bounds.first->idx);
4857     }
4858
4859   std::sort (matches.begin (), matches.end ());
4860
4861   /* Finally call the callback, once per match.  */
4862   ULONGEST prev = -1;
4863   for (offset_type idx : matches)
4864     {
4865       if (prev != idx)
4866         {
4867           match_callback (idx);
4868           prev = idx;
4869         }
4870     }
4871
4872   /* Above we use a type wider than idx's for 'prev', since 0 and
4873      (offset_type)-1 are both possible values.  */
4874   static_assert (sizeof (prev) > sizeof (offset_type), "");
4875 }
4876
4877 #if GDB_SELF_TEST
4878
4879 namespace selftests { namespace dw2_expand_symtabs_matching {
4880
4881 /* A mock .gdb_index/.debug_names-like name index table, enough to
4882    exercise dw2_expand_symtabs_matching_symbol, which works with the
4883    mapped_index_base interface.  Builds an index from the symbol list
4884    passed as parameter to the constructor.  */
4885 class mock_mapped_index : public mapped_index_base
4886 {
4887 public:
4888   mock_mapped_index (gdb::array_view<const char *> symbols)
4889     : m_symbol_table (symbols)
4890   {}
4891
4892   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4893
4894   /* Return the number of names in the symbol table.  */
4895   virtual size_t symbol_name_count () const
4896   {
4897     return m_symbol_table.size ();
4898   }
4899
4900   /* Get the name of the symbol at IDX in the symbol table.  */
4901   virtual const char *symbol_name_at (offset_type idx) const
4902   {
4903     return m_symbol_table[idx];
4904   }
4905
4906 private:
4907   gdb::array_view<const char *> m_symbol_table;
4908 };
4909
4910 /* Convenience function that converts a NULL pointer to a "<null>"
4911    string, to pass to print routines.  */
4912
4913 static const char *
4914 string_or_null (const char *str)
4915 {
4916   return str != NULL ? str : "<null>";
4917 }
4918
4919 /* Check if a lookup_name_info built from
4920    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4921    index.  EXPECTED_LIST is the list of expected matches, in expected
4922    matching order.  If no match expected, then an empty list is
4923    specified.  Returns true on success.  On failure prints a warning
4924    indicating the file:line that failed, and returns false.  */
4925
4926 static bool
4927 check_match (const char *file, int line,
4928              mock_mapped_index &mock_index,
4929              const char *name, symbol_name_match_type match_type,
4930              bool completion_mode,
4931              std::initializer_list<const char *> expected_list)
4932 {
4933   lookup_name_info lookup_name (name, match_type, completion_mode);
4934
4935   bool matched = true;
4936
4937   auto mismatch = [&] (const char *expected_str,
4938                        const char *got)
4939   {
4940     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4941                "expected=\"%s\", got=\"%s\"\n"),
4942              file, line,
4943              (match_type == symbol_name_match_type::FULL
4944               ? "FULL" : "WILD"),
4945              name, string_or_null (expected_str), string_or_null (got));
4946     matched = false;
4947   };
4948
4949   auto expected_it = expected_list.begin ();
4950   auto expected_end = expected_list.end ();
4951
4952   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4953                                       NULL, ALL_DOMAIN,
4954                                       [&] (offset_type idx)
4955   {
4956     const char *matched_name = mock_index.symbol_name_at (idx);
4957     const char *expected_str
4958       = expected_it == expected_end ? NULL : *expected_it++;
4959
4960     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4961       mismatch (expected_str, matched_name);
4962   });
4963
4964   const char *expected_str
4965   = expected_it == expected_end ? NULL : *expected_it++;
4966   if (expected_str != NULL)
4967     mismatch (expected_str, NULL);
4968
4969   return matched;
4970 }
4971
4972 /* The symbols added to the mock mapped_index for testing (in
4973    canonical form).  */
4974 static const char *test_symbols[] = {
4975   "function",
4976   "std::bar",
4977   "std::zfunction",
4978   "std::zfunction2",
4979   "w1::w2",
4980   "ns::foo<char*>",
4981   "ns::foo<int>",
4982   "ns::foo<long>",
4983   "ns2::tmpl<int>::foo2",
4984   "(anonymous namespace)::A::B::C",
4985
4986   /* These are used to check that the increment-last-char in the
4987      matching algorithm for completion doesn't match "t1_fund" when
4988      completing "t1_func".  */
4989   "t1_func",
4990   "t1_func1",
4991   "t1_fund",
4992   "t1_fund1",
4993
4994   /* A UTF-8 name with multi-byte sequences to make sure that
4995      cp-name-parser understands this as a single identifier ("função"
4996      is "function" in PT).  */
4997   u8"u8função",
4998
4999   /* \377 (0xff) is Latin1 'ÿ'.  */
5000   "yfunc\377",
5001
5002   /* \377 (0xff) is Latin1 'ÿ'.  */
5003   "\377",
5004   "\377\377123",
5005
5006   /* A name with all sorts of complications.  Starts with "z" to make
5007      it easier for the completion tests below.  */
5008 #define Z_SYM_NAME \
5009   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5010     "::tuple<(anonymous namespace)::ui*, " \
5011     "std::default_delete<(anonymous namespace)::ui>, void>"
5012
5013   Z_SYM_NAME
5014 };
5015
5016 /* Returns true if the mapped_index_base::find_name_component_bounds
5017    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5018    in completion mode.  */
5019
5020 static bool
5021 check_find_bounds_finds (mapped_index_base &index,
5022                          const char *search_name,
5023                          gdb::array_view<const char *> expected_syms)
5024 {
5025   lookup_name_info lookup_name (search_name,
5026                                 symbol_name_match_type::FULL, true);
5027
5028   auto bounds = index.find_name_components_bounds (lookup_name);
5029
5030   size_t distance = std::distance (bounds.first, bounds.second);
5031   if (distance != expected_syms.size ())
5032     return false;
5033
5034   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5035     {
5036       auto nc_elem = bounds.first + exp_elem;
5037       const char *qualified = index.symbol_name_at (nc_elem->idx);
5038       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5039         return false;
5040     }
5041
5042   return true;
5043 }
5044
5045 /* Test the lower-level mapped_index::find_name_component_bounds
5046    method.  */
5047
5048 static void
5049 test_mapped_index_find_name_component_bounds ()
5050 {
5051   mock_mapped_index mock_index (test_symbols);
5052
5053   mock_index.build_name_components ();
5054
5055   /* Test the lower-level mapped_index::find_name_component_bounds
5056      method in completion mode.  */
5057   {
5058     static const char *expected_syms[] = {
5059       "t1_func",
5060       "t1_func1",
5061     };
5062
5063     SELF_CHECK (check_find_bounds_finds (mock_index,
5064                                          "t1_func", expected_syms));
5065   }
5066
5067   /* Check that the increment-last-char in the name matching algorithm
5068      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5069   {
5070     static const char *expected_syms1[] = {
5071       "\377",
5072       "\377\377123",
5073     };
5074     SELF_CHECK (check_find_bounds_finds (mock_index,
5075                                          "\377", expected_syms1));
5076
5077     static const char *expected_syms2[] = {
5078       "\377\377123",
5079     };
5080     SELF_CHECK (check_find_bounds_finds (mock_index,
5081                                          "\377\377", expected_syms2));
5082   }
5083 }
5084
5085 /* Test dw2_expand_symtabs_matching_symbol.  */
5086
5087 static void
5088 test_dw2_expand_symtabs_matching_symbol ()
5089 {
5090   mock_mapped_index mock_index (test_symbols);
5091
5092   /* We let all tests run until the end even if some fails, for debug
5093      convenience.  */
5094   bool any_mismatch = false;
5095
5096   /* Create the expected symbols list (an initializer_list).  Needed
5097      because lists have commas, and we need to pass them to CHECK,
5098      which is a macro.  */
5099 #define EXPECT(...) { __VA_ARGS__ }
5100
5101   /* Wrapper for check_match that passes down the current
5102      __FILE__/__LINE__.  */
5103 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5104   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5105                                 mock_index,                             \
5106                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5107                                 EXPECTED_LIST)
5108
5109   /* Identity checks.  */
5110   for (const char *sym : test_symbols)
5111     {
5112       /* Should be able to match all existing symbols.  */
5113       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5114                    EXPECT (sym));
5115
5116       /* Should be able to match all existing symbols with
5117          parameters.  */
5118       std::string with_params = std::string (sym) + "(int)";
5119       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5120                    EXPECT (sym));
5121
5122       /* Should be able to match all existing symbols with
5123          parameters and qualifiers.  */
5124       with_params = std::string (sym) + " ( int ) const";
5125       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5126                    EXPECT (sym));
5127
5128       /* This should really find sym, but cp-name-parser.y doesn't
5129          know about lvalue/rvalue qualifiers yet.  */
5130       with_params = std::string (sym) + " ( int ) &&";
5131       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5132                    {});
5133     }
5134
5135   /* Check that the name matching algorithm for completion doesn't get
5136      confused with Latin1 'ÿ' / 0xff.  */
5137   {
5138     static const char str[] = "\377";
5139     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5140                  EXPECT ("\377", "\377\377123"));
5141   }
5142
5143   /* Check that the increment-last-char in the matching algorithm for
5144      completion doesn't match "t1_fund" when completing "t1_func".  */
5145   {
5146     static const char str[] = "t1_func";
5147     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5148                  EXPECT ("t1_func", "t1_func1"));
5149   }
5150
5151   /* Check that completion mode works at each prefix of the expected
5152      symbol name.  */
5153   {
5154     static const char str[] = "function(int)";
5155     size_t len = strlen (str);
5156     std::string lookup;
5157
5158     for (size_t i = 1; i < len; i++)
5159       {
5160         lookup.assign (str, i);
5161         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5162                      EXPECT ("function"));
5163       }
5164   }
5165
5166   /* While "w" is a prefix of both components, the match function
5167      should still only be called once.  */
5168   {
5169     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5170                  EXPECT ("w1::w2"));
5171     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5172                  EXPECT ("w1::w2"));
5173   }
5174
5175   /* Same, with a "complicated" symbol.  */
5176   {
5177     static const char str[] = Z_SYM_NAME;
5178     size_t len = strlen (str);
5179     std::string lookup;
5180
5181     for (size_t i = 1; i < len; i++)
5182       {
5183         lookup.assign (str, i);
5184         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5185                      EXPECT (Z_SYM_NAME));
5186       }
5187   }
5188
5189   /* In FULL mode, an incomplete symbol doesn't match.  */
5190   {
5191     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5192                  {});
5193   }
5194
5195   /* A complete symbol with parameters matches any overload, since the
5196      index has no overload info.  */
5197   {
5198     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5199                  EXPECT ("std::zfunction", "std::zfunction2"));
5200     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5201                  EXPECT ("std::zfunction", "std::zfunction2"));
5202     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5203                  EXPECT ("std::zfunction", "std::zfunction2"));
5204   }
5205
5206   /* Check that whitespace is ignored appropriately.  A symbol with a
5207      template argument list. */
5208   {
5209     static const char expected[] = "ns::foo<int>";
5210     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5211                  EXPECT (expected));
5212     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5213                  EXPECT (expected));
5214   }
5215
5216   /* Check that whitespace is ignored appropriately.  A symbol with a
5217      template argument list that includes a pointer.  */
5218   {
5219     static const char expected[] = "ns::foo<char*>";
5220     /* Try both completion and non-completion modes.  */
5221     static const bool completion_mode[2] = {false, true};
5222     for (size_t i = 0; i < 2; i++)
5223       {
5224         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5225                      completion_mode[i], EXPECT (expected));
5226         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5227                      completion_mode[i], EXPECT (expected));
5228
5229         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5230                      completion_mode[i], EXPECT (expected));
5231         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5232                      completion_mode[i], EXPECT (expected));
5233       }
5234   }
5235
5236   {
5237     /* Check method qualifiers are ignored.  */
5238     static const char expected[] = "ns::foo<char*>";
5239     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5240                  symbol_name_match_type::FULL, true, EXPECT (expected));
5241     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5242                  symbol_name_match_type::FULL, true, EXPECT (expected));
5243     CHECK_MATCH ("foo < char * >  ( int ) const",
5244                  symbol_name_match_type::WILD, true, EXPECT (expected));
5245     CHECK_MATCH ("foo < char * >  ( int ) &&",
5246                  symbol_name_match_type::WILD, true, EXPECT (expected));
5247   }
5248
5249   /* Test lookup names that don't match anything.  */
5250   {
5251     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5252                  {});
5253
5254     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5255                  {});
5256   }
5257
5258   /* Some wild matching tests, exercising "(anonymous namespace)",
5259      which should not be confused with a parameter list.  */
5260   {
5261     static const char *syms[] = {
5262       "A::B::C",
5263       "B::C",
5264       "C",
5265       "A :: B :: C ( int )",
5266       "B :: C ( int )",
5267       "C ( int )",
5268     };
5269
5270     for (const char *s : syms)
5271       {
5272         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5273                      EXPECT ("(anonymous namespace)::A::B::C"));
5274       }
5275   }
5276
5277   {
5278     static const char expected[] = "ns2::tmpl<int>::foo2";
5279     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5280                  EXPECT (expected));
5281     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5282                  EXPECT (expected));
5283   }
5284
5285   SELF_CHECK (!any_mismatch);
5286
5287 #undef EXPECT
5288 #undef CHECK_MATCH
5289 }
5290
5291 static void
5292 run_test ()
5293 {
5294   test_mapped_index_find_name_component_bounds ();
5295   test_dw2_expand_symtabs_matching_symbol ();
5296 }
5297
5298 }} // namespace selftests::dw2_expand_symtabs_matching
5299
5300 #endif /* GDB_SELF_TEST */
5301
5302 /* If FILE_MATCHER is NULL or if PER_CU has
5303    dwarf2_per_cu_quick_data::MARK set (see
5304    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5305    EXPANSION_NOTIFY on it.  */
5306
5307 static void
5308 dw2_expand_symtabs_matching_one
5309   (struct dwarf2_per_cu_data *per_cu,
5310    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5311    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5312 {
5313   if (file_matcher == NULL || per_cu->v.quick->mark)
5314     {
5315       bool symtab_was_null
5316         = (per_cu->v.quick->compunit_symtab == NULL);
5317
5318       dw2_instantiate_symtab (per_cu);
5319
5320       if (expansion_notify != NULL
5321           && symtab_was_null
5322           && per_cu->v.quick->compunit_symtab != NULL)
5323         expansion_notify (per_cu->v.quick->compunit_symtab);
5324     }
5325 }
5326
5327 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5328    matched, to expand corresponding CUs that were marked.  IDX is the
5329    index of the symbol name that matched.  */
5330
5331 static void
5332 dw2_expand_marked_cus
5333   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5334    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5335    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5336    search_domain kind)
5337 {
5338   offset_type *vec, vec_len, vec_idx;
5339   bool global_seen = false;
5340   mapped_index &index = *dwarf2_per_objfile->index_table;
5341
5342   vec = (offset_type *) (index.constant_pool
5343                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5344   vec_len = MAYBE_SWAP (vec[0]);
5345   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5346     {
5347       struct dwarf2_per_cu_data *per_cu;
5348       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5349       /* This value is only valid for index versions >= 7.  */
5350       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5351       gdb_index_symbol_kind symbol_kind =
5352         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5353       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5354       /* Only check the symbol attributes if they're present.
5355          Indices prior to version 7 don't record them,
5356          and indices >= 7 may elide them for certain symbols
5357          (gold does this).  */
5358       int attrs_valid =
5359         (index.version >= 7
5360          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5361
5362       /* Work around gold/15646.  */
5363       if (attrs_valid)
5364         {
5365           if (!is_static && global_seen)
5366             continue;
5367           if (!is_static)
5368             global_seen = true;
5369         }
5370
5371       /* Only check the symbol's kind if it has one.  */
5372       if (attrs_valid)
5373         {
5374           switch (kind)
5375             {
5376             case VARIABLES_DOMAIN:
5377               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5378                 continue;
5379               break;
5380             case FUNCTIONS_DOMAIN:
5381               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5382                 continue;
5383               break;
5384             case TYPES_DOMAIN:
5385               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5386                 continue;
5387               break;
5388             default:
5389               break;
5390             }
5391         }
5392
5393       /* Don't crash on bad data.  */
5394       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5395                        + dwarf2_per_objfile->n_type_units))
5396         {
5397           complaint (&symfile_complaints,
5398                      _(".gdb_index entry has bad CU index"
5399                        " [in module %s]"),
5400                        objfile_name (dwarf2_per_objfile->objfile));
5401           continue;
5402         }
5403
5404       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5405       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5406                                        expansion_notify);
5407     }
5408 }
5409
5410 /* If FILE_MATCHER is non-NULL, set all the
5411    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5412    that match FILE_MATCHER.  */
5413
5414 static void
5415 dw_expand_symtabs_matching_file_matcher
5416   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5417    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5418 {
5419   if (file_matcher == NULL)
5420     return;
5421
5422   objfile *const objfile = dwarf2_per_objfile->objfile;
5423
5424   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5425                                             htab_eq_pointer,
5426                                             NULL, xcalloc, xfree));
5427   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5428                                                 htab_eq_pointer,
5429                                                 NULL, xcalloc, xfree));
5430
5431   /* The rule is CUs specify all the files, including those used by
5432      any TU, so there's no need to scan TUs here.  */
5433
5434   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5435     {
5436       int j;
5437       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5438       struct quick_file_names *file_data;
5439       void **slot;
5440
5441       QUIT;
5442
5443       per_cu->v.quick->mark = 0;
5444
5445       /* We only need to look at symtabs not already expanded.  */
5446       if (per_cu->v.quick->compunit_symtab)
5447         continue;
5448
5449       file_data = dw2_get_file_names (per_cu);
5450       if (file_data == NULL)
5451         continue;
5452
5453       if (htab_find (visited_not_found.get (), file_data) != NULL)
5454         continue;
5455       else if (htab_find (visited_found.get (), file_data) != NULL)
5456         {
5457           per_cu->v.quick->mark = 1;
5458           continue;
5459         }
5460
5461       for (j = 0; j < file_data->num_file_names; ++j)
5462         {
5463           const char *this_real_name;
5464
5465           if (file_matcher (file_data->file_names[j], false))
5466             {
5467               per_cu->v.quick->mark = 1;
5468               break;
5469             }
5470
5471           /* Before we invoke realpath, which can get expensive when many
5472              files are involved, do a quick comparison of the basenames.  */
5473           if (!basenames_may_differ
5474               && !file_matcher (lbasename (file_data->file_names[j]),
5475                                 true))
5476             continue;
5477
5478           this_real_name = dw2_get_real_path (objfile, file_data, j);
5479           if (file_matcher (this_real_name, false))
5480             {
5481               per_cu->v.quick->mark = 1;
5482               break;
5483             }
5484         }
5485
5486       slot = htab_find_slot (per_cu->v.quick->mark
5487                              ? visited_found.get ()
5488                              : visited_not_found.get (),
5489                              file_data, INSERT);
5490       *slot = file_data;
5491     }
5492 }
5493
5494 static void
5495 dw2_expand_symtabs_matching
5496   (struct objfile *objfile,
5497    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5498    const lookup_name_info &lookup_name,
5499    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5500    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5501    enum search_domain kind)
5502 {
5503   struct dwarf2_per_objfile *dwarf2_per_objfile
5504     = get_dwarf2_per_objfile (objfile);
5505
5506   /* index_table is NULL if OBJF_READNOW.  */
5507   if (!dwarf2_per_objfile->index_table)
5508     return;
5509
5510   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5511
5512   mapped_index &index = *dwarf2_per_objfile->index_table;
5513
5514   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5515                                       symbol_matcher,
5516                                       kind, [&] (offset_type idx)
5517     {
5518       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5519                              expansion_notify, kind);
5520     });
5521 }
5522
5523 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5524    symtab.  */
5525
5526 static struct compunit_symtab *
5527 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5528                                           CORE_ADDR pc)
5529 {
5530   int i;
5531
5532   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5533       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5534     return cust;
5535
5536   if (cust->includes == NULL)
5537     return NULL;
5538
5539   for (i = 0; cust->includes[i]; ++i)
5540     {
5541       struct compunit_symtab *s = cust->includes[i];
5542
5543       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5544       if (s != NULL)
5545         return s;
5546     }
5547
5548   return NULL;
5549 }
5550
5551 static struct compunit_symtab *
5552 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5553                                   struct bound_minimal_symbol msymbol,
5554                                   CORE_ADDR pc,
5555                                   struct obj_section *section,
5556                                   int warn_if_readin)
5557 {
5558   struct dwarf2_per_cu_data *data;
5559   struct compunit_symtab *result;
5560
5561   if (!objfile->psymtabs_addrmap)
5562     return NULL;
5563
5564   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5565                                                      pc);
5566   if (!data)
5567     return NULL;
5568
5569   if (warn_if_readin && data->v.quick->compunit_symtab)
5570     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5571              paddress (get_objfile_arch (objfile), pc));
5572
5573   result
5574     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5575                                                 pc);
5576   gdb_assert (result != NULL);
5577   return result;
5578 }
5579
5580 static void
5581 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5582                           void *data, int need_fullname)
5583 {
5584   struct dwarf2_per_objfile *dwarf2_per_objfile
5585     = get_dwarf2_per_objfile (objfile);
5586
5587   if (!dwarf2_per_objfile->filenames_cache)
5588     {
5589       dwarf2_per_objfile->filenames_cache.emplace ();
5590
5591       htab_up visited (htab_create_alloc (10,
5592                                           htab_hash_pointer, htab_eq_pointer,
5593                                           NULL, xcalloc, xfree));
5594
5595       /* The rule is CUs specify all the files, including those used
5596          by any TU, so there's no need to scan TUs here.  We can
5597          ignore file names coming from already-expanded CUs.  */
5598
5599       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5600         {
5601           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5602
5603           if (per_cu->v.quick->compunit_symtab)
5604             {
5605               void **slot = htab_find_slot (visited.get (),
5606                                             per_cu->v.quick->file_names,
5607                                             INSERT);
5608
5609               *slot = per_cu->v.quick->file_names;
5610             }
5611         }
5612
5613       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5614         {
5615           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5616           struct quick_file_names *file_data;
5617           void **slot;
5618
5619           /* We only need to look at symtabs not already expanded.  */
5620           if (per_cu->v.quick->compunit_symtab)
5621             continue;
5622
5623           file_data = dw2_get_file_names (per_cu);
5624           if (file_data == NULL)
5625             continue;
5626
5627           slot = htab_find_slot (visited.get (), file_data, INSERT);
5628           if (*slot)
5629             {
5630               /* Already visited.  */
5631               continue;
5632             }
5633           *slot = file_data;
5634
5635           for (int j = 0; j < file_data->num_file_names; ++j)
5636             {
5637               const char *filename = file_data->file_names[j];
5638               dwarf2_per_objfile->filenames_cache->seen (filename);
5639             }
5640         }
5641     }
5642
5643   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5644     {
5645       gdb::unique_xmalloc_ptr<char> this_real_name;
5646
5647       if (need_fullname)
5648         this_real_name = gdb_realpath (filename);
5649       (*fun) (filename, this_real_name.get (), data);
5650     });
5651 }
5652
5653 static int
5654 dw2_has_symbols (struct objfile *objfile)
5655 {
5656   return 1;
5657 }
5658
5659 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5660 {
5661   dw2_has_symbols,
5662   dw2_find_last_source_symtab,
5663   dw2_forget_cached_source_info,
5664   dw2_map_symtabs_matching_filename,
5665   dw2_lookup_symbol,
5666   dw2_print_stats,
5667   dw2_dump,
5668   dw2_relocate,
5669   dw2_expand_symtabs_for_function,
5670   dw2_expand_all_symtabs,
5671   dw2_expand_symtabs_with_fullname,
5672   dw2_map_matching_symbols,
5673   dw2_expand_symtabs_matching,
5674   dw2_find_pc_sect_compunit_symtab,
5675   NULL,
5676   dw2_map_symbol_filenames
5677 };
5678
5679 /* DWARF-5 debug_names reader.  */
5680
5681 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5682 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5683
5684 /* A helper function that reads the .debug_names section in SECTION
5685    and fills in MAP.  FILENAME is the name of the file containing the
5686    section; it is used for error reporting.
5687
5688    Returns true if all went well, false otherwise.  */
5689
5690 static bool
5691 read_debug_names_from_section (struct objfile *objfile,
5692                                const char *filename,
5693                                struct dwarf2_section_info *section,
5694                                mapped_debug_names &map)
5695 {
5696   if (dwarf2_section_empty_p (section))
5697     return false;
5698
5699   /* Older elfutils strip versions could keep the section in the main
5700      executable while splitting it for the separate debug info file.  */
5701   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5702     return false;
5703
5704   dwarf2_read_section (objfile, section);
5705
5706   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5707
5708   const gdb_byte *addr = section->buffer;
5709
5710   bfd *const abfd = get_section_bfd_owner (section);
5711
5712   unsigned int bytes_read;
5713   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5714   addr += bytes_read;
5715
5716   map.dwarf5_is_dwarf64 = bytes_read != 4;
5717   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5718   if (bytes_read + length != section->size)
5719     {
5720       /* There may be multiple per-CU indices.  */
5721       warning (_("Section .debug_names in %s length %s does not match "
5722                  "section length %s, ignoring .debug_names."),
5723                filename, plongest (bytes_read + length),
5724                pulongest (section->size));
5725       return false;
5726     }
5727
5728   /* The version number.  */
5729   uint16_t version = read_2_bytes (abfd, addr);
5730   addr += 2;
5731   if (version != 5)
5732     {
5733       warning (_("Section .debug_names in %s has unsupported version %d, "
5734                  "ignoring .debug_names."),
5735                filename, version);
5736       return false;
5737     }
5738
5739   /* Padding.  */
5740   uint16_t padding = read_2_bytes (abfd, addr);
5741   addr += 2;
5742   if (padding != 0)
5743     {
5744       warning (_("Section .debug_names in %s has unsupported padding %d, "
5745                  "ignoring .debug_names."),
5746                filename, padding);
5747       return false;
5748     }
5749
5750   /* comp_unit_count - The number of CUs in the CU list.  */
5751   map.cu_count = read_4_bytes (abfd, addr);
5752   addr += 4;
5753
5754   /* local_type_unit_count - The number of TUs in the local TU
5755      list.  */
5756   map.tu_count = read_4_bytes (abfd, addr);
5757   addr += 4;
5758
5759   /* foreign_type_unit_count - The number of TUs in the foreign TU
5760      list.  */
5761   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5762   addr += 4;
5763   if (foreign_tu_count != 0)
5764     {
5765       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5766                  "ignoring .debug_names."),
5767                filename, static_cast<unsigned long> (foreign_tu_count));
5768       return false;
5769     }
5770
5771   /* bucket_count - The number of hash buckets in the hash lookup
5772      table.  */
5773   map.bucket_count = read_4_bytes (abfd, addr);
5774   addr += 4;
5775
5776   /* name_count - The number of unique names in the index.  */
5777   map.name_count = read_4_bytes (abfd, addr);
5778   addr += 4;
5779
5780   /* abbrev_table_size - The size in bytes of the abbreviations
5781      table.  */
5782   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5783   addr += 4;
5784
5785   /* augmentation_string_size - The size in bytes of the augmentation
5786      string.  This value is rounded up to a multiple of 4.  */
5787   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5788   addr += 4;
5789   map.augmentation_is_gdb = ((augmentation_string_size
5790                               == sizeof (dwarf5_augmentation))
5791                              && memcmp (addr, dwarf5_augmentation,
5792                                         sizeof (dwarf5_augmentation)) == 0);
5793   augmentation_string_size += (-augmentation_string_size) & 3;
5794   addr += augmentation_string_size;
5795
5796   /* List of CUs */
5797   map.cu_table_reordered = addr;
5798   addr += map.cu_count * map.offset_size;
5799
5800   /* List of Local TUs */
5801   map.tu_table_reordered = addr;
5802   addr += map.tu_count * map.offset_size;
5803
5804   /* Hash Lookup Table */
5805   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5806   addr += map.bucket_count * 4;
5807   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5808   addr += map.name_count * 4;
5809
5810   /* Name Table */
5811   map.name_table_string_offs_reordered = addr;
5812   addr += map.name_count * map.offset_size;
5813   map.name_table_entry_offs_reordered = addr;
5814   addr += map.name_count * map.offset_size;
5815
5816   const gdb_byte *abbrev_table_start = addr;
5817   for (;;)
5818     {
5819       unsigned int bytes_read;
5820       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5821       addr += bytes_read;
5822       if (index_num == 0)
5823         break;
5824
5825       const auto insertpair
5826         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5827       if (!insertpair.second)
5828         {
5829           warning (_("Section .debug_names in %s has duplicate index %s, "
5830                      "ignoring .debug_names."),
5831                    filename, pulongest (index_num));
5832           return false;
5833         }
5834       mapped_debug_names::index_val &indexval = insertpair.first->second;
5835       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5836       addr += bytes_read;
5837
5838       for (;;)
5839         {
5840           mapped_debug_names::index_val::attr attr;
5841           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5842           addr += bytes_read;
5843           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5844           addr += bytes_read;
5845           if (attr.form == DW_FORM_implicit_const)
5846             {
5847               attr.implicit_const = read_signed_leb128 (abfd, addr,
5848                                                         &bytes_read);
5849               addr += bytes_read;
5850             }
5851           if (attr.dw_idx == 0 && attr.form == 0)
5852             break;
5853           indexval.attr_vec.push_back (std::move (attr));
5854         }
5855     }
5856   if (addr != abbrev_table_start + abbrev_table_size)
5857     {
5858       warning (_("Section .debug_names in %s has abbreviation_table "
5859                  "of size %zu vs. written as %u, ignoring .debug_names."),
5860                filename, addr - abbrev_table_start, abbrev_table_size);
5861       return false;
5862     }
5863   map.entry_pool = addr;
5864
5865   return true;
5866 }
5867
5868 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5869    list.  */
5870
5871 static void
5872 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5873                                   const mapped_debug_names &map,
5874                                   dwarf2_section_info &section,
5875                                   bool is_dwz, int base_offset)
5876 {
5877   sect_offset sect_off_prev;
5878   for (uint32_t i = 0; i <= map.cu_count; ++i)
5879     {
5880       sect_offset sect_off_next;
5881       if (i < map.cu_count)
5882         {
5883           sect_off_next
5884             = (sect_offset) (extract_unsigned_integer
5885                              (map.cu_table_reordered + i * map.offset_size,
5886                               map.offset_size,
5887                               map.dwarf5_byte_order));
5888         }
5889       else
5890         sect_off_next = (sect_offset) section.size;
5891       if (i >= 1)
5892         {
5893           const ULONGEST length = sect_off_next - sect_off_prev;
5894           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5895             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5896                                          sect_off_prev, length);
5897         }
5898       sect_off_prev = sect_off_next;
5899     }
5900 }
5901
5902 /* Read the CU list from the mapped index, and use it to create all
5903    the CU objects for this dwarf2_per_objfile.  */
5904
5905 static void
5906 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5907                              const mapped_debug_names &map,
5908                              const mapped_debug_names &dwz_map)
5909 {
5910   struct objfile *objfile = dwarf2_per_objfile->objfile;
5911
5912   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5913   dwarf2_per_objfile->all_comp_units
5914     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5915                  dwarf2_per_objfile->n_comp_units);
5916
5917   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5918                                     dwarf2_per_objfile->info,
5919                                     false /* is_dwz */,
5920                                     0 /* base_offset */);
5921
5922   if (dwz_map.cu_count == 0)
5923     return;
5924
5925   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5926   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5927                                     true /* is_dwz */,
5928                                     map.cu_count /* base_offset */);
5929 }
5930
5931 /* Read .debug_names.  If everything went ok, initialize the "quick"
5932    elements of all the CUs and return true.  Otherwise, return false.  */
5933
5934 static bool
5935 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5936 {
5937   mapped_debug_names local_map (dwarf2_per_objfile);
5938   mapped_debug_names dwz_map (dwarf2_per_objfile);
5939   struct objfile *objfile = dwarf2_per_objfile->objfile;
5940
5941   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5942                                       &dwarf2_per_objfile->debug_names,
5943                                       local_map))
5944     return false;
5945
5946   /* Don't use the index if it's empty.  */
5947   if (local_map.name_count == 0)
5948     return false;
5949
5950   /* If there is a .dwz file, read it so we can get its CU list as
5951      well.  */
5952   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5953   if (dwz != NULL)
5954     {
5955       if (!read_debug_names_from_section (objfile,
5956                                           bfd_get_filename (dwz->dwz_bfd),
5957                                           &dwz->debug_names, dwz_map))
5958         {
5959           warning (_("could not read '.debug_names' section from %s; skipping"),
5960                    bfd_get_filename (dwz->dwz_bfd));
5961           return false;
5962         }
5963     }
5964
5965   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5966
5967   if (local_map.tu_count != 0)
5968     {
5969       /* We can only handle a single .debug_types when we have an
5970          index.  */
5971       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5972         return false;
5973
5974       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5975                                                 dwarf2_per_objfile->types, 0);
5976
5977       create_signatured_type_table_from_debug_names
5978         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5979     }
5980
5981   create_addrmap_from_aranges (dwarf2_per_objfile,
5982                                &dwarf2_per_objfile->debug_aranges);
5983
5984   dwarf2_per_objfile->debug_names_table.reset
5985     (new mapped_debug_names (dwarf2_per_objfile));
5986   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5987   dwarf2_per_objfile->using_index = 1;
5988   dwarf2_per_objfile->quick_file_names_table =
5989     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5990
5991   return true;
5992 }
5993
5994 /* Symbol name hashing function as specified by DWARF-5.  */
5995
5996 static uint32_t
5997 dwarf5_djb_hash (const char *str_)
5998 {
5999   const unsigned char *str = (const unsigned char *) str_;
6000
6001   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6002      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6003
6004   uint32_t hash = 5381;
6005   while (int c = *str++)
6006     hash = hash * 33 + tolower (c);
6007   return hash;
6008 }
6009
6010 /* Type used to manage iterating over all CUs looking for a symbol for
6011    .debug_names.  */
6012
6013 class dw2_debug_names_iterator
6014 {
6015 public:
6016   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6017      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6018   dw2_debug_names_iterator (const mapped_debug_names &map,
6019                             bool want_specific_block,
6020                             block_enum block_index, domain_enum domain,
6021                             const char *name)
6022     : m_map (map), m_want_specific_block (want_specific_block),
6023       m_block_index (block_index), m_domain (domain),
6024       m_addr (find_vec_in_debug_names (map, name))
6025   {}
6026
6027   dw2_debug_names_iterator (const mapped_debug_names &map,
6028                             search_domain search, uint32_t namei)
6029     : m_map (map),
6030       m_search (search),
6031       m_addr (find_vec_in_debug_names (map, namei))
6032   {}
6033
6034   /* Return the next matching CU or NULL if there are no more.  */
6035   dwarf2_per_cu_data *next ();
6036
6037 private:
6038   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6039                                                   const char *name);
6040   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6041                                                   uint32_t namei);
6042
6043   /* The internalized form of .debug_names.  */
6044   const mapped_debug_names &m_map;
6045
6046   /* If true, only look for symbols that match BLOCK_INDEX.  */
6047   const bool m_want_specific_block = false;
6048
6049   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6050      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6051      value.  */
6052   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6053
6054   /* The kind of symbol we're looking for.  */
6055   const domain_enum m_domain = UNDEF_DOMAIN;
6056   const search_domain m_search = ALL_DOMAIN;
6057
6058   /* The list of CUs from the index entry of the symbol, or NULL if
6059      not found.  */
6060   const gdb_byte *m_addr;
6061 };
6062
6063 const char *
6064 mapped_debug_names::namei_to_name (uint32_t namei) const
6065 {
6066   const ULONGEST namei_string_offs
6067     = extract_unsigned_integer ((name_table_string_offs_reordered
6068                                  + namei * offset_size),
6069                                 offset_size,
6070                                 dwarf5_byte_order);
6071   return read_indirect_string_at_offset
6072     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6073 }
6074
6075 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6076    found, return pointer to its pool data.  If NAME cannot be found,
6077    return NULL.  */
6078
6079 const gdb_byte *
6080 dw2_debug_names_iterator::find_vec_in_debug_names
6081   (const mapped_debug_names &map, const char *name)
6082 {
6083   int (*cmp) (const char *, const char *);
6084
6085   if (current_language->la_language == language_cplus
6086       || current_language->la_language == language_fortran
6087       || current_language->la_language == language_d)
6088     {
6089       /* NAME is already canonical.  Drop any qualifiers as
6090          .debug_names does not contain any.  */
6091
6092       if (strchr (name, '(') != NULL)
6093         {
6094           gdb::unique_xmalloc_ptr<char> without_params
6095             = cp_remove_params (name);
6096
6097           if (without_params != NULL)
6098             {
6099               name = without_params.get();
6100             }
6101         }
6102     }
6103
6104   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6105
6106   const uint32_t full_hash = dwarf5_djb_hash (name);
6107   uint32_t namei
6108     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6109                                 (map.bucket_table_reordered
6110                                  + (full_hash % map.bucket_count)), 4,
6111                                 map.dwarf5_byte_order);
6112   if (namei == 0)
6113     return NULL;
6114   --namei;
6115   if (namei >= map.name_count)
6116     {
6117       complaint (&symfile_complaints,
6118                  _("Wrong .debug_names with name index %u but name_count=%u "
6119                    "[in module %s]"),
6120                  namei, map.name_count,
6121                  objfile_name (map.dwarf2_per_objfile->objfile));
6122       return NULL;
6123     }
6124
6125   for (;;)
6126     {
6127       const uint32_t namei_full_hash
6128         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6129                                     (map.hash_table_reordered + namei), 4,
6130                                     map.dwarf5_byte_order);
6131       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6132         return NULL;
6133
6134       if (full_hash == namei_full_hash)
6135         {
6136           const char *const namei_string = map.namei_to_name (namei);
6137
6138 #if 0 /* An expensive sanity check.  */
6139           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6140             {
6141               complaint (&symfile_complaints,
6142                          _("Wrong .debug_names hash for string at index %u "
6143                            "[in module %s]"),
6144                          namei, objfile_name (dwarf2_per_objfile->objfile));
6145               return NULL;
6146             }
6147 #endif
6148
6149           if (cmp (namei_string, name) == 0)
6150             {
6151               const ULONGEST namei_entry_offs
6152                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6153                                              + namei * map.offset_size),
6154                                             map.offset_size, map.dwarf5_byte_order);
6155               return map.entry_pool + namei_entry_offs;
6156             }
6157         }
6158
6159       ++namei;
6160       if (namei >= map.name_count)
6161         return NULL;
6162     }
6163 }
6164
6165 const gdb_byte *
6166 dw2_debug_names_iterator::find_vec_in_debug_names
6167   (const mapped_debug_names &map, uint32_t namei)
6168 {
6169   if (namei >= map.name_count)
6170     {
6171       complaint (&symfile_complaints,
6172                  _("Wrong .debug_names with name index %u but name_count=%u "
6173                    "[in module %s]"),
6174                  namei, map.name_count,
6175                  objfile_name (map.dwarf2_per_objfile->objfile));
6176       return NULL;
6177     }
6178
6179   const ULONGEST namei_entry_offs
6180     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6181                                  + namei * map.offset_size),
6182                                 map.offset_size, map.dwarf5_byte_order);
6183   return map.entry_pool + namei_entry_offs;
6184 }
6185
6186 /* See dw2_debug_names_iterator.  */
6187
6188 dwarf2_per_cu_data *
6189 dw2_debug_names_iterator::next ()
6190 {
6191   if (m_addr == NULL)
6192     return NULL;
6193
6194   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6195   struct objfile *objfile = dwarf2_per_objfile->objfile;
6196   bfd *const abfd = objfile->obfd;
6197
6198  again:
6199
6200   unsigned int bytes_read;
6201   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6202   m_addr += bytes_read;
6203   if (abbrev == 0)
6204     return NULL;
6205
6206   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6207   if (indexval_it == m_map.abbrev_map.cend ())
6208     {
6209       complaint (&symfile_complaints,
6210                  _("Wrong .debug_names undefined abbrev code %s "
6211                    "[in module %s]"),
6212                  pulongest (abbrev), objfile_name (objfile));
6213       return NULL;
6214     }
6215   const mapped_debug_names::index_val &indexval = indexval_it->second;
6216   bool have_is_static = false;
6217   bool is_static;
6218   dwarf2_per_cu_data *per_cu = NULL;
6219   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6220     {
6221       ULONGEST ull;
6222       switch (attr.form)
6223         {
6224         case DW_FORM_implicit_const:
6225           ull = attr.implicit_const;
6226           break;
6227         case DW_FORM_flag_present:
6228           ull = 1;
6229           break;
6230         case DW_FORM_udata:
6231           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6232           m_addr += bytes_read;
6233           break;
6234         default:
6235           complaint (&symfile_complaints,
6236                      _("Unsupported .debug_names form %s [in module %s]"),
6237                      dwarf_form_name (attr.form),
6238                      objfile_name (objfile));
6239           return NULL;
6240         }
6241       switch (attr.dw_idx)
6242         {
6243         case DW_IDX_compile_unit:
6244           /* Don't crash on bad data.  */
6245           if (ull >= dwarf2_per_objfile->n_comp_units)
6246             {
6247               complaint (&symfile_complaints,
6248                          _(".debug_names entry has bad CU index %s"
6249                            " [in module %s]"),
6250                          pulongest (ull),
6251                          objfile_name (dwarf2_per_objfile->objfile));
6252               continue;
6253             }
6254           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6255           break;
6256         case DW_IDX_type_unit:
6257           /* Don't crash on bad data.  */
6258           if (ull >= dwarf2_per_objfile->n_type_units)
6259             {
6260               complaint (&symfile_complaints,
6261                          _(".debug_names entry has bad TU index %s"
6262                            " [in module %s]"),
6263                          pulongest (ull),
6264                          objfile_name (dwarf2_per_objfile->objfile));
6265               continue;
6266             }
6267           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6268                                  dwarf2_per_objfile->n_comp_units + ull);
6269           break;
6270         case DW_IDX_GNU_internal:
6271           if (!m_map.augmentation_is_gdb)
6272             break;
6273           have_is_static = true;
6274           is_static = true;
6275           break;
6276         case DW_IDX_GNU_external:
6277           if (!m_map.augmentation_is_gdb)
6278             break;
6279           have_is_static = true;
6280           is_static = false;
6281           break;
6282         }
6283     }
6284
6285   /* Skip if already read in.  */
6286   if (per_cu->v.quick->compunit_symtab)
6287     goto again;
6288
6289   /* Check static vs global.  */
6290   if (have_is_static)
6291     {
6292       const bool want_static = m_block_index != GLOBAL_BLOCK;
6293       if (m_want_specific_block && want_static != is_static)
6294         goto again;
6295     }
6296
6297   /* Match dw2_symtab_iter_next, symbol_kind
6298      and debug_names::psymbol_tag.  */
6299   switch (m_domain)
6300     {
6301     case VAR_DOMAIN:
6302       switch (indexval.dwarf_tag)
6303         {
6304         case DW_TAG_variable:
6305         case DW_TAG_subprogram:
6306         /* Some types are also in VAR_DOMAIN.  */
6307         case DW_TAG_typedef:
6308         case DW_TAG_structure_type:
6309           break;
6310         default:
6311           goto again;
6312         }
6313       break;
6314     case STRUCT_DOMAIN:
6315       switch (indexval.dwarf_tag)
6316         {
6317         case DW_TAG_typedef:
6318         case DW_TAG_structure_type:
6319           break;
6320         default:
6321           goto again;
6322         }
6323       break;
6324     case LABEL_DOMAIN:
6325       switch (indexval.dwarf_tag)
6326         {
6327         case 0:
6328         case DW_TAG_variable:
6329           break;
6330         default:
6331           goto again;
6332         }
6333       break;
6334     default:
6335       break;
6336     }
6337
6338   /* Match dw2_expand_symtabs_matching, symbol_kind and
6339      debug_names::psymbol_tag.  */
6340   switch (m_search)
6341     {
6342     case VARIABLES_DOMAIN:
6343       switch (indexval.dwarf_tag)
6344         {
6345         case DW_TAG_variable:
6346           break;
6347         default:
6348           goto again;
6349         }
6350       break;
6351     case FUNCTIONS_DOMAIN:
6352       switch (indexval.dwarf_tag)
6353         {
6354         case DW_TAG_subprogram:
6355           break;
6356         default:
6357           goto again;
6358         }
6359       break;
6360     case TYPES_DOMAIN:
6361       switch (indexval.dwarf_tag)
6362         {
6363         case DW_TAG_typedef:
6364         case DW_TAG_structure_type:
6365           break;
6366         default:
6367           goto again;
6368         }
6369       break;
6370     default:
6371       break;
6372     }
6373
6374   return per_cu;
6375 }
6376
6377 static struct compunit_symtab *
6378 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6379                                const char *name, domain_enum domain)
6380 {
6381   const block_enum block_index = static_cast<block_enum> (block_index_int);
6382   struct dwarf2_per_objfile *dwarf2_per_objfile
6383     = get_dwarf2_per_objfile (objfile);
6384
6385   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6386   if (!mapp)
6387     {
6388       /* index is NULL if OBJF_READNOW.  */
6389       return NULL;
6390     }
6391   const auto &map = *mapp;
6392
6393   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6394                                  block_index, domain, name);
6395
6396   struct compunit_symtab *stab_best = NULL;
6397   struct dwarf2_per_cu_data *per_cu;
6398   while ((per_cu = iter.next ()) != NULL)
6399     {
6400       struct symbol *sym, *with_opaque = NULL;
6401       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6402       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6403       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6404
6405       sym = block_find_symbol (block, name, domain,
6406                                block_find_non_opaque_type_preferred,
6407                                &with_opaque);
6408
6409       /* Some caution must be observed with overloaded functions and
6410          methods, since the index will not contain any overload
6411          information (but NAME might contain it).  */
6412
6413       if (sym != NULL
6414           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6415         return stab;
6416       if (with_opaque != NULL
6417           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6418         stab_best = stab;
6419
6420       /* Keep looking through other CUs.  */
6421     }
6422
6423   return stab_best;
6424 }
6425
6426 /* This dumps minimal information about .debug_names.  It is called
6427    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6428    uses this to verify that .debug_names has been loaded.  */
6429
6430 static void
6431 dw2_debug_names_dump (struct objfile *objfile)
6432 {
6433   struct dwarf2_per_objfile *dwarf2_per_objfile
6434     = get_dwarf2_per_objfile (objfile);
6435
6436   gdb_assert (dwarf2_per_objfile->using_index);
6437   printf_filtered (".debug_names:");
6438   if (dwarf2_per_objfile->debug_names_table)
6439     printf_filtered (" exists\n");
6440   else
6441     printf_filtered (" faked for \"readnow\"\n");
6442   printf_filtered ("\n");
6443 }
6444
6445 static void
6446 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6447                                              const char *func_name)
6448 {
6449   struct dwarf2_per_objfile *dwarf2_per_objfile
6450     = get_dwarf2_per_objfile (objfile);
6451
6452   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6453   if (dwarf2_per_objfile->debug_names_table)
6454     {
6455       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6456
6457       /* Note: It doesn't matter what we pass for block_index here.  */
6458       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6459                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6460
6461       struct dwarf2_per_cu_data *per_cu;
6462       while ((per_cu = iter.next ()) != NULL)
6463         dw2_instantiate_symtab (per_cu);
6464     }
6465 }
6466
6467 static void
6468 dw2_debug_names_expand_symtabs_matching
6469   (struct objfile *objfile,
6470    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6471    const lookup_name_info &lookup_name,
6472    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6473    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6474    enum search_domain kind)
6475 {
6476   struct dwarf2_per_objfile *dwarf2_per_objfile
6477     = get_dwarf2_per_objfile (objfile);
6478
6479   /* debug_names_table is NULL if OBJF_READNOW.  */
6480   if (!dwarf2_per_objfile->debug_names_table)
6481     return;
6482
6483   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6484
6485   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6486
6487   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6488                                       symbol_matcher,
6489                                       kind, [&] (offset_type namei)
6490     {
6491       /* The name was matched, now expand corresponding CUs that were
6492          marked.  */
6493       dw2_debug_names_iterator iter (map, kind, namei);
6494
6495       struct dwarf2_per_cu_data *per_cu;
6496       while ((per_cu = iter.next ()) != NULL)
6497         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6498                                          expansion_notify);
6499     });
6500 }
6501
6502 const struct quick_symbol_functions dwarf2_debug_names_functions =
6503 {
6504   dw2_has_symbols,
6505   dw2_find_last_source_symtab,
6506   dw2_forget_cached_source_info,
6507   dw2_map_symtabs_matching_filename,
6508   dw2_debug_names_lookup_symbol,
6509   dw2_print_stats,
6510   dw2_debug_names_dump,
6511   dw2_relocate,
6512   dw2_debug_names_expand_symtabs_for_function,
6513   dw2_expand_all_symtabs,
6514   dw2_expand_symtabs_with_fullname,
6515   dw2_map_matching_symbols,
6516   dw2_debug_names_expand_symtabs_matching,
6517   dw2_find_pc_sect_compunit_symtab,
6518   NULL,
6519   dw2_map_symbol_filenames
6520 };
6521
6522 /* See symfile.h.  */
6523
6524 bool
6525 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6526 {
6527   struct dwarf2_per_objfile *dwarf2_per_objfile
6528     = get_dwarf2_per_objfile (objfile);
6529
6530   /* If we're about to read full symbols, don't bother with the
6531      indices.  In this case we also don't care if some other debug
6532      format is making psymtabs, because they are all about to be
6533      expanded anyway.  */
6534   if ((objfile->flags & OBJF_READNOW))
6535     {
6536       int i;
6537
6538       dwarf2_per_objfile->using_index = 1;
6539       create_all_comp_units (dwarf2_per_objfile);
6540       create_all_type_units (dwarf2_per_objfile);
6541       dwarf2_per_objfile->quick_file_names_table =
6542         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6543
6544       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6545                        + dwarf2_per_objfile->n_type_units); ++i)
6546         {
6547           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6548
6549           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6550                                             struct dwarf2_per_cu_quick_data);
6551         }
6552
6553       /* Return 1 so that gdb sees the "quick" functions.  However,
6554          these functions will be no-ops because we will have expanded
6555          all symtabs.  */
6556       *index_kind = dw_index_kind::GDB_INDEX;
6557       return true;
6558     }
6559
6560   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6561     {
6562       *index_kind = dw_index_kind::DEBUG_NAMES;
6563       return true;
6564     }
6565
6566   if (dwarf2_read_index (objfile))
6567     {
6568       *index_kind = dw_index_kind::GDB_INDEX;
6569       return true;
6570     }
6571
6572   return false;
6573 }
6574
6575 \f
6576
6577 /* Build a partial symbol table.  */
6578
6579 void
6580 dwarf2_build_psymtabs (struct objfile *objfile)
6581 {
6582   struct dwarf2_per_objfile *dwarf2_per_objfile
6583     = get_dwarf2_per_objfile (objfile);
6584
6585   if (objfile->global_psymbols.capacity () == 0
6586       && objfile->static_psymbols.capacity () == 0)
6587     init_psymbol_list (objfile, 1024);
6588
6589   TRY
6590     {
6591       /* This isn't really ideal: all the data we allocate on the
6592          objfile's obstack is still uselessly kept around.  However,
6593          freeing it seems unsafe.  */
6594       psymtab_discarder psymtabs (objfile);
6595       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6596       psymtabs.keep ();
6597     }
6598   CATCH (except, RETURN_MASK_ERROR)
6599     {
6600       exception_print (gdb_stderr, except);
6601     }
6602   END_CATCH
6603 }
6604
6605 /* Return the total length of the CU described by HEADER.  */
6606
6607 static unsigned int
6608 get_cu_length (const struct comp_unit_head *header)
6609 {
6610   return header->initial_length_size + header->length;
6611 }
6612
6613 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6614
6615 static inline bool
6616 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6617 {
6618   sect_offset bottom = cu_header->sect_off;
6619   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6620
6621   return sect_off >= bottom && sect_off < top;
6622 }
6623
6624 /* Find the base address of the compilation unit for range lists and
6625    location lists.  It will normally be specified by DW_AT_low_pc.
6626    In DWARF-3 draft 4, the base address could be overridden by
6627    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6628    compilation units with discontinuous ranges.  */
6629
6630 static void
6631 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6632 {
6633   struct attribute *attr;
6634
6635   cu->base_known = 0;
6636   cu->base_address = 0;
6637
6638   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6639   if (attr)
6640     {
6641       cu->base_address = attr_value_as_address (attr);
6642       cu->base_known = 1;
6643     }
6644   else
6645     {
6646       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6647       if (attr)
6648         {
6649           cu->base_address = attr_value_as_address (attr);
6650           cu->base_known = 1;
6651         }
6652     }
6653 }
6654
6655 /* Read in the comp unit header information from the debug_info at info_ptr.
6656    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6657    NOTE: This leaves members offset, first_die_offset to be filled in
6658    by the caller.  */
6659
6660 static const gdb_byte *
6661 read_comp_unit_head (struct comp_unit_head *cu_header,
6662                      const gdb_byte *info_ptr,
6663                      struct dwarf2_section_info *section,
6664                      rcuh_kind section_kind)
6665 {
6666   int signed_addr;
6667   unsigned int bytes_read;
6668   const char *filename = get_section_file_name (section);
6669   bfd *abfd = get_section_bfd_owner (section);
6670
6671   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6672   cu_header->initial_length_size = bytes_read;
6673   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6674   info_ptr += bytes_read;
6675   cu_header->version = read_2_bytes (abfd, info_ptr);
6676   info_ptr += 2;
6677   if (cu_header->version < 5)
6678     switch (section_kind)
6679       {
6680       case rcuh_kind::COMPILE:
6681         cu_header->unit_type = DW_UT_compile;
6682         break;
6683       case rcuh_kind::TYPE:
6684         cu_header->unit_type = DW_UT_type;
6685         break;
6686       default:
6687         internal_error (__FILE__, __LINE__,
6688                         _("read_comp_unit_head: invalid section_kind"));
6689       }
6690   else
6691     {
6692       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6693                                                  (read_1_byte (abfd, info_ptr));
6694       info_ptr += 1;
6695       switch (cu_header->unit_type)
6696         {
6697         case DW_UT_compile:
6698           if (section_kind != rcuh_kind::COMPILE)
6699             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6700                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6701                    filename);
6702           break;
6703         case DW_UT_type:
6704           section_kind = rcuh_kind::TYPE;
6705           break;
6706         default:
6707           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6708                  "(is %d, should be %d or %d) [in module %s]"),
6709                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6710         }
6711
6712       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6713       info_ptr += 1;
6714     }
6715   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6716                                                           cu_header,
6717                                                           &bytes_read);
6718   info_ptr += bytes_read;
6719   if (cu_header->version < 5)
6720     {
6721       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6722       info_ptr += 1;
6723     }
6724   signed_addr = bfd_get_sign_extend_vma (abfd);
6725   if (signed_addr < 0)
6726     internal_error (__FILE__, __LINE__,
6727                     _("read_comp_unit_head: dwarf from non elf file"));
6728   cu_header->signed_addr_p = signed_addr;
6729
6730   if (section_kind == rcuh_kind::TYPE)
6731     {
6732       LONGEST type_offset;
6733
6734       cu_header->signature = read_8_bytes (abfd, info_ptr);
6735       info_ptr += 8;
6736
6737       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6738       info_ptr += bytes_read;
6739       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6740       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6741         error (_("Dwarf Error: Too big type_offset in compilation unit "
6742                "header (is %s) [in module %s]"), plongest (type_offset),
6743                filename);
6744     }
6745
6746   return info_ptr;
6747 }
6748
6749 /* Helper function that returns the proper abbrev section for
6750    THIS_CU.  */
6751
6752 static struct dwarf2_section_info *
6753 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6754 {
6755   struct dwarf2_section_info *abbrev;
6756   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6757
6758   if (this_cu->is_dwz)
6759     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6760   else
6761     abbrev = &dwarf2_per_objfile->abbrev;
6762
6763   return abbrev;
6764 }
6765
6766 /* Subroutine of read_and_check_comp_unit_head and
6767    read_and_check_type_unit_head to simplify them.
6768    Perform various error checking on the header.  */
6769
6770 static void
6771 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6772                             struct comp_unit_head *header,
6773                             struct dwarf2_section_info *section,
6774                             struct dwarf2_section_info *abbrev_section)
6775 {
6776   const char *filename = get_section_file_name (section);
6777
6778   if (header->version < 2 || header->version > 5)
6779     error (_("Dwarf Error: wrong version in compilation unit header "
6780            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6781            filename);
6782
6783   if (to_underlying (header->abbrev_sect_off)
6784       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6785     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6786            "(offset 0x%x + 6) [in module %s]"),
6787            to_underlying (header->abbrev_sect_off),
6788            to_underlying (header->sect_off),
6789            filename);
6790
6791   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6792      avoid potential 32-bit overflow.  */
6793   if (((ULONGEST) header->sect_off + get_cu_length (header))
6794       > section->size)
6795     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6796            "(offset 0x%x + 0) [in module %s]"),
6797            header->length, to_underlying (header->sect_off),
6798            filename);
6799 }
6800
6801 /* Read in a CU/TU header and perform some basic error checking.
6802    The contents of the header are stored in HEADER.
6803    The result is a pointer to the start of the first DIE.  */
6804
6805 static const gdb_byte *
6806 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6807                                struct comp_unit_head *header,
6808                                struct dwarf2_section_info *section,
6809                                struct dwarf2_section_info *abbrev_section,
6810                                const gdb_byte *info_ptr,
6811                                rcuh_kind section_kind)
6812 {
6813   const gdb_byte *beg_of_comp_unit = info_ptr;
6814
6815   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6816
6817   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6818
6819   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6820
6821   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6822                               abbrev_section);
6823
6824   return info_ptr;
6825 }
6826
6827 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6828
6829 static sect_offset
6830 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6831                     struct dwarf2_section_info *section,
6832                     sect_offset sect_off)
6833 {
6834   bfd *abfd = get_section_bfd_owner (section);
6835   const gdb_byte *info_ptr;
6836   unsigned int initial_length_size, offset_size;
6837   uint16_t version;
6838
6839   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6840   info_ptr = section->buffer + to_underlying (sect_off);
6841   read_initial_length (abfd, info_ptr, &initial_length_size);
6842   offset_size = initial_length_size == 4 ? 4 : 8;
6843   info_ptr += initial_length_size;
6844
6845   version = read_2_bytes (abfd, info_ptr);
6846   info_ptr += 2;
6847   if (version >= 5)
6848     {
6849       /* Skip unit type and address size.  */
6850       info_ptr += 2;
6851     }
6852
6853   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6854 }
6855
6856 /* Allocate a new partial symtab for file named NAME and mark this new
6857    partial symtab as being an include of PST.  */
6858
6859 static void
6860 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6861                                struct objfile *objfile)
6862 {
6863   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6864
6865   if (!IS_ABSOLUTE_PATH (subpst->filename))
6866     {
6867       /* It shares objfile->objfile_obstack.  */
6868       subpst->dirname = pst->dirname;
6869     }
6870
6871   subpst->textlow = 0;
6872   subpst->texthigh = 0;
6873
6874   subpst->dependencies
6875     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6876   subpst->dependencies[0] = pst;
6877   subpst->number_of_dependencies = 1;
6878
6879   subpst->globals_offset = 0;
6880   subpst->n_global_syms = 0;
6881   subpst->statics_offset = 0;
6882   subpst->n_static_syms = 0;
6883   subpst->compunit_symtab = NULL;
6884   subpst->read_symtab = pst->read_symtab;
6885   subpst->readin = 0;
6886
6887   /* No private part is necessary for include psymtabs.  This property
6888      can be used to differentiate between such include psymtabs and
6889      the regular ones.  */
6890   subpst->read_symtab_private = NULL;
6891 }
6892
6893 /* Read the Line Number Program data and extract the list of files
6894    included by the source file represented by PST.  Build an include
6895    partial symtab for each of these included files.  */
6896
6897 static void
6898 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6899                                struct die_info *die,
6900                                struct partial_symtab *pst)
6901 {
6902   line_header_up lh;
6903   struct attribute *attr;
6904
6905   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6906   if (attr)
6907     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6908   if (lh == NULL)
6909     return;  /* No linetable, so no includes.  */
6910
6911   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6912   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6913 }
6914
6915 static hashval_t
6916 hash_signatured_type (const void *item)
6917 {
6918   const struct signatured_type *sig_type
6919     = (const struct signatured_type *) item;
6920
6921   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6922   return sig_type->signature;
6923 }
6924
6925 static int
6926 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6927 {
6928   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6929   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6930
6931   return lhs->signature == rhs->signature;
6932 }
6933
6934 /* Allocate a hash table for signatured types.  */
6935
6936 static htab_t
6937 allocate_signatured_type_table (struct objfile *objfile)
6938 {
6939   return htab_create_alloc_ex (41,
6940                                hash_signatured_type,
6941                                eq_signatured_type,
6942                                NULL,
6943                                &objfile->objfile_obstack,
6944                                hashtab_obstack_allocate,
6945                                dummy_obstack_deallocate);
6946 }
6947
6948 /* A helper function to add a signatured type CU to a table.  */
6949
6950 static int
6951 add_signatured_type_cu_to_table (void **slot, void *datum)
6952 {
6953   struct signatured_type *sigt = (struct signatured_type *) *slot;
6954   struct signatured_type ***datap = (struct signatured_type ***) datum;
6955
6956   **datap = sigt;
6957   ++*datap;
6958
6959   return 1;
6960 }
6961
6962 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6963    and fill them into TYPES_HTAB.  It will process only type units,
6964    therefore DW_UT_type.  */
6965
6966 static void
6967 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6968                               struct dwo_file *dwo_file,
6969                               dwarf2_section_info *section, htab_t &types_htab,
6970                               rcuh_kind section_kind)
6971 {
6972   struct objfile *objfile = dwarf2_per_objfile->objfile;
6973   struct dwarf2_section_info *abbrev_section;
6974   bfd *abfd;
6975   const gdb_byte *info_ptr, *end_ptr;
6976
6977   abbrev_section = (dwo_file != NULL
6978                     ? &dwo_file->sections.abbrev
6979                     : &dwarf2_per_objfile->abbrev);
6980
6981   if (dwarf_read_debug)
6982     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6983                         get_section_name (section),
6984                         get_section_file_name (abbrev_section));
6985
6986   dwarf2_read_section (objfile, section);
6987   info_ptr = section->buffer;
6988
6989   if (info_ptr == NULL)
6990     return;
6991
6992   /* We can't set abfd until now because the section may be empty or
6993      not present, in which case the bfd is unknown.  */
6994   abfd = get_section_bfd_owner (section);
6995
6996   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6997      because we don't need to read any dies: the signature is in the
6998      header.  */
6999
7000   end_ptr = info_ptr + section->size;
7001   while (info_ptr < end_ptr)
7002     {
7003       struct signatured_type *sig_type;
7004       struct dwo_unit *dwo_tu;
7005       void **slot;
7006       const gdb_byte *ptr = info_ptr;
7007       struct comp_unit_head header;
7008       unsigned int length;
7009
7010       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7011
7012       /* Initialize it due to a false compiler warning.  */
7013       header.signature = -1;
7014       header.type_cu_offset_in_tu = (cu_offset) -1;
7015
7016       /* We need to read the type's signature in order to build the hash
7017          table, but we don't need anything else just yet.  */
7018
7019       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7020                                            abbrev_section, ptr, section_kind);
7021
7022       length = get_cu_length (&header);
7023
7024       /* Skip dummy type units.  */
7025       if (ptr >= info_ptr + length
7026           || peek_abbrev_code (abfd, ptr) == 0
7027           || header.unit_type != DW_UT_type)
7028         {
7029           info_ptr += length;
7030           continue;
7031         }
7032
7033       if (types_htab == NULL)
7034         {
7035           if (dwo_file)
7036             types_htab = allocate_dwo_unit_table (objfile);
7037           else
7038             types_htab = allocate_signatured_type_table (objfile);
7039         }
7040
7041       if (dwo_file)
7042         {
7043           sig_type = NULL;
7044           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7045                                    struct dwo_unit);
7046           dwo_tu->dwo_file = dwo_file;
7047           dwo_tu->signature = header.signature;
7048           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7049           dwo_tu->section = section;
7050           dwo_tu->sect_off = sect_off;
7051           dwo_tu->length = length;
7052         }
7053       else
7054         {
7055           /* N.B.: type_offset is not usable if this type uses a DWO file.
7056              The real type_offset is in the DWO file.  */
7057           dwo_tu = NULL;
7058           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7059                                      struct signatured_type);
7060           sig_type->signature = header.signature;
7061           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7062           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7063           sig_type->per_cu.is_debug_types = 1;
7064           sig_type->per_cu.section = section;
7065           sig_type->per_cu.sect_off = sect_off;
7066           sig_type->per_cu.length = length;
7067         }
7068
7069       slot = htab_find_slot (types_htab,
7070                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7071                              INSERT);
7072       gdb_assert (slot != NULL);
7073       if (*slot != NULL)
7074         {
7075           sect_offset dup_sect_off;
7076
7077           if (dwo_file)
7078             {
7079               const struct dwo_unit *dup_tu
7080                 = (const struct dwo_unit *) *slot;
7081
7082               dup_sect_off = dup_tu->sect_off;
7083             }
7084           else
7085             {
7086               const struct signatured_type *dup_tu
7087                 = (const struct signatured_type *) *slot;
7088
7089               dup_sect_off = dup_tu->per_cu.sect_off;
7090             }
7091
7092           complaint (&symfile_complaints,
7093                      _("debug type entry at offset 0x%x is duplicate to"
7094                        " the entry at offset 0x%x, signature %s"),
7095                      to_underlying (sect_off), to_underlying (dup_sect_off),
7096                      hex_string (header.signature));
7097         }
7098       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7099
7100       if (dwarf_read_debug > 1)
7101         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7102                             to_underlying (sect_off),
7103                             hex_string (header.signature));
7104
7105       info_ptr += length;
7106     }
7107 }
7108
7109 /* Create the hash table of all entries in the .debug_types
7110    (or .debug_types.dwo) section(s).
7111    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7112    otherwise it is NULL.
7113
7114    The result is a pointer to the hash table or NULL if there are no types.
7115
7116    Note: This function processes DWO files only, not DWP files.  */
7117
7118 static void
7119 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7120                                struct dwo_file *dwo_file,
7121                                VEC (dwarf2_section_info_def) *types,
7122                                htab_t &types_htab)
7123 {
7124   int ix;
7125   struct dwarf2_section_info *section;
7126
7127   if (VEC_empty (dwarf2_section_info_def, types))
7128     return;
7129
7130   for (ix = 0;
7131        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7132        ++ix)
7133     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7134                                   types_htab, rcuh_kind::TYPE);
7135 }
7136
7137 /* Create the hash table of all entries in the .debug_types section,
7138    and initialize all_type_units.
7139    The result is zero if there is an error (e.g. missing .debug_types section),
7140    otherwise non-zero.  */
7141
7142 static int
7143 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7144 {
7145   htab_t types_htab = NULL;
7146   struct signatured_type **iter;
7147
7148   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7149                                 &dwarf2_per_objfile->info, types_htab,
7150                                 rcuh_kind::COMPILE);
7151   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7152                                  dwarf2_per_objfile->types, types_htab);
7153   if (types_htab == NULL)
7154     {
7155       dwarf2_per_objfile->signatured_types = NULL;
7156       return 0;
7157     }
7158
7159   dwarf2_per_objfile->signatured_types = types_htab;
7160
7161   dwarf2_per_objfile->n_type_units
7162     = dwarf2_per_objfile->n_allocated_type_units
7163     = htab_elements (types_htab);
7164   dwarf2_per_objfile->all_type_units =
7165     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7166   iter = &dwarf2_per_objfile->all_type_units[0];
7167   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7168   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7169               == dwarf2_per_objfile->n_type_units);
7170
7171   return 1;
7172 }
7173
7174 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7175    If SLOT is non-NULL, it is the entry to use in the hash table.
7176    Otherwise we find one.  */
7177
7178 static struct signatured_type *
7179 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7180                void **slot)
7181 {
7182   struct objfile *objfile = dwarf2_per_objfile->objfile;
7183   int n_type_units = dwarf2_per_objfile->n_type_units;
7184   struct signatured_type *sig_type;
7185
7186   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7187   ++n_type_units;
7188   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7189     {
7190       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7191         dwarf2_per_objfile->n_allocated_type_units = 1;
7192       dwarf2_per_objfile->n_allocated_type_units *= 2;
7193       dwarf2_per_objfile->all_type_units
7194         = XRESIZEVEC (struct signatured_type *,
7195                       dwarf2_per_objfile->all_type_units,
7196                       dwarf2_per_objfile->n_allocated_type_units);
7197       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7198     }
7199   dwarf2_per_objfile->n_type_units = n_type_units;
7200
7201   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7202                              struct signatured_type);
7203   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7204   sig_type->signature = sig;
7205   sig_type->per_cu.is_debug_types = 1;
7206   if (dwarf2_per_objfile->using_index)
7207     {
7208       sig_type->per_cu.v.quick =
7209         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7210                         struct dwarf2_per_cu_quick_data);
7211     }
7212
7213   if (slot == NULL)
7214     {
7215       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7216                              sig_type, INSERT);
7217     }
7218   gdb_assert (*slot == NULL);
7219   *slot = sig_type;
7220   /* The rest of sig_type must be filled in by the caller.  */
7221   return sig_type;
7222 }
7223
7224 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7225    Fill in SIG_ENTRY with DWO_ENTRY.  */
7226
7227 static void
7228 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7229                                   struct signatured_type *sig_entry,
7230                                   struct dwo_unit *dwo_entry)
7231 {
7232   /* Make sure we're not clobbering something we don't expect to.  */
7233   gdb_assert (! sig_entry->per_cu.queued);
7234   gdb_assert (sig_entry->per_cu.cu == NULL);
7235   if (dwarf2_per_objfile->using_index)
7236     {
7237       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7238       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7239     }
7240   else
7241       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7242   gdb_assert (sig_entry->signature == dwo_entry->signature);
7243   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7244   gdb_assert (sig_entry->type_unit_group == NULL);
7245   gdb_assert (sig_entry->dwo_unit == NULL);
7246
7247   sig_entry->per_cu.section = dwo_entry->section;
7248   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7249   sig_entry->per_cu.length = dwo_entry->length;
7250   sig_entry->per_cu.reading_dwo_directly = 1;
7251   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7252   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7253   sig_entry->dwo_unit = dwo_entry;
7254 }
7255
7256 /* Subroutine of lookup_signatured_type.
7257    If we haven't read the TU yet, create the signatured_type data structure
7258    for a TU to be read in directly from a DWO file, bypassing the stub.
7259    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7260    using .gdb_index, then when reading a CU we want to stay in the DWO file
7261    containing that CU.  Otherwise we could end up reading several other DWO
7262    files (due to comdat folding) to process the transitive closure of all the
7263    mentioned TUs, and that can be slow.  The current DWO file will have every
7264    type signature that it needs.
7265    We only do this for .gdb_index because in the psymtab case we already have
7266    to read all the DWOs to build the type unit groups.  */
7267
7268 static struct signatured_type *
7269 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7270 {
7271   struct dwarf2_per_objfile *dwarf2_per_objfile
7272     = cu->per_cu->dwarf2_per_objfile;
7273   struct objfile *objfile = dwarf2_per_objfile->objfile;
7274   struct dwo_file *dwo_file;
7275   struct dwo_unit find_dwo_entry, *dwo_entry;
7276   struct signatured_type find_sig_entry, *sig_entry;
7277   void **slot;
7278
7279   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7280
7281   /* If TU skeletons have been removed then we may not have read in any
7282      TUs yet.  */
7283   if (dwarf2_per_objfile->signatured_types == NULL)
7284     {
7285       dwarf2_per_objfile->signatured_types
7286         = allocate_signatured_type_table (objfile);
7287     }
7288
7289   /* We only ever need to read in one copy of a signatured type.
7290      Use the global signatured_types array to do our own comdat-folding
7291      of types.  If this is the first time we're reading this TU, and
7292      the TU has an entry in .gdb_index, replace the recorded data from
7293      .gdb_index with this TU.  */
7294
7295   find_sig_entry.signature = sig;
7296   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7297                          &find_sig_entry, INSERT);
7298   sig_entry = (struct signatured_type *) *slot;
7299
7300   /* We can get here with the TU already read, *or* in the process of being
7301      read.  Don't reassign the global entry to point to this DWO if that's
7302      the case.  Also note that if the TU is already being read, it may not
7303      have come from a DWO, the program may be a mix of Fission-compiled
7304      code and non-Fission-compiled code.  */
7305
7306   /* Have we already tried to read this TU?
7307      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7308      needn't exist in the global table yet).  */
7309   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7310     return sig_entry;
7311
7312   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7313      dwo_unit of the TU itself.  */
7314   dwo_file = cu->dwo_unit->dwo_file;
7315
7316   /* Ok, this is the first time we're reading this TU.  */
7317   if (dwo_file->tus == NULL)
7318     return NULL;
7319   find_dwo_entry.signature = sig;
7320   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7321   if (dwo_entry == NULL)
7322     return NULL;
7323
7324   /* If the global table doesn't have an entry for this TU, add one.  */
7325   if (sig_entry == NULL)
7326     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7327
7328   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7329   sig_entry->per_cu.tu_read = 1;
7330   return sig_entry;
7331 }
7332
7333 /* Subroutine of lookup_signatured_type.
7334    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7335    then try the DWP file.  If the TU stub (skeleton) has been removed then
7336    it won't be in .gdb_index.  */
7337
7338 static struct signatured_type *
7339 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7340 {
7341   struct dwarf2_per_objfile *dwarf2_per_objfile
7342     = cu->per_cu->dwarf2_per_objfile;
7343   struct objfile *objfile = dwarf2_per_objfile->objfile;
7344   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7345   struct dwo_unit *dwo_entry;
7346   struct signatured_type find_sig_entry, *sig_entry;
7347   void **slot;
7348
7349   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7350   gdb_assert (dwp_file != NULL);
7351
7352   /* If TU skeletons have been removed then we may not have read in any
7353      TUs yet.  */
7354   if (dwarf2_per_objfile->signatured_types == NULL)
7355     {
7356       dwarf2_per_objfile->signatured_types
7357         = allocate_signatured_type_table (objfile);
7358     }
7359
7360   find_sig_entry.signature = sig;
7361   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7362                          &find_sig_entry, INSERT);
7363   sig_entry = (struct signatured_type *) *slot;
7364
7365   /* Have we already tried to read this TU?
7366      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7367      needn't exist in the global table yet).  */
7368   if (sig_entry != NULL)
7369     return sig_entry;
7370
7371   if (dwp_file->tus == NULL)
7372     return NULL;
7373   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7374                                       sig, 1 /* is_debug_types */);
7375   if (dwo_entry == NULL)
7376     return NULL;
7377
7378   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7379   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7380
7381   return sig_entry;
7382 }
7383
7384 /* Lookup a signature based type for DW_FORM_ref_sig8.
7385    Returns NULL if signature SIG is not present in the table.
7386    It is up to the caller to complain about this.  */
7387
7388 static struct signatured_type *
7389 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7390 {
7391   struct dwarf2_per_objfile *dwarf2_per_objfile
7392     = cu->per_cu->dwarf2_per_objfile;
7393
7394   if (cu->dwo_unit
7395       && dwarf2_per_objfile->using_index)
7396     {
7397       /* We're in a DWO/DWP file, and we're using .gdb_index.
7398          These cases require special processing.  */
7399       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7400         return lookup_dwo_signatured_type (cu, sig);
7401       else
7402         return lookup_dwp_signatured_type (cu, sig);
7403     }
7404   else
7405     {
7406       struct signatured_type find_entry, *entry;
7407
7408       if (dwarf2_per_objfile->signatured_types == NULL)
7409         return NULL;
7410       find_entry.signature = sig;
7411       entry = ((struct signatured_type *)
7412                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7413       return entry;
7414     }
7415 }
7416 \f
7417 /* Low level DIE reading support.  */
7418
7419 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7420
7421 static void
7422 init_cu_die_reader (struct die_reader_specs *reader,
7423                     struct dwarf2_cu *cu,
7424                     struct dwarf2_section_info *section,
7425                     struct dwo_file *dwo_file,
7426                     struct abbrev_table *abbrev_table)
7427 {
7428   gdb_assert (section->readin && section->buffer != NULL);
7429   reader->abfd = get_section_bfd_owner (section);
7430   reader->cu = cu;
7431   reader->dwo_file = dwo_file;
7432   reader->die_section = section;
7433   reader->buffer = section->buffer;
7434   reader->buffer_end = section->buffer + section->size;
7435   reader->comp_dir = NULL;
7436   reader->abbrev_table = abbrev_table;
7437 }
7438
7439 /* Subroutine of init_cutu_and_read_dies to simplify it.
7440    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7441    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7442    already.
7443
7444    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7445    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7446    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7447    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7448    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7449    STUB_COMP_DIR may be non-NULL.
7450    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7451    are filled in with the info of the DIE from the DWO file.
7452    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7453    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7454    kept around for at least as long as *RESULT_READER.
7455
7456    The result is non-zero if a valid (non-dummy) DIE was found.  */
7457
7458 static int
7459 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7460                         struct dwo_unit *dwo_unit,
7461                         struct die_info *stub_comp_unit_die,
7462                         const char *stub_comp_dir,
7463                         struct die_reader_specs *result_reader,
7464                         const gdb_byte **result_info_ptr,
7465                         struct die_info **result_comp_unit_die,
7466                         int *result_has_children,
7467                         abbrev_table_up *result_dwo_abbrev_table)
7468 {
7469   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7470   struct objfile *objfile = dwarf2_per_objfile->objfile;
7471   struct dwarf2_cu *cu = this_cu->cu;
7472   bfd *abfd;
7473   const gdb_byte *begin_info_ptr, *info_ptr;
7474   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7475   int i,num_extra_attrs;
7476   struct dwarf2_section_info *dwo_abbrev_section;
7477   struct attribute *attr;
7478   struct die_info *comp_unit_die;
7479
7480   /* At most one of these may be provided.  */
7481   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7482
7483   /* These attributes aren't processed until later:
7484      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7485      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7486      referenced later.  However, these attributes are found in the stub
7487      which we won't have later.  In order to not impose this complication
7488      on the rest of the code, we read them here and copy them to the
7489      DWO CU/TU die.  */
7490
7491   stmt_list = NULL;
7492   low_pc = NULL;
7493   high_pc = NULL;
7494   ranges = NULL;
7495   comp_dir = NULL;
7496
7497   if (stub_comp_unit_die != NULL)
7498     {
7499       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7500          DWO file.  */
7501       if (! this_cu->is_debug_types)
7502         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7503       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7504       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7505       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7506       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7507
7508       /* There should be a DW_AT_addr_base attribute here (if needed).
7509          We need the value before we can process DW_FORM_GNU_addr_index.  */
7510       cu->addr_base = 0;
7511       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7512       if (attr)
7513         cu->addr_base = DW_UNSND (attr);
7514
7515       /* There should be a DW_AT_ranges_base attribute here (if needed).
7516          We need the value before we can process DW_AT_ranges.  */
7517       cu->ranges_base = 0;
7518       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7519       if (attr)
7520         cu->ranges_base = DW_UNSND (attr);
7521     }
7522   else if (stub_comp_dir != NULL)
7523     {
7524       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7525       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7526       comp_dir->name = DW_AT_comp_dir;
7527       comp_dir->form = DW_FORM_string;
7528       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7529       DW_STRING (comp_dir) = stub_comp_dir;
7530     }
7531
7532   /* Set up for reading the DWO CU/TU.  */
7533   cu->dwo_unit = dwo_unit;
7534   dwarf2_section_info *section = dwo_unit->section;
7535   dwarf2_read_section (objfile, section);
7536   abfd = get_section_bfd_owner (section);
7537   begin_info_ptr = info_ptr = (section->buffer
7538                                + to_underlying (dwo_unit->sect_off));
7539   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7540
7541   if (this_cu->is_debug_types)
7542     {
7543       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7544
7545       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7546                                                 &cu->header, section,
7547                                                 dwo_abbrev_section,
7548                                                 info_ptr, rcuh_kind::TYPE);
7549       /* This is not an assert because it can be caused by bad debug info.  */
7550       if (sig_type->signature != cu->header.signature)
7551         {
7552           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7553                    " TU at offset 0x%x [in module %s]"),
7554                  hex_string (sig_type->signature),
7555                  hex_string (cu->header.signature),
7556                  to_underlying (dwo_unit->sect_off),
7557                  bfd_get_filename (abfd));
7558         }
7559       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7560       /* For DWOs coming from DWP files, we don't know the CU length
7561          nor the type's offset in the TU until now.  */
7562       dwo_unit->length = get_cu_length (&cu->header);
7563       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7564
7565       /* Establish the type offset that can be used to lookup the type.
7566          For DWO files, we don't know it until now.  */
7567       sig_type->type_offset_in_section
7568         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7569     }
7570   else
7571     {
7572       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7573                                                 &cu->header, section,
7574                                                 dwo_abbrev_section,
7575                                                 info_ptr, rcuh_kind::COMPILE);
7576       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7577       /* For DWOs coming from DWP files, we don't know the CU length
7578          until now.  */
7579       dwo_unit->length = get_cu_length (&cu->header);
7580     }
7581
7582   *result_dwo_abbrev_table
7583     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7584                                cu->header.abbrev_sect_off);
7585   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7586                       result_dwo_abbrev_table->get ());
7587
7588   /* Read in the die, but leave space to copy over the attributes
7589      from the stub.  This has the benefit of simplifying the rest of
7590      the code - all the work to maintain the illusion of a single
7591      DW_TAG_{compile,type}_unit DIE is done here.  */
7592   num_extra_attrs = ((stmt_list != NULL)
7593                      + (low_pc != NULL)
7594                      + (high_pc != NULL)
7595                      + (ranges != NULL)
7596                      + (comp_dir != NULL));
7597   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7598                               result_has_children, num_extra_attrs);
7599
7600   /* Copy over the attributes from the stub to the DIE we just read in.  */
7601   comp_unit_die = *result_comp_unit_die;
7602   i = comp_unit_die->num_attrs;
7603   if (stmt_list != NULL)
7604     comp_unit_die->attrs[i++] = *stmt_list;
7605   if (low_pc != NULL)
7606     comp_unit_die->attrs[i++] = *low_pc;
7607   if (high_pc != NULL)
7608     comp_unit_die->attrs[i++] = *high_pc;
7609   if (ranges != NULL)
7610     comp_unit_die->attrs[i++] = *ranges;
7611   if (comp_dir != NULL)
7612     comp_unit_die->attrs[i++] = *comp_dir;
7613   comp_unit_die->num_attrs += num_extra_attrs;
7614
7615   if (dwarf_die_debug)
7616     {
7617       fprintf_unfiltered (gdb_stdlog,
7618                           "Read die from %s@0x%x of %s:\n",
7619                           get_section_name (section),
7620                           (unsigned) (begin_info_ptr - section->buffer),
7621                           bfd_get_filename (abfd));
7622       dump_die (comp_unit_die, dwarf_die_debug);
7623     }
7624
7625   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7626      TUs by skipping the stub and going directly to the entry in the DWO file.
7627      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7628      to get it via circuitous means.  Blech.  */
7629   if (comp_dir != NULL)
7630     result_reader->comp_dir = DW_STRING (comp_dir);
7631
7632   /* Skip dummy compilation units.  */
7633   if (info_ptr >= begin_info_ptr + dwo_unit->length
7634       || peek_abbrev_code (abfd, info_ptr) == 0)
7635     return 0;
7636
7637   *result_info_ptr = info_ptr;
7638   return 1;
7639 }
7640
7641 /* Subroutine of init_cutu_and_read_dies to simplify it.
7642    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7643    Returns NULL if the specified DWO unit cannot be found.  */
7644
7645 static struct dwo_unit *
7646 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7647                  struct die_info *comp_unit_die)
7648 {
7649   struct dwarf2_cu *cu = this_cu->cu;
7650   ULONGEST signature;
7651   struct dwo_unit *dwo_unit;
7652   const char *comp_dir, *dwo_name;
7653
7654   gdb_assert (cu != NULL);
7655
7656   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7657   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7658   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7659
7660   if (this_cu->is_debug_types)
7661     {
7662       struct signatured_type *sig_type;
7663
7664       /* Since this_cu is the first member of struct signatured_type,
7665          we can go from a pointer to one to a pointer to the other.  */
7666       sig_type = (struct signatured_type *) this_cu;
7667       signature = sig_type->signature;
7668       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7669     }
7670   else
7671     {
7672       struct attribute *attr;
7673
7674       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7675       if (! attr)
7676         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7677                  " [in module %s]"),
7678                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7679       signature = DW_UNSND (attr);
7680       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7681                                        signature);
7682     }
7683
7684   return dwo_unit;
7685 }
7686
7687 /* Subroutine of init_cutu_and_read_dies to simplify it.
7688    See it for a description of the parameters.
7689    Read a TU directly from a DWO file, bypassing the stub.  */
7690
7691 static void
7692 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7693                            int use_existing_cu, int keep,
7694                            die_reader_func_ftype *die_reader_func,
7695                            void *data)
7696 {
7697   std::unique_ptr<dwarf2_cu> new_cu;
7698   struct signatured_type *sig_type;
7699   struct die_reader_specs reader;
7700   const gdb_byte *info_ptr;
7701   struct die_info *comp_unit_die;
7702   int has_children;
7703   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7704
7705   /* Verify we can do the following downcast, and that we have the
7706      data we need.  */
7707   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7708   sig_type = (struct signatured_type *) this_cu;
7709   gdb_assert (sig_type->dwo_unit != NULL);
7710
7711   if (use_existing_cu && this_cu->cu != NULL)
7712     {
7713       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7714       /* There's no need to do the rereading_dwo_cu handling that
7715          init_cutu_and_read_dies does since we don't read the stub.  */
7716     }
7717   else
7718     {
7719       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7720       gdb_assert (this_cu->cu == NULL);
7721       new_cu.reset (new dwarf2_cu (this_cu));
7722     }
7723
7724   /* A future optimization, if needed, would be to use an existing
7725      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7726      could share abbrev tables.  */
7727
7728   /* The abbreviation table used by READER, this must live at least as long as
7729      READER.  */
7730   abbrev_table_up dwo_abbrev_table;
7731
7732   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7733                               NULL /* stub_comp_unit_die */,
7734                               sig_type->dwo_unit->dwo_file->comp_dir,
7735                               &reader, &info_ptr,
7736                               &comp_unit_die, &has_children,
7737                               &dwo_abbrev_table) == 0)
7738     {
7739       /* Dummy die.  */
7740       return;
7741     }
7742
7743   /* All the "real" work is done here.  */
7744   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7745
7746   /* This duplicates the code in init_cutu_and_read_dies,
7747      but the alternative is making the latter more complex.
7748      This function is only for the special case of using DWO files directly:
7749      no point in overly complicating the general case just to handle this.  */
7750   if (new_cu != NULL && keep)
7751     {
7752       /* Link this CU into read_in_chain.  */
7753       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7754       dwarf2_per_objfile->read_in_chain = this_cu;
7755       /* The chain owns it now.  */
7756       new_cu.release ();
7757     }
7758 }
7759
7760 /* Initialize a CU (or TU) and read its DIEs.
7761    If the CU defers to a DWO file, read the DWO file as well.
7762
7763    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7764    Otherwise the table specified in the comp unit header is read in and used.
7765    This is an optimization for when we already have the abbrev table.
7766
7767    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7768    Otherwise, a new CU is allocated with xmalloc.
7769
7770    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7771    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7772
7773    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7774    linker) then DIE_READER_FUNC will not get called.  */
7775
7776 static void
7777 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7778                          struct abbrev_table *abbrev_table,
7779                          int use_existing_cu, int keep,
7780                          die_reader_func_ftype *die_reader_func,
7781                          void *data)
7782 {
7783   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7784   struct objfile *objfile = dwarf2_per_objfile->objfile;
7785   struct dwarf2_section_info *section = this_cu->section;
7786   bfd *abfd = get_section_bfd_owner (section);
7787   struct dwarf2_cu *cu;
7788   const gdb_byte *begin_info_ptr, *info_ptr;
7789   struct die_reader_specs reader;
7790   struct die_info *comp_unit_die;
7791   int has_children;
7792   struct attribute *attr;
7793   struct signatured_type *sig_type = NULL;
7794   struct dwarf2_section_info *abbrev_section;
7795   /* Non-zero if CU currently points to a DWO file and we need to
7796      reread it.  When this happens we need to reread the skeleton die
7797      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7798   int rereading_dwo_cu = 0;
7799
7800   if (dwarf_die_debug)
7801     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7802                         this_cu->is_debug_types ? "type" : "comp",
7803                         to_underlying (this_cu->sect_off));
7804
7805   if (use_existing_cu)
7806     gdb_assert (keep);
7807
7808   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7809      file (instead of going through the stub), short-circuit all of this.  */
7810   if (this_cu->reading_dwo_directly)
7811     {
7812       /* Narrow down the scope of possibilities to have to understand.  */
7813       gdb_assert (this_cu->is_debug_types);
7814       gdb_assert (abbrev_table == NULL);
7815       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7816                                  die_reader_func, data);
7817       return;
7818     }
7819
7820   /* This is cheap if the section is already read in.  */
7821   dwarf2_read_section (objfile, section);
7822
7823   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7824
7825   abbrev_section = get_abbrev_section_for_cu (this_cu);
7826
7827   std::unique_ptr<dwarf2_cu> new_cu;
7828   if (use_existing_cu && this_cu->cu != NULL)
7829     {
7830       cu = this_cu->cu;
7831       /* If this CU is from a DWO file we need to start over, we need to
7832          refetch the attributes from the skeleton CU.
7833          This could be optimized by retrieving those attributes from when we
7834          were here the first time: the previous comp_unit_die was stored in
7835          comp_unit_obstack.  But there's no data yet that we need this
7836          optimization.  */
7837       if (cu->dwo_unit != NULL)
7838         rereading_dwo_cu = 1;
7839     }
7840   else
7841     {
7842       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7843       gdb_assert (this_cu->cu == NULL);
7844       new_cu.reset (new dwarf2_cu (this_cu));
7845       cu = new_cu.get ();
7846     }
7847
7848   /* Get the header.  */
7849   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7850     {
7851       /* We already have the header, there's no need to read it in again.  */
7852       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7853     }
7854   else
7855     {
7856       if (this_cu->is_debug_types)
7857         {
7858           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7859                                                     &cu->header, section,
7860                                                     abbrev_section, info_ptr,
7861                                                     rcuh_kind::TYPE);
7862
7863           /* Since per_cu is the first member of struct signatured_type,
7864              we can go from a pointer to one to a pointer to the other.  */
7865           sig_type = (struct signatured_type *) this_cu;
7866           gdb_assert (sig_type->signature == cu->header.signature);
7867           gdb_assert (sig_type->type_offset_in_tu
7868                       == cu->header.type_cu_offset_in_tu);
7869           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7870
7871           /* LENGTH has not been set yet for type units if we're
7872              using .gdb_index.  */
7873           this_cu->length = get_cu_length (&cu->header);
7874
7875           /* Establish the type offset that can be used to lookup the type.  */
7876           sig_type->type_offset_in_section =
7877             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7878
7879           this_cu->dwarf_version = cu->header.version;
7880         }
7881       else
7882         {
7883           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7884                                                     &cu->header, section,
7885                                                     abbrev_section,
7886                                                     info_ptr,
7887                                                     rcuh_kind::COMPILE);
7888
7889           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7890           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7891           this_cu->dwarf_version = cu->header.version;
7892         }
7893     }
7894
7895   /* Skip dummy compilation units.  */
7896   if (info_ptr >= begin_info_ptr + this_cu->length
7897       || peek_abbrev_code (abfd, info_ptr) == 0)
7898     return;
7899
7900   /* If we don't have them yet, read the abbrevs for this compilation unit.
7901      And if we need to read them now, make sure they're freed when we're
7902      done (own the table through ABBREV_TABLE_HOLDER).  */
7903   abbrev_table_up abbrev_table_holder;
7904   if (abbrev_table != NULL)
7905     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7906   else
7907     {
7908       abbrev_table_holder
7909         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7910                                    cu->header.abbrev_sect_off);
7911       abbrev_table = abbrev_table_holder.get ();
7912     }
7913
7914   /* Read the top level CU/TU die.  */
7915   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7916   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7917
7918   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7919      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7920      table from the DWO file and pass the ownership over to us.  It will be
7921      referenced from READER, so we must make sure to free it after we're done
7922      with READER.
7923
7924      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7925      DWO CU, that this test will fail (the attribute will not be present).  */
7926   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7927   abbrev_table_up dwo_abbrev_table;
7928   if (attr)
7929     {
7930       struct dwo_unit *dwo_unit;
7931       struct die_info *dwo_comp_unit_die;
7932
7933       if (has_children)
7934         {
7935           complaint (&symfile_complaints,
7936                      _("compilation unit with DW_AT_GNU_dwo_name"
7937                        " has children (offset 0x%x) [in module %s]"),
7938                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7939         }
7940       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7941       if (dwo_unit != NULL)
7942         {
7943           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7944                                       comp_unit_die, NULL,
7945                                       &reader, &info_ptr,
7946                                       &dwo_comp_unit_die, &has_children,
7947                                       &dwo_abbrev_table) == 0)
7948             {
7949               /* Dummy die.  */
7950               return;
7951             }
7952           comp_unit_die = dwo_comp_unit_die;
7953         }
7954       else
7955         {
7956           /* Yikes, we couldn't find the rest of the DIE, we only have
7957              the stub.  A complaint has already been logged.  There's
7958              not much more we can do except pass on the stub DIE to
7959              die_reader_func.  We don't want to throw an error on bad
7960              debug info.  */
7961         }
7962     }
7963
7964   /* All of the above is setup for this call.  Yikes.  */
7965   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7966
7967   /* Done, clean up.  */
7968   if (new_cu != NULL && keep)
7969     {
7970       /* Link this CU into read_in_chain.  */
7971       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7972       dwarf2_per_objfile->read_in_chain = this_cu;
7973       /* The chain owns it now.  */
7974       new_cu.release ();
7975     }
7976 }
7977
7978 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7979    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7980    to have already done the lookup to find the DWO file).
7981
7982    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7983    THIS_CU->is_debug_types, but nothing else.
7984
7985    We fill in THIS_CU->length.
7986
7987    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7988    linker) then DIE_READER_FUNC will not get called.
7989
7990    THIS_CU->cu is always freed when done.
7991    This is done in order to not leave THIS_CU->cu in a state where we have
7992    to care whether it refers to the "main" CU or the DWO CU.  */
7993
7994 static void
7995 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7996                                    struct dwo_file *dwo_file,
7997                                    die_reader_func_ftype *die_reader_func,
7998                                    void *data)
7999 {
8000   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8001   struct objfile *objfile = dwarf2_per_objfile->objfile;
8002   struct dwarf2_section_info *section = this_cu->section;
8003   bfd *abfd = get_section_bfd_owner (section);
8004   struct dwarf2_section_info *abbrev_section;
8005   const gdb_byte *begin_info_ptr, *info_ptr;
8006   struct die_reader_specs reader;
8007   struct die_info *comp_unit_die;
8008   int has_children;
8009
8010   if (dwarf_die_debug)
8011     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
8012                         this_cu->is_debug_types ? "type" : "comp",
8013                         to_underlying (this_cu->sect_off));
8014
8015   gdb_assert (this_cu->cu == NULL);
8016
8017   abbrev_section = (dwo_file != NULL
8018                     ? &dwo_file->sections.abbrev
8019                     : get_abbrev_section_for_cu (this_cu));
8020
8021   /* This is cheap if the section is already read in.  */
8022   dwarf2_read_section (objfile, section);
8023
8024   struct dwarf2_cu cu (this_cu);
8025
8026   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8027   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8028                                             &cu.header, section,
8029                                             abbrev_section, info_ptr,
8030                                             (this_cu->is_debug_types
8031                                              ? rcuh_kind::TYPE
8032                                              : rcuh_kind::COMPILE));
8033
8034   this_cu->length = get_cu_length (&cu.header);
8035
8036   /* Skip dummy compilation units.  */
8037   if (info_ptr >= begin_info_ptr + this_cu->length
8038       || peek_abbrev_code (abfd, info_ptr) == 0)
8039     return;
8040
8041   abbrev_table_up abbrev_table
8042     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8043                                cu.header.abbrev_sect_off);
8044
8045   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8046   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8047
8048   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8049 }
8050
8051 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8052    does not lookup the specified DWO file.
8053    This cannot be used to read DWO files.
8054
8055    THIS_CU->cu is always freed when done.
8056    This is done in order to not leave THIS_CU->cu in a state where we have
8057    to care whether it refers to the "main" CU or the DWO CU.
8058    We can revisit this if the data shows there's a performance issue.  */
8059
8060 static void
8061 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8062                                 die_reader_func_ftype *die_reader_func,
8063                                 void *data)
8064 {
8065   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8066 }
8067 \f
8068 /* Type Unit Groups.
8069
8070    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8071    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8072    so that all types coming from the same compilation (.o file) are grouped
8073    together.  A future step could be to put the types in the same symtab as
8074    the CU the types ultimately came from.  */
8075
8076 static hashval_t
8077 hash_type_unit_group (const void *item)
8078 {
8079   const struct type_unit_group *tu_group
8080     = (const struct type_unit_group *) item;
8081
8082   return hash_stmt_list_entry (&tu_group->hash);
8083 }
8084
8085 static int
8086 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8087 {
8088   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8089   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8090
8091   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8092 }
8093
8094 /* Allocate a hash table for type unit groups.  */
8095
8096 static htab_t
8097 allocate_type_unit_groups_table (struct objfile *objfile)
8098 {
8099   return htab_create_alloc_ex (3,
8100                                hash_type_unit_group,
8101                                eq_type_unit_group,
8102                                NULL,
8103                                &objfile->objfile_obstack,
8104                                hashtab_obstack_allocate,
8105                                dummy_obstack_deallocate);
8106 }
8107
8108 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8109    partial symtabs.  We combine several TUs per psymtab to not let the size
8110    of any one psymtab grow too big.  */
8111 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8112 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8113
8114 /* Helper routine for get_type_unit_group.
8115    Create the type_unit_group object used to hold one or more TUs.  */
8116
8117 static struct type_unit_group *
8118 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8119 {
8120   struct dwarf2_per_objfile *dwarf2_per_objfile
8121     = cu->per_cu->dwarf2_per_objfile;
8122   struct objfile *objfile = dwarf2_per_objfile->objfile;
8123   struct dwarf2_per_cu_data *per_cu;
8124   struct type_unit_group *tu_group;
8125
8126   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8127                              struct type_unit_group);
8128   per_cu = &tu_group->per_cu;
8129   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8130
8131   if (dwarf2_per_objfile->using_index)
8132     {
8133       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8134                                         struct dwarf2_per_cu_quick_data);
8135     }
8136   else
8137     {
8138       unsigned int line_offset = to_underlying (line_offset_struct);
8139       struct partial_symtab *pst;
8140       char *name;
8141
8142       /* Give the symtab a useful name for debug purposes.  */
8143       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8144         name = xstrprintf ("<type_units_%d>",
8145                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8146       else
8147         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8148
8149       pst = create_partial_symtab (per_cu, name);
8150       pst->anonymous = 1;
8151
8152       xfree (name);
8153     }
8154
8155   tu_group->hash.dwo_unit = cu->dwo_unit;
8156   tu_group->hash.line_sect_off = line_offset_struct;
8157
8158   return tu_group;
8159 }
8160
8161 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8162    STMT_LIST is a DW_AT_stmt_list attribute.  */
8163
8164 static struct type_unit_group *
8165 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8166 {
8167   struct dwarf2_per_objfile *dwarf2_per_objfile
8168     = cu->per_cu->dwarf2_per_objfile;
8169   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8170   struct type_unit_group *tu_group;
8171   void **slot;
8172   unsigned int line_offset;
8173   struct type_unit_group type_unit_group_for_lookup;
8174
8175   if (dwarf2_per_objfile->type_unit_groups == NULL)
8176     {
8177       dwarf2_per_objfile->type_unit_groups =
8178         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8179     }
8180
8181   /* Do we need to create a new group, or can we use an existing one?  */
8182
8183   if (stmt_list)
8184     {
8185       line_offset = DW_UNSND (stmt_list);
8186       ++tu_stats->nr_symtab_sharers;
8187     }
8188   else
8189     {
8190       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8191          We can do various things here like create one group per TU or
8192          spread them over multiple groups to split up the expansion work.
8193          To avoid worst case scenarios (too many groups or too large groups)
8194          we, umm, group them in bunches.  */
8195       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8196                      | (tu_stats->nr_stmt_less_type_units
8197                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8198       ++tu_stats->nr_stmt_less_type_units;
8199     }
8200
8201   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8202   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8203   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8204                          &type_unit_group_for_lookup, INSERT);
8205   if (*slot != NULL)
8206     {
8207       tu_group = (struct type_unit_group *) *slot;
8208       gdb_assert (tu_group != NULL);
8209     }
8210   else
8211     {
8212       sect_offset line_offset_struct = (sect_offset) line_offset;
8213       tu_group = create_type_unit_group (cu, line_offset_struct);
8214       *slot = tu_group;
8215       ++tu_stats->nr_symtabs;
8216     }
8217
8218   return tu_group;
8219 }
8220 \f
8221 /* Partial symbol tables.  */
8222
8223 /* Create a psymtab named NAME and assign it to PER_CU.
8224
8225    The caller must fill in the following details:
8226    dirname, textlow, texthigh.  */
8227
8228 static struct partial_symtab *
8229 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8230 {
8231   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8232   struct partial_symtab *pst;
8233
8234   pst = start_psymtab_common (objfile, name, 0,
8235                               objfile->global_psymbols,
8236                               objfile->static_psymbols);
8237
8238   pst->psymtabs_addrmap_supported = 1;
8239
8240   /* This is the glue that links PST into GDB's symbol API.  */
8241   pst->read_symtab_private = per_cu;
8242   pst->read_symtab = dwarf2_read_symtab;
8243   per_cu->v.psymtab = pst;
8244
8245   return pst;
8246 }
8247
8248 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8249    type.  */
8250
8251 struct process_psymtab_comp_unit_data
8252 {
8253   /* True if we are reading a DW_TAG_partial_unit.  */
8254
8255   int want_partial_unit;
8256
8257   /* The "pretend" language that is used if the CU doesn't declare a
8258      language.  */
8259
8260   enum language pretend_language;
8261 };
8262
8263 /* die_reader_func for process_psymtab_comp_unit.  */
8264
8265 static void
8266 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8267                                   const gdb_byte *info_ptr,
8268                                   struct die_info *comp_unit_die,
8269                                   int has_children,
8270                                   void *data)
8271 {
8272   struct dwarf2_cu *cu = reader->cu;
8273   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8274   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8275   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8276   CORE_ADDR baseaddr;
8277   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8278   struct partial_symtab *pst;
8279   enum pc_bounds_kind cu_bounds_kind;
8280   const char *filename;
8281   struct process_psymtab_comp_unit_data *info
8282     = (struct process_psymtab_comp_unit_data *) data;
8283
8284   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8285     return;
8286
8287   gdb_assert (! per_cu->is_debug_types);
8288
8289   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8290
8291   cu->list_in_scope = &file_symbols;
8292
8293   /* Allocate a new partial symbol table structure.  */
8294   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8295   if (filename == NULL)
8296     filename = "";
8297
8298   pst = create_partial_symtab (per_cu, filename);
8299
8300   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8301   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8302
8303   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8304
8305   dwarf2_find_base_address (comp_unit_die, cu);
8306
8307   /* Possibly set the default values of LOWPC and HIGHPC from
8308      `DW_AT_ranges'.  */
8309   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8310                                          &best_highpc, cu, pst);
8311   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8312     /* Store the contiguous range if it is not empty; it can be empty for
8313        CUs with no code.  */
8314     addrmap_set_empty (objfile->psymtabs_addrmap,
8315                        gdbarch_adjust_dwarf2_addr (gdbarch,
8316                                                    best_lowpc + baseaddr),
8317                        gdbarch_adjust_dwarf2_addr (gdbarch,
8318                                                    best_highpc + baseaddr) - 1,
8319                        pst);
8320
8321   /* Check if comp unit has_children.
8322      If so, read the rest of the partial symbols from this comp unit.
8323      If not, there's no more debug_info for this comp unit.  */
8324   if (has_children)
8325     {
8326       struct partial_die_info *first_die;
8327       CORE_ADDR lowpc, highpc;
8328
8329       lowpc = ((CORE_ADDR) -1);
8330       highpc = ((CORE_ADDR) 0);
8331
8332       first_die = load_partial_dies (reader, info_ptr, 1);
8333
8334       scan_partial_symbols (first_die, &lowpc, &highpc,
8335                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8336
8337       /* If we didn't find a lowpc, set it to highpc to avoid
8338          complaints from `maint check'.  */
8339       if (lowpc == ((CORE_ADDR) -1))
8340         lowpc = highpc;
8341
8342       /* If the compilation unit didn't have an explicit address range,
8343          then use the information extracted from its child dies.  */
8344       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8345         {
8346           best_lowpc = lowpc;
8347           best_highpc = highpc;
8348         }
8349     }
8350   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8351   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8352
8353   end_psymtab_common (objfile, pst);
8354
8355   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8356     {
8357       int i;
8358       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8359       struct dwarf2_per_cu_data *iter;
8360
8361       /* Fill in 'dependencies' here; we fill in 'users' in a
8362          post-pass.  */
8363       pst->number_of_dependencies = len;
8364       pst->dependencies =
8365         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8366       for (i = 0;
8367            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8368                         i, iter);
8369            ++i)
8370         pst->dependencies[i] = iter->v.psymtab;
8371
8372       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8373     }
8374
8375   /* Get the list of files included in the current compilation unit,
8376      and build a psymtab for each of them.  */
8377   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8378
8379   if (dwarf_read_debug)
8380     {
8381       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8382
8383       fprintf_unfiltered (gdb_stdlog,
8384                           "Psymtab for %s unit @0x%x: %s - %s"
8385                           ", %d global, %d static syms\n",
8386                           per_cu->is_debug_types ? "type" : "comp",
8387                           to_underlying (per_cu->sect_off),
8388                           paddress (gdbarch, pst->textlow),
8389                           paddress (gdbarch, pst->texthigh),
8390                           pst->n_global_syms, pst->n_static_syms);
8391     }
8392 }
8393
8394 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8395    Process compilation unit THIS_CU for a psymtab.  */
8396
8397 static void
8398 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8399                            int want_partial_unit,
8400                            enum language pretend_language)
8401 {
8402   /* If this compilation unit was already read in, free the
8403      cached copy in order to read it in again.  This is
8404      necessary because we skipped some symbols when we first
8405      read in the compilation unit (see load_partial_dies).
8406      This problem could be avoided, but the benefit is unclear.  */
8407   if (this_cu->cu != NULL)
8408     free_one_cached_comp_unit (this_cu);
8409
8410   if (this_cu->is_debug_types)
8411     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8412                              NULL);
8413   else
8414     {
8415       process_psymtab_comp_unit_data info;
8416       info.want_partial_unit = want_partial_unit;
8417       info.pretend_language = pretend_language;
8418       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8419                                process_psymtab_comp_unit_reader, &info);
8420     }
8421
8422   /* Age out any secondary CUs.  */
8423   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8424 }
8425
8426 /* Reader function for build_type_psymtabs.  */
8427
8428 static void
8429 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8430                             const gdb_byte *info_ptr,
8431                             struct die_info *type_unit_die,
8432                             int has_children,
8433                             void *data)
8434 {
8435   struct dwarf2_per_objfile *dwarf2_per_objfile
8436     = reader->cu->per_cu->dwarf2_per_objfile;
8437   struct objfile *objfile = dwarf2_per_objfile->objfile;
8438   struct dwarf2_cu *cu = reader->cu;
8439   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8440   struct signatured_type *sig_type;
8441   struct type_unit_group *tu_group;
8442   struct attribute *attr;
8443   struct partial_die_info *first_die;
8444   CORE_ADDR lowpc, highpc;
8445   struct partial_symtab *pst;
8446
8447   gdb_assert (data == NULL);
8448   gdb_assert (per_cu->is_debug_types);
8449   sig_type = (struct signatured_type *) per_cu;
8450
8451   if (! has_children)
8452     return;
8453
8454   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8455   tu_group = get_type_unit_group (cu, attr);
8456
8457   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8458
8459   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8460   cu->list_in_scope = &file_symbols;
8461   pst = create_partial_symtab (per_cu, "");
8462   pst->anonymous = 1;
8463
8464   first_die = load_partial_dies (reader, info_ptr, 1);
8465
8466   lowpc = (CORE_ADDR) -1;
8467   highpc = (CORE_ADDR) 0;
8468   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8469
8470   end_psymtab_common (objfile, pst);
8471 }
8472
8473 /* Struct used to sort TUs by their abbreviation table offset.  */
8474
8475 struct tu_abbrev_offset
8476 {
8477   struct signatured_type *sig_type;
8478   sect_offset abbrev_offset;
8479 };
8480
8481 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8482
8483 static int
8484 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8485 {
8486   const struct tu_abbrev_offset * const *a
8487     = (const struct tu_abbrev_offset * const*) ap;
8488   const struct tu_abbrev_offset * const *b
8489     = (const struct tu_abbrev_offset * const*) bp;
8490   sect_offset aoff = (*a)->abbrev_offset;
8491   sect_offset boff = (*b)->abbrev_offset;
8492
8493   return (aoff > boff) - (aoff < boff);
8494 }
8495
8496 /* Efficiently read all the type units.
8497    This does the bulk of the work for build_type_psymtabs.
8498
8499    The efficiency is because we sort TUs by the abbrev table they use and
8500    only read each abbrev table once.  In one program there are 200K TUs
8501    sharing 8K abbrev tables.
8502
8503    The main purpose of this function is to support building the
8504    dwarf2_per_objfile->type_unit_groups table.
8505    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8506    can collapse the search space by grouping them by stmt_list.
8507    The savings can be significant, in the same program from above the 200K TUs
8508    share 8K stmt_list tables.
8509
8510    FUNC is expected to call get_type_unit_group, which will create the
8511    struct type_unit_group if necessary and add it to
8512    dwarf2_per_objfile->type_unit_groups.  */
8513
8514 static void
8515 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8516 {
8517   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8518   struct cleanup *cleanups;
8519   abbrev_table_up abbrev_table;
8520   sect_offset abbrev_offset;
8521   struct tu_abbrev_offset *sorted_by_abbrev;
8522   int i;
8523
8524   /* It's up to the caller to not call us multiple times.  */
8525   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8526
8527   if (dwarf2_per_objfile->n_type_units == 0)
8528     return;
8529
8530   /* TUs typically share abbrev tables, and there can be way more TUs than
8531      abbrev tables.  Sort by abbrev table to reduce the number of times we
8532      read each abbrev table in.
8533      Alternatives are to punt or to maintain a cache of abbrev tables.
8534      This is simpler and efficient enough for now.
8535
8536      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8537      symtab to use).  Typically TUs with the same abbrev offset have the same
8538      stmt_list value too so in practice this should work well.
8539
8540      The basic algorithm here is:
8541
8542       sort TUs by abbrev table
8543       for each TU with same abbrev table:
8544         read abbrev table if first user
8545         read TU top level DIE
8546           [IWBN if DWO skeletons had DW_AT_stmt_list]
8547         call FUNC  */
8548
8549   if (dwarf_read_debug)
8550     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8551
8552   /* Sort in a separate table to maintain the order of all_type_units
8553      for .gdb_index: TU indices directly index all_type_units.  */
8554   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8555                               dwarf2_per_objfile->n_type_units);
8556   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8557     {
8558       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8559
8560       sorted_by_abbrev[i].sig_type = sig_type;
8561       sorted_by_abbrev[i].abbrev_offset =
8562         read_abbrev_offset (dwarf2_per_objfile,
8563                             sig_type->per_cu.section,
8564                             sig_type->per_cu.sect_off);
8565     }
8566   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8567   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8568          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8569
8570   abbrev_offset = (sect_offset) ~(unsigned) 0;
8571
8572   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8573     {
8574       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8575
8576       /* Switch to the next abbrev table if necessary.  */
8577       if (abbrev_table == NULL
8578           || tu->abbrev_offset != abbrev_offset)
8579         {
8580           abbrev_offset = tu->abbrev_offset;
8581           abbrev_table =
8582             abbrev_table_read_table (dwarf2_per_objfile,
8583                                      &dwarf2_per_objfile->abbrev,
8584                                      abbrev_offset);
8585           ++tu_stats->nr_uniq_abbrev_tables;
8586         }
8587
8588       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8589                                0, 0, build_type_psymtabs_reader, NULL);
8590     }
8591
8592   do_cleanups (cleanups);
8593 }
8594
8595 /* Print collected type unit statistics.  */
8596
8597 static void
8598 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8599 {
8600   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8601
8602   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8603   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8604                       dwarf2_per_objfile->n_type_units);
8605   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8606                       tu_stats->nr_uniq_abbrev_tables);
8607   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8608                       tu_stats->nr_symtabs);
8609   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8610                       tu_stats->nr_symtab_sharers);
8611   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8612                       tu_stats->nr_stmt_less_type_units);
8613   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8614                       tu_stats->nr_all_type_units_reallocs);
8615 }
8616
8617 /* Traversal function for build_type_psymtabs.  */
8618
8619 static int
8620 build_type_psymtab_dependencies (void **slot, void *info)
8621 {
8622   struct dwarf2_per_objfile *dwarf2_per_objfile
8623     = (struct dwarf2_per_objfile *) info;
8624   struct objfile *objfile = dwarf2_per_objfile->objfile;
8625   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8626   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8627   struct partial_symtab *pst = per_cu->v.psymtab;
8628   int len = VEC_length (sig_type_ptr, tu_group->tus);
8629   struct signatured_type *iter;
8630   int i;
8631
8632   gdb_assert (len > 0);
8633   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8634
8635   pst->number_of_dependencies = len;
8636   pst->dependencies =
8637     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8638   for (i = 0;
8639        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8640        ++i)
8641     {
8642       gdb_assert (iter->per_cu.is_debug_types);
8643       pst->dependencies[i] = iter->per_cu.v.psymtab;
8644       iter->type_unit_group = tu_group;
8645     }
8646
8647   VEC_free (sig_type_ptr, tu_group->tus);
8648
8649   return 1;
8650 }
8651
8652 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8653    Build partial symbol tables for the .debug_types comp-units.  */
8654
8655 static void
8656 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8657 {
8658   if (! create_all_type_units (dwarf2_per_objfile))
8659     return;
8660
8661   build_type_psymtabs_1 (dwarf2_per_objfile);
8662 }
8663
8664 /* Traversal function for process_skeletonless_type_unit.
8665    Read a TU in a DWO file and build partial symbols for it.  */
8666
8667 static int
8668 process_skeletonless_type_unit (void **slot, void *info)
8669 {
8670   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8671   struct dwarf2_per_objfile *dwarf2_per_objfile
8672     = (struct dwarf2_per_objfile *) info;
8673   struct signatured_type find_entry, *entry;
8674
8675   /* If this TU doesn't exist in the global table, add it and read it in.  */
8676
8677   if (dwarf2_per_objfile->signatured_types == NULL)
8678     {
8679       dwarf2_per_objfile->signatured_types
8680         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8681     }
8682
8683   find_entry.signature = dwo_unit->signature;
8684   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8685                          INSERT);
8686   /* If we've already seen this type there's nothing to do.  What's happening
8687      is we're doing our own version of comdat-folding here.  */
8688   if (*slot != NULL)
8689     return 1;
8690
8691   /* This does the job that create_all_type_units would have done for
8692      this TU.  */
8693   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8694   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8695   *slot = entry;
8696
8697   /* This does the job that build_type_psymtabs_1 would have done.  */
8698   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8699                            build_type_psymtabs_reader, NULL);
8700
8701   return 1;
8702 }
8703
8704 /* Traversal function for process_skeletonless_type_units.  */
8705
8706 static int
8707 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8708 {
8709   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8710
8711   if (dwo_file->tus != NULL)
8712     {
8713       htab_traverse_noresize (dwo_file->tus,
8714                               process_skeletonless_type_unit, info);
8715     }
8716
8717   return 1;
8718 }
8719
8720 /* Scan all TUs of DWO files, verifying we've processed them.
8721    This is needed in case a TU was emitted without its skeleton.
8722    Note: This can't be done until we know what all the DWO files are.  */
8723
8724 static void
8725 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8726 {
8727   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8728   if (get_dwp_file (dwarf2_per_objfile) == NULL
8729       && dwarf2_per_objfile->dwo_files != NULL)
8730     {
8731       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8732                               process_dwo_file_for_skeletonless_type_units,
8733                               dwarf2_per_objfile);
8734     }
8735 }
8736
8737 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8738
8739 static void
8740 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8741 {
8742   int i;
8743
8744   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8745     {
8746       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8747       struct partial_symtab *pst = per_cu->v.psymtab;
8748       int j;
8749
8750       if (pst == NULL)
8751         continue;
8752
8753       for (j = 0; j < pst->number_of_dependencies; ++j)
8754         {
8755           /* Set the 'user' field only if it is not already set.  */
8756           if (pst->dependencies[j]->user == NULL)
8757             pst->dependencies[j]->user = pst;
8758         }
8759     }
8760 }
8761
8762 /* Build the partial symbol table by doing a quick pass through the
8763    .debug_info and .debug_abbrev sections.  */
8764
8765 static void
8766 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8767 {
8768   struct cleanup *back_to;
8769   int i;
8770   struct objfile *objfile = dwarf2_per_objfile->objfile;
8771
8772   if (dwarf_read_debug)
8773     {
8774       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8775                           objfile_name (objfile));
8776     }
8777
8778   dwarf2_per_objfile->reading_partial_symbols = 1;
8779
8780   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8781
8782   /* Any cached compilation units will be linked by the per-objfile
8783      read_in_chain.  Make sure to free them when we're done.  */
8784   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8785
8786   build_type_psymtabs (dwarf2_per_objfile);
8787
8788   create_all_comp_units (dwarf2_per_objfile);
8789
8790   /* Create a temporary address map on a temporary obstack.  We later
8791      copy this to the final obstack.  */
8792   auto_obstack temp_obstack;
8793
8794   scoped_restore save_psymtabs_addrmap
8795     = make_scoped_restore (&objfile->psymtabs_addrmap,
8796                            addrmap_create_mutable (&temp_obstack));
8797
8798   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8799     {
8800       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8801
8802       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8803     }
8804
8805   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8806   process_skeletonless_type_units (dwarf2_per_objfile);
8807
8808   /* Now that all TUs have been processed we can fill in the dependencies.  */
8809   if (dwarf2_per_objfile->type_unit_groups != NULL)
8810     {
8811       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8812                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8813     }
8814
8815   if (dwarf_read_debug)
8816     print_tu_stats (dwarf2_per_objfile);
8817
8818   set_partial_user (dwarf2_per_objfile);
8819
8820   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8821                                                     &objfile->objfile_obstack);
8822   /* At this point we want to keep the address map.  */
8823   save_psymtabs_addrmap.release ();
8824
8825   do_cleanups (back_to);
8826
8827   if (dwarf_read_debug)
8828     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8829                         objfile_name (objfile));
8830 }
8831
8832 /* die_reader_func for load_partial_comp_unit.  */
8833
8834 static void
8835 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8836                                const gdb_byte *info_ptr,
8837                                struct die_info *comp_unit_die,
8838                                int has_children,
8839                                void *data)
8840 {
8841   struct dwarf2_cu *cu = reader->cu;
8842
8843   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8844
8845   /* Check if comp unit has_children.
8846      If so, read the rest of the partial symbols from this comp unit.
8847      If not, there's no more debug_info for this comp unit.  */
8848   if (has_children)
8849     load_partial_dies (reader, info_ptr, 0);
8850 }
8851
8852 /* Load the partial DIEs for a secondary CU into memory.
8853    This is also used when rereading a primary CU with load_all_dies.  */
8854
8855 static void
8856 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8857 {
8858   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8859                            load_partial_comp_unit_reader, NULL);
8860 }
8861
8862 static void
8863 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8864                               struct dwarf2_section_info *section,
8865                               struct dwarf2_section_info *abbrev_section,
8866                               unsigned int is_dwz,
8867                               int *n_allocated,
8868                               int *n_comp_units,
8869                               struct dwarf2_per_cu_data ***all_comp_units)
8870 {
8871   const gdb_byte *info_ptr;
8872   struct objfile *objfile = dwarf2_per_objfile->objfile;
8873
8874   if (dwarf_read_debug)
8875     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8876                         get_section_name (section),
8877                         get_section_file_name (section));
8878
8879   dwarf2_read_section (objfile, section);
8880
8881   info_ptr = section->buffer;
8882
8883   while (info_ptr < section->buffer + section->size)
8884     {
8885       struct dwarf2_per_cu_data *this_cu;
8886
8887       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8888
8889       comp_unit_head cu_header;
8890       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8891                                      abbrev_section, info_ptr,
8892                                      rcuh_kind::COMPILE);
8893
8894       /* Save the compilation unit for later lookup.  */
8895       if (cu_header.unit_type != DW_UT_type)
8896         {
8897           this_cu = XOBNEW (&objfile->objfile_obstack,
8898                             struct dwarf2_per_cu_data);
8899           memset (this_cu, 0, sizeof (*this_cu));
8900         }
8901       else
8902         {
8903           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8904                                   struct signatured_type);
8905           memset (sig_type, 0, sizeof (*sig_type));
8906           sig_type->signature = cu_header.signature;
8907           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8908           this_cu = &sig_type->per_cu;
8909         }
8910       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8911       this_cu->sect_off = sect_off;
8912       this_cu->length = cu_header.length + cu_header.initial_length_size;
8913       this_cu->is_dwz = is_dwz;
8914       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8915       this_cu->section = section;
8916
8917       if (*n_comp_units == *n_allocated)
8918         {
8919           *n_allocated *= 2;
8920           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8921                                         *all_comp_units, *n_allocated);
8922         }
8923       (*all_comp_units)[*n_comp_units] = this_cu;
8924       ++*n_comp_units;
8925
8926       info_ptr = info_ptr + this_cu->length;
8927     }
8928 }
8929
8930 /* Create a list of all compilation units in OBJFILE.
8931    This is only done for -readnow and building partial symtabs.  */
8932
8933 static void
8934 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8935 {
8936   int n_allocated;
8937   int n_comp_units;
8938   struct dwarf2_per_cu_data **all_comp_units;
8939   struct dwz_file *dwz;
8940   struct objfile *objfile = dwarf2_per_objfile->objfile;
8941
8942   n_comp_units = 0;
8943   n_allocated = 10;
8944   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8945
8946   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8947                                 &dwarf2_per_objfile->abbrev, 0,
8948                                 &n_allocated, &n_comp_units, &all_comp_units);
8949
8950   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8951   if (dwz != NULL)
8952     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8953                                   1, &n_allocated, &n_comp_units,
8954                                   &all_comp_units);
8955
8956   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8957                                                   struct dwarf2_per_cu_data *,
8958                                                   n_comp_units);
8959   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8960           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8961   xfree (all_comp_units);
8962   dwarf2_per_objfile->n_comp_units = n_comp_units;
8963 }
8964
8965 /* Process all loaded DIEs for compilation unit CU, starting at
8966    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8967    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8968    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8969    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8970
8971 static void
8972 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8973                       CORE_ADDR *highpc, int set_addrmap,
8974                       struct dwarf2_cu *cu)
8975 {
8976   struct partial_die_info *pdi;
8977
8978   /* Now, march along the PDI's, descending into ones which have
8979      interesting children but skipping the children of the other ones,
8980      until we reach the end of the compilation unit.  */
8981
8982   pdi = first_die;
8983
8984   while (pdi != NULL)
8985     {
8986       fixup_partial_die (pdi, cu);
8987
8988       /* Anonymous namespaces or modules have no name but have interesting
8989          children, so we need to look at them.  Ditto for anonymous
8990          enums.  */
8991
8992       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8993           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8994           || pdi->tag == DW_TAG_imported_unit
8995           || pdi->tag == DW_TAG_inlined_subroutine)
8996         {
8997           switch (pdi->tag)
8998             {
8999             case DW_TAG_subprogram:
9000             case DW_TAG_inlined_subroutine:
9001               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9002               break;
9003             case DW_TAG_constant:
9004             case DW_TAG_variable:
9005             case DW_TAG_typedef:
9006             case DW_TAG_union_type:
9007               if (!pdi->is_declaration)
9008                 {
9009                   add_partial_symbol (pdi, cu);
9010                 }
9011               break;
9012             case DW_TAG_class_type:
9013             case DW_TAG_interface_type:
9014             case DW_TAG_structure_type:
9015               if (!pdi->is_declaration)
9016                 {
9017                   add_partial_symbol (pdi, cu);
9018                 }
9019               if (cu->language == language_rust && pdi->has_children)
9020                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9021                                       set_addrmap, cu);
9022               break;
9023             case DW_TAG_enumeration_type:
9024               if (!pdi->is_declaration)
9025                 add_partial_enumeration (pdi, cu);
9026               break;
9027             case DW_TAG_base_type:
9028             case DW_TAG_subrange_type:
9029               /* File scope base type definitions are added to the partial
9030                  symbol table.  */
9031               add_partial_symbol (pdi, cu);
9032               break;
9033             case DW_TAG_namespace:
9034               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9035               break;
9036             case DW_TAG_module:
9037               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9038               break;
9039             case DW_TAG_imported_unit:
9040               {
9041                 struct dwarf2_per_cu_data *per_cu;
9042
9043                 /* For now we don't handle imported units in type units.  */
9044                 if (cu->per_cu->is_debug_types)
9045                   {
9046                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9047                              " supported in type units [in module %s]"),
9048                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9049                   }
9050
9051                 per_cu = dwarf2_find_containing_comp_unit
9052                            (pdi->d.sect_off, pdi->is_dwz,
9053                             cu->per_cu->dwarf2_per_objfile);
9054
9055                 /* Go read the partial unit, if needed.  */
9056                 if (per_cu->v.psymtab == NULL)
9057                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9058
9059                 VEC_safe_push (dwarf2_per_cu_ptr,
9060                                cu->per_cu->imported_symtabs, per_cu);
9061               }
9062               break;
9063             case DW_TAG_imported_declaration:
9064               add_partial_symbol (pdi, cu);
9065               break;
9066             default:
9067               break;
9068             }
9069         }
9070
9071       /* If the die has a sibling, skip to the sibling.  */
9072
9073       pdi = pdi->die_sibling;
9074     }
9075 }
9076
9077 /* Functions used to compute the fully scoped name of a partial DIE.
9078
9079    Normally, this is simple.  For C++, the parent DIE's fully scoped
9080    name is concatenated with "::" and the partial DIE's name.
9081    Enumerators are an exception; they use the scope of their parent
9082    enumeration type, i.e. the name of the enumeration type is not
9083    prepended to the enumerator.
9084
9085    There are two complexities.  One is DW_AT_specification; in this
9086    case "parent" means the parent of the target of the specification,
9087    instead of the direct parent of the DIE.  The other is compilers
9088    which do not emit DW_TAG_namespace; in this case we try to guess
9089    the fully qualified name of structure types from their members'
9090    linkage names.  This must be done using the DIE's children rather
9091    than the children of any DW_AT_specification target.  We only need
9092    to do this for structures at the top level, i.e. if the target of
9093    any DW_AT_specification (if any; otherwise the DIE itself) does not
9094    have a parent.  */
9095
9096 /* Compute the scope prefix associated with PDI's parent, in
9097    compilation unit CU.  The result will be allocated on CU's
9098    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9099    field.  NULL is returned if no prefix is necessary.  */
9100 static const char *
9101 partial_die_parent_scope (struct partial_die_info *pdi,
9102                           struct dwarf2_cu *cu)
9103 {
9104   const char *grandparent_scope;
9105   struct partial_die_info *parent, *real_pdi;
9106
9107   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9108      then this means the parent of the specification DIE.  */
9109
9110   real_pdi = pdi;
9111   while (real_pdi->has_specification)
9112     real_pdi = find_partial_die (real_pdi->spec_offset,
9113                                  real_pdi->spec_is_dwz, cu);
9114
9115   parent = real_pdi->die_parent;
9116   if (parent == NULL)
9117     return NULL;
9118
9119   if (parent->scope_set)
9120     return parent->scope;
9121
9122   fixup_partial_die (parent, cu);
9123
9124   grandparent_scope = partial_die_parent_scope (parent, cu);
9125
9126   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9127      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9128      Work around this problem here.  */
9129   if (cu->language == language_cplus
9130       && parent->tag == DW_TAG_namespace
9131       && strcmp (parent->name, "::") == 0
9132       && grandparent_scope == NULL)
9133     {
9134       parent->scope = NULL;
9135       parent->scope_set = 1;
9136       return NULL;
9137     }
9138
9139   if (pdi->tag == DW_TAG_enumerator)
9140     /* Enumerators should not get the name of the enumeration as a prefix.  */
9141     parent->scope = grandparent_scope;
9142   else if (parent->tag == DW_TAG_namespace
9143       || parent->tag == DW_TAG_module
9144       || parent->tag == DW_TAG_structure_type
9145       || parent->tag == DW_TAG_class_type
9146       || parent->tag == DW_TAG_interface_type
9147       || parent->tag == DW_TAG_union_type
9148       || parent->tag == DW_TAG_enumeration_type)
9149     {
9150       if (grandparent_scope == NULL)
9151         parent->scope = parent->name;
9152       else
9153         parent->scope = typename_concat (&cu->comp_unit_obstack,
9154                                          grandparent_scope,
9155                                          parent->name, 0, cu);
9156     }
9157   else
9158     {
9159       /* FIXME drow/2004-04-01: What should we be doing with
9160          function-local names?  For partial symbols, we should probably be
9161          ignoring them.  */
9162       complaint (&symfile_complaints,
9163                  _("unhandled containing DIE tag %d for DIE at %d"),
9164                  parent->tag, to_underlying (pdi->sect_off));
9165       parent->scope = grandparent_scope;
9166     }
9167
9168   parent->scope_set = 1;
9169   return parent->scope;
9170 }
9171
9172 /* Return the fully scoped name associated with PDI, from compilation unit
9173    CU.  The result will be allocated with malloc.  */
9174
9175 static char *
9176 partial_die_full_name (struct partial_die_info *pdi,
9177                        struct dwarf2_cu *cu)
9178 {
9179   const char *parent_scope;
9180
9181   /* If this is a template instantiation, we can not work out the
9182      template arguments from partial DIEs.  So, unfortunately, we have
9183      to go through the full DIEs.  At least any work we do building
9184      types here will be reused if full symbols are loaded later.  */
9185   if (pdi->has_template_arguments)
9186     {
9187       fixup_partial_die (pdi, cu);
9188
9189       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9190         {
9191           struct die_info *die;
9192           struct attribute attr;
9193           struct dwarf2_cu *ref_cu = cu;
9194
9195           /* DW_FORM_ref_addr is using section offset.  */
9196           attr.name = (enum dwarf_attribute) 0;
9197           attr.form = DW_FORM_ref_addr;
9198           attr.u.unsnd = to_underlying (pdi->sect_off);
9199           die = follow_die_ref (NULL, &attr, &ref_cu);
9200
9201           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9202         }
9203     }
9204
9205   parent_scope = partial_die_parent_scope (pdi, cu);
9206   if (parent_scope == NULL)
9207     return NULL;
9208   else
9209     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9210 }
9211
9212 static void
9213 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9214 {
9215   struct dwarf2_per_objfile *dwarf2_per_objfile
9216     = cu->per_cu->dwarf2_per_objfile;
9217   struct objfile *objfile = dwarf2_per_objfile->objfile;
9218   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9219   CORE_ADDR addr = 0;
9220   const char *actual_name = NULL;
9221   CORE_ADDR baseaddr;
9222   char *built_actual_name;
9223
9224   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9225
9226   built_actual_name = partial_die_full_name (pdi, cu);
9227   if (built_actual_name != NULL)
9228     actual_name = built_actual_name;
9229
9230   if (actual_name == NULL)
9231     actual_name = pdi->name;
9232
9233   switch (pdi->tag)
9234     {
9235     case DW_TAG_inlined_subroutine:
9236     case DW_TAG_subprogram:
9237       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9238       if (pdi->is_external || cu->language == language_ada)
9239         {
9240           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9241              of the global scope.  But in Ada, we want to be able to access
9242              nested procedures globally.  So all Ada subprograms are stored
9243              in the global scope.  */
9244           add_psymbol_to_list (actual_name, strlen (actual_name),
9245                                built_actual_name != NULL,
9246                                VAR_DOMAIN, LOC_BLOCK,
9247                                &objfile->global_psymbols,
9248                                addr, cu->language, objfile);
9249         }
9250       else
9251         {
9252           add_psymbol_to_list (actual_name, strlen (actual_name),
9253                                built_actual_name != NULL,
9254                                VAR_DOMAIN, LOC_BLOCK,
9255                                &objfile->static_psymbols,
9256                                addr, cu->language, objfile);
9257         }
9258
9259       if (pdi->main_subprogram && actual_name != NULL)
9260         set_objfile_main_name (objfile, actual_name, cu->language);
9261       break;
9262     case DW_TAG_constant:
9263       {
9264         std::vector<partial_symbol *> *list;
9265
9266         if (pdi->is_external)
9267           list = &objfile->global_psymbols;
9268         else
9269           list = &objfile->static_psymbols;
9270         add_psymbol_to_list (actual_name, strlen (actual_name),
9271                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9272                              list, 0, cu->language, objfile);
9273       }
9274       break;
9275     case DW_TAG_variable:
9276       if (pdi->d.locdesc)
9277         addr = decode_locdesc (pdi->d.locdesc, cu);
9278
9279       if (pdi->d.locdesc
9280           && addr == 0
9281           && !dwarf2_per_objfile->has_section_at_zero)
9282         {
9283           /* A global or static variable may also have been stripped
9284              out by the linker if unused, in which case its address
9285              will be nullified; do not add such variables into partial
9286              symbol table then.  */
9287         }
9288       else if (pdi->is_external)
9289         {
9290           /* Global Variable.
9291              Don't enter into the minimal symbol tables as there is
9292              a minimal symbol table entry from the ELF symbols already.
9293              Enter into partial symbol table if it has a location
9294              descriptor or a type.
9295              If the location descriptor is missing, new_symbol will create
9296              a LOC_UNRESOLVED symbol, the address of the variable will then
9297              be determined from the minimal symbol table whenever the variable
9298              is referenced.
9299              The address for the partial symbol table entry is not
9300              used by GDB, but it comes in handy for debugging partial symbol
9301              table building.  */
9302
9303           if (pdi->d.locdesc || pdi->has_type)
9304             add_psymbol_to_list (actual_name, strlen (actual_name),
9305                                  built_actual_name != NULL,
9306                                  VAR_DOMAIN, LOC_STATIC,
9307                                  &objfile->global_psymbols,
9308                                  addr + baseaddr,
9309                                  cu->language, objfile);
9310         }
9311       else
9312         {
9313           int has_loc = pdi->d.locdesc != NULL;
9314
9315           /* Static Variable.  Skip symbols whose value we cannot know (those
9316              without location descriptors or constant values).  */
9317           if (!has_loc && !pdi->has_const_value)
9318             {
9319               xfree (built_actual_name);
9320               return;
9321             }
9322
9323           add_psymbol_to_list (actual_name, strlen (actual_name),
9324                                built_actual_name != NULL,
9325                                VAR_DOMAIN, LOC_STATIC,
9326                                &objfile->static_psymbols,
9327                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9328                                cu->language, objfile);
9329         }
9330       break;
9331     case DW_TAG_typedef:
9332     case DW_TAG_base_type:
9333     case DW_TAG_subrange_type:
9334       add_psymbol_to_list (actual_name, strlen (actual_name),
9335                            built_actual_name != NULL,
9336                            VAR_DOMAIN, LOC_TYPEDEF,
9337                            &objfile->static_psymbols,
9338                            0, cu->language, objfile);
9339       break;
9340     case DW_TAG_imported_declaration:
9341     case DW_TAG_namespace:
9342       add_psymbol_to_list (actual_name, strlen (actual_name),
9343                            built_actual_name != NULL,
9344                            VAR_DOMAIN, LOC_TYPEDEF,
9345                            &objfile->global_psymbols,
9346                            0, cu->language, objfile);
9347       break;
9348     case DW_TAG_module:
9349       add_psymbol_to_list (actual_name, strlen (actual_name),
9350                            built_actual_name != NULL,
9351                            MODULE_DOMAIN, LOC_TYPEDEF,
9352                            &objfile->global_psymbols,
9353                            0, cu->language, objfile);
9354       break;
9355     case DW_TAG_class_type:
9356     case DW_TAG_interface_type:
9357     case DW_TAG_structure_type:
9358     case DW_TAG_union_type:
9359     case DW_TAG_enumeration_type:
9360       /* Skip external references.  The DWARF standard says in the section
9361          about "Structure, Union, and Class Type Entries": "An incomplete
9362          structure, union or class type is represented by a structure,
9363          union or class entry that does not have a byte size attribute
9364          and that has a DW_AT_declaration attribute."  */
9365       if (!pdi->has_byte_size && pdi->is_declaration)
9366         {
9367           xfree (built_actual_name);
9368           return;
9369         }
9370
9371       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9372          static vs. global.  */
9373       add_psymbol_to_list (actual_name, strlen (actual_name),
9374                            built_actual_name != NULL,
9375                            STRUCT_DOMAIN, LOC_TYPEDEF,
9376                            cu->language == language_cplus
9377                            ? &objfile->global_psymbols
9378                            : &objfile->static_psymbols,
9379                            0, cu->language, objfile);
9380
9381       break;
9382     case DW_TAG_enumerator:
9383       add_psymbol_to_list (actual_name, strlen (actual_name),
9384                            built_actual_name != NULL,
9385                            VAR_DOMAIN, LOC_CONST,
9386                            cu->language == language_cplus
9387                            ? &objfile->global_psymbols
9388                            : &objfile->static_psymbols,
9389                            0, cu->language, objfile);
9390       break;
9391     default:
9392       break;
9393     }
9394
9395   xfree (built_actual_name);
9396 }
9397
9398 /* Read a partial die corresponding to a namespace; also, add a symbol
9399    corresponding to that namespace to the symbol table.  NAMESPACE is
9400    the name of the enclosing namespace.  */
9401
9402 static void
9403 add_partial_namespace (struct partial_die_info *pdi,
9404                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9405                        int set_addrmap, struct dwarf2_cu *cu)
9406 {
9407   /* Add a symbol for the namespace.  */
9408
9409   add_partial_symbol (pdi, cu);
9410
9411   /* Now scan partial symbols in that namespace.  */
9412
9413   if (pdi->has_children)
9414     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9415 }
9416
9417 /* Read a partial die corresponding to a Fortran module.  */
9418
9419 static void
9420 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9421                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9422 {
9423   /* Add a symbol for the namespace.  */
9424
9425   add_partial_symbol (pdi, cu);
9426
9427   /* Now scan partial symbols in that module.  */
9428
9429   if (pdi->has_children)
9430     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9431 }
9432
9433 /* Read a partial die corresponding to a subprogram or an inlined
9434    subprogram and create a partial symbol for that subprogram.
9435    When the CU language allows it, this routine also defines a partial
9436    symbol for each nested subprogram that this subprogram contains.
9437    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9438    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9439
9440    PDI may also be a lexical block, in which case we simply search
9441    recursively for subprograms defined inside that lexical block.
9442    Again, this is only performed when the CU language allows this
9443    type of definitions.  */
9444
9445 static void
9446 add_partial_subprogram (struct partial_die_info *pdi,
9447                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9448                         int set_addrmap, struct dwarf2_cu *cu)
9449 {
9450   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9451     {
9452       if (pdi->has_pc_info)
9453         {
9454           if (pdi->lowpc < *lowpc)
9455             *lowpc = pdi->lowpc;
9456           if (pdi->highpc > *highpc)
9457             *highpc = pdi->highpc;
9458           if (set_addrmap)
9459             {
9460               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9461               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9462               CORE_ADDR baseaddr;
9463               CORE_ADDR highpc;
9464               CORE_ADDR lowpc;
9465
9466               baseaddr = ANOFFSET (objfile->section_offsets,
9467                                    SECT_OFF_TEXT (objfile));
9468               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9469                                                   pdi->lowpc + baseaddr);
9470               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9471                                                    pdi->highpc + baseaddr);
9472               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9473                                  cu->per_cu->v.psymtab);
9474             }
9475         }
9476
9477       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9478         {
9479           if (!pdi->is_declaration)
9480             /* Ignore subprogram DIEs that do not have a name, they are
9481                illegal.  Do not emit a complaint at this point, we will
9482                do so when we convert this psymtab into a symtab.  */
9483             if (pdi->name)
9484               add_partial_symbol (pdi, cu);
9485         }
9486     }
9487
9488   if (! pdi->has_children)
9489     return;
9490
9491   if (cu->language == language_ada)
9492     {
9493       pdi = pdi->die_child;
9494       while (pdi != NULL)
9495         {
9496           fixup_partial_die (pdi, cu);
9497           if (pdi->tag == DW_TAG_subprogram
9498               || pdi->tag == DW_TAG_inlined_subroutine
9499               || pdi->tag == DW_TAG_lexical_block)
9500             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9501           pdi = pdi->die_sibling;
9502         }
9503     }
9504 }
9505
9506 /* Read a partial die corresponding to an enumeration type.  */
9507
9508 static void
9509 add_partial_enumeration (struct partial_die_info *enum_pdi,
9510                          struct dwarf2_cu *cu)
9511 {
9512   struct partial_die_info *pdi;
9513
9514   if (enum_pdi->name != NULL)
9515     add_partial_symbol (enum_pdi, cu);
9516
9517   pdi = enum_pdi->die_child;
9518   while (pdi)
9519     {
9520       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9521         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9522       else
9523         add_partial_symbol (pdi, cu);
9524       pdi = pdi->die_sibling;
9525     }
9526 }
9527
9528 /* Return the initial uleb128 in the die at INFO_PTR.  */
9529
9530 static unsigned int
9531 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9532 {
9533   unsigned int bytes_read;
9534
9535   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9536 }
9537
9538 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9539    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9540
9541    Return the corresponding abbrev, or NULL if the number is zero (indicating
9542    an empty DIE).  In either case *BYTES_READ will be set to the length of
9543    the initial number.  */
9544
9545 static struct abbrev_info *
9546 peek_die_abbrev (const die_reader_specs &reader,
9547                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9548 {
9549   dwarf2_cu *cu = reader.cu;
9550   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9551   unsigned int abbrev_number
9552     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9553
9554   if (abbrev_number == 0)
9555     return NULL;
9556
9557   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9558   if (!abbrev)
9559     {
9560       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9561                " at offset 0x%x [in module %s]"),
9562              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9563              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9564     }
9565
9566   return abbrev;
9567 }
9568
9569 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9570    Returns a pointer to the end of a series of DIEs, terminated by an empty
9571    DIE.  Any children of the skipped DIEs will also be skipped.  */
9572
9573 static const gdb_byte *
9574 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9575 {
9576   while (1)
9577     {
9578       unsigned int bytes_read;
9579       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9580
9581       if (abbrev == NULL)
9582         return info_ptr + bytes_read;
9583       else
9584         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9585     }
9586 }
9587
9588 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9589    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9590    abbrev corresponding to that skipped uleb128 should be passed in
9591    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9592    children.  */
9593
9594 static const gdb_byte *
9595 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9596               struct abbrev_info *abbrev)
9597 {
9598   unsigned int bytes_read;
9599   struct attribute attr;
9600   bfd *abfd = reader->abfd;
9601   struct dwarf2_cu *cu = reader->cu;
9602   const gdb_byte *buffer = reader->buffer;
9603   const gdb_byte *buffer_end = reader->buffer_end;
9604   unsigned int form, i;
9605
9606   for (i = 0; i < abbrev->num_attrs; i++)
9607     {
9608       /* The only abbrev we care about is DW_AT_sibling.  */
9609       if (abbrev->attrs[i].name == DW_AT_sibling)
9610         {
9611           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9612           if (attr.form == DW_FORM_ref_addr)
9613             complaint (&symfile_complaints,
9614                        _("ignoring absolute DW_AT_sibling"));
9615           else
9616             {
9617               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9618               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9619
9620               if (sibling_ptr < info_ptr)
9621                 complaint (&symfile_complaints,
9622                            _("DW_AT_sibling points backwards"));
9623               else if (sibling_ptr > reader->buffer_end)
9624                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9625               else
9626                 return sibling_ptr;
9627             }
9628         }
9629
9630       /* If it isn't DW_AT_sibling, skip this attribute.  */
9631       form = abbrev->attrs[i].form;
9632     skip_attribute:
9633       switch (form)
9634         {
9635         case DW_FORM_ref_addr:
9636           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9637              and later it is offset sized.  */
9638           if (cu->header.version == 2)
9639             info_ptr += cu->header.addr_size;
9640           else
9641             info_ptr += cu->header.offset_size;
9642           break;
9643         case DW_FORM_GNU_ref_alt:
9644           info_ptr += cu->header.offset_size;
9645           break;
9646         case DW_FORM_addr:
9647           info_ptr += cu->header.addr_size;
9648           break;
9649         case DW_FORM_data1:
9650         case DW_FORM_ref1:
9651         case DW_FORM_flag:
9652           info_ptr += 1;
9653           break;
9654         case DW_FORM_flag_present:
9655         case DW_FORM_implicit_const:
9656           break;
9657         case DW_FORM_data2:
9658         case DW_FORM_ref2:
9659           info_ptr += 2;
9660           break;
9661         case DW_FORM_data4:
9662         case DW_FORM_ref4:
9663           info_ptr += 4;
9664           break;
9665         case DW_FORM_data8:
9666         case DW_FORM_ref8:
9667         case DW_FORM_ref_sig8:
9668           info_ptr += 8;
9669           break;
9670         case DW_FORM_data16:
9671           info_ptr += 16;
9672           break;
9673         case DW_FORM_string:
9674           read_direct_string (abfd, info_ptr, &bytes_read);
9675           info_ptr += bytes_read;
9676           break;
9677         case DW_FORM_sec_offset:
9678         case DW_FORM_strp:
9679         case DW_FORM_GNU_strp_alt:
9680           info_ptr += cu->header.offset_size;
9681           break;
9682         case DW_FORM_exprloc:
9683         case DW_FORM_block:
9684           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9685           info_ptr += bytes_read;
9686           break;
9687         case DW_FORM_block1:
9688           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9689           break;
9690         case DW_FORM_block2:
9691           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9692           break;
9693         case DW_FORM_block4:
9694           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9695           break;
9696         case DW_FORM_sdata:
9697         case DW_FORM_udata:
9698         case DW_FORM_ref_udata:
9699         case DW_FORM_GNU_addr_index:
9700         case DW_FORM_GNU_str_index:
9701           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9702           break;
9703         case DW_FORM_indirect:
9704           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9705           info_ptr += bytes_read;
9706           /* We need to continue parsing from here, so just go back to
9707              the top.  */
9708           goto skip_attribute;
9709
9710         default:
9711           error (_("Dwarf Error: Cannot handle %s "
9712                    "in DWARF reader [in module %s]"),
9713                  dwarf_form_name (form),
9714                  bfd_get_filename (abfd));
9715         }
9716     }
9717
9718   if (abbrev->has_children)
9719     return skip_children (reader, info_ptr);
9720   else
9721     return info_ptr;
9722 }
9723
9724 /* Locate ORIG_PDI's sibling.
9725    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9726
9727 static const gdb_byte *
9728 locate_pdi_sibling (const struct die_reader_specs *reader,
9729                     struct partial_die_info *orig_pdi,
9730                     const gdb_byte *info_ptr)
9731 {
9732   /* Do we know the sibling already?  */
9733
9734   if (orig_pdi->sibling)
9735     return orig_pdi->sibling;
9736
9737   /* Are there any children to deal with?  */
9738
9739   if (!orig_pdi->has_children)
9740     return info_ptr;
9741
9742   /* Skip the children the long way.  */
9743
9744   return skip_children (reader, info_ptr);
9745 }
9746
9747 /* Expand this partial symbol table into a full symbol table.  SELF is
9748    not NULL.  */
9749
9750 static void
9751 dwarf2_read_symtab (struct partial_symtab *self,
9752                     struct objfile *objfile)
9753 {
9754   struct dwarf2_per_objfile *dwarf2_per_objfile
9755     = get_dwarf2_per_objfile (objfile);
9756
9757   if (self->readin)
9758     {
9759       warning (_("bug: psymtab for %s is already read in."),
9760                self->filename);
9761     }
9762   else
9763     {
9764       if (info_verbose)
9765         {
9766           printf_filtered (_("Reading in symbols for %s..."),
9767                            self->filename);
9768           gdb_flush (gdb_stdout);
9769         }
9770
9771       /* If this psymtab is constructed from a debug-only objfile, the
9772          has_section_at_zero flag will not necessarily be correct.  We
9773          can get the correct value for this flag by looking at the data
9774          associated with the (presumably stripped) associated objfile.  */
9775       if (objfile->separate_debug_objfile_backlink)
9776         {
9777           struct dwarf2_per_objfile *dpo_backlink
9778             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9779
9780           dwarf2_per_objfile->has_section_at_zero
9781             = dpo_backlink->has_section_at_zero;
9782         }
9783
9784       dwarf2_per_objfile->reading_partial_symbols = 0;
9785
9786       psymtab_to_symtab_1 (self);
9787
9788       /* Finish up the debug error message.  */
9789       if (info_verbose)
9790         printf_filtered (_("done.\n"));
9791     }
9792
9793   process_cu_includes (dwarf2_per_objfile);
9794 }
9795 \f
9796 /* Reading in full CUs.  */
9797
9798 /* Add PER_CU to the queue.  */
9799
9800 static void
9801 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9802                  enum language pretend_language)
9803 {
9804   struct dwarf2_queue_item *item;
9805
9806   per_cu->queued = 1;
9807   item = XNEW (struct dwarf2_queue_item);
9808   item->per_cu = per_cu;
9809   item->pretend_language = pretend_language;
9810   item->next = NULL;
9811
9812   if (dwarf2_queue == NULL)
9813     dwarf2_queue = item;
9814   else
9815     dwarf2_queue_tail->next = item;
9816
9817   dwarf2_queue_tail = item;
9818 }
9819
9820 /* If PER_CU is not yet queued, add it to the queue.
9821    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9822    dependency.
9823    The result is non-zero if PER_CU was queued, otherwise the result is zero
9824    meaning either PER_CU is already queued or it is already loaded.
9825
9826    N.B. There is an invariant here that if a CU is queued then it is loaded.
9827    The caller is required to load PER_CU if we return non-zero.  */
9828
9829 static int
9830 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9831                        struct dwarf2_per_cu_data *per_cu,
9832                        enum language pretend_language)
9833 {
9834   /* We may arrive here during partial symbol reading, if we need full
9835      DIEs to process an unusual case (e.g. template arguments).  Do
9836      not queue PER_CU, just tell our caller to load its DIEs.  */
9837   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9838     {
9839       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9840         return 1;
9841       return 0;
9842     }
9843
9844   /* Mark the dependence relation so that we don't flush PER_CU
9845      too early.  */
9846   if (dependent_cu != NULL)
9847     dwarf2_add_dependence (dependent_cu, per_cu);
9848
9849   /* If it's already on the queue, we have nothing to do.  */
9850   if (per_cu->queued)
9851     return 0;
9852
9853   /* If the compilation unit is already loaded, just mark it as
9854      used.  */
9855   if (per_cu->cu != NULL)
9856     {
9857       per_cu->cu->last_used = 0;
9858       return 0;
9859     }
9860
9861   /* Add it to the queue.  */
9862   queue_comp_unit (per_cu, pretend_language);
9863
9864   return 1;
9865 }
9866
9867 /* Process the queue.  */
9868
9869 static void
9870 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9871 {
9872   struct dwarf2_queue_item *item, *next_item;
9873
9874   if (dwarf_read_debug)
9875     {
9876       fprintf_unfiltered (gdb_stdlog,
9877                           "Expanding one or more symtabs of objfile %s ...\n",
9878                           objfile_name (dwarf2_per_objfile->objfile));
9879     }
9880
9881   /* The queue starts out with one item, but following a DIE reference
9882      may load a new CU, adding it to the end of the queue.  */
9883   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9884     {
9885       if ((dwarf2_per_objfile->using_index
9886            ? !item->per_cu->v.quick->compunit_symtab
9887            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9888           /* Skip dummy CUs.  */
9889           && item->per_cu->cu != NULL)
9890         {
9891           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9892           unsigned int debug_print_threshold;
9893           char buf[100];
9894
9895           if (per_cu->is_debug_types)
9896             {
9897               struct signatured_type *sig_type =
9898                 (struct signatured_type *) per_cu;
9899
9900               sprintf (buf, "TU %s at offset 0x%x",
9901                        hex_string (sig_type->signature),
9902                        to_underlying (per_cu->sect_off));
9903               /* There can be 100s of TUs.
9904                  Only print them in verbose mode.  */
9905               debug_print_threshold = 2;
9906             }
9907           else
9908             {
9909               sprintf (buf, "CU at offset 0x%x",
9910                        to_underlying (per_cu->sect_off));
9911               debug_print_threshold = 1;
9912             }
9913
9914           if (dwarf_read_debug >= debug_print_threshold)
9915             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9916
9917           if (per_cu->is_debug_types)
9918             process_full_type_unit (per_cu, item->pretend_language);
9919           else
9920             process_full_comp_unit (per_cu, item->pretend_language);
9921
9922           if (dwarf_read_debug >= debug_print_threshold)
9923             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9924         }
9925
9926       item->per_cu->queued = 0;
9927       next_item = item->next;
9928       xfree (item);
9929     }
9930
9931   dwarf2_queue_tail = NULL;
9932
9933   if (dwarf_read_debug)
9934     {
9935       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9936                           objfile_name (dwarf2_per_objfile->objfile));
9937     }
9938 }
9939
9940 /* Free all allocated queue entries.  This function only releases anything if
9941    an error was thrown; if the queue was processed then it would have been
9942    freed as we went along.  */
9943
9944 static void
9945 dwarf2_release_queue (void *dummy)
9946 {
9947   struct dwarf2_queue_item *item, *last;
9948
9949   item = dwarf2_queue;
9950   while (item)
9951     {
9952       /* Anything still marked queued is likely to be in an
9953          inconsistent state, so discard it.  */
9954       if (item->per_cu->queued)
9955         {
9956           if (item->per_cu->cu != NULL)
9957             free_one_cached_comp_unit (item->per_cu);
9958           item->per_cu->queued = 0;
9959         }
9960
9961       last = item;
9962       item = item->next;
9963       xfree (last);
9964     }
9965
9966   dwarf2_queue = dwarf2_queue_tail = NULL;
9967 }
9968
9969 /* Read in full symbols for PST, and anything it depends on.  */
9970
9971 static void
9972 psymtab_to_symtab_1 (struct partial_symtab *pst)
9973 {
9974   struct dwarf2_per_cu_data *per_cu;
9975   int i;
9976
9977   if (pst->readin)
9978     return;
9979
9980   for (i = 0; i < pst->number_of_dependencies; i++)
9981     if (!pst->dependencies[i]->readin
9982         && pst->dependencies[i]->user == NULL)
9983       {
9984         /* Inform about additional files that need to be read in.  */
9985         if (info_verbose)
9986           {
9987             /* FIXME: i18n: Need to make this a single string.  */
9988             fputs_filtered (" ", gdb_stdout);
9989             wrap_here ("");
9990             fputs_filtered ("and ", gdb_stdout);
9991             wrap_here ("");
9992             printf_filtered ("%s...", pst->dependencies[i]->filename);
9993             wrap_here ("");     /* Flush output.  */
9994             gdb_flush (gdb_stdout);
9995           }
9996         psymtab_to_symtab_1 (pst->dependencies[i]);
9997       }
9998
9999   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10000
10001   if (per_cu == NULL)
10002     {
10003       /* It's an include file, no symbols to read for it.
10004          Everything is in the parent symtab.  */
10005       pst->readin = 1;
10006       return;
10007     }
10008
10009   dw2_do_instantiate_symtab (per_cu);
10010 }
10011
10012 /* Trivial hash function for die_info: the hash value of a DIE
10013    is its offset in .debug_info for this objfile.  */
10014
10015 static hashval_t
10016 die_hash (const void *item)
10017 {
10018   const struct die_info *die = (const struct die_info *) item;
10019
10020   return to_underlying (die->sect_off);
10021 }
10022
10023 /* Trivial comparison function for die_info structures: two DIEs
10024    are equal if they have the same offset.  */
10025
10026 static int
10027 die_eq (const void *item_lhs, const void *item_rhs)
10028 {
10029   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10030   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10031
10032   return die_lhs->sect_off == die_rhs->sect_off;
10033 }
10034
10035 /* die_reader_func for load_full_comp_unit.
10036    This is identical to read_signatured_type_reader,
10037    but is kept separate for now.  */
10038
10039 static void
10040 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10041                             const gdb_byte *info_ptr,
10042                             struct die_info *comp_unit_die,
10043                             int has_children,
10044                             void *data)
10045 {
10046   struct dwarf2_cu *cu = reader->cu;
10047   enum language *language_ptr = (enum language *) data;
10048
10049   gdb_assert (cu->die_hash == NULL);
10050   cu->die_hash =
10051     htab_create_alloc_ex (cu->header.length / 12,
10052                           die_hash,
10053                           die_eq,
10054                           NULL,
10055                           &cu->comp_unit_obstack,
10056                           hashtab_obstack_allocate,
10057                           dummy_obstack_deallocate);
10058
10059   if (has_children)
10060     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10061                                                   &info_ptr, comp_unit_die);
10062   cu->dies = comp_unit_die;
10063   /* comp_unit_die is not stored in die_hash, no need.  */
10064
10065   /* We try not to read any attributes in this function, because not
10066      all CUs needed for references have been loaded yet, and symbol
10067      table processing isn't initialized.  But we have to set the CU language,
10068      or we won't be able to build types correctly.
10069      Similarly, if we do not read the producer, we can not apply
10070      producer-specific interpretation.  */
10071   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10072 }
10073
10074 /* Load the DIEs associated with PER_CU into memory.  */
10075
10076 static void
10077 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10078                      enum language pretend_language)
10079 {
10080   gdb_assert (! this_cu->is_debug_types);
10081
10082   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10083                            load_full_comp_unit_reader, &pretend_language);
10084 }
10085
10086 /* Add a DIE to the delayed physname list.  */
10087
10088 static void
10089 add_to_method_list (struct type *type, int fnfield_index, int index,
10090                     const char *name, struct die_info *die,
10091                     struct dwarf2_cu *cu)
10092 {
10093   struct delayed_method_info mi;
10094   mi.type = type;
10095   mi.fnfield_index = fnfield_index;
10096   mi.index = index;
10097   mi.name = name;
10098   mi.die = die;
10099   cu->method_list.push_back (mi);
10100 }
10101
10102 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10103    "const" / "volatile".  If so, decrements LEN by the length of the
10104    modifier and return true.  Otherwise return false.  */
10105
10106 template<size_t N>
10107 static bool
10108 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10109 {
10110   size_t mod_len = sizeof (mod) - 1;
10111   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10112     {
10113       len -= mod_len;
10114       return true;
10115     }
10116   return false;
10117 }
10118
10119 /* Compute the physnames of any methods on the CU's method list.
10120
10121    The computation of method physnames is delayed in order to avoid the
10122    (bad) condition that one of the method's formal parameters is of an as yet
10123    incomplete type.  */
10124
10125 static void
10126 compute_delayed_physnames (struct dwarf2_cu *cu)
10127 {
10128   /* Only C++ delays computing physnames.  */
10129   if (cu->method_list.empty ())
10130     return;
10131   gdb_assert (cu->language == language_cplus);
10132
10133   for (struct delayed_method_info &mi : cu->method_list)
10134     {
10135       const char *physname;
10136       struct fn_fieldlist *fn_flp
10137         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10138       physname = dwarf2_physname (mi.name, mi.die, cu);
10139       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10140         = physname ? physname : "";
10141
10142       /* Since there's no tag to indicate whether a method is a
10143          const/volatile overload, extract that information out of the
10144          demangled name.  */
10145       if (physname != NULL)
10146         {
10147           size_t len = strlen (physname);
10148
10149           while (1)
10150             {
10151               if (physname[len] == ')') /* shortcut */
10152                 break;
10153               else if (check_modifier (physname, len, " const"))
10154                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10155               else if (check_modifier (physname, len, " volatile"))
10156                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10157               else
10158                 break;
10159             }
10160         }
10161     }
10162
10163   /* The list is no longer needed.  */
10164   cu->method_list.clear ();
10165 }
10166
10167 /* Go objects should be embedded in a DW_TAG_module DIE,
10168    and it's not clear if/how imported objects will appear.
10169    To keep Go support simple until that's worked out,
10170    go back through what we've read and create something usable.
10171    We could do this while processing each DIE, and feels kinda cleaner,
10172    but that way is more invasive.
10173    This is to, for example, allow the user to type "p var" or "b main"
10174    without having to specify the package name, and allow lookups
10175    of module.object to work in contexts that use the expression
10176    parser.  */
10177
10178 static void
10179 fixup_go_packaging (struct dwarf2_cu *cu)
10180 {
10181   char *package_name = NULL;
10182   struct pending *list;
10183   int i;
10184
10185   for (list = global_symbols; list != NULL; list = list->next)
10186     {
10187       for (i = 0; i < list->nsyms; ++i)
10188         {
10189           struct symbol *sym = list->symbol[i];
10190
10191           if (SYMBOL_LANGUAGE (sym) == language_go
10192               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10193             {
10194               char *this_package_name = go_symbol_package_name (sym);
10195
10196               if (this_package_name == NULL)
10197                 continue;
10198               if (package_name == NULL)
10199                 package_name = this_package_name;
10200               else
10201                 {
10202                   struct objfile *objfile
10203                     = cu->per_cu->dwarf2_per_objfile->objfile;
10204                   if (strcmp (package_name, this_package_name) != 0)
10205                     complaint (&symfile_complaints,
10206                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10207                                (symbol_symtab (sym) != NULL
10208                                 ? symtab_to_filename_for_display
10209                                     (symbol_symtab (sym))
10210                                 : objfile_name (objfile)),
10211                                this_package_name, package_name);
10212                   xfree (this_package_name);
10213                 }
10214             }
10215         }
10216     }
10217
10218   if (package_name != NULL)
10219     {
10220       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10221       const char *saved_package_name
10222         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10223                                         package_name,
10224                                         strlen (package_name));
10225       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10226                                      saved_package_name);
10227       struct symbol *sym;
10228
10229       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10230
10231       sym = allocate_symbol (objfile);
10232       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10233       SYMBOL_SET_NAMES (sym, saved_package_name,
10234                         strlen (saved_package_name), 0, objfile);
10235       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10236          e.g., "main" finds the "main" module and not C's main().  */
10237       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10238       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10239       SYMBOL_TYPE (sym) = type;
10240
10241       add_symbol_to_list (sym, &global_symbols);
10242
10243       xfree (package_name);
10244     }
10245 }
10246
10247 /* Return the symtab for PER_CU.  This works properly regardless of
10248    whether we're using the index or psymtabs.  */
10249
10250 static struct compunit_symtab *
10251 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10252 {
10253   return (per_cu->dwarf2_per_objfile->using_index
10254           ? per_cu->v.quick->compunit_symtab
10255           : per_cu->v.psymtab->compunit_symtab);
10256 }
10257
10258 /* A helper function for computing the list of all symbol tables
10259    included by PER_CU.  */
10260
10261 static void
10262 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10263                                 htab_t all_children, htab_t all_type_symtabs,
10264                                 struct dwarf2_per_cu_data *per_cu,
10265                                 struct compunit_symtab *immediate_parent)
10266 {
10267   void **slot;
10268   int ix;
10269   struct compunit_symtab *cust;
10270   struct dwarf2_per_cu_data *iter;
10271
10272   slot = htab_find_slot (all_children, per_cu, INSERT);
10273   if (*slot != NULL)
10274     {
10275       /* This inclusion and its children have been processed.  */
10276       return;
10277     }
10278
10279   *slot = per_cu;
10280   /* Only add a CU if it has a symbol table.  */
10281   cust = get_compunit_symtab (per_cu);
10282   if (cust != NULL)
10283     {
10284       /* If this is a type unit only add its symbol table if we haven't
10285          seen it yet (type unit per_cu's can share symtabs).  */
10286       if (per_cu->is_debug_types)
10287         {
10288           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10289           if (*slot == NULL)
10290             {
10291               *slot = cust;
10292               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10293               if (cust->user == NULL)
10294                 cust->user = immediate_parent;
10295             }
10296         }
10297       else
10298         {
10299           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10300           if (cust->user == NULL)
10301             cust->user = immediate_parent;
10302         }
10303     }
10304
10305   for (ix = 0;
10306        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10307        ++ix)
10308     {
10309       recursively_compute_inclusions (result, all_children,
10310                                       all_type_symtabs, iter, cust);
10311     }
10312 }
10313
10314 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10315    PER_CU.  */
10316
10317 static void
10318 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10319 {
10320   gdb_assert (! per_cu->is_debug_types);
10321
10322   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10323     {
10324       int ix, len;
10325       struct dwarf2_per_cu_data *per_cu_iter;
10326       struct compunit_symtab *compunit_symtab_iter;
10327       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10328       htab_t all_children, all_type_symtabs;
10329       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10330
10331       /* If we don't have a symtab, we can just skip this case.  */
10332       if (cust == NULL)
10333         return;
10334
10335       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10336                                         NULL, xcalloc, xfree);
10337       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10338                                             NULL, xcalloc, xfree);
10339
10340       for (ix = 0;
10341            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10342                         ix, per_cu_iter);
10343            ++ix)
10344         {
10345           recursively_compute_inclusions (&result_symtabs, all_children,
10346                                           all_type_symtabs, per_cu_iter,
10347                                           cust);
10348         }
10349
10350       /* Now we have a transitive closure of all the included symtabs.  */
10351       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10352       cust->includes
10353         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10354                      struct compunit_symtab *, len + 1);
10355       for (ix = 0;
10356            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10357                         compunit_symtab_iter);
10358            ++ix)
10359         cust->includes[ix] = compunit_symtab_iter;
10360       cust->includes[len] = NULL;
10361
10362       VEC_free (compunit_symtab_ptr, result_symtabs);
10363       htab_delete (all_children);
10364       htab_delete (all_type_symtabs);
10365     }
10366 }
10367
10368 /* Compute the 'includes' field for the symtabs of all the CUs we just
10369    read.  */
10370
10371 static void
10372 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10373 {
10374   int ix;
10375   struct dwarf2_per_cu_data *iter;
10376
10377   for (ix = 0;
10378        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10379                     ix, iter);
10380        ++ix)
10381     {
10382       if (! iter->is_debug_types)
10383         compute_compunit_symtab_includes (iter);
10384     }
10385
10386   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10387 }
10388
10389 /* Generate full symbol information for PER_CU, whose DIEs have
10390    already been loaded into memory.  */
10391
10392 static void
10393 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10394                         enum language pretend_language)
10395 {
10396   struct dwarf2_cu *cu = per_cu->cu;
10397   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10398   struct objfile *objfile = dwarf2_per_objfile->objfile;
10399   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10400   CORE_ADDR lowpc, highpc;
10401   struct compunit_symtab *cust;
10402   CORE_ADDR baseaddr;
10403   struct block *static_block;
10404   CORE_ADDR addr;
10405
10406   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10407
10408   buildsym_init ();
10409   scoped_free_pendings free_pending;
10410
10411   /* Clear the list here in case something was left over.  */
10412   cu->method_list.clear ();
10413
10414   cu->list_in_scope = &file_symbols;
10415
10416   cu->language = pretend_language;
10417   cu->language_defn = language_def (cu->language);
10418
10419   /* Do line number decoding in read_file_scope () */
10420   process_die (cu->dies, cu);
10421
10422   /* For now fudge the Go package.  */
10423   if (cu->language == language_go)
10424     fixup_go_packaging (cu);
10425
10426   /* Now that we have processed all the DIEs in the CU, all the types 
10427      should be complete, and it should now be safe to compute all of the
10428      physnames.  */
10429   compute_delayed_physnames (cu);
10430
10431   /* Some compilers don't define a DW_AT_high_pc attribute for the
10432      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10433      it, by scanning the DIE's below the compilation unit.  */
10434   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10435
10436   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10437   static_block = end_symtab_get_static_block (addr, 0, 1);
10438
10439   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10440      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10441      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10442      addrmap to help ensure it has an accurate map of pc values belonging to
10443      this comp unit.  */
10444   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10445
10446   cust = end_symtab_from_static_block (static_block,
10447                                        SECT_OFF_TEXT (objfile), 0);
10448
10449   if (cust != NULL)
10450     {
10451       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10452
10453       /* Set symtab language to language from DW_AT_language.  If the
10454          compilation is from a C file generated by language preprocessors, do
10455          not set the language if it was already deduced by start_subfile.  */
10456       if (!(cu->language == language_c
10457             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10458         COMPUNIT_FILETABS (cust)->language = cu->language;
10459
10460       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10461          produce DW_AT_location with location lists but it can be possibly
10462          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10463          there were bugs in prologue debug info, fixed later in GCC-4.5
10464          by "unwind info for epilogues" patch (which is not directly related).
10465
10466          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10467          needed, it would be wrong due to missing DW_AT_producer there.
10468
10469          Still one can confuse GDB by using non-standard GCC compilation
10470          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10471          */ 
10472       if (cu->has_loclist && gcc_4_minor >= 5)
10473         cust->locations_valid = 1;
10474
10475       if (gcc_4_minor >= 5)
10476         cust->epilogue_unwind_valid = 1;
10477
10478       cust->call_site_htab = cu->call_site_htab;
10479     }
10480
10481   if (dwarf2_per_objfile->using_index)
10482     per_cu->v.quick->compunit_symtab = cust;
10483   else
10484     {
10485       struct partial_symtab *pst = per_cu->v.psymtab;
10486       pst->compunit_symtab = cust;
10487       pst->readin = 1;
10488     }
10489
10490   /* Push it for inclusion processing later.  */
10491   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10492 }
10493
10494 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10495    already been loaded into memory.  */
10496
10497 static void
10498 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10499                         enum language pretend_language)
10500 {
10501   struct dwarf2_cu *cu = per_cu->cu;
10502   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10503   struct objfile *objfile = dwarf2_per_objfile->objfile;
10504   struct compunit_symtab *cust;
10505   struct signatured_type *sig_type;
10506
10507   gdb_assert (per_cu->is_debug_types);
10508   sig_type = (struct signatured_type *) per_cu;
10509
10510   buildsym_init ();
10511   scoped_free_pendings free_pending;
10512
10513   /* Clear the list here in case something was left over.  */
10514   cu->method_list.clear ();
10515
10516   cu->list_in_scope = &file_symbols;
10517
10518   cu->language = pretend_language;
10519   cu->language_defn = language_def (cu->language);
10520
10521   /* The symbol tables are set up in read_type_unit_scope.  */
10522   process_die (cu->dies, cu);
10523
10524   /* For now fudge the Go package.  */
10525   if (cu->language == language_go)
10526     fixup_go_packaging (cu);
10527
10528   /* Now that we have processed all the DIEs in the CU, all the types 
10529      should be complete, and it should now be safe to compute all of the
10530      physnames.  */
10531   compute_delayed_physnames (cu);
10532
10533   /* TUs share symbol tables.
10534      If this is the first TU to use this symtab, complete the construction
10535      of it with end_expandable_symtab.  Otherwise, complete the addition of
10536      this TU's symbols to the existing symtab.  */
10537   if (sig_type->type_unit_group->compunit_symtab == NULL)
10538     {
10539       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10540       sig_type->type_unit_group->compunit_symtab = cust;
10541
10542       if (cust != NULL)
10543         {
10544           /* Set symtab language to language from DW_AT_language.  If the
10545              compilation is from a C file generated by language preprocessors,
10546              do not set the language if it was already deduced by
10547              start_subfile.  */
10548           if (!(cu->language == language_c
10549                 && COMPUNIT_FILETABS (cust)->language != language_c))
10550             COMPUNIT_FILETABS (cust)->language = cu->language;
10551         }
10552     }
10553   else
10554     {
10555       augment_type_symtab ();
10556       cust = sig_type->type_unit_group->compunit_symtab;
10557     }
10558
10559   if (dwarf2_per_objfile->using_index)
10560     per_cu->v.quick->compunit_symtab = cust;
10561   else
10562     {
10563       struct partial_symtab *pst = per_cu->v.psymtab;
10564       pst->compunit_symtab = cust;
10565       pst->readin = 1;
10566     }
10567 }
10568
10569 /* Process an imported unit DIE.  */
10570
10571 static void
10572 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10573 {
10574   struct attribute *attr;
10575
10576   /* For now we don't handle imported units in type units.  */
10577   if (cu->per_cu->is_debug_types)
10578     {
10579       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10580                " supported in type units [in module %s]"),
10581              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10582     }
10583
10584   attr = dwarf2_attr (die, DW_AT_import, cu);
10585   if (attr != NULL)
10586     {
10587       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10588       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10589       dwarf2_per_cu_data *per_cu
10590         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10591                                             cu->per_cu->dwarf2_per_objfile);
10592
10593       /* If necessary, add it to the queue and load its DIEs.  */
10594       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10595         load_full_comp_unit (per_cu, cu->language);
10596
10597       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10598                      per_cu);
10599     }
10600 }
10601
10602 /* RAII object that represents a process_die scope: i.e.,
10603    starts/finishes processing a DIE.  */
10604 class process_die_scope
10605 {
10606 public:
10607   process_die_scope (die_info *die, dwarf2_cu *cu)
10608     : m_die (die), m_cu (cu)
10609   {
10610     /* We should only be processing DIEs not already in process.  */
10611     gdb_assert (!m_die->in_process);
10612     m_die->in_process = true;
10613   }
10614
10615   ~process_die_scope ()
10616   {
10617     m_die->in_process = false;
10618
10619     /* If we're done processing the DIE for the CU that owns the line
10620        header, we don't need the line header anymore.  */
10621     if (m_cu->line_header_die_owner == m_die)
10622       {
10623         delete m_cu->line_header;
10624         m_cu->line_header = NULL;
10625         m_cu->line_header_die_owner = NULL;
10626       }
10627   }
10628
10629 private:
10630   die_info *m_die;
10631   dwarf2_cu *m_cu;
10632 };
10633
10634 /* Process a die and its children.  */
10635
10636 static void
10637 process_die (struct die_info *die, struct dwarf2_cu *cu)
10638 {
10639   process_die_scope scope (die, cu);
10640
10641   switch (die->tag)
10642     {
10643     case DW_TAG_padding:
10644       break;
10645     case DW_TAG_compile_unit:
10646     case DW_TAG_partial_unit:
10647       read_file_scope (die, cu);
10648       break;
10649     case DW_TAG_type_unit:
10650       read_type_unit_scope (die, cu);
10651       break;
10652     case DW_TAG_subprogram:
10653     case DW_TAG_inlined_subroutine:
10654       read_func_scope (die, cu);
10655       break;
10656     case DW_TAG_lexical_block:
10657     case DW_TAG_try_block:
10658     case DW_TAG_catch_block:
10659       read_lexical_block_scope (die, cu);
10660       break;
10661     case DW_TAG_call_site:
10662     case DW_TAG_GNU_call_site:
10663       read_call_site_scope (die, cu);
10664       break;
10665     case DW_TAG_class_type:
10666     case DW_TAG_interface_type:
10667     case DW_TAG_structure_type:
10668     case DW_TAG_union_type:
10669       process_structure_scope (die, cu);
10670       break;
10671     case DW_TAG_enumeration_type:
10672       process_enumeration_scope (die, cu);
10673       break;
10674
10675     /* These dies have a type, but processing them does not create
10676        a symbol or recurse to process the children.  Therefore we can
10677        read them on-demand through read_type_die.  */
10678     case DW_TAG_subroutine_type:
10679     case DW_TAG_set_type:
10680     case DW_TAG_array_type:
10681     case DW_TAG_pointer_type:
10682     case DW_TAG_ptr_to_member_type:
10683     case DW_TAG_reference_type:
10684     case DW_TAG_rvalue_reference_type:
10685     case DW_TAG_string_type:
10686       break;
10687
10688     case DW_TAG_base_type:
10689     case DW_TAG_subrange_type:
10690     case DW_TAG_typedef:
10691       /* Add a typedef symbol for the type definition, if it has a
10692          DW_AT_name.  */
10693       new_symbol (die, read_type_die (die, cu), cu);
10694       break;
10695     case DW_TAG_common_block:
10696       read_common_block (die, cu);
10697       break;
10698     case DW_TAG_common_inclusion:
10699       break;
10700     case DW_TAG_namespace:
10701       cu->processing_has_namespace_info = 1;
10702       read_namespace (die, cu);
10703       break;
10704     case DW_TAG_module:
10705       cu->processing_has_namespace_info = 1;
10706       read_module (die, cu);
10707       break;
10708     case DW_TAG_imported_declaration:
10709       cu->processing_has_namespace_info = 1;
10710       if (read_namespace_alias (die, cu))
10711         break;
10712       /* The declaration is not a global namespace alias: fall through.  */
10713     case DW_TAG_imported_module:
10714       cu->processing_has_namespace_info = 1;
10715       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10716                                  || cu->language != language_fortran))
10717         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10718                    dwarf_tag_name (die->tag));
10719       read_import_statement (die, cu);
10720       break;
10721
10722     case DW_TAG_imported_unit:
10723       process_imported_unit_die (die, cu);
10724       break;
10725
10726     case DW_TAG_variable:
10727       read_variable (die, cu);
10728       break;
10729
10730     default:
10731       new_symbol (die, NULL, cu);
10732       break;
10733     }
10734 }
10735 \f
10736 /* DWARF name computation.  */
10737
10738 /* A helper function for dwarf2_compute_name which determines whether DIE
10739    needs to have the name of the scope prepended to the name listed in the
10740    die.  */
10741
10742 static int
10743 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10744 {
10745   struct attribute *attr;
10746
10747   switch (die->tag)
10748     {
10749     case DW_TAG_namespace:
10750     case DW_TAG_typedef:
10751     case DW_TAG_class_type:
10752     case DW_TAG_interface_type:
10753     case DW_TAG_structure_type:
10754     case DW_TAG_union_type:
10755     case DW_TAG_enumeration_type:
10756     case DW_TAG_enumerator:
10757     case DW_TAG_subprogram:
10758     case DW_TAG_inlined_subroutine:
10759     case DW_TAG_member:
10760     case DW_TAG_imported_declaration:
10761       return 1;
10762
10763     case DW_TAG_variable:
10764     case DW_TAG_constant:
10765       /* We only need to prefix "globally" visible variables.  These include
10766          any variable marked with DW_AT_external or any variable that
10767          lives in a namespace.  [Variables in anonymous namespaces
10768          require prefixing, but they are not DW_AT_external.]  */
10769
10770       if (dwarf2_attr (die, DW_AT_specification, cu))
10771         {
10772           struct dwarf2_cu *spec_cu = cu;
10773
10774           return die_needs_namespace (die_specification (die, &spec_cu),
10775                                       spec_cu);
10776         }
10777
10778       attr = dwarf2_attr (die, DW_AT_external, cu);
10779       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10780           && die->parent->tag != DW_TAG_module)
10781         return 0;
10782       /* A variable in a lexical block of some kind does not need a
10783          namespace, even though in C++ such variables may be external
10784          and have a mangled name.  */
10785       if (die->parent->tag ==  DW_TAG_lexical_block
10786           || die->parent->tag ==  DW_TAG_try_block
10787           || die->parent->tag ==  DW_TAG_catch_block
10788           || die->parent->tag == DW_TAG_subprogram)
10789         return 0;
10790       return 1;
10791
10792     default:
10793       return 0;
10794     }
10795 }
10796
10797 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10798    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10799    defined for the given DIE.  */
10800
10801 static struct attribute *
10802 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10803 {
10804   struct attribute *attr;
10805
10806   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10807   if (attr == NULL)
10808     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10809
10810   return attr;
10811 }
10812
10813 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10814    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10815    defined for the given DIE.  */
10816
10817 static const char *
10818 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10819 {
10820   const char *linkage_name;
10821
10822   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10823   if (linkage_name == NULL)
10824     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10825
10826   return linkage_name;
10827 }
10828
10829 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10830    compute the physname for the object, which include a method's:
10831    - formal parameters (C++),
10832    - receiver type (Go),
10833
10834    The term "physname" is a bit confusing.
10835    For C++, for example, it is the demangled name.
10836    For Go, for example, it's the mangled name.
10837
10838    For Ada, return the DIE's linkage name rather than the fully qualified
10839    name.  PHYSNAME is ignored..
10840
10841    The result is allocated on the objfile_obstack and canonicalized.  */
10842
10843 static const char *
10844 dwarf2_compute_name (const char *name,
10845                      struct die_info *die, struct dwarf2_cu *cu,
10846                      int physname)
10847 {
10848   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10849
10850   if (name == NULL)
10851     name = dwarf2_name (die, cu);
10852
10853   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10854      but otherwise compute it by typename_concat inside GDB.
10855      FIXME: Actually this is not really true, or at least not always true.
10856      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10857      Fortran names because there is no mangling standard.  So new_symbol
10858      will set the demangled name to the result of dwarf2_full_name, and it is
10859      the demangled name that GDB uses if it exists.  */
10860   if (cu->language == language_ada
10861       || (cu->language == language_fortran && physname))
10862     {
10863       /* For Ada unit, we prefer the linkage name over the name, as
10864          the former contains the exported name, which the user expects
10865          to be able to reference.  Ideally, we want the user to be able
10866          to reference this entity using either natural or linkage name,
10867          but we haven't started looking at this enhancement yet.  */
10868       const char *linkage_name = dw2_linkage_name (die, cu);
10869
10870       if (linkage_name != NULL)
10871         return linkage_name;
10872     }
10873
10874   /* These are the only languages we know how to qualify names in.  */
10875   if (name != NULL
10876       && (cu->language == language_cplus
10877           || cu->language == language_fortran || cu->language == language_d
10878           || cu->language == language_rust))
10879     {
10880       if (die_needs_namespace (die, cu))
10881         {
10882           const char *prefix;
10883           const char *canonical_name = NULL;
10884
10885           string_file buf;
10886
10887           prefix = determine_prefix (die, cu);
10888           if (*prefix != '\0')
10889             {
10890               char *prefixed_name = typename_concat (NULL, prefix, name,
10891                                                      physname, cu);
10892
10893               buf.puts (prefixed_name);
10894               xfree (prefixed_name);
10895             }
10896           else
10897             buf.puts (name);
10898
10899           /* Template parameters may be specified in the DIE's DW_AT_name, or
10900              as children with DW_TAG_template_type_param or
10901              DW_TAG_value_type_param.  If the latter, add them to the name
10902              here.  If the name already has template parameters, then
10903              skip this step; some versions of GCC emit both, and
10904              it is more efficient to use the pre-computed name.
10905
10906              Something to keep in mind about this process: it is very
10907              unlikely, or in some cases downright impossible, to produce
10908              something that will match the mangled name of a function.
10909              If the definition of the function has the same debug info,
10910              we should be able to match up with it anyway.  But fallbacks
10911              using the minimal symbol, for instance to find a method
10912              implemented in a stripped copy of libstdc++, will not work.
10913              If we do not have debug info for the definition, we will have to
10914              match them up some other way.
10915
10916              When we do name matching there is a related problem with function
10917              templates; two instantiated function templates are allowed to
10918              differ only by their return types, which we do not add here.  */
10919
10920           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10921             {
10922               struct attribute *attr;
10923               struct die_info *child;
10924               int first = 1;
10925
10926               die->building_fullname = 1;
10927
10928               for (child = die->child; child != NULL; child = child->sibling)
10929                 {
10930                   struct type *type;
10931                   LONGEST value;
10932                   const gdb_byte *bytes;
10933                   struct dwarf2_locexpr_baton *baton;
10934                   struct value *v;
10935
10936                   if (child->tag != DW_TAG_template_type_param
10937                       && child->tag != DW_TAG_template_value_param)
10938                     continue;
10939
10940                   if (first)
10941                     {
10942                       buf.puts ("<");
10943                       first = 0;
10944                     }
10945                   else
10946                     buf.puts (", ");
10947
10948                   attr = dwarf2_attr (child, DW_AT_type, cu);
10949                   if (attr == NULL)
10950                     {
10951                       complaint (&symfile_complaints,
10952                                  _("template parameter missing DW_AT_type"));
10953                       buf.puts ("UNKNOWN_TYPE");
10954                       continue;
10955                     }
10956                   type = die_type (child, cu);
10957
10958                   if (child->tag == DW_TAG_template_type_param)
10959                     {
10960                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10961                       continue;
10962                     }
10963
10964                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10965                   if (attr == NULL)
10966                     {
10967                       complaint (&symfile_complaints,
10968                                  _("template parameter missing "
10969                                    "DW_AT_const_value"));
10970                       buf.puts ("UNKNOWN_VALUE");
10971                       continue;
10972                     }
10973
10974                   dwarf2_const_value_attr (attr, type, name,
10975                                            &cu->comp_unit_obstack, cu,
10976                                            &value, &bytes, &baton);
10977
10978                   if (TYPE_NOSIGN (type))
10979                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10980                        changed, this can use value_print instead.  */
10981                     c_printchar (value, type, &buf);
10982                   else
10983                     {
10984                       struct value_print_options opts;
10985
10986                       if (baton != NULL)
10987                         v = dwarf2_evaluate_loc_desc (type, NULL,
10988                                                       baton->data,
10989                                                       baton->size,
10990                                                       baton->per_cu);
10991                       else if (bytes != NULL)
10992                         {
10993                           v = allocate_value (type);
10994                           memcpy (value_contents_writeable (v), bytes,
10995                                   TYPE_LENGTH (type));
10996                         }
10997                       else
10998                         v = value_from_longest (type, value);
10999
11000                       /* Specify decimal so that we do not depend on
11001                          the radix.  */
11002                       get_formatted_print_options (&opts, 'd');
11003                       opts.raw = 1;
11004                       value_print (v, &buf, &opts);
11005                       release_value (v);
11006                       value_free (v);
11007                     }
11008                 }
11009
11010               die->building_fullname = 0;
11011
11012               if (!first)
11013                 {
11014                   /* Close the argument list, with a space if necessary
11015                      (nested templates).  */
11016                   if (!buf.empty () && buf.string ().back () == '>')
11017                     buf.puts (" >");
11018                   else
11019                     buf.puts (">");
11020                 }
11021             }
11022
11023           /* For C++ methods, append formal parameter type
11024              information, if PHYSNAME.  */
11025
11026           if (physname && die->tag == DW_TAG_subprogram
11027               && cu->language == language_cplus)
11028             {
11029               struct type *type = read_type_die (die, cu);
11030
11031               c_type_print_args (type, &buf, 1, cu->language,
11032                                  &type_print_raw_options);
11033
11034               if (cu->language == language_cplus)
11035                 {
11036                   /* Assume that an artificial first parameter is
11037                      "this", but do not crash if it is not.  RealView
11038                      marks unnamed (and thus unused) parameters as
11039                      artificial; there is no way to differentiate
11040                      the two cases.  */
11041                   if (TYPE_NFIELDS (type) > 0
11042                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11043                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11044                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11045                                                                         0))))
11046                     buf.puts (" const");
11047                 }
11048             }
11049
11050           const std::string &intermediate_name = buf.string ();
11051
11052           if (cu->language == language_cplus)
11053             canonical_name
11054               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11055                                           &objfile->per_bfd->storage_obstack);
11056
11057           /* If we only computed INTERMEDIATE_NAME, or if
11058              INTERMEDIATE_NAME is already canonical, then we need to
11059              copy it to the appropriate obstack.  */
11060           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11061             name = ((const char *)
11062                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11063                                    intermediate_name.c_str (),
11064                                    intermediate_name.length ()));
11065           else
11066             name = canonical_name;
11067         }
11068     }
11069
11070   return name;
11071 }
11072
11073 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11074    If scope qualifiers are appropriate they will be added.  The result
11075    will be allocated on the storage_obstack, or NULL if the DIE does
11076    not have a name.  NAME may either be from a previous call to
11077    dwarf2_name or NULL.
11078
11079    The output string will be canonicalized (if C++).  */
11080
11081 static const char *
11082 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11083 {
11084   return dwarf2_compute_name (name, die, cu, 0);
11085 }
11086
11087 /* Construct a physname for the given DIE in CU.  NAME may either be
11088    from a previous call to dwarf2_name or NULL.  The result will be
11089    allocated on the objfile_objstack or NULL if the DIE does not have a
11090    name.
11091
11092    The output string will be canonicalized (if C++).  */
11093
11094 static const char *
11095 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11096 {
11097   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11098   const char *retval, *mangled = NULL, *canon = NULL;
11099   int need_copy = 1;
11100
11101   /* In this case dwarf2_compute_name is just a shortcut not building anything
11102      on its own.  */
11103   if (!die_needs_namespace (die, cu))
11104     return dwarf2_compute_name (name, die, cu, 1);
11105
11106   mangled = dw2_linkage_name (die, cu);
11107
11108   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11109      See https://github.com/rust-lang/rust/issues/32925.  */
11110   if (cu->language == language_rust && mangled != NULL
11111       && strchr (mangled, '{') != NULL)
11112     mangled = NULL;
11113
11114   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11115      has computed.  */
11116   gdb::unique_xmalloc_ptr<char> demangled;
11117   if (mangled != NULL)
11118     {
11119       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11120          type.  It is easier for GDB users to search for such functions as
11121          `name(params)' than `long name(params)'.  In such case the minimal
11122          symbol names do not match the full symbol names but for template
11123          functions there is never a need to look up their definition from their
11124          declaration so the only disadvantage remains the minimal symbol
11125          variant `long name(params)' does not have the proper inferior type.
11126          */
11127
11128       if (cu->language == language_go)
11129         {
11130           /* This is a lie, but we already lie to the caller new_symbol.
11131              new_symbol assumes we return the mangled name.
11132              This just undoes that lie until things are cleaned up.  */
11133         }
11134       else
11135         {
11136           demangled.reset (gdb_demangle (mangled,
11137                                          (DMGL_PARAMS | DMGL_ANSI
11138                                           | DMGL_RET_DROP)));
11139         }
11140       if (demangled)
11141         canon = demangled.get ();
11142       else
11143         {
11144           canon = mangled;
11145           need_copy = 0;
11146         }
11147     }
11148
11149   if (canon == NULL || check_physname)
11150     {
11151       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11152
11153       if (canon != NULL && strcmp (physname, canon) != 0)
11154         {
11155           /* It may not mean a bug in GDB.  The compiler could also
11156              compute DW_AT_linkage_name incorrectly.  But in such case
11157              GDB would need to be bug-to-bug compatible.  */
11158
11159           complaint (&symfile_complaints,
11160                      _("Computed physname <%s> does not match demangled <%s> "
11161                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11162                      physname, canon, mangled, to_underlying (die->sect_off),
11163                      objfile_name (objfile));
11164
11165           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11166              is available here - over computed PHYSNAME.  It is safer
11167              against both buggy GDB and buggy compilers.  */
11168
11169           retval = canon;
11170         }
11171       else
11172         {
11173           retval = physname;
11174           need_copy = 0;
11175         }
11176     }
11177   else
11178     retval = canon;
11179
11180   if (need_copy)
11181     retval = ((const char *)
11182               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11183                              retval, strlen (retval)));
11184
11185   return retval;
11186 }
11187
11188 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11189    a new symbol for it.
11190
11191    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11192
11193 static int
11194 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11195 {
11196   struct attribute *attr;
11197
11198   /* If the die does not have a name, this is not a namespace
11199      alias.  */
11200   attr = dwarf2_attr (die, DW_AT_name, cu);
11201   if (attr != NULL)
11202     {
11203       int num;
11204       struct die_info *d = die;
11205       struct dwarf2_cu *imported_cu = cu;
11206
11207       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11208          keep inspecting DIEs until we hit the underlying import.  */
11209 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11210       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11211         {
11212           attr = dwarf2_attr (d, DW_AT_import, cu);
11213           if (attr == NULL)
11214             break;
11215
11216           d = follow_die_ref (d, attr, &imported_cu);
11217           if (d->tag != DW_TAG_imported_declaration)
11218             break;
11219         }
11220
11221       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11222         {
11223           complaint (&symfile_complaints,
11224                      _("DIE at 0x%x has too many recursively imported "
11225                        "declarations"), to_underlying (d->sect_off));
11226           return 0;
11227         }
11228
11229       if (attr != NULL)
11230         {
11231           struct type *type;
11232           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11233
11234           type = get_die_type_at_offset (sect_off, cu->per_cu);
11235           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11236             {
11237               /* This declaration is a global namespace alias.  Add
11238                  a symbol for it whose type is the aliased namespace.  */
11239               new_symbol (die, type, cu);
11240               return 1;
11241             }
11242         }
11243     }
11244
11245   return 0;
11246 }
11247
11248 /* Return the using directives repository (global or local?) to use in the
11249    current context for LANGUAGE.
11250
11251    For Ada, imported declarations can materialize renamings, which *may* be
11252    global.  However it is impossible (for now?) in DWARF to distinguish
11253    "external" imported declarations and "static" ones.  As all imported
11254    declarations seem to be static in all other languages, make them all CU-wide
11255    global only in Ada.  */
11256
11257 static struct using_direct **
11258 using_directives (enum language language)
11259 {
11260   if (language == language_ada && context_stack_depth == 0)
11261     return &global_using_directives;
11262   else
11263     return &local_using_directives;
11264 }
11265
11266 /* Read the import statement specified by the given die and record it.  */
11267
11268 static void
11269 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11270 {
11271   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11272   struct attribute *import_attr;
11273   struct die_info *imported_die, *child_die;
11274   struct dwarf2_cu *imported_cu;
11275   const char *imported_name;
11276   const char *imported_name_prefix;
11277   const char *canonical_name;
11278   const char *import_alias;
11279   const char *imported_declaration = NULL;
11280   const char *import_prefix;
11281   std::vector<const char *> excludes;
11282
11283   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11284   if (import_attr == NULL)
11285     {
11286       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11287                  dwarf_tag_name (die->tag));
11288       return;
11289     }
11290
11291   imported_cu = cu;
11292   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11293   imported_name = dwarf2_name (imported_die, imported_cu);
11294   if (imported_name == NULL)
11295     {
11296       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11297
11298         The import in the following code:
11299         namespace A
11300           {
11301             typedef int B;
11302           }
11303
11304         int main ()
11305           {
11306             using A::B;
11307             B b;
11308             return b;
11309           }
11310
11311         ...
11312          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11313             <52>   DW_AT_decl_file   : 1
11314             <53>   DW_AT_decl_line   : 6
11315             <54>   DW_AT_import      : <0x75>
11316          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11317             <59>   DW_AT_name        : B
11318             <5b>   DW_AT_decl_file   : 1
11319             <5c>   DW_AT_decl_line   : 2
11320             <5d>   DW_AT_type        : <0x6e>
11321         ...
11322          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11323             <76>   DW_AT_byte_size   : 4
11324             <77>   DW_AT_encoding    : 5        (signed)
11325
11326         imports the wrong die ( 0x75 instead of 0x58 ).
11327         This case will be ignored until the gcc bug is fixed.  */
11328       return;
11329     }
11330
11331   /* Figure out the local name after import.  */
11332   import_alias = dwarf2_name (die, cu);
11333
11334   /* Figure out where the statement is being imported to.  */
11335   import_prefix = determine_prefix (die, cu);
11336
11337   /* Figure out what the scope of the imported die is and prepend it
11338      to the name of the imported die.  */
11339   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11340
11341   if (imported_die->tag != DW_TAG_namespace
11342       && imported_die->tag != DW_TAG_module)
11343     {
11344       imported_declaration = imported_name;
11345       canonical_name = imported_name_prefix;
11346     }
11347   else if (strlen (imported_name_prefix) > 0)
11348     canonical_name = obconcat (&objfile->objfile_obstack,
11349                                imported_name_prefix,
11350                                (cu->language == language_d ? "." : "::"),
11351                                imported_name, (char *) NULL);
11352   else
11353     canonical_name = imported_name;
11354
11355   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11356     for (child_die = die->child; child_die && child_die->tag;
11357          child_die = sibling_die (child_die))
11358       {
11359         /* DWARF-4: A Fortran use statement with a “rename list” may be
11360            represented by an imported module entry with an import attribute
11361            referring to the module and owned entries corresponding to those
11362            entities that are renamed as part of being imported.  */
11363
11364         if (child_die->tag != DW_TAG_imported_declaration)
11365           {
11366             complaint (&symfile_complaints,
11367                        _("child DW_TAG_imported_declaration expected "
11368                          "- DIE at 0x%x [in module %s]"),
11369                        to_underlying (child_die->sect_off), objfile_name (objfile));
11370             continue;
11371           }
11372
11373         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11374         if (import_attr == NULL)
11375           {
11376             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11377                        dwarf_tag_name (child_die->tag));
11378             continue;
11379           }
11380
11381         imported_cu = cu;
11382         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11383                                               &imported_cu);
11384         imported_name = dwarf2_name (imported_die, imported_cu);
11385         if (imported_name == NULL)
11386           {
11387             complaint (&symfile_complaints,
11388                        _("child DW_TAG_imported_declaration has unknown "
11389                          "imported name - DIE at 0x%x [in module %s]"),
11390                        to_underlying (child_die->sect_off), objfile_name (objfile));
11391             continue;
11392           }
11393
11394         excludes.push_back (imported_name);
11395
11396         process_die (child_die, cu);
11397       }
11398
11399   add_using_directive (using_directives (cu->language),
11400                        import_prefix,
11401                        canonical_name,
11402                        import_alias,
11403                        imported_declaration,
11404                        excludes,
11405                        0,
11406                        &objfile->objfile_obstack);
11407 }
11408
11409 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11410    types, but gives them a size of zero.  Starting with version 14,
11411    ICC is compatible with GCC.  */
11412
11413 static int
11414 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11415 {
11416   if (!cu->checked_producer)
11417     check_producer (cu);
11418
11419   return cu->producer_is_icc_lt_14;
11420 }
11421
11422 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11423    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11424    this, it was first present in GCC release 4.3.0.  */
11425
11426 static int
11427 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11428 {
11429   if (!cu->checked_producer)
11430     check_producer (cu);
11431
11432   return cu->producer_is_gcc_lt_4_3;
11433 }
11434
11435 static file_and_directory
11436 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11437 {
11438   file_and_directory res;
11439
11440   /* Find the filename.  Do not use dwarf2_name here, since the filename
11441      is not a source language identifier.  */
11442   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11443   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11444
11445   if (res.comp_dir == NULL
11446       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11447       && IS_ABSOLUTE_PATH (res.name))
11448     {
11449       res.comp_dir_storage = ldirname (res.name);
11450       if (!res.comp_dir_storage.empty ())
11451         res.comp_dir = res.comp_dir_storage.c_str ();
11452     }
11453   if (res.comp_dir != NULL)
11454     {
11455       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11456          directory, get rid of it.  */
11457       const char *cp = strchr (res.comp_dir, ':');
11458
11459       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11460         res.comp_dir = cp + 1;
11461     }
11462
11463   if (res.name == NULL)
11464     res.name = "<unknown>";
11465
11466   return res;
11467 }
11468
11469 /* Handle DW_AT_stmt_list for a compilation unit.
11470    DIE is the DW_TAG_compile_unit die for CU.
11471    COMP_DIR is the compilation directory.  LOWPC is passed to
11472    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11473
11474 static void
11475 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11476                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11477 {
11478   struct dwarf2_per_objfile *dwarf2_per_objfile
11479     = cu->per_cu->dwarf2_per_objfile;
11480   struct objfile *objfile = dwarf2_per_objfile->objfile;
11481   struct attribute *attr;
11482   struct line_header line_header_local;
11483   hashval_t line_header_local_hash;
11484   void **slot;
11485   int decode_mapping;
11486
11487   gdb_assert (! cu->per_cu->is_debug_types);
11488
11489   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11490   if (attr == NULL)
11491     return;
11492
11493   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11494
11495   /* The line header hash table is only created if needed (it exists to
11496      prevent redundant reading of the line table for partial_units).
11497      If we're given a partial_unit, we'll need it.  If we're given a
11498      compile_unit, then use the line header hash table if it's already
11499      created, but don't create one just yet.  */
11500
11501   if (dwarf2_per_objfile->line_header_hash == NULL
11502       && die->tag == DW_TAG_partial_unit)
11503     {
11504       dwarf2_per_objfile->line_header_hash
11505         = htab_create_alloc_ex (127, line_header_hash_voidp,
11506                                 line_header_eq_voidp,
11507                                 free_line_header_voidp,
11508                                 &objfile->objfile_obstack,
11509                                 hashtab_obstack_allocate,
11510                                 dummy_obstack_deallocate);
11511     }
11512
11513   line_header_local.sect_off = line_offset;
11514   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11515   line_header_local_hash = line_header_hash (&line_header_local);
11516   if (dwarf2_per_objfile->line_header_hash != NULL)
11517     {
11518       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11519                                        &line_header_local,
11520                                        line_header_local_hash, NO_INSERT);
11521
11522       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11523          is not present in *SLOT (since if there is something in *SLOT then
11524          it will be for a partial_unit).  */
11525       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11526         {
11527           gdb_assert (*slot != NULL);
11528           cu->line_header = (struct line_header *) *slot;
11529           return;
11530         }
11531     }
11532
11533   /* dwarf_decode_line_header does not yet provide sufficient information.
11534      We always have to call also dwarf_decode_lines for it.  */
11535   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11536   if (lh == NULL)
11537     return;
11538
11539   cu->line_header = lh.release ();
11540   cu->line_header_die_owner = die;
11541
11542   if (dwarf2_per_objfile->line_header_hash == NULL)
11543     slot = NULL;
11544   else
11545     {
11546       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11547                                        &line_header_local,
11548                                        line_header_local_hash, INSERT);
11549       gdb_assert (slot != NULL);
11550     }
11551   if (slot != NULL && *slot == NULL)
11552     {
11553       /* This newly decoded line number information unit will be owned
11554          by line_header_hash hash table.  */
11555       *slot = cu->line_header;
11556       cu->line_header_die_owner = NULL;
11557     }
11558   else
11559     {
11560       /* We cannot free any current entry in (*slot) as that struct line_header
11561          may be already used by multiple CUs.  Create only temporary decoded
11562          line_header for this CU - it may happen at most once for each line
11563          number information unit.  And if we're not using line_header_hash
11564          then this is what we want as well.  */
11565       gdb_assert (die->tag != DW_TAG_partial_unit);
11566     }
11567   decode_mapping = (die->tag != DW_TAG_partial_unit);
11568   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11569                       decode_mapping);
11570
11571 }
11572
11573 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11574
11575 static void
11576 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11577 {
11578   struct dwarf2_per_objfile *dwarf2_per_objfile
11579     = cu->per_cu->dwarf2_per_objfile;
11580   struct objfile *objfile = dwarf2_per_objfile->objfile;
11581   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11582   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11583   CORE_ADDR highpc = ((CORE_ADDR) 0);
11584   struct attribute *attr;
11585   struct die_info *child_die;
11586   CORE_ADDR baseaddr;
11587
11588   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11589
11590   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11591
11592   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11593      from finish_block.  */
11594   if (lowpc == ((CORE_ADDR) -1))
11595     lowpc = highpc;
11596   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11597
11598   file_and_directory fnd = find_file_and_directory (die, cu);
11599
11600   prepare_one_comp_unit (cu, die, cu->language);
11601
11602   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11603      standardised yet.  As a workaround for the language detection we fall
11604      back to the DW_AT_producer string.  */
11605   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11606     cu->language = language_opencl;
11607
11608   /* Similar hack for Go.  */
11609   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11610     set_cu_language (DW_LANG_Go, cu);
11611
11612   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11613
11614   /* Decode line number information if present.  We do this before
11615      processing child DIEs, so that the line header table is available
11616      for DW_AT_decl_file.  */
11617   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11618
11619   /* Process all dies in compilation unit.  */
11620   if (die->child != NULL)
11621     {
11622       child_die = die->child;
11623       while (child_die && child_die->tag)
11624         {
11625           process_die (child_die, cu);
11626           child_die = sibling_die (child_die);
11627         }
11628     }
11629
11630   /* Decode macro information, if present.  Dwarf 2 macro information
11631      refers to information in the line number info statement program
11632      header, so we can only read it if we've read the header
11633      successfully.  */
11634   attr = dwarf2_attr (die, DW_AT_macros, cu);
11635   if (attr == NULL)
11636     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11637   if (attr && cu->line_header)
11638     {
11639       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11640         complaint (&symfile_complaints,
11641                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11642
11643       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11644     }
11645   else
11646     {
11647       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11648       if (attr && cu->line_header)
11649         {
11650           unsigned int macro_offset = DW_UNSND (attr);
11651
11652           dwarf_decode_macros (cu, macro_offset, 0);
11653         }
11654     }
11655 }
11656
11657 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11658    Create the set of symtabs used by this TU, or if this TU is sharing
11659    symtabs with another TU and the symtabs have already been created
11660    then restore those symtabs in the line header.
11661    We don't need the pc/line-number mapping for type units.  */
11662
11663 static void
11664 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11665 {
11666   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11667   struct type_unit_group *tu_group;
11668   int first_time;
11669   struct attribute *attr;
11670   unsigned int i;
11671   struct signatured_type *sig_type;
11672
11673   gdb_assert (per_cu->is_debug_types);
11674   sig_type = (struct signatured_type *) per_cu;
11675
11676   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11677
11678   /* If we're using .gdb_index (includes -readnow) then
11679      per_cu->type_unit_group may not have been set up yet.  */
11680   if (sig_type->type_unit_group == NULL)
11681     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11682   tu_group = sig_type->type_unit_group;
11683
11684   /* If we've already processed this stmt_list there's no real need to
11685      do it again, we could fake it and just recreate the part we need
11686      (file name,index -> symtab mapping).  If data shows this optimization
11687      is useful we can do it then.  */
11688   first_time = tu_group->compunit_symtab == NULL;
11689
11690   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11691      debug info.  */
11692   line_header_up lh;
11693   if (attr != NULL)
11694     {
11695       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11696       lh = dwarf_decode_line_header (line_offset, cu);
11697     }
11698   if (lh == NULL)
11699     {
11700       if (first_time)
11701         dwarf2_start_symtab (cu, "", NULL, 0);
11702       else
11703         {
11704           gdb_assert (tu_group->symtabs == NULL);
11705           restart_symtab (tu_group->compunit_symtab, "", 0);
11706         }
11707       return;
11708     }
11709
11710   cu->line_header = lh.release ();
11711   cu->line_header_die_owner = die;
11712
11713   if (first_time)
11714     {
11715       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11716
11717       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11718          still initializing it, and our caller (a few levels up)
11719          process_full_type_unit still needs to know if this is the first
11720          time.  */
11721
11722       tu_group->num_symtabs = cu->line_header->file_names.size ();
11723       tu_group->symtabs = XNEWVEC (struct symtab *,
11724                                    cu->line_header->file_names.size ());
11725
11726       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11727         {
11728           file_entry &fe = cu->line_header->file_names[i];
11729
11730           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11731
11732           if (current_subfile->symtab == NULL)
11733             {
11734               /* NOTE: start_subfile will recognize when it's been
11735                  passed a file it has already seen.  So we can't
11736                  assume there's a simple mapping from
11737                  cu->line_header->file_names to subfiles, plus
11738                  cu->line_header->file_names may contain dups.  */
11739               current_subfile->symtab
11740                 = allocate_symtab (cust, current_subfile->name);
11741             }
11742
11743           fe.symtab = current_subfile->symtab;
11744           tu_group->symtabs[i] = fe.symtab;
11745         }
11746     }
11747   else
11748     {
11749       restart_symtab (tu_group->compunit_symtab, "", 0);
11750
11751       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11752         {
11753           file_entry &fe = cu->line_header->file_names[i];
11754
11755           fe.symtab = tu_group->symtabs[i];
11756         }
11757     }
11758
11759   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11760      so they don't have a "real" (so to speak) symtab anyway.
11761      There is later code that will assign the main symtab to all symbols
11762      that don't have one.  We need to handle the case of a symbol with a
11763      missing symtab (DW_AT_decl_file) anyway.  */
11764 }
11765
11766 /* Process DW_TAG_type_unit.
11767    For TUs we want to skip the first top level sibling if it's not the
11768    actual type being defined by this TU.  In this case the first top
11769    level sibling is there to provide context only.  */
11770
11771 static void
11772 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11773 {
11774   struct die_info *child_die;
11775
11776   prepare_one_comp_unit (cu, die, language_minimal);
11777
11778   /* Initialize (or reinitialize) the machinery for building symtabs.
11779      We do this before processing child DIEs, so that the line header table
11780      is available for DW_AT_decl_file.  */
11781   setup_type_unit_groups (die, cu);
11782
11783   if (die->child != NULL)
11784     {
11785       child_die = die->child;
11786       while (child_die && child_die->tag)
11787         {
11788           process_die (child_die, cu);
11789           child_die = sibling_die (child_die);
11790         }
11791     }
11792 }
11793 \f
11794 /* DWO/DWP files.
11795
11796    http://gcc.gnu.org/wiki/DebugFission
11797    http://gcc.gnu.org/wiki/DebugFissionDWP
11798
11799    To simplify handling of both DWO files ("object" files with the DWARF info)
11800    and DWP files (a file with the DWOs packaged up into one file), we treat
11801    DWP files as having a collection of virtual DWO files.  */
11802
11803 static hashval_t
11804 hash_dwo_file (const void *item)
11805 {
11806   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11807   hashval_t hash;
11808
11809   hash = htab_hash_string (dwo_file->dwo_name);
11810   if (dwo_file->comp_dir != NULL)
11811     hash += htab_hash_string (dwo_file->comp_dir);
11812   return hash;
11813 }
11814
11815 static int
11816 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11817 {
11818   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11819   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11820
11821   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11822     return 0;
11823   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11824     return lhs->comp_dir == rhs->comp_dir;
11825   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11826 }
11827
11828 /* Allocate a hash table for DWO files.  */
11829
11830 static htab_t
11831 allocate_dwo_file_hash_table (struct objfile *objfile)
11832 {
11833   return htab_create_alloc_ex (41,
11834                                hash_dwo_file,
11835                                eq_dwo_file,
11836                                NULL,
11837                                &objfile->objfile_obstack,
11838                                hashtab_obstack_allocate,
11839                                dummy_obstack_deallocate);
11840 }
11841
11842 /* Lookup DWO file DWO_NAME.  */
11843
11844 static void **
11845 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11846                       const char *dwo_name,
11847                       const char *comp_dir)
11848 {
11849   struct dwo_file find_entry;
11850   void **slot;
11851
11852   if (dwarf2_per_objfile->dwo_files == NULL)
11853     dwarf2_per_objfile->dwo_files
11854       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11855
11856   memset (&find_entry, 0, sizeof (find_entry));
11857   find_entry.dwo_name = dwo_name;
11858   find_entry.comp_dir = comp_dir;
11859   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11860
11861   return slot;
11862 }
11863
11864 static hashval_t
11865 hash_dwo_unit (const void *item)
11866 {
11867   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11868
11869   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11870   return dwo_unit->signature;
11871 }
11872
11873 static int
11874 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11875 {
11876   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11877   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11878
11879   /* The signature is assumed to be unique within the DWO file.
11880      So while object file CU dwo_id's always have the value zero,
11881      that's OK, assuming each object file DWO file has only one CU,
11882      and that's the rule for now.  */
11883   return lhs->signature == rhs->signature;
11884 }
11885
11886 /* Allocate a hash table for DWO CUs,TUs.
11887    There is one of these tables for each of CUs,TUs for each DWO file.  */
11888
11889 static htab_t
11890 allocate_dwo_unit_table (struct objfile *objfile)
11891 {
11892   /* Start out with a pretty small number.
11893      Generally DWO files contain only one CU and maybe some TUs.  */
11894   return htab_create_alloc_ex (3,
11895                                hash_dwo_unit,
11896                                eq_dwo_unit,
11897                                NULL,
11898                                &objfile->objfile_obstack,
11899                                hashtab_obstack_allocate,
11900                                dummy_obstack_deallocate);
11901 }
11902
11903 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11904
11905 struct create_dwo_cu_data
11906 {
11907   struct dwo_file *dwo_file;
11908   struct dwo_unit dwo_unit;
11909 };
11910
11911 /* die_reader_func for create_dwo_cu.  */
11912
11913 static void
11914 create_dwo_cu_reader (const struct die_reader_specs *reader,
11915                       const gdb_byte *info_ptr,
11916                       struct die_info *comp_unit_die,
11917                       int has_children,
11918                       void *datap)
11919 {
11920   struct dwarf2_cu *cu = reader->cu;
11921   sect_offset sect_off = cu->per_cu->sect_off;
11922   struct dwarf2_section_info *section = cu->per_cu->section;
11923   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11924   struct dwo_file *dwo_file = data->dwo_file;
11925   struct dwo_unit *dwo_unit = &data->dwo_unit;
11926   struct attribute *attr;
11927
11928   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11929   if (attr == NULL)
11930     {
11931       complaint (&symfile_complaints,
11932                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11933                    " its dwo_id [in module %s]"),
11934                  to_underlying (sect_off), dwo_file->dwo_name);
11935       return;
11936     }
11937
11938   dwo_unit->dwo_file = dwo_file;
11939   dwo_unit->signature = DW_UNSND (attr);
11940   dwo_unit->section = section;
11941   dwo_unit->sect_off = sect_off;
11942   dwo_unit->length = cu->per_cu->length;
11943
11944   if (dwarf_read_debug)
11945     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11946                         to_underlying (sect_off),
11947                         hex_string (dwo_unit->signature));
11948 }
11949
11950 /* Create the dwo_units for the CUs in a DWO_FILE.
11951    Note: This function processes DWO files only, not DWP files.  */
11952
11953 static void
11954 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11955                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11956                        htab_t &cus_htab)
11957 {
11958   struct objfile *objfile = dwarf2_per_objfile->objfile;
11959   const gdb_byte *info_ptr, *end_ptr;
11960
11961   dwarf2_read_section (objfile, &section);
11962   info_ptr = section.buffer;
11963
11964   if (info_ptr == NULL)
11965     return;
11966
11967   if (dwarf_read_debug)
11968     {
11969       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11970                           get_section_name (&section),
11971                           get_section_file_name (&section));
11972     }
11973
11974   end_ptr = info_ptr + section.size;
11975   while (info_ptr < end_ptr)
11976     {
11977       struct dwarf2_per_cu_data per_cu;
11978       struct create_dwo_cu_data create_dwo_cu_data;
11979       struct dwo_unit *dwo_unit;
11980       void **slot;
11981       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11982
11983       memset (&create_dwo_cu_data.dwo_unit, 0,
11984               sizeof (create_dwo_cu_data.dwo_unit));
11985       memset (&per_cu, 0, sizeof (per_cu));
11986       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11987       per_cu.is_debug_types = 0;
11988       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11989       per_cu.section = &section;
11990       create_dwo_cu_data.dwo_file = &dwo_file;
11991
11992       init_cutu_and_read_dies_no_follow (
11993           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11994       info_ptr += per_cu.length;
11995
11996       // If the unit could not be parsed, skip it.
11997       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11998         continue;
11999
12000       if (cus_htab == NULL)
12001         cus_htab = allocate_dwo_unit_table (objfile);
12002
12003       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12004       *dwo_unit = create_dwo_cu_data.dwo_unit;
12005       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12006       gdb_assert (slot != NULL);
12007       if (*slot != NULL)
12008         {
12009           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12010           sect_offset dup_sect_off = dup_cu->sect_off;
12011
12012           complaint (&symfile_complaints,
12013                      _("debug cu entry at offset 0x%x is duplicate to"
12014                        " the entry at offset 0x%x, signature %s"),
12015                      to_underlying (sect_off), to_underlying (dup_sect_off),
12016                      hex_string (dwo_unit->signature));
12017         }
12018       *slot = (void *)dwo_unit;
12019     }
12020 }
12021
12022 /* DWP file .debug_{cu,tu}_index section format:
12023    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12024
12025    DWP Version 1:
12026
12027    Both index sections have the same format, and serve to map a 64-bit
12028    signature to a set of section numbers.  Each section begins with a header,
12029    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12030    indexes, and a pool of 32-bit section numbers.  The index sections will be
12031    aligned at 8-byte boundaries in the file.
12032
12033    The index section header consists of:
12034
12035     V, 32 bit version number
12036     -, 32 bits unused
12037     N, 32 bit number of compilation units or type units in the index
12038     M, 32 bit number of slots in the hash table
12039
12040    Numbers are recorded using the byte order of the application binary.
12041
12042    The hash table begins at offset 16 in the section, and consists of an array
12043    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12044    order of the application binary).  Unused slots in the hash table are 0.
12045    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12046
12047    The parallel table begins immediately after the hash table
12048    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12049    array of 32-bit indexes (using the byte order of the application binary),
12050    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12051    table contains a 32-bit index into the pool of section numbers.  For unused
12052    hash table slots, the corresponding entry in the parallel table will be 0.
12053
12054    The pool of section numbers begins immediately following the hash table
12055    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12056    section numbers consists of an array of 32-bit words (using the byte order
12057    of the application binary).  Each item in the array is indexed starting
12058    from 0.  The hash table entry provides the index of the first section
12059    number in the set.  Additional section numbers in the set follow, and the
12060    set is terminated by a 0 entry (section number 0 is not used in ELF).
12061
12062    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12063    section must be the first entry in the set, and the .debug_abbrev.dwo must
12064    be the second entry. Other members of the set may follow in any order.
12065
12066    ---
12067
12068    DWP Version 2:
12069
12070    DWP Version 2 combines all the .debug_info, etc. sections into one,
12071    and the entries in the index tables are now offsets into these sections.
12072    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12073    section.
12074
12075    Index Section Contents:
12076     Header
12077     Hash Table of Signatures   dwp_hash_table.hash_table
12078     Parallel Table of Indices  dwp_hash_table.unit_table
12079     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12080     Table of Section Sizes     dwp_hash_table.v2.sizes
12081
12082    The index section header consists of:
12083
12084     V, 32 bit version number
12085     L, 32 bit number of columns in the table of section offsets
12086     N, 32 bit number of compilation units or type units in the index
12087     M, 32 bit number of slots in the hash table
12088
12089    Numbers are recorded using the byte order of the application binary.
12090
12091    The hash table has the same format as version 1.
12092    The parallel table of indices has the same format as version 1,
12093    except that the entries are origin-1 indices into the table of sections
12094    offsets and the table of section sizes.
12095
12096    The table of offsets begins immediately following the parallel table
12097    (at offset 16 + 12 * M from the beginning of the section).  The table is
12098    a two-dimensional array of 32-bit words (using the byte order of the
12099    application binary), with L columns and N+1 rows, in row-major order.
12100    Each row in the array is indexed starting from 0.  The first row provides
12101    a key to the remaining rows: each column in this row provides an identifier
12102    for a debug section, and the offsets in the same column of subsequent rows
12103    refer to that section.  The section identifiers are:
12104
12105     DW_SECT_INFO         1  .debug_info.dwo
12106     DW_SECT_TYPES        2  .debug_types.dwo
12107     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12108     DW_SECT_LINE         4  .debug_line.dwo
12109     DW_SECT_LOC          5  .debug_loc.dwo
12110     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12111     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12112     DW_SECT_MACRO        8  .debug_macro.dwo
12113
12114    The offsets provided by the CU and TU index sections are the base offsets
12115    for the contributions made by each CU or TU to the corresponding section
12116    in the package file.  Each CU and TU header contains an abbrev_offset
12117    field, used to find the abbreviations table for that CU or TU within the
12118    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12119    be interpreted as relative to the base offset given in the index section.
12120    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12121    should be interpreted as relative to the base offset for .debug_line.dwo,
12122    and offsets into other debug sections obtained from DWARF attributes should
12123    also be interpreted as relative to the corresponding base offset.
12124
12125    The table of sizes begins immediately following the table of offsets.
12126    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12127    with L columns and N rows, in row-major order.  Each row in the array is
12128    indexed starting from 1 (row 0 is shared by the two tables).
12129
12130    ---
12131
12132    Hash table lookup is handled the same in version 1 and 2:
12133
12134    We assume that N and M will not exceed 2^32 - 1.
12135    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12136
12137    Given a 64-bit compilation unit signature or a type signature S, an entry
12138    in the hash table is located as follows:
12139
12140    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12141       the low-order k bits all set to 1.
12142
12143    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12144
12145    3) If the hash table entry at index H matches the signature, use that
12146       entry.  If the hash table entry at index H is unused (all zeroes),
12147       terminate the search: the signature is not present in the table.
12148
12149    4) Let H = (H + H') modulo M. Repeat at Step 3.
12150
12151    Because M > N and H' and M are relatively prime, the search is guaranteed
12152    to stop at an unused slot or find the match.  */
12153
12154 /* Create a hash table to map DWO IDs to their CU/TU entry in
12155    .debug_{info,types}.dwo in DWP_FILE.
12156    Returns NULL if there isn't one.
12157    Note: This function processes DWP files only, not DWO files.  */
12158
12159 static struct dwp_hash_table *
12160 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12161                        struct dwp_file *dwp_file, int is_debug_types)
12162 {
12163   struct objfile *objfile = dwarf2_per_objfile->objfile;
12164   bfd *dbfd = dwp_file->dbfd;
12165   const gdb_byte *index_ptr, *index_end;
12166   struct dwarf2_section_info *index;
12167   uint32_t version, nr_columns, nr_units, nr_slots;
12168   struct dwp_hash_table *htab;
12169
12170   if (is_debug_types)
12171     index = &dwp_file->sections.tu_index;
12172   else
12173     index = &dwp_file->sections.cu_index;
12174
12175   if (dwarf2_section_empty_p (index))
12176     return NULL;
12177   dwarf2_read_section (objfile, index);
12178
12179   index_ptr = index->buffer;
12180   index_end = index_ptr + index->size;
12181
12182   version = read_4_bytes (dbfd, index_ptr);
12183   index_ptr += 4;
12184   if (version == 2)
12185     nr_columns = read_4_bytes (dbfd, index_ptr);
12186   else
12187     nr_columns = 0;
12188   index_ptr += 4;
12189   nr_units = read_4_bytes (dbfd, index_ptr);
12190   index_ptr += 4;
12191   nr_slots = read_4_bytes (dbfd, index_ptr);
12192   index_ptr += 4;
12193
12194   if (version != 1 && version != 2)
12195     {
12196       error (_("Dwarf Error: unsupported DWP file version (%s)"
12197                " [in module %s]"),
12198              pulongest (version), dwp_file->name);
12199     }
12200   if (nr_slots != (nr_slots & -nr_slots))
12201     {
12202       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12203                " is not power of 2 [in module %s]"),
12204              pulongest (nr_slots), dwp_file->name);
12205     }
12206
12207   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12208   htab->version = version;
12209   htab->nr_columns = nr_columns;
12210   htab->nr_units = nr_units;
12211   htab->nr_slots = nr_slots;
12212   htab->hash_table = index_ptr;
12213   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12214
12215   /* Exit early if the table is empty.  */
12216   if (nr_slots == 0 || nr_units == 0
12217       || (version == 2 && nr_columns == 0))
12218     {
12219       /* All must be zero.  */
12220       if (nr_slots != 0 || nr_units != 0
12221           || (version == 2 && nr_columns != 0))
12222         {
12223           complaint (&symfile_complaints,
12224                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12225                        " all zero [in modules %s]"),
12226                      dwp_file->name);
12227         }
12228       return htab;
12229     }
12230
12231   if (version == 1)
12232     {
12233       htab->section_pool.v1.indices =
12234         htab->unit_table + sizeof (uint32_t) * nr_slots;
12235       /* It's harder to decide whether the section is too small in v1.
12236          V1 is deprecated anyway so we punt.  */
12237     }
12238   else
12239     {
12240       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12241       int *ids = htab->section_pool.v2.section_ids;
12242       /* Reverse map for error checking.  */
12243       int ids_seen[DW_SECT_MAX + 1];
12244       int i;
12245
12246       if (nr_columns < 2)
12247         {
12248           error (_("Dwarf Error: bad DWP hash table, too few columns"
12249                    " in section table [in module %s]"),
12250                  dwp_file->name);
12251         }
12252       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12253         {
12254           error (_("Dwarf Error: bad DWP hash table, too many columns"
12255                    " in section table [in module %s]"),
12256                  dwp_file->name);
12257         }
12258       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12259       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12260       for (i = 0; i < nr_columns; ++i)
12261         {
12262           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12263
12264           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12265             {
12266               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12267                        " in section table [in module %s]"),
12268                      id, dwp_file->name);
12269             }
12270           if (ids_seen[id] != -1)
12271             {
12272               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12273                        " id %d in section table [in module %s]"),
12274                      id, dwp_file->name);
12275             }
12276           ids_seen[id] = i;
12277           ids[i] = id;
12278         }
12279       /* Must have exactly one info or types section.  */
12280       if (((ids_seen[DW_SECT_INFO] != -1)
12281            + (ids_seen[DW_SECT_TYPES] != -1))
12282           != 1)
12283         {
12284           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12285                    " DWO info/types section [in module %s]"),
12286                  dwp_file->name);
12287         }
12288       /* Must have an abbrev section.  */
12289       if (ids_seen[DW_SECT_ABBREV] == -1)
12290         {
12291           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12292                    " section [in module %s]"),
12293                  dwp_file->name);
12294         }
12295       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12296       htab->section_pool.v2.sizes =
12297         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12298                                          * nr_units * nr_columns);
12299       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12300                                           * nr_units * nr_columns))
12301           > index_end)
12302         {
12303           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12304                    " [in module %s]"),
12305                  dwp_file->name);
12306         }
12307     }
12308
12309   return htab;
12310 }
12311
12312 /* Update SECTIONS with the data from SECTP.
12313
12314    This function is like the other "locate" section routines that are
12315    passed to bfd_map_over_sections, but in this context the sections to
12316    read comes from the DWP V1 hash table, not the full ELF section table.
12317
12318    The result is non-zero for success, or zero if an error was found.  */
12319
12320 static int
12321 locate_v1_virtual_dwo_sections (asection *sectp,
12322                                 struct virtual_v1_dwo_sections *sections)
12323 {
12324   const struct dwop_section_names *names = &dwop_section_names;
12325
12326   if (section_is_p (sectp->name, &names->abbrev_dwo))
12327     {
12328       /* There can be only one.  */
12329       if (sections->abbrev.s.section != NULL)
12330         return 0;
12331       sections->abbrev.s.section = sectp;
12332       sections->abbrev.size = bfd_get_section_size (sectp);
12333     }
12334   else if (section_is_p (sectp->name, &names->info_dwo)
12335            || section_is_p (sectp->name, &names->types_dwo))
12336     {
12337       /* There can be only one.  */
12338       if (sections->info_or_types.s.section != NULL)
12339         return 0;
12340       sections->info_or_types.s.section = sectp;
12341       sections->info_or_types.size = bfd_get_section_size (sectp);
12342     }
12343   else if (section_is_p (sectp->name, &names->line_dwo))
12344     {
12345       /* There can be only one.  */
12346       if (sections->line.s.section != NULL)
12347         return 0;
12348       sections->line.s.section = sectp;
12349       sections->line.size = bfd_get_section_size (sectp);
12350     }
12351   else if (section_is_p (sectp->name, &names->loc_dwo))
12352     {
12353       /* There can be only one.  */
12354       if (sections->loc.s.section != NULL)
12355         return 0;
12356       sections->loc.s.section = sectp;
12357       sections->loc.size = bfd_get_section_size (sectp);
12358     }
12359   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12360     {
12361       /* There can be only one.  */
12362       if (sections->macinfo.s.section != NULL)
12363         return 0;
12364       sections->macinfo.s.section = sectp;
12365       sections->macinfo.size = bfd_get_section_size (sectp);
12366     }
12367   else if (section_is_p (sectp->name, &names->macro_dwo))
12368     {
12369       /* There can be only one.  */
12370       if (sections->macro.s.section != NULL)
12371         return 0;
12372       sections->macro.s.section = sectp;
12373       sections->macro.size = bfd_get_section_size (sectp);
12374     }
12375   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12376     {
12377       /* There can be only one.  */
12378       if (sections->str_offsets.s.section != NULL)
12379         return 0;
12380       sections->str_offsets.s.section = sectp;
12381       sections->str_offsets.size = bfd_get_section_size (sectp);
12382     }
12383   else
12384     {
12385       /* No other kind of section is valid.  */
12386       return 0;
12387     }
12388
12389   return 1;
12390 }
12391
12392 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12393    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12394    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12395    This is for DWP version 1 files.  */
12396
12397 static struct dwo_unit *
12398 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12399                            struct dwp_file *dwp_file,
12400                            uint32_t unit_index,
12401                            const char *comp_dir,
12402                            ULONGEST signature, int is_debug_types)
12403 {
12404   struct objfile *objfile = dwarf2_per_objfile->objfile;
12405   const struct dwp_hash_table *dwp_htab =
12406     is_debug_types ? dwp_file->tus : dwp_file->cus;
12407   bfd *dbfd = dwp_file->dbfd;
12408   const char *kind = is_debug_types ? "TU" : "CU";
12409   struct dwo_file *dwo_file;
12410   struct dwo_unit *dwo_unit;
12411   struct virtual_v1_dwo_sections sections;
12412   void **dwo_file_slot;
12413   int i;
12414
12415   gdb_assert (dwp_file->version == 1);
12416
12417   if (dwarf_read_debug)
12418     {
12419       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12420                           kind,
12421                           pulongest (unit_index), hex_string (signature),
12422                           dwp_file->name);
12423     }
12424
12425   /* Fetch the sections of this DWO unit.
12426      Put a limit on the number of sections we look for so that bad data
12427      doesn't cause us to loop forever.  */
12428
12429 #define MAX_NR_V1_DWO_SECTIONS \
12430   (1 /* .debug_info or .debug_types */ \
12431    + 1 /* .debug_abbrev */ \
12432    + 1 /* .debug_line */ \
12433    + 1 /* .debug_loc */ \
12434    + 1 /* .debug_str_offsets */ \
12435    + 1 /* .debug_macro or .debug_macinfo */ \
12436    + 1 /* trailing zero */)
12437
12438   memset (&sections, 0, sizeof (sections));
12439
12440   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12441     {
12442       asection *sectp;
12443       uint32_t section_nr =
12444         read_4_bytes (dbfd,
12445                       dwp_htab->section_pool.v1.indices
12446                       + (unit_index + i) * sizeof (uint32_t));
12447
12448       if (section_nr == 0)
12449         break;
12450       if (section_nr >= dwp_file->num_sections)
12451         {
12452           error (_("Dwarf Error: bad DWP hash table, section number too large"
12453                    " [in module %s]"),
12454                  dwp_file->name);
12455         }
12456
12457       sectp = dwp_file->elf_sections[section_nr];
12458       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12459         {
12460           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12461                    " [in module %s]"),
12462                  dwp_file->name);
12463         }
12464     }
12465
12466   if (i < 2
12467       || dwarf2_section_empty_p (&sections.info_or_types)
12468       || dwarf2_section_empty_p (&sections.abbrev))
12469     {
12470       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12471                " [in module %s]"),
12472              dwp_file->name);
12473     }
12474   if (i == MAX_NR_V1_DWO_SECTIONS)
12475     {
12476       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12477                " [in module %s]"),
12478              dwp_file->name);
12479     }
12480
12481   /* It's easier for the rest of the code if we fake a struct dwo_file and
12482      have dwo_unit "live" in that.  At least for now.
12483
12484      The DWP file can be made up of a random collection of CUs and TUs.
12485      However, for each CU + set of TUs that came from the same original DWO
12486      file, we can combine them back into a virtual DWO file to save space
12487      (fewer struct dwo_file objects to allocate).  Remember that for really
12488      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12489
12490   std::string virtual_dwo_name =
12491     string_printf ("virtual-dwo/%d-%d-%d-%d",
12492                    get_section_id (&sections.abbrev),
12493                    get_section_id (&sections.line),
12494                    get_section_id (&sections.loc),
12495                    get_section_id (&sections.str_offsets));
12496   /* Can we use an existing virtual DWO file?  */
12497   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12498                                         virtual_dwo_name.c_str (),
12499                                         comp_dir);
12500   /* Create one if necessary.  */
12501   if (*dwo_file_slot == NULL)
12502     {
12503       if (dwarf_read_debug)
12504         {
12505           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12506                               virtual_dwo_name.c_str ());
12507         }
12508       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12509       dwo_file->dwo_name
12510         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12511                                         virtual_dwo_name.c_str (),
12512                                         virtual_dwo_name.size ());
12513       dwo_file->comp_dir = comp_dir;
12514       dwo_file->sections.abbrev = sections.abbrev;
12515       dwo_file->sections.line = sections.line;
12516       dwo_file->sections.loc = sections.loc;
12517       dwo_file->sections.macinfo = sections.macinfo;
12518       dwo_file->sections.macro = sections.macro;
12519       dwo_file->sections.str_offsets = sections.str_offsets;
12520       /* The "str" section is global to the entire DWP file.  */
12521       dwo_file->sections.str = dwp_file->sections.str;
12522       /* The info or types section is assigned below to dwo_unit,
12523          there's no need to record it in dwo_file.
12524          Also, we can't simply record type sections in dwo_file because
12525          we record a pointer into the vector in dwo_unit.  As we collect more
12526          types we'll grow the vector and eventually have to reallocate space
12527          for it, invalidating all copies of pointers into the previous
12528          contents.  */
12529       *dwo_file_slot = dwo_file;
12530     }
12531   else
12532     {
12533       if (dwarf_read_debug)
12534         {
12535           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12536                               virtual_dwo_name.c_str ());
12537         }
12538       dwo_file = (struct dwo_file *) *dwo_file_slot;
12539     }
12540
12541   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12542   dwo_unit->dwo_file = dwo_file;
12543   dwo_unit->signature = signature;
12544   dwo_unit->section =
12545     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12546   *dwo_unit->section = sections.info_or_types;
12547   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12548
12549   return dwo_unit;
12550 }
12551
12552 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12553    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12554    piece within that section used by a TU/CU, return a virtual section
12555    of just that piece.  */
12556
12557 static struct dwarf2_section_info
12558 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12559                        struct dwarf2_section_info *section,
12560                        bfd_size_type offset, bfd_size_type size)
12561 {
12562   struct dwarf2_section_info result;
12563   asection *sectp;
12564
12565   gdb_assert (section != NULL);
12566   gdb_assert (!section->is_virtual);
12567
12568   memset (&result, 0, sizeof (result));
12569   result.s.containing_section = section;
12570   result.is_virtual = 1;
12571
12572   if (size == 0)
12573     return result;
12574
12575   sectp = get_section_bfd_section (section);
12576
12577   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12578      bounds of the real section.  This is a pretty-rare event, so just
12579      flag an error (easier) instead of a warning and trying to cope.  */
12580   if (sectp == NULL
12581       || offset + size > bfd_get_section_size (sectp))
12582     {
12583       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12584                " in section %s [in module %s]"),
12585              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12586              objfile_name (dwarf2_per_objfile->objfile));
12587     }
12588
12589   result.virtual_offset = offset;
12590   result.size = size;
12591   return result;
12592 }
12593
12594 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12595    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12596    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12597    This is for DWP version 2 files.  */
12598
12599 static struct dwo_unit *
12600 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12601                            struct dwp_file *dwp_file,
12602                            uint32_t unit_index,
12603                            const char *comp_dir,
12604                            ULONGEST signature, int is_debug_types)
12605 {
12606   struct objfile *objfile = dwarf2_per_objfile->objfile;
12607   const struct dwp_hash_table *dwp_htab =
12608     is_debug_types ? dwp_file->tus : dwp_file->cus;
12609   bfd *dbfd = dwp_file->dbfd;
12610   const char *kind = is_debug_types ? "TU" : "CU";
12611   struct dwo_file *dwo_file;
12612   struct dwo_unit *dwo_unit;
12613   struct virtual_v2_dwo_sections sections;
12614   void **dwo_file_slot;
12615   int i;
12616
12617   gdb_assert (dwp_file->version == 2);
12618
12619   if (dwarf_read_debug)
12620     {
12621       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12622                           kind,
12623                           pulongest (unit_index), hex_string (signature),
12624                           dwp_file->name);
12625     }
12626
12627   /* Fetch the section offsets of this DWO unit.  */
12628
12629   memset (&sections, 0, sizeof (sections));
12630
12631   for (i = 0; i < dwp_htab->nr_columns; ++i)
12632     {
12633       uint32_t offset = read_4_bytes (dbfd,
12634                                       dwp_htab->section_pool.v2.offsets
12635                                       + (((unit_index - 1) * dwp_htab->nr_columns
12636                                           + i)
12637                                          * sizeof (uint32_t)));
12638       uint32_t size = read_4_bytes (dbfd,
12639                                     dwp_htab->section_pool.v2.sizes
12640                                     + (((unit_index - 1) * dwp_htab->nr_columns
12641                                         + i)
12642                                        * sizeof (uint32_t)));
12643
12644       switch (dwp_htab->section_pool.v2.section_ids[i])
12645         {
12646         case DW_SECT_INFO:
12647         case DW_SECT_TYPES:
12648           sections.info_or_types_offset = offset;
12649           sections.info_or_types_size = size;
12650           break;
12651         case DW_SECT_ABBREV:
12652           sections.abbrev_offset = offset;
12653           sections.abbrev_size = size;
12654           break;
12655         case DW_SECT_LINE:
12656           sections.line_offset = offset;
12657           sections.line_size = size;
12658           break;
12659         case DW_SECT_LOC:
12660           sections.loc_offset = offset;
12661           sections.loc_size = size;
12662           break;
12663         case DW_SECT_STR_OFFSETS:
12664           sections.str_offsets_offset = offset;
12665           sections.str_offsets_size = size;
12666           break;
12667         case DW_SECT_MACINFO:
12668           sections.macinfo_offset = offset;
12669           sections.macinfo_size = size;
12670           break;
12671         case DW_SECT_MACRO:
12672           sections.macro_offset = offset;
12673           sections.macro_size = size;
12674           break;
12675         }
12676     }
12677
12678   /* It's easier for the rest of the code if we fake a struct dwo_file and
12679      have dwo_unit "live" in that.  At least for now.
12680
12681      The DWP file can be made up of a random collection of CUs and TUs.
12682      However, for each CU + set of TUs that came from the same original DWO
12683      file, we can combine them back into a virtual DWO file to save space
12684      (fewer struct dwo_file objects to allocate).  Remember that for really
12685      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12686
12687   std::string virtual_dwo_name =
12688     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12689                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12690                    (long) (sections.line_size ? sections.line_offset : 0),
12691                    (long) (sections.loc_size ? sections.loc_offset : 0),
12692                    (long) (sections.str_offsets_size
12693                            ? sections.str_offsets_offset : 0));
12694   /* Can we use an existing virtual DWO file?  */
12695   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12696                                         virtual_dwo_name.c_str (),
12697                                         comp_dir);
12698   /* Create one if necessary.  */
12699   if (*dwo_file_slot == NULL)
12700     {
12701       if (dwarf_read_debug)
12702         {
12703           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12704                               virtual_dwo_name.c_str ());
12705         }
12706       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12707       dwo_file->dwo_name
12708         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12709                                         virtual_dwo_name.c_str (),
12710                                         virtual_dwo_name.size ());
12711       dwo_file->comp_dir = comp_dir;
12712       dwo_file->sections.abbrev =
12713         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12714                                sections.abbrev_offset, sections.abbrev_size);
12715       dwo_file->sections.line =
12716         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12717                                sections.line_offset, sections.line_size);
12718       dwo_file->sections.loc =
12719         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12720                                sections.loc_offset, sections.loc_size);
12721       dwo_file->sections.macinfo =
12722         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12723                                sections.macinfo_offset, sections.macinfo_size);
12724       dwo_file->sections.macro =
12725         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12726                                sections.macro_offset, sections.macro_size);
12727       dwo_file->sections.str_offsets =
12728         create_dwp_v2_section (dwarf2_per_objfile,
12729                                &dwp_file->sections.str_offsets,
12730                                sections.str_offsets_offset,
12731                                sections.str_offsets_size);
12732       /* The "str" section is global to the entire DWP file.  */
12733       dwo_file->sections.str = dwp_file->sections.str;
12734       /* The info or types section is assigned below to dwo_unit,
12735          there's no need to record it in dwo_file.
12736          Also, we can't simply record type sections in dwo_file because
12737          we record a pointer into the vector in dwo_unit.  As we collect more
12738          types we'll grow the vector and eventually have to reallocate space
12739          for it, invalidating all copies of pointers into the previous
12740          contents.  */
12741       *dwo_file_slot = dwo_file;
12742     }
12743   else
12744     {
12745       if (dwarf_read_debug)
12746         {
12747           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12748                               virtual_dwo_name.c_str ());
12749         }
12750       dwo_file = (struct dwo_file *) *dwo_file_slot;
12751     }
12752
12753   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12754   dwo_unit->dwo_file = dwo_file;
12755   dwo_unit->signature = signature;
12756   dwo_unit->section =
12757     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12758   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12759                                               is_debug_types
12760                                               ? &dwp_file->sections.types
12761                                               : &dwp_file->sections.info,
12762                                               sections.info_or_types_offset,
12763                                               sections.info_or_types_size);
12764   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12765
12766   return dwo_unit;
12767 }
12768
12769 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12770    Returns NULL if the signature isn't found.  */
12771
12772 static struct dwo_unit *
12773 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12774                         struct dwp_file *dwp_file, const char *comp_dir,
12775                         ULONGEST signature, int is_debug_types)
12776 {
12777   const struct dwp_hash_table *dwp_htab =
12778     is_debug_types ? dwp_file->tus : dwp_file->cus;
12779   bfd *dbfd = dwp_file->dbfd;
12780   uint32_t mask = dwp_htab->nr_slots - 1;
12781   uint32_t hash = signature & mask;
12782   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12783   unsigned int i;
12784   void **slot;
12785   struct dwo_unit find_dwo_cu;
12786
12787   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12788   find_dwo_cu.signature = signature;
12789   slot = htab_find_slot (is_debug_types
12790                          ? dwp_file->loaded_tus
12791                          : dwp_file->loaded_cus,
12792                          &find_dwo_cu, INSERT);
12793
12794   if (*slot != NULL)
12795     return (struct dwo_unit *) *slot;
12796
12797   /* Use a for loop so that we don't loop forever on bad debug info.  */
12798   for (i = 0; i < dwp_htab->nr_slots; ++i)
12799     {
12800       ULONGEST signature_in_table;
12801
12802       signature_in_table =
12803         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12804       if (signature_in_table == signature)
12805         {
12806           uint32_t unit_index =
12807             read_4_bytes (dbfd,
12808                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12809
12810           if (dwp_file->version == 1)
12811             {
12812               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12813                                                  dwp_file, unit_index,
12814                                                  comp_dir, signature,
12815                                                  is_debug_types);
12816             }
12817           else
12818             {
12819               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12820                                                  dwp_file, unit_index,
12821                                                  comp_dir, signature,
12822                                                  is_debug_types);
12823             }
12824           return (struct dwo_unit *) *slot;
12825         }
12826       if (signature_in_table == 0)
12827         return NULL;
12828       hash = (hash + hash2) & mask;
12829     }
12830
12831   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12832            " [in module %s]"),
12833          dwp_file->name);
12834 }
12835
12836 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12837    Open the file specified by FILE_NAME and hand it off to BFD for
12838    preliminary analysis.  Return a newly initialized bfd *, which
12839    includes a canonicalized copy of FILE_NAME.
12840    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12841    SEARCH_CWD is true if the current directory is to be searched.
12842    It will be searched before debug-file-directory.
12843    If successful, the file is added to the bfd include table of the
12844    objfile's bfd (see gdb_bfd_record_inclusion).
12845    If unable to find/open the file, return NULL.
12846    NOTE: This function is derived from symfile_bfd_open.  */
12847
12848 static gdb_bfd_ref_ptr
12849 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12850                     const char *file_name, int is_dwp, int search_cwd)
12851 {
12852   int desc, flags;
12853   char *absolute_name;
12854   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12855      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12856      to debug_file_directory.  */
12857   char *search_path;
12858   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12859
12860   if (search_cwd)
12861     {
12862       if (*debug_file_directory != '\0')
12863         search_path = concat (".", dirname_separator_string,
12864                               debug_file_directory, (char *) NULL);
12865       else
12866         search_path = xstrdup (".");
12867     }
12868   else
12869     search_path = xstrdup (debug_file_directory);
12870
12871   flags = OPF_RETURN_REALPATH;
12872   if (is_dwp)
12873     flags |= OPF_SEARCH_IN_PATH;
12874   desc = openp (search_path, flags, file_name,
12875                 O_RDONLY | O_BINARY, &absolute_name);
12876   xfree (search_path);
12877   if (desc < 0)
12878     return NULL;
12879
12880   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12881   xfree (absolute_name);
12882   if (sym_bfd == NULL)
12883     return NULL;
12884   bfd_set_cacheable (sym_bfd.get (), 1);
12885
12886   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12887     return NULL;
12888
12889   /* Success.  Record the bfd as having been included by the objfile's bfd.
12890      This is important because things like demangled_names_hash lives in the
12891      objfile's per_bfd space and may have references to things like symbol
12892      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12893   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12894
12895   return sym_bfd;
12896 }
12897
12898 /* Try to open DWO file FILE_NAME.
12899    COMP_DIR is the DW_AT_comp_dir attribute.
12900    The result is the bfd handle of the file.
12901    If there is a problem finding or opening the file, return NULL.
12902    Upon success, the canonicalized path of the file is stored in the bfd,
12903    same as symfile_bfd_open.  */
12904
12905 static gdb_bfd_ref_ptr
12906 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12907                const char *file_name, const char *comp_dir)
12908 {
12909   if (IS_ABSOLUTE_PATH (file_name))
12910     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12911                                0 /*is_dwp*/, 0 /*search_cwd*/);
12912
12913   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12914
12915   if (comp_dir != NULL)
12916     {
12917       char *path_to_try = concat (comp_dir, SLASH_STRING,
12918                                   file_name, (char *) NULL);
12919
12920       /* NOTE: If comp_dir is a relative path, this will also try the
12921          search path, which seems useful.  */
12922       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12923                                                 path_to_try,
12924                                                 0 /*is_dwp*/,
12925                                                 1 /*search_cwd*/));
12926       xfree (path_to_try);
12927       if (abfd != NULL)
12928         return abfd;
12929     }
12930
12931   /* That didn't work, try debug-file-directory, which, despite its name,
12932      is a list of paths.  */
12933
12934   if (*debug_file_directory == '\0')
12935     return NULL;
12936
12937   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12938                              0 /*is_dwp*/, 1 /*search_cwd*/);
12939 }
12940
12941 /* This function is mapped across the sections and remembers the offset and
12942    size of each of the DWO debugging sections we are interested in.  */
12943
12944 static void
12945 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12946 {
12947   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12948   const struct dwop_section_names *names = &dwop_section_names;
12949
12950   if (section_is_p (sectp->name, &names->abbrev_dwo))
12951     {
12952       dwo_sections->abbrev.s.section = sectp;
12953       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12954     }
12955   else if (section_is_p (sectp->name, &names->info_dwo))
12956     {
12957       dwo_sections->info.s.section = sectp;
12958       dwo_sections->info.size = bfd_get_section_size (sectp);
12959     }
12960   else if (section_is_p (sectp->name, &names->line_dwo))
12961     {
12962       dwo_sections->line.s.section = sectp;
12963       dwo_sections->line.size = bfd_get_section_size (sectp);
12964     }
12965   else if (section_is_p (sectp->name, &names->loc_dwo))
12966     {
12967       dwo_sections->loc.s.section = sectp;
12968       dwo_sections->loc.size = bfd_get_section_size (sectp);
12969     }
12970   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12971     {
12972       dwo_sections->macinfo.s.section = sectp;
12973       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12974     }
12975   else if (section_is_p (sectp->name, &names->macro_dwo))
12976     {
12977       dwo_sections->macro.s.section = sectp;
12978       dwo_sections->macro.size = bfd_get_section_size (sectp);
12979     }
12980   else if (section_is_p (sectp->name, &names->str_dwo))
12981     {
12982       dwo_sections->str.s.section = sectp;
12983       dwo_sections->str.size = bfd_get_section_size (sectp);
12984     }
12985   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12986     {
12987       dwo_sections->str_offsets.s.section = sectp;
12988       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12989     }
12990   else if (section_is_p (sectp->name, &names->types_dwo))
12991     {
12992       struct dwarf2_section_info type_section;
12993
12994       memset (&type_section, 0, sizeof (type_section));
12995       type_section.s.section = sectp;
12996       type_section.size = bfd_get_section_size (sectp);
12997       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12998                      &type_section);
12999     }
13000 }
13001
13002 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13003    by PER_CU.  This is for the non-DWP case.
13004    The result is NULL if DWO_NAME can't be found.  */
13005
13006 static struct dwo_file *
13007 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13008                         const char *dwo_name, const char *comp_dir)
13009 {
13010   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13011   struct objfile *objfile = dwarf2_per_objfile->objfile;
13012   struct dwo_file *dwo_file;
13013   struct cleanup *cleanups;
13014
13015   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13016   if (dbfd == NULL)
13017     {
13018       if (dwarf_read_debug)
13019         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13020       return NULL;
13021     }
13022   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13023   dwo_file->dwo_name = dwo_name;
13024   dwo_file->comp_dir = comp_dir;
13025   dwo_file->dbfd = dbfd.release ();
13026
13027   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13028   cleanup_data->dwo_file = dwo_file;
13029   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13030
13031   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13032
13033   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13034                          &dwo_file->sections);
13035
13036   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13037                          dwo_file->cus);
13038
13039   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13040                                  dwo_file->sections.types, dwo_file->tus);
13041
13042   discard_cleanups (cleanups);
13043
13044   if (dwarf_read_debug)
13045     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13046
13047   return dwo_file;
13048 }
13049
13050 /* This function is mapped across the sections and remembers the offset and
13051    size of each of the DWP debugging sections common to version 1 and 2 that
13052    we are interested in.  */
13053
13054 static void
13055 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13056                                    void *dwp_file_ptr)
13057 {
13058   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13059   const struct dwop_section_names *names = &dwop_section_names;
13060   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13061
13062   /* Record the ELF section number for later lookup: this is what the
13063      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13064   gdb_assert (elf_section_nr < dwp_file->num_sections);
13065   dwp_file->elf_sections[elf_section_nr] = sectp;
13066
13067   /* Look for specific sections that we need.  */
13068   if (section_is_p (sectp->name, &names->str_dwo))
13069     {
13070       dwp_file->sections.str.s.section = sectp;
13071       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13072     }
13073   else if (section_is_p (sectp->name, &names->cu_index))
13074     {
13075       dwp_file->sections.cu_index.s.section = sectp;
13076       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13077     }
13078   else if (section_is_p (sectp->name, &names->tu_index))
13079     {
13080       dwp_file->sections.tu_index.s.section = sectp;
13081       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13082     }
13083 }
13084
13085 /* This function is mapped across the sections and remembers the offset and
13086    size of each of the DWP version 2 debugging sections that we are interested
13087    in.  This is split into a separate function because we don't know if we
13088    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13089
13090 static void
13091 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13092 {
13093   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13094   const struct dwop_section_names *names = &dwop_section_names;
13095   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13096
13097   /* Record the ELF section number for later lookup: this is what the
13098      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13099   gdb_assert (elf_section_nr < dwp_file->num_sections);
13100   dwp_file->elf_sections[elf_section_nr] = sectp;
13101
13102   /* Look for specific sections that we need.  */
13103   if (section_is_p (sectp->name, &names->abbrev_dwo))
13104     {
13105       dwp_file->sections.abbrev.s.section = sectp;
13106       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13107     }
13108   else if (section_is_p (sectp->name, &names->info_dwo))
13109     {
13110       dwp_file->sections.info.s.section = sectp;
13111       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13112     }
13113   else if (section_is_p (sectp->name, &names->line_dwo))
13114     {
13115       dwp_file->sections.line.s.section = sectp;
13116       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13117     }
13118   else if (section_is_p (sectp->name, &names->loc_dwo))
13119     {
13120       dwp_file->sections.loc.s.section = sectp;
13121       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13122     }
13123   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13124     {
13125       dwp_file->sections.macinfo.s.section = sectp;
13126       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13127     }
13128   else if (section_is_p (sectp->name, &names->macro_dwo))
13129     {
13130       dwp_file->sections.macro.s.section = sectp;
13131       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13132     }
13133   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13134     {
13135       dwp_file->sections.str_offsets.s.section = sectp;
13136       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13137     }
13138   else if (section_is_p (sectp->name, &names->types_dwo))
13139     {
13140       dwp_file->sections.types.s.section = sectp;
13141       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13142     }
13143 }
13144
13145 /* Hash function for dwp_file loaded CUs/TUs.  */
13146
13147 static hashval_t
13148 hash_dwp_loaded_cutus (const void *item)
13149 {
13150   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13151
13152   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13153   return dwo_unit->signature;
13154 }
13155
13156 /* Equality function for dwp_file loaded CUs/TUs.  */
13157
13158 static int
13159 eq_dwp_loaded_cutus (const void *a, const void *b)
13160 {
13161   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13162   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13163
13164   return dua->signature == dub->signature;
13165 }
13166
13167 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13168
13169 static htab_t
13170 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13171 {
13172   return htab_create_alloc_ex (3,
13173                                hash_dwp_loaded_cutus,
13174                                eq_dwp_loaded_cutus,
13175                                NULL,
13176                                &objfile->objfile_obstack,
13177                                hashtab_obstack_allocate,
13178                                dummy_obstack_deallocate);
13179 }
13180
13181 /* Try to open DWP file FILE_NAME.
13182    The result is the bfd handle of the file.
13183    If there is a problem finding or opening the file, return NULL.
13184    Upon success, the canonicalized path of the file is stored in the bfd,
13185    same as symfile_bfd_open.  */
13186
13187 static gdb_bfd_ref_ptr
13188 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13189                const char *file_name)
13190 {
13191   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13192                                             1 /*is_dwp*/,
13193                                             1 /*search_cwd*/));
13194   if (abfd != NULL)
13195     return abfd;
13196
13197   /* Work around upstream bug 15652.
13198      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13199      [Whether that's a "bug" is debatable, but it is getting in our way.]
13200      We have no real idea where the dwp file is, because gdb's realpath-ing
13201      of the executable's path may have discarded the needed info.
13202      [IWBN if the dwp file name was recorded in the executable, akin to
13203      .gnu_debuglink, but that doesn't exist yet.]
13204      Strip the directory from FILE_NAME and search again.  */
13205   if (*debug_file_directory != '\0')
13206     {
13207       /* Don't implicitly search the current directory here.
13208          If the user wants to search "." to handle this case,
13209          it must be added to debug-file-directory.  */
13210       return try_open_dwop_file (dwarf2_per_objfile,
13211                                  lbasename (file_name), 1 /*is_dwp*/,
13212                                  0 /*search_cwd*/);
13213     }
13214
13215   return NULL;
13216 }
13217
13218 /* Initialize the use of the DWP file for the current objfile.
13219    By convention the name of the DWP file is ${objfile}.dwp.
13220    The result is NULL if it can't be found.  */
13221
13222 static struct dwp_file *
13223 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13224 {
13225   struct objfile *objfile = dwarf2_per_objfile->objfile;
13226   struct dwp_file *dwp_file;
13227
13228   /* Try to find first .dwp for the binary file before any symbolic links
13229      resolving.  */
13230
13231   /* If the objfile is a debug file, find the name of the real binary
13232      file and get the name of dwp file from there.  */
13233   std::string dwp_name;
13234   if (objfile->separate_debug_objfile_backlink != NULL)
13235     {
13236       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13237       const char *backlink_basename = lbasename (backlink->original_name);
13238
13239       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13240     }
13241   else
13242     dwp_name = objfile->original_name;
13243
13244   dwp_name += ".dwp";
13245
13246   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13247   if (dbfd == NULL
13248       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13249     {
13250       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13251       dwp_name = objfile_name (objfile);
13252       dwp_name += ".dwp";
13253       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13254     }
13255
13256   if (dbfd == NULL)
13257     {
13258       if (dwarf_read_debug)
13259         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13260       return NULL;
13261     }
13262   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13263   dwp_file->name = bfd_get_filename (dbfd.get ());
13264   dwp_file->dbfd = dbfd.release ();
13265
13266   /* +1: section 0 is unused */
13267   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13268   dwp_file->elf_sections =
13269     OBSTACK_CALLOC (&objfile->objfile_obstack,
13270                     dwp_file->num_sections, asection *);
13271
13272   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13273                          dwp_file);
13274
13275   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13276
13277   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13278
13279   /* The DWP file version is stored in the hash table.  Oh well.  */
13280   if (dwp_file->cus && dwp_file->tus
13281       && dwp_file->cus->version != dwp_file->tus->version)
13282     {
13283       /* Technically speaking, we should try to limp along, but this is
13284          pretty bizarre.  We use pulongest here because that's the established
13285          portability solution (e.g, we cannot use %u for uint32_t).  */
13286       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13287                " TU version %s [in DWP file %s]"),
13288              pulongest (dwp_file->cus->version),
13289              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13290     }
13291
13292   if (dwp_file->cus)
13293     dwp_file->version = dwp_file->cus->version;
13294   else if (dwp_file->tus)
13295     dwp_file->version = dwp_file->tus->version;
13296   else
13297     dwp_file->version = 2;
13298
13299   if (dwp_file->version == 2)
13300     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13301                            dwp_file);
13302
13303   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13304   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13305
13306   if (dwarf_read_debug)
13307     {
13308       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13309       fprintf_unfiltered (gdb_stdlog,
13310                           "    %s CUs, %s TUs\n",
13311                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13312                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13313     }
13314
13315   return dwp_file;
13316 }
13317
13318 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13319
13320 static struct dwp_file *
13321 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13322 {
13323   if (! dwarf2_per_objfile->dwp_checked)
13324     {
13325       dwarf2_per_objfile->dwp_file
13326         = open_and_init_dwp_file (dwarf2_per_objfile);
13327       dwarf2_per_objfile->dwp_checked = 1;
13328     }
13329   return dwarf2_per_objfile->dwp_file;
13330 }
13331
13332 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13333    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13334    or in the DWP file for the objfile, referenced by THIS_UNIT.
13335    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13336    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13337
13338    This is called, for example, when wanting to read a variable with a
13339    complex location.  Therefore we don't want to do file i/o for every call.
13340    Therefore we don't want to look for a DWO file on every call.
13341    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13342    then we check if we've already seen DWO_NAME, and only THEN do we check
13343    for a DWO file.
13344
13345    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13346    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13347
13348 static struct dwo_unit *
13349 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13350                  const char *dwo_name, const char *comp_dir,
13351                  ULONGEST signature, int is_debug_types)
13352 {
13353   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13354   struct objfile *objfile = dwarf2_per_objfile->objfile;
13355   const char *kind = is_debug_types ? "TU" : "CU";
13356   void **dwo_file_slot;
13357   struct dwo_file *dwo_file;
13358   struct dwp_file *dwp_file;
13359
13360   /* First see if there's a DWP file.
13361      If we have a DWP file but didn't find the DWO inside it, don't
13362      look for the original DWO file.  It makes gdb behave differently
13363      depending on whether one is debugging in the build tree.  */
13364
13365   dwp_file = get_dwp_file (dwarf2_per_objfile);
13366   if (dwp_file != NULL)
13367     {
13368       const struct dwp_hash_table *dwp_htab =
13369         is_debug_types ? dwp_file->tus : dwp_file->cus;
13370
13371       if (dwp_htab != NULL)
13372         {
13373           struct dwo_unit *dwo_cutu =
13374             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13375                                     signature, is_debug_types);
13376
13377           if (dwo_cutu != NULL)
13378             {
13379               if (dwarf_read_debug)
13380                 {
13381                   fprintf_unfiltered (gdb_stdlog,
13382                                       "Virtual DWO %s %s found: @%s\n",
13383                                       kind, hex_string (signature),
13384                                       host_address_to_string (dwo_cutu));
13385                 }
13386               return dwo_cutu;
13387             }
13388         }
13389     }
13390   else
13391     {
13392       /* No DWP file, look for the DWO file.  */
13393
13394       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13395                                             dwo_name, comp_dir);
13396       if (*dwo_file_slot == NULL)
13397         {
13398           /* Read in the file and build a table of the CUs/TUs it contains.  */
13399           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13400         }
13401       /* NOTE: This will be NULL if unable to open the file.  */
13402       dwo_file = (struct dwo_file *) *dwo_file_slot;
13403
13404       if (dwo_file != NULL)
13405         {
13406           struct dwo_unit *dwo_cutu = NULL;
13407
13408           if (is_debug_types && dwo_file->tus)
13409             {
13410               struct dwo_unit find_dwo_cutu;
13411
13412               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13413               find_dwo_cutu.signature = signature;
13414               dwo_cutu
13415                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13416             }
13417           else if (!is_debug_types && dwo_file->cus)
13418             {
13419               struct dwo_unit find_dwo_cutu;
13420
13421               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13422               find_dwo_cutu.signature = signature;
13423               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13424                                                        &find_dwo_cutu);
13425             }
13426
13427           if (dwo_cutu != NULL)
13428             {
13429               if (dwarf_read_debug)
13430                 {
13431                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13432                                       kind, dwo_name, hex_string (signature),
13433                                       host_address_to_string (dwo_cutu));
13434                 }
13435               return dwo_cutu;
13436             }
13437         }
13438     }
13439
13440   /* We didn't find it.  This could mean a dwo_id mismatch, or
13441      someone deleted the DWO/DWP file, or the search path isn't set up
13442      correctly to find the file.  */
13443
13444   if (dwarf_read_debug)
13445     {
13446       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13447                           kind, dwo_name, hex_string (signature));
13448     }
13449
13450   /* This is a warning and not a complaint because it can be caused by
13451      pilot error (e.g., user accidentally deleting the DWO).  */
13452   {
13453     /* Print the name of the DWP file if we looked there, helps the user
13454        better diagnose the problem.  */
13455     std::string dwp_text;
13456
13457     if (dwp_file != NULL)
13458       dwp_text = string_printf (" [in DWP file %s]",
13459                                 lbasename (dwp_file->name));
13460
13461     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13462                " [in module %s]"),
13463              kind, dwo_name, hex_string (signature),
13464              dwp_text.c_str (),
13465              this_unit->is_debug_types ? "TU" : "CU",
13466              to_underlying (this_unit->sect_off), objfile_name (objfile));
13467   }
13468   return NULL;
13469 }
13470
13471 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13472    See lookup_dwo_cutu_unit for details.  */
13473
13474 static struct dwo_unit *
13475 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13476                       const char *dwo_name, const char *comp_dir,
13477                       ULONGEST signature)
13478 {
13479   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13480 }
13481
13482 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13483    See lookup_dwo_cutu_unit for details.  */
13484
13485 static struct dwo_unit *
13486 lookup_dwo_type_unit (struct signatured_type *this_tu,
13487                       const char *dwo_name, const char *comp_dir)
13488 {
13489   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13490 }
13491
13492 /* Traversal function for queue_and_load_all_dwo_tus.  */
13493
13494 static int
13495 queue_and_load_dwo_tu (void **slot, void *info)
13496 {
13497   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13498   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13499   ULONGEST signature = dwo_unit->signature;
13500   struct signatured_type *sig_type =
13501     lookup_dwo_signatured_type (per_cu->cu, signature);
13502
13503   if (sig_type != NULL)
13504     {
13505       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13506
13507       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13508          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13509          while processing PER_CU.  */
13510       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13511         load_full_type_unit (sig_cu);
13512       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13513     }
13514
13515   return 1;
13516 }
13517
13518 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13519    The DWO may have the only definition of the type, though it may not be
13520    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13521    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13522
13523 static void
13524 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13525 {
13526   struct dwo_unit *dwo_unit;
13527   struct dwo_file *dwo_file;
13528
13529   gdb_assert (!per_cu->is_debug_types);
13530   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13531   gdb_assert (per_cu->cu != NULL);
13532
13533   dwo_unit = per_cu->cu->dwo_unit;
13534   gdb_assert (dwo_unit != NULL);
13535
13536   dwo_file = dwo_unit->dwo_file;
13537   if (dwo_file->tus != NULL)
13538     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13539 }
13540
13541 /* Free all resources associated with DWO_FILE.
13542    Close the DWO file and munmap the sections.
13543    All memory should be on the objfile obstack.  */
13544
13545 static void
13546 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13547 {
13548
13549   /* Note: dbfd is NULL for virtual DWO files.  */
13550   gdb_bfd_unref (dwo_file->dbfd);
13551
13552   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13553 }
13554
13555 /* Wrapper for free_dwo_file for use in cleanups.  */
13556
13557 static void
13558 free_dwo_file_cleanup (void *arg)
13559 {
13560   struct free_dwo_file_cleanup_data *data
13561     = (struct free_dwo_file_cleanup_data *) arg;
13562   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13563
13564   free_dwo_file (data->dwo_file, objfile);
13565
13566   xfree (data);
13567 }
13568
13569 /* Traversal function for free_dwo_files.  */
13570
13571 static int
13572 free_dwo_file_from_slot (void **slot, void *info)
13573 {
13574   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13575   struct objfile *objfile = (struct objfile *) info;
13576
13577   free_dwo_file (dwo_file, objfile);
13578
13579   return 1;
13580 }
13581
13582 /* Free all resources associated with DWO_FILES.  */
13583
13584 static void
13585 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13586 {
13587   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13588 }
13589 \f
13590 /* Read in various DIEs.  */
13591
13592 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13593    Inherit only the children of the DW_AT_abstract_origin DIE not being
13594    already referenced by DW_AT_abstract_origin from the children of the
13595    current DIE.  */
13596
13597 static void
13598 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13599 {
13600   struct die_info *child_die;
13601   sect_offset *offsetp;
13602   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13603   struct die_info *origin_die;
13604   /* Iterator of the ORIGIN_DIE children.  */
13605   struct die_info *origin_child_die;
13606   struct attribute *attr;
13607   struct dwarf2_cu *origin_cu;
13608   struct pending **origin_previous_list_in_scope;
13609
13610   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13611   if (!attr)
13612     return;
13613
13614   /* Note that following die references may follow to a die in a
13615      different cu.  */
13616
13617   origin_cu = cu;
13618   origin_die = follow_die_ref (die, attr, &origin_cu);
13619
13620   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13621      symbols in.  */
13622   origin_previous_list_in_scope = origin_cu->list_in_scope;
13623   origin_cu->list_in_scope = cu->list_in_scope;
13624
13625   if (die->tag != origin_die->tag
13626       && !(die->tag == DW_TAG_inlined_subroutine
13627            && origin_die->tag == DW_TAG_subprogram))
13628     complaint (&symfile_complaints,
13629                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13630                to_underlying (die->sect_off),
13631                to_underlying (origin_die->sect_off));
13632
13633   std::vector<sect_offset> offsets;
13634
13635   for (child_die = die->child;
13636        child_die && child_die->tag;
13637        child_die = sibling_die (child_die))
13638     {
13639       struct die_info *child_origin_die;
13640       struct dwarf2_cu *child_origin_cu;
13641
13642       /* We are trying to process concrete instance entries:
13643          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13644          it's not relevant to our analysis here. i.e. detecting DIEs that are
13645          present in the abstract instance but not referenced in the concrete
13646          one.  */
13647       if (child_die->tag == DW_TAG_call_site
13648           || child_die->tag == DW_TAG_GNU_call_site)
13649         continue;
13650
13651       /* For each CHILD_DIE, find the corresponding child of
13652          ORIGIN_DIE.  If there is more than one layer of
13653          DW_AT_abstract_origin, follow them all; there shouldn't be,
13654          but GCC versions at least through 4.4 generate this (GCC PR
13655          40573).  */
13656       child_origin_die = child_die;
13657       child_origin_cu = cu;
13658       while (1)
13659         {
13660           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13661                               child_origin_cu);
13662           if (attr == NULL)
13663             break;
13664           child_origin_die = follow_die_ref (child_origin_die, attr,
13665                                              &child_origin_cu);
13666         }
13667
13668       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13669          counterpart may exist.  */
13670       if (child_origin_die != child_die)
13671         {
13672           if (child_die->tag != child_origin_die->tag
13673               && !(child_die->tag == DW_TAG_inlined_subroutine
13674                    && child_origin_die->tag == DW_TAG_subprogram))
13675             complaint (&symfile_complaints,
13676                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13677                          "different tags"),
13678                        to_underlying (child_die->sect_off),
13679                        to_underlying (child_origin_die->sect_off));
13680           if (child_origin_die->parent != origin_die)
13681             complaint (&symfile_complaints,
13682                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13683                          "different parents"),
13684                        to_underlying (child_die->sect_off),
13685                        to_underlying (child_origin_die->sect_off));
13686           else
13687             offsets.push_back (child_origin_die->sect_off);
13688         }
13689     }
13690   std::sort (offsets.begin (), offsets.end ());
13691   sect_offset *offsets_end = offsets.data () + offsets.size ();
13692   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13693     if (offsetp[-1] == *offsetp)
13694       complaint (&symfile_complaints,
13695                  _("Multiple children of DIE 0x%x refer "
13696                    "to DIE 0x%x as their abstract origin"),
13697                  to_underlying (die->sect_off), to_underlying (*offsetp));
13698
13699   offsetp = offsets.data ();
13700   origin_child_die = origin_die->child;
13701   while (origin_child_die && origin_child_die->tag)
13702     {
13703       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13704       while (offsetp < offsets_end
13705              && *offsetp < origin_child_die->sect_off)
13706         offsetp++;
13707       if (offsetp >= offsets_end
13708           || *offsetp > origin_child_die->sect_off)
13709         {
13710           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13711              Check whether we're already processing ORIGIN_CHILD_DIE.
13712              This can happen with mutually referenced abstract_origins.
13713              PR 16581.  */
13714           if (!origin_child_die->in_process)
13715             process_die (origin_child_die, origin_cu);
13716         }
13717       origin_child_die = sibling_die (origin_child_die);
13718     }
13719   origin_cu->list_in_scope = origin_previous_list_in_scope;
13720 }
13721
13722 static void
13723 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13724 {
13725   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13726   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13727   struct context_stack *newobj;
13728   CORE_ADDR lowpc;
13729   CORE_ADDR highpc;
13730   struct die_info *child_die;
13731   struct attribute *attr, *call_line, *call_file;
13732   const char *name;
13733   CORE_ADDR baseaddr;
13734   struct block *block;
13735   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13736   std::vector<struct symbol *> template_args;
13737   struct template_symbol *templ_func = NULL;
13738
13739   if (inlined_func)
13740     {
13741       /* If we do not have call site information, we can't show the
13742          caller of this inlined function.  That's too confusing, so
13743          only use the scope for local variables.  */
13744       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13745       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13746       if (call_line == NULL || call_file == NULL)
13747         {
13748           read_lexical_block_scope (die, cu);
13749           return;
13750         }
13751     }
13752
13753   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13754
13755   name = dwarf2_name (die, cu);
13756
13757   /* Ignore functions with missing or empty names.  These are actually
13758      illegal according to the DWARF standard.  */
13759   if (name == NULL)
13760     {
13761       complaint (&symfile_complaints,
13762                  _("missing name for subprogram DIE at %d"),
13763                  to_underlying (die->sect_off));
13764       return;
13765     }
13766
13767   /* Ignore functions with missing or invalid low and high pc attributes.  */
13768   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13769       <= PC_BOUNDS_INVALID)
13770     {
13771       attr = dwarf2_attr (die, DW_AT_external, cu);
13772       if (!attr || !DW_UNSND (attr))
13773         complaint (&symfile_complaints,
13774                    _("cannot get low and high bounds "
13775                      "for subprogram DIE at %d"),
13776                    to_underlying (die->sect_off));
13777       return;
13778     }
13779
13780   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13781   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13782
13783   /* If we have any template arguments, then we must allocate a
13784      different sort of symbol.  */
13785   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13786     {
13787       if (child_die->tag == DW_TAG_template_type_param
13788           || child_die->tag == DW_TAG_template_value_param)
13789         {
13790           templ_func = allocate_template_symbol (objfile);
13791           templ_func->subclass = SYMBOL_TEMPLATE;
13792           break;
13793         }
13794     }
13795
13796   newobj = push_context (0, lowpc);
13797   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13798                              (struct symbol *) templ_func);
13799
13800   /* If there is a location expression for DW_AT_frame_base, record
13801      it.  */
13802   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13803   if (attr)
13804     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13805
13806   /* If there is a location for the static link, record it.  */
13807   newobj->static_link = NULL;
13808   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13809   if (attr)
13810     {
13811       newobj->static_link
13812         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13813       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13814     }
13815
13816   cu->list_in_scope = &local_symbols;
13817
13818   if (die->child != NULL)
13819     {
13820       child_die = die->child;
13821       while (child_die && child_die->tag)
13822         {
13823           if (child_die->tag == DW_TAG_template_type_param
13824               || child_die->tag == DW_TAG_template_value_param)
13825             {
13826               struct symbol *arg = new_symbol (child_die, NULL, cu);
13827
13828               if (arg != NULL)
13829                 template_args.push_back (arg);
13830             }
13831           else
13832             process_die (child_die, cu);
13833           child_die = sibling_die (child_die);
13834         }
13835     }
13836
13837   inherit_abstract_dies (die, cu);
13838
13839   /* If we have a DW_AT_specification, we might need to import using
13840      directives from the context of the specification DIE.  See the
13841      comment in determine_prefix.  */
13842   if (cu->language == language_cplus
13843       && dwarf2_attr (die, DW_AT_specification, cu))
13844     {
13845       struct dwarf2_cu *spec_cu = cu;
13846       struct die_info *spec_die = die_specification (die, &spec_cu);
13847
13848       while (spec_die)
13849         {
13850           child_die = spec_die->child;
13851           while (child_die && child_die->tag)
13852             {
13853               if (child_die->tag == DW_TAG_imported_module)
13854                 process_die (child_die, spec_cu);
13855               child_die = sibling_die (child_die);
13856             }
13857
13858           /* In some cases, GCC generates specification DIEs that
13859              themselves contain DW_AT_specification attributes.  */
13860           spec_die = die_specification (spec_die, &spec_cu);
13861         }
13862     }
13863
13864   newobj = pop_context ();
13865   /* Make a block for the local symbols within.  */
13866   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13867                         newobj->static_link, lowpc, highpc);
13868
13869   /* For C++, set the block's scope.  */
13870   if ((cu->language == language_cplus
13871        || cu->language == language_fortran
13872        || cu->language == language_d
13873        || cu->language == language_rust)
13874       && cu->processing_has_namespace_info)
13875     block_set_scope (block, determine_prefix (die, cu),
13876                      &objfile->objfile_obstack);
13877
13878   /* If we have address ranges, record them.  */
13879   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13880
13881   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13882
13883   /* Attach template arguments to function.  */
13884   if (!template_args.empty ())
13885     {
13886       gdb_assert (templ_func != NULL);
13887
13888       templ_func->n_template_arguments = template_args.size ();
13889       templ_func->template_arguments
13890         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13891                      templ_func->n_template_arguments);
13892       memcpy (templ_func->template_arguments,
13893               template_args.data (),
13894               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13895     }
13896
13897   /* In C++, we can have functions nested inside functions (e.g., when
13898      a function declares a class that has methods).  This means that
13899      when we finish processing a function scope, we may need to go
13900      back to building a containing block's symbol lists.  */
13901   local_symbols = newobj->locals;
13902   local_using_directives = newobj->local_using_directives;
13903
13904   /* If we've finished processing a top-level function, subsequent
13905      symbols go in the file symbol list.  */
13906   if (outermost_context_p ())
13907     cu->list_in_scope = &file_symbols;
13908 }
13909
13910 /* Process all the DIES contained within a lexical block scope.  Start
13911    a new scope, process the dies, and then close the scope.  */
13912
13913 static void
13914 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13915 {
13916   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13917   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13918   struct context_stack *newobj;
13919   CORE_ADDR lowpc, highpc;
13920   struct die_info *child_die;
13921   CORE_ADDR baseaddr;
13922
13923   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13924
13925   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13926   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13927      as multiple lexical blocks?  Handling children in a sane way would
13928      be nasty.  Might be easier to properly extend generic blocks to
13929      describe ranges.  */
13930   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13931     {
13932     case PC_BOUNDS_NOT_PRESENT:
13933       /* DW_TAG_lexical_block has no attributes, process its children as if
13934          there was no wrapping by that DW_TAG_lexical_block.
13935          GCC does no longer produces such DWARF since GCC r224161.  */
13936       for (child_die = die->child;
13937            child_die != NULL && child_die->tag;
13938            child_die = sibling_die (child_die))
13939         process_die (child_die, cu);
13940       return;
13941     case PC_BOUNDS_INVALID:
13942       return;
13943     }
13944   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13945   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13946
13947   push_context (0, lowpc);
13948   if (die->child != NULL)
13949     {
13950       child_die = die->child;
13951       while (child_die && child_die->tag)
13952         {
13953           process_die (child_die, cu);
13954           child_die = sibling_die (child_die);
13955         }
13956     }
13957   inherit_abstract_dies (die, cu);
13958   newobj = pop_context ();
13959
13960   if (local_symbols != NULL || local_using_directives != NULL)
13961     {
13962       struct block *block
13963         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13964                         newobj->start_addr, highpc);
13965
13966       /* Note that recording ranges after traversing children, as we
13967          do here, means that recording a parent's ranges entails
13968          walking across all its children's ranges as they appear in
13969          the address map, which is quadratic behavior.
13970
13971          It would be nicer to record the parent's ranges before
13972          traversing its children, simply overriding whatever you find
13973          there.  But since we don't even decide whether to create a
13974          block until after we've traversed its children, that's hard
13975          to do.  */
13976       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13977     }
13978   local_symbols = newobj->locals;
13979   local_using_directives = newobj->local_using_directives;
13980 }
13981
13982 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13983
13984 static void
13985 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13986 {
13987   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13988   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13989   CORE_ADDR pc, baseaddr;
13990   struct attribute *attr;
13991   struct call_site *call_site, call_site_local;
13992   void **slot;
13993   int nparams;
13994   struct die_info *child_die;
13995
13996   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13997
13998   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13999   if (attr == NULL)
14000     {
14001       /* This was a pre-DWARF-5 GNU extension alias
14002          for DW_AT_call_return_pc.  */
14003       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14004     }
14005   if (!attr)
14006     {
14007       complaint (&symfile_complaints,
14008                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14009                    "DIE 0x%x [in module %s]"),
14010                  to_underlying (die->sect_off), objfile_name (objfile));
14011       return;
14012     }
14013   pc = attr_value_as_address (attr) + baseaddr;
14014   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14015
14016   if (cu->call_site_htab == NULL)
14017     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14018                                                NULL, &objfile->objfile_obstack,
14019                                                hashtab_obstack_allocate, NULL);
14020   call_site_local.pc = pc;
14021   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14022   if (*slot != NULL)
14023     {
14024       complaint (&symfile_complaints,
14025                  _("Duplicate PC %s for DW_TAG_call_site "
14026                    "DIE 0x%x [in module %s]"),
14027                  paddress (gdbarch, pc), to_underlying (die->sect_off),
14028                  objfile_name (objfile));
14029       return;
14030     }
14031
14032   /* Count parameters at the caller.  */
14033
14034   nparams = 0;
14035   for (child_die = die->child; child_die && child_die->tag;
14036        child_die = sibling_die (child_die))
14037     {
14038       if (child_die->tag != DW_TAG_call_site_parameter
14039           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14040         {
14041           complaint (&symfile_complaints,
14042                      _("Tag %d is not DW_TAG_call_site_parameter in "
14043                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14044                      child_die->tag, to_underlying (child_die->sect_off),
14045                      objfile_name (objfile));
14046           continue;
14047         }
14048
14049       nparams++;
14050     }
14051
14052   call_site
14053     = ((struct call_site *)
14054        obstack_alloc (&objfile->objfile_obstack,
14055                       sizeof (*call_site)
14056                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14057   *slot = call_site;
14058   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14059   call_site->pc = pc;
14060
14061   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14062       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14063     {
14064       struct die_info *func_die;
14065
14066       /* Skip also over DW_TAG_inlined_subroutine.  */
14067       for (func_die = die->parent;
14068            func_die && func_die->tag != DW_TAG_subprogram
14069            && func_die->tag != DW_TAG_subroutine_type;
14070            func_die = func_die->parent);
14071
14072       /* DW_AT_call_all_calls is a superset
14073          of DW_AT_call_all_tail_calls.  */
14074       if (func_die
14075           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14076           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14077           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14078           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14079         {
14080           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14081              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14082              both the initial caller containing the real return address PC and
14083              the final callee containing the current PC of a chain of tail
14084              calls do not need to have the tail call list complete.  But any
14085              function candidate for a virtual tail call frame searched via
14086              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14087              determined unambiguously.  */
14088         }
14089       else
14090         {
14091           struct type *func_type = NULL;
14092
14093           if (func_die)
14094             func_type = get_die_type (func_die, cu);
14095           if (func_type != NULL)
14096             {
14097               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14098
14099               /* Enlist this call site to the function.  */
14100               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14101               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14102             }
14103           else
14104             complaint (&symfile_complaints,
14105                        _("Cannot find function owning DW_TAG_call_site "
14106                          "DIE 0x%x [in module %s]"),
14107                        to_underlying (die->sect_off), objfile_name (objfile));
14108         }
14109     }
14110
14111   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14112   if (attr == NULL)
14113     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14114   if (attr == NULL)
14115     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14116   if (attr == NULL)
14117     {
14118       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14119       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14120     }
14121   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14122   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14123     /* Keep NULL DWARF_BLOCK.  */;
14124   else if (attr_form_is_block (attr))
14125     {
14126       struct dwarf2_locexpr_baton *dlbaton;
14127
14128       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14129       dlbaton->data = DW_BLOCK (attr)->data;
14130       dlbaton->size = DW_BLOCK (attr)->size;
14131       dlbaton->per_cu = cu->per_cu;
14132
14133       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14134     }
14135   else if (attr_form_is_ref (attr))
14136     {
14137       struct dwarf2_cu *target_cu = cu;
14138       struct die_info *target_die;
14139
14140       target_die = follow_die_ref (die, attr, &target_cu);
14141       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14142       if (die_is_declaration (target_die, target_cu))
14143         {
14144           const char *target_physname;
14145
14146           /* Prefer the mangled name; otherwise compute the demangled one.  */
14147           target_physname = dw2_linkage_name (target_die, target_cu);
14148           if (target_physname == NULL)
14149             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14150           if (target_physname == NULL)
14151             complaint (&symfile_complaints,
14152                        _("DW_AT_call_target target DIE has invalid "
14153                          "physname, for referencing DIE 0x%x [in module %s]"),
14154                        to_underlying (die->sect_off), objfile_name (objfile));
14155           else
14156             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14157         }
14158       else
14159         {
14160           CORE_ADDR lowpc;
14161
14162           /* DW_AT_entry_pc should be preferred.  */
14163           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14164               <= PC_BOUNDS_INVALID)
14165             complaint (&symfile_complaints,
14166                        _("DW_AT_call_target target DIE has invalid "
14167                          "low pc, for referencing DIE 0x%x [in module %s]"),
14168                        to_underlying (die->sect_off), objfile_name (objfile));
14169           else
14170             {
14171               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14172               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14173             }
14174         }
14175     }
14176   else
14177     complaint (&symfile_complaints,
14178                _("DW_TAG_call_site DW_AT_call_target is neither "
14179                  "block nor reference, for DIE 0x%x [in module %s]"),
14180                to_underlying (die->sect_off), objfile_name (objfile));
14181
14182   call_site->per_cu = cu->per_cu;
14183
14184   for (child_die = die->child;
14185        child_die && child_die->tag;
14186        child_die = sibling_die (child_die))
14187     {
14188       struct call_site_parameter *parameter;
14189       struct attribute *loc, *origin;
14190
14191       if (child_die->tag != DW_TAG_call_site_parameter
14192           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14193         {
14194           /* Already printed the complaint above.  */
14195           continue;
14196         }
14197
14198       gdb_assert (call_site->parameter_count < nparams);
14199       parameter = &call_site->parameter[call_site->parameter_count];
14200
14201       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14202          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14203          register is contained in DW_AT_call_value.  */
14204
14205       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14206       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14207       if (origin == NULL)
14208         {
14209           /* This was a pre-DWARF-5 GNU extension alias
14210              for DW_AT_call_parameter.  */
14211           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14212         }
14213       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14214         {
14215           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14216
14217           sect_offset sect_off
14218             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14219           if (!offset_in_cu_p (&cu->header, sect_off))
14220             {
14221               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14222                  binding can be done only inside one CU.  Such referenced DIE
14223                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14224               complaint (&symfile_complaints,
14225                          _("DW_AT_call_parameter offset is not in CU for "
14226                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14227                          to_underlying (child_die->sect_off),
14228                          objfile_name (objfile));
14229               continue;
14230             }
14231           parameter->u.param_cu_off
14232             = (cu_offset) (sect_off - cu->header.sect_off);
14233         }
14234       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14235         {
14236           complaint (&symfile_complaints,
14237                      _("No DW_FORM_block* DW_AT_location for "
14238                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14239                      to_underlying (child_die->sect_off), objfile_name (objfile));
14240           continue;
14241         }
14242       else
14243         {
14244           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14245             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14246           if (parameter->u.dwarf_reg != -1)
14247             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14248           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14249                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14250                                              &parameter->u.fb_offset))
14251             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14252           else
14253             {
14254               complaint (&symfile_complaints,
14255                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14256                            "for DW_FORM_block* DW_AT_location is supported for "
14257                            "DW_TAG_call_site child DIE 0x%x "
14258                            "[in module %s]"),
14259                          to_underlying (child_die->sect_off),
14260                          objfile_name (objfile));
14261               continue;
14262             }
14263         }
14264
14265       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14266       if (attr == NULL)
14267         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14268       if (!attr_form_is_block (attr))
14269         {
14270           complaint (&symfile_complaints,
14271                      _("No DW_FORM_block* DW_AT_call_value for "
14272                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14273                      to_underlying (child_die->sect_off),
14274                      objfile_name (objfile));
14275           continue;
14276         }
14277       parameter->value = DW_BLOCK (attr)->data;
14278       parameter->value_size = DW_BLOCK (attr)->size;
14279
14280       /* Parameters are not pre-cleared by memset above.  */
14281       parameter->data_value = NULL;
14282       parameter->data_value_size = 0;
14283       call_site->parameter_count++;
14284
14285       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14286       if (attr == NULL)
14287         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14288       if (attr)
14289         {
14290           if (!attr_form_is_block (attr))
14291             complaint (&symfile_complaints,
14292                        _("No DW_FORM_block* DW_AT_call_data_value for "
14293                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14294                        to_underlying (child_die->sect_off),
14295                        objfile_name (objfile));
14296           else
14297             {
14298               parameter->data_value = DW_BLOCK (attr)->data;
14299               parameter->data_value_size = DW_BLOCK (attr)->size;
14300             }
14301         }
14302     }
14303 }
14304
14305 /* Helper function for read_variable.  If DIE represents a virtual
14306    table, then return the type of the concrete object that is
14307    associated with the virtual table.  Otherwise, return NULL.  */
14308
14309 static struct type *
14310 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14311 {
14312   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14313   if (attr == NULL)
14314     return NULL;
14315
14316   /* Find the type DIE.  */
14317   struct die_info *type_die = NULL;
14318   struct dwarf2_cu *type_cu = cu;
14319
14320   if (attr_form_is_ref (attr))
14321     type_die = follow_die_ref (die, attr, &type_cu);
14322   if (type_die == NULL)
14323     return NULL;
14324
14325   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14326     return NULL;
14327   return die_containing_type (type_die, type_cu);
14328 }
14329
14330 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14331
14332 static void
14333 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14334 {
14335   struct rust_vtable_symbol *storage = NULL;
14336
14337   if (cu->language == language_rust)
14338     {
14339       struct type *containing_type = rust_containing_type (die, cu);
14340
14341       if (containing_type != NULL)
14342         {
14343           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14344
14345           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14346                                     struct rust_vtable_symbol);
14347           initialize_objfile_symbol (storage);
14348           storage->concrete_type = containing_type;
14349           storage->subclass = SYMBOL_RUST_VTABLE;
14350         }
14351     }
14352
14353   new_symbol (die, NULL, cu, storage);
14354 }
14355
14356 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14357    reading .debug_rnglists.
14358    Callback's type should be:
14359     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14360    Return true if the attributes are present and valid, otherwise,
14361    return false.  */
14362
14363 template <typename Callback>
14364 static bool
14365 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14366                          Callback &&callback)
14367 {
14368   struct dwarf2_per_objfile *dwarf2_per_objfile
14369     = cu->per_cu->dwarf2_per_objfile;
14370   struct objfile *objfile = dwarf2_per_objfile->objfile;
14371   bfd *obfd = objfile->obfd;
14372   /* Base address selection entry.  */
14373   CORE_ADDR base;
14374   int found_base;
14375   const gdb_byte *buffer;
14376   CORE_ADDR baseaddr;
14377   bool overflow = false;
14378
14379   found_base = cu->base_known;
14380   base = cu->base_address;
14381
14382   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14383   if (offset >= dwarf2_per_objfile->rnglists.size)
14384     {
14385       complaint (&symfile_complaints,
14386                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14387                  offset);
14388       return false;
14389     }
14390   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14391
14392   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14393
14394   while (1)
14395     {
14396       /* Initialize it due to a false compiler warning.  */
14397       CORE_ADDR range_beginning = 0, range_end = 0;
14398       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14399                                  + dwarf2_per_objfile->rnglists.size);
14400       unsigned int bytes_read;
14401
14402       if (buffer == buf_end)
14403         {
14404           overflow = true;
14405           break;
14406         }
14407       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14408       switch (rlet)
14409         {
14410         case DW_RLE_end_of_list:
14411           break;
14412         case DW_RLE_base_address:
14413           if (buffer + cu->header.addr_size > buf_end)
14414             {
14415               overflow = true;
14416               break;
14417             }
14418           base = read_address (obfd, buffer, cu, &bytes_read);
14419           found_base = 1;
14420           buffer += bytes_read;
14421           break;
14422         case DW_RLE_start_length:
14423           if (buffer + cu->header.addr_size > buf_end)
14424             {
14425               overflow = true;
14426               break;
14427             }
14428           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14429           buffer += bytes_read;
14430           range_end = (range_beginning
14431                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14432           buffer += bytes_read;
14433           if (buffer > buf_end)
14434             {
14435               overflow = true;
14436               break;
14437             }
14438           break;
14439         case DW_RLE_offset_pair:
14440           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14441           buffer += bytes_read;
14442           if (buffer > buf_end)
14443             {
14444               overflow = true;
14445               break;
14446             }
14447           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14448           buffer += bytes_read;
14449           if (buffer > buf_end)
14450             {
14451               overflow = true;
14452               break;
14453             }
14454           break;
14455         case DW_RLE_start_end:
14456           if (buffer + 2 * cu->header.addr_size > buf_end)
14457             {
14458               overflow = true;
14459               break;
14460             }
14461           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14462           buffer += bytes_read;
14463           range_end = read_address (obfd, buffer, cu, &bytes_read);
14464           buffer += bytes_read;
14465           break;
14466         default:
14467           complaint (&symfile_complaints,
14468                      _("Invalid .debug_rnglists data (no base address)"));
14469           return false;
14470         }
14471       if (rlet == DW_RLE_end_of_list || overflow)
14472         break;
14473       if (rlet == DW_RLE_base_address)
14474         continue;
14475
14476       if (!found_base)
14477         {
14478           /* We have no valid base address for the ranges
14479              data.  */
14480           complaint (&symfile_complaints,
14481                      _("Invalid .debug_rnglists data (no base address)"));
14482           return false;
14483         }
14484
14485       if (range_beginning > range_end)
14486         {
14487           /* Inverted range entries are invalid.  */
14488           complaint (&symfile_complaints,
14489                      _("Invalid .debug_rnglists data (inverted range)"));
14490           return false;
14491         }
14492
14493       /* Empty range entries have no effect.  */
14494       if (range_beginning == range_end)
14495         continue;
14496
14497       range_beginning += base;
14498       range_end += base;
14499
14500       /* A not-uncommon case of bad debug info.
14501          Don't pollute the addrmap with bad data.  */
14502       if (range_beginning + baseaddr == 0
14503           && !dwarf2_per_objfile->has_section_at_zero)
14504         {
14505           complaint (&symfile_complaints,
14506                      _(".debug_rnglists entry has start address of zero"
14507                        " [in module %s]"), objfile_name (objfile));
14508           continue;
14509         }
14510
14511       callback (range_beginning, range_end);
14512     }
14513
14514   if (overflow)
14515     {
14516       complaint (&symfile_complaints,
14517                  _("Offset %d is not terminated "
14518                    "for DW_AT_ranges attribute"),
14519                  offset);
14520       return false;
14521     }
14522
14523   return true;
14524 }
14525
14526 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14527    Callback's type should be:
14528     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14529    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14530
14531 template <typename Callback>
14532 static int
14533 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14534                        Callback &&callback)
14535 {
14536   struct dwarf2_per_objfile *dwarf2_per_objfile
14537       = cu->per_cu->dwarf2_per_objfile;
14538   struct objfile *objfile = dwarf2_per_objfile->objfile;
14539   struct comp_unit_head *cu_header = &cu->header;
14540   bfd *obfd = objfile->obfd;
14541   unsigned int addr_size = cu_header->addr_size;
14542   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14543   /* Base address selection entry.  */
14544   CORE_ADDR base;
14545   int found_base;
14546   unsigned int dummy;
14547   const gdb_byte *buffer;
14548   CORE_ADDR baseaddr;
14549
14550   if (cu_header->version >= 5)
14551     return dwarf2_rnglists_process (offset, cu, callback);
14552
14553   found_base = cu->base_known;
14554   base = cu->base_address;
14555
14556   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14557   if (offset >= dwarf2_per_objfile->ranges.size)
14558     {
14559       complaint (&symfile_complaints,
14560                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14561                  offset);
14562       return 0;
14563     }
14564   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14565
14566   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14567
14568   while (1)
14569     {
14570       CORE_ADDR range_beginning, range_end;
14571
14572       range_beginning = read_address (obfd, buffer, cu, &dummy);
14573       buffer += addr_size;
14574       range_end = read_address (obfd, buffer, cu, &dummy);
14575       buffer += addr_size;
14576       offset += 2 * addr_size;
14577
14578       /* An end of list marker is a pair of zero addresses.  */
14579       if (range_beginning == 0 && range_end == 0)
14580         /* Found the end of list entry.  */
14581         break;
14582
14583       /* Each base address selection entry is a pair of 2 values.
14584          The first is the largest possible address, the second is
14585          the base address.  Check for a base address here.  */
14586       if ((range_beginning & mask) == mask)
14587         {
14588           /* If we found the largest possible address, then we already
14589              have the base address in range_end.  */
14590           base = range_end;
14591           found_base = 1;
14592           continue;
14593         }
14594
14595       if (!found_base)
14596         {
14597           /* We have no valid base address for the ranges
14598              data.  */
14599           complaint (&symfile_complaints,
14600                      _("Invalid .debug_ranges data (no base address)"));
14601           return 0;
14602         }
14603
14604       if (range_beginning > range_end)
14605         {
14606           /* Inverted range entries are invalid.  */
14607           complaint (&symfile_complaints,
14608                      _("Invalid .debug_ranges data (inverted range)"));
14609           return 0;
14610         }
14611
14612       /* Empty range entries have no effect.  */
14613       if (range_beginning == range_end)
14614         continue;
14615
14616       range_beginning += base;
14617       range_end += base;
14618
14619       /* A not-uncommon case of bad debug info.
14620          Don't pollute the addrmap with bad data.  */
14621       if (range_beginning + baseaddr == 0
14622           && !dwarf2_per_objfile->has_section_at_zero)
14623         {
14624           complaint (&symfile_complaints,
14625                      _(".debug_ranges entry has start address of zero"
14626                        " [in module %s]"), objfile_name (objfile));
14627           continue;
14628         }
14629
14630       callback (range_beginning, range_end);
14631     }
14632
14633   return 1;
14634 }
14635
14636 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14637    Return 1 if the attributes are present and valid, otherwise, return 0.
14638    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14639
14640 static int
14641 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14642                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14643                     struct partial_symtab *ranges_pst)
14644 {
14645   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14646   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14647   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14648                                        SECT_OFF_TEXT (objfile));
14649   int low_set = 0;
14650   CORE_ADDR low = 0;
14651   CORE_ADDR high = 0;
14652   int retval;
14653
14654   retval = dwarf2_ranges_process (offset, cu,
14655     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14656     {
14657       if (ranges_pst != NULL)
14658         {
14659           CORE_ADDR lowpc;
14660           CORE_ADDR highpc;
14661
14662           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14663                                               range_beginning + baseaddr);
14664           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14665                                                range_end + baseaddr);
14666           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14667                              ranges_pst);
14668         }
14669
14670       /* FIXME: This is recording everything as a low-high
14671          segment of consecutive addresses.  We should have a
14672          data structure for discontiguous block ranges
14673          instead.  */
14674       if (! low_set)
14675         {
14676           low = range_beginning;
14677           high = range_end;
14678           low_set = 1;
14679         }
14680       else
14681         {
14682           if (range_beginning < low)
14683             low = range_beginning;
14684           if (range_end > high)
14685             high = range_end;
14686         }
14687     });
14688   if (!retval)
14689     return 0;
14690
14691   if (! low_set)
14692     /* If the first entry is an end-of-list marker, the range
14693        describes an empty scope, i.e. no instructions.  */
14694     return 0;
14695
14696   if (low_return)
14697     *low_return = low;
14698   if (high_return)
14699     *high_return = high;
14700   return 1;
14701 }
14702
14703 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14704    definition for the return value.  *LOWPC and *HIGHPC are set iff
14705    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14706
14707 static enum pc_bounds_kind
14708 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14709                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14710                       struct partial_symtab *pst)
14711 {
14712   struct dwarf2_per_objfile *dwarf2_per_objfile
14713     = cu->per_cu->dwarf2_per_objfile;
14714   struct attribute *attr;
14715   struct attribute *attr_high;
14716   CORE_ADDR low = 0;
14717   CORE_ADDR high = 0;
14718   enum pc_bounds_kind ret;
14719
14720   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14721   if (attr_high)
14722     {
14723       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14724       if (attr)
14725         {
14726           low = attr_value_as_address (attr);
14727           high = attr_value_as_address (attr_high);
14728           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14729             high += low;
14730         }
14731       else
14732         /* Found high w/o low attribute.  */
14733         return PC_BOUNDS_INVALID;
14734
14735       /* Found consecutive range of addresses.  */
14736       ret = PC_BOUNDS_HIGH_LOW;
14737     }
14738   else
14739     {
14740       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14741       if (attr != NULL)
14742         {
14743           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14744              We take advantage of the fact that DW_AT_ranges does not appear
14745              in DW_TAG_compile_unit of DWO files.  */
14746           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14747           unsigned int ranges_offset = (DW_UNSND (attr)
14748                                         + (need_ranges_base
14749                                            ? cu->ranges_base
14750                                            : 0));
14751
14752           /* Value of the DW_AT_ranges attribute is the offset in the
14753              .debug_ranges section.  */
14754           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14755             return PC_BOUNDS_INVALID;
14756           /* Found discontinuous range of addresses.  */
14757           ret = PC_BOUNDS_RANGES;
14758         }
14759       else
14760         return PC_BOUNDS_NOT_PRESENT;
14761     }
14762
14763   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14764   if (high <= low)
14765     return PC_BOUNDS_INVALID;
14766
14767   /* When using the GNU linker, .gnu.linkonce. sections are used to
14768      eliminate duplicate copies of functions and vtables and such.
14769      The linker will arbitrarily choose one and discard the others.
14770      The AT_*_pc values for such functions refer to local labels in
14771      these sections.  If the section from that file was discarded, the
14772      labels are not in the output, so the relocs get a value of 0.
14773      If this is a discarded function, mark the pc bounds as invalid,
14774      so that GDB will ignore it.  */
14775   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14776     return PC_BOUNDS_INVALID;
14777
14778   *lowpc = low;
14779   if (highpc)
14780     *highpc = high;
14781   return ret;
14782 }
14783
14784 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14785    its low and high PC addresses.  Do nothing if these addresses could not
14786    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14787    and HIGHPC to the high address if greater than HIGHPC.  */
14788
14789 static void
14790 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14791                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14792                                  struct dwarf2_cu *cu)
14793 {
14794   CORE_ADDR low, high;
14795   struct die_info *child = die->child;
14796
14797   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14798     {
14799       *lowpc = std::min (*lowpc, low);
14800       *highpc = std::max (*highpc, high);
14801     }
14802
14803   /* If the language does not allow nested subprograms (either inside
14804      subprograms or lexical blocks), we're done.  */
14805   if (cu->language != language_ada)
14806     return;
14807
14808   /* Check all the children of the given DIE.  If it contains nested
14809      subprograms, then check their pc bounds.  Likewise, we need to
14810      check lexical blocks as well, as they may also contain subprogram
14811      definitions.  */
14812   while (child && child->tag)
14813     {
14814       if (child->tag == DW_TAG_subprogram
14815           || child->tag == DW_TAG_lexical_block)
14816         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14817       child = sibling_die (child);
14818     }
14819 }
14820
14821 /* Get the low and high pc's represented by the scope DIE, and store
14822    them in *LOWPC and *HIGHPC.  If the correct values can't be
14823    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14824
14825 static void
14826 get_scope_pc_bounds (struct die_info *die,
14827                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14828                      struct dwarf2_cu *cu)
14829 {
14830   CORE_ADDR best_low = (CORE_ADDR) -1;
14831   CORE_ADDR best_high = (CORE_ADDR) 0;
14832   CORE_ADDR current_low, current_high;
14833
14834   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14835       >= PC_BOUNDS_RANGES)
14836     {
14837       best_low = current_low;
14838       best_high = current_high;
14839     }
14840   else
14841     {
14842       struct die_info *child = die->child;
14843
14844       while (child && child->tag)
14845         {
14846           switch (child->tag) {
14847           case DW_TAG_subprogram:
14848             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14849             break;
14850           case DW_TAG_namespace:
14851           case DW_TAG_module:
14852             /* FIXME: carlton/2004-01-16: Should we do this for
14853                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14854                that current GCC's always emit the DIEs corresponding
14855                to definitions of methods of classes as children of a
14856                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14857                the DIEs giving the declarations, which could be
14858                anywhere).  But I don't see any reason why the
14859                standards says that they have to be there.  */
14860             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14861
14862             if (current_low != ((CORE_ADDR) -1))
14863               {
14864                 best_low = std::min (best_low, current_low);
14865                 best_high = std::max (best_high, current_high);
14866               }
14867             break;
14868           default:
14869             /* Ignore.  */
14870             break;
14871           }
14872
14873           child = sibling_die (child);
14874         }
14875     }
14876
14877   *lowpc = best_low;
14878   *highpc = best_high;
14879 }
14880
14881 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14882    in DIE.  */
14883
14884 static void
14885 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14886                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14887 {
14888   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14889   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14890   struct attribute *attr;
14891   struct attribute *attr_high;
14892
14893   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14894   if (attr_high)
14895     {
14896       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14897       if (attr)
14898         {
14899           CORE_ADDR low = attr_value_as_address (attr);
14900           CORE_ADDR high = attr_value_as_address (attr_high);
14901
14902           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14903             high += low;
14904
14905           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14906           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14907           record_block_range (block, low, high - 1);
14908         }
14909     }
14910
14911   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14912   if (attr)
14913     {
14914       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14915          We take advantage of the fact that DW_AT_ranges does not appear
14916          in DW_TAG_compile_unit of DWO files.  */
14917       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14918
14919       /* The value of the DW_AT_ranges attribute is the offset of the
14920          address range list in the .debug_ranges section.  */
14921       unsigned long offset = (DW_UNSND (attr)
14922                               + (need_ranges_base ? cu->ranges_base : 0));
14923       const gdb_byte *buffer;
14924
14925       /* For some target architectures, but not others, the
14926          read_address function sign-extends the addresses it returns.
14927          To recognize base address selection entries, we need a
14928          mask.  */
14929       unsigned int addr_size = cu->header.addr_size;
14930       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14931
14932       /* The base address, to which the next pair is relative.  Note
14933          that this 'base' is a DWARF concept: most entries in a range
14934          list are relative, to reduce the number of relocs against the
14935          debugging information.  This is separate from this function's
14936          'baseaddr' argument, which GDB uses to relocate debugging
14937          information from a shared library based on the address at
14938          which the library was loaded.  */
14939       CORE_ADDR base = cu->base_address;
14940       int base_known = cu->base_known;
14941
14942       dwarf2_ranges_process (offset, cu,
14943         [&] (CORE_ADDR start, CORE_ADDR end)
14944         {
14945           start += baseaddr;
14946           end += baseaddr;
14947           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14948           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14949           record_block_range (block, start, end - 1);
14950         });
14951     }
14952 }
14953
14954 /* Check whether the producer field indicates either of GCC < 4.6, or the
14955    Intel C/C++ compiler, and cache the result in CU.  */
14956
14957 static void
14958 check_producer (struct dwarf2_cu *cu)
14959 {
14960   int major, minor;
14961
14962   if (cu->producer == NULL)
14963     {
14964       /* For unknown compilers expect their behavior is DWARF version
14965          compliant.
14966
14967          GCC started to support .debug_types sections by -gdwarf-4 since
14968          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14969          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14970          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14971          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14972     }
14973   else if (producer_is_gcc (cu->producer, &major, &minor))
14974     {
14975       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14976       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14977     }
14978   else if (producer_is_icc (cu->producer, &major, &minor))
14979     cu->producer_is_icc_lt_14 = major < 14;
14980   else
14981     {
14982       /* For other non-GCC compilers, expect their behavior is DWARF version
14983          compliant.  */
14984     }
14985
14986   cu->checked_producer = 1;
14987 }
14988
14989 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14990    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14991    during 4.6.0 experimental.  */
14992
14993 static int
14994 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14995 {
14996   if (!cu->checked_producer)
14997     check_producer (cu);
14998
14999   return cu->producer_is_gxx_lt_4_6;
15000 }
15001
15002 /* Return the default accessibility type if it is not overriden by
15003    DW_AT_accessibility.  */
15004
15005 static enum dwarf_access_attribute
15006 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15007 {
15008   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15009     {
15010       /* The default DWARF 2 accessibility for members is public, the default
15011          accessibility for inheritance is private.  */
15012
15013       if (die->tag != DW_TAG_inheritance)
15014         return DW_ACCESS_public;
15015       else
15016         return DW_ACCESS_private;
15017     }
15018   else
15019     {
15020       /* DWARF 3+ defines the default accessibility a different way.  The same
15021          rules apply now for DW_TAG_inheritance as for the members and it only
15022          depends on the container kind.  */
15023
15024       if (die->parent->tag == DW_TAG_class_type)
15025         return DW_ACCESS_private;
15026       else
15027         return DW_ACCESS_public;
15028     }
15029 }
15030
15031 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15032    offset.  If the attribute was not found return 0, otherwise return
15033    1.  If it was found but could not properly be handled, set *OFFSET
15034    to 0.  */
15035
15036 static int
15037 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15038                              LONGEST *offset)
15039 {
15040   struct attribute *attr;
15041
15042   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15043   if (attr != NULL)
15044     {
15045       *offset = 0;
15046
15047       /* Note that we do not check for a section offset first here.
15048          This is because DW_AT_data_member_location is new in DWARF 4,
15049          so if we see it, we can assume that a constant form is really
15050          a constant and not a section offset.  */
15051       if (attr_form_is_constant (attr))
15052         *offset = dwarf2_get_attr_constant_value (attr, 0);
15053       else if (attr_form_is_section_offset (attr))
15054         dwarf2_complex_location_expr_complaint ();
15055       else if (attr_form_is_block (attr))
15056         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15057       else
15058         dwarf2_complex_location_expr_complaint ();
15059
15060       return 1;
15061     }
15062
15063   return 0;
15064 }
15065
15066 /* Add an aggregate field to the field list.  */
15067
15068 static void
15069 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15070                   struct dwarf2_cu *cu)
15071 {
15072   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15073   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15074   struct nextfield *new_field;
15075   struct attribute *attr;
15076   struct field *fp;
15077   const char *fieldname = "";
15078
15079   /* Allocate a new field list entry and link it in.  */
15080   new_field = XNEW (struct nextfield);
15081   make_cleanup (xfree, new_field);
15082   memset (new_field, 0, sizeof (struct nextfield));
15083
15084   if (die->tag == DW_TAG_inheritance)
15085     {
15086       new_field->next = fip->baseclasses;
15087       fip->baseclasses = new_field;
15088     }
15089   else
15090     {
15091       new_field->next = fip->fields;
15092       fip->fields = new_field;
15093     }
15094   fip->nfields++;
15095
15096   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15097   if (attr)
15098     new_field->accessibility = DW_UNSND (attr);
15099   else
15100     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15101   if (new_field->accessibility != DW_ACCESS_public)
15102     fip->non_public_fields = 1;
15103
15104   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15105   if (attr)
15106     new_field->virtuality = DW_UNSND (attr);
15107   else
15108     new_field->virtuality = DW_VIRTUALITY_none;
15109
15110   fp = &new_field->field;
15111
15112   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15113     {
15114       LONGEST offset;
15115
15116       /* Data member other than a C++ static data member.  */
15117
15118       /* Get type of field.  */
15119       fp->type = die_type (die, cu);
15120
15121       SET_FIELD_BITPOS (*fp, 0);
15122
15123       /* Get bit size of field (zero if none).  */
15124       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15125       if (attr)
15126         {
15127           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15128         }
15129       else
15130         {
15131           FIELD_BITSIZE (*fp) = 0;
15132         }
15133
15134       /* Get bit offset of field.  */
15135       if (handle_data_member_location (die, cu, &offset))
15136         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15137       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15138       if (attr)
15139         {
15140           if (gdbarch_bits_big_endian (gdbarch))
15141             {
15142               /* For big endian bits, the DW_AT_bit_offset gives the
15143                  additional bit offset from the MSB of the containing
15144                  anonymous object to the MSB of the field.  We don't
15145                  have to do anything special since we don't need to
15146                  know the size of the anonymous object.  */
15147               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15148             }
15149           else
15150             {
15151               /* For little endian bits, compute the bit offset to the
15152                  MSB of the anonymous object, subtract off the number of
15153                  bits from the MSB of the field to the MSB of the
15154                  object, and then subtract off the number of bits of
15155                  the field itself.  The result is the bit offset of
15156                  the LSB of the field.  */
15157               int anonymous_size;
15158               int bit_offset = DW_UNSND (attr);
15159
15160               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15161               if (attr)
15162                 {
15163                   /* The size of the anonymous object containing
15164                      the bit field is explicit, so use the
15165                      indicated size (in bytes).  */
15166                   anonymous_size = DW_UNSND (attr);
15167                 }
15168               else
15169                 {
15170                   /* The size of the anonymous object containing
15171                      the bit field must be inferred from the type
15172                      attribute of the data member containing the
15173                      bit field.  */
15174                   anonymous_size = TYPE_LENGTH (fp->type);
15175                 }
15176               SET_FIELD_BITPOS (*fp,
15177                                 (FIELD_BITPOS (*fp)
15178                                  + anonymous_size * bits_per_byte
15179                                  - bit_offset - FIELD_BITSIZE (*fp)));
15180             }
15181         }
15182       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15183       if (attr != NULL)
15184         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15185                                 + dwarf2_get_attr_constant_value (attr, 0)));
15186
15187       /* Get name of field.  */
15188       fieldname = dwarf2_name (die, cu);
15189       if (fieldname == NULL)
15190         fieldname = "";
15191
15192       /* The name is already allocated along with this objfile, so we don't
15193          need to duplicate it for the type.  */
15194       fp->name = fieldname;
15195
15196       /* Change accessibility for artificial fields (e.g. virtual table
15197          pointer or virtual base class pointer) to private.  */
15198       if (dwarf2_attr (die, DW_AT_artificial, cu))
15199         {
15200           FIELD_ARTIFICIAL (*fp) = 1;
15201           new_field->accessibility = DW_ACCESS_private;
15202           fip->non_public_fields = 1;
15203         }
15204     }
15205   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15206     {
15207       /* C++ static member.  */
15208
15209       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15210          is a declaration, but all versions of G++ as of this writing
15211          (so through at least 3.2.1) incorrectly generate
15212          DW_TAG_variable tags.  */
15213
15214       const char *physname;
15215
15216       /* Get name of field.  */
15217       fieldname = dwarf2_name (die, cu);
15218       if (fieldname == NULL)
15219         return;
15220
15221       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15222       if (attr
15223           /* Only create a symbol if this is an external value.
15224              new_symbol checks this and puts the value in the global symbol
15225              table, which we want.  If it is not external, new_symbol
15226              will try to put the value in cu->list_in_scope which is wrong.  */
15227           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15228         {
15229           /* A static const member, not much different than an enum as far as
15230              we're concerned, except that we can support more types.  */
15231           new_symbol (die, NULL, cu);
15232         }
15233
15234       /* Get physical name.  */
15235       physname = dwarf2_physname (fieldname, die, cu);
15236
15237       /* The name is already allocated along with this objfile, so we don't
15238          need to duplicate it for the type.  */
15239       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15240       FIELD_TYPE (*fp) = die_type (die, cu);
15241       FIELD_NAME (*fp) = fieldname;
15242     }
15243   else if (die->tag == DW_TAG_inheritance)
15244     {
15245       LONGEST offset;
15246
15247       /* C++ base class field.  */
15248       if (handle_data_member_location (die, cu, &offset))
15249         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15250       FIELD_BITSIZE (*fp) = 0;
15251       FIELD_TYPE (*fp) = die_type (die, cu);
15252       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15253       fip->nbaseclasses++;
15254     }
15255 }
15256
15257 /* Can the type given by DIE define another type?  */
15258
15259 static bool
15260 type_can_define_types (const struct die_info *die)
15261 {
15262   switch (die->tag)
15263     {
15264     case DW_TAG_typedef:
15265     case DW_TAG_class_type:
15266     case DW_TAG_structure_type:
15267     case DW_TAG_union_type:
15268     case DW_TAG_enumeration_type:
15269       return true;
15270
15271     default:
15272       return false;
15273     }
15274 }
15275
15276 /* Add a type definition defined in the scope of the FIP's class.  */
15277
15278 static void
15279 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15280                       struct dwarf2_cu *cu)
15281 {
15282   struct decl_field_list *new_field;
15283   struct decl_field *fp;
15284
15285   /* Allocate a new field list entry and link it in.  */
15286   new_field = XCNEW (struct decl_field_list);
15287   make_cleanup (xfree, new_field);
15288
15289   gdb_assert (type_can_define_types (die));
15290
15291   fp = &new_field->field;
15292
15293   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15294   fp->name = dwarf2_name (die, cu);
15295   fp->type = read_type_die (die, cu);
15296
15297   /* Save accessibility.  */
15298   enum dwarf_access_attribute accessibility;
15299   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15300   if (attr != NULL)
15301     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15302   else
15303     accessibility = dwarf2_default_access_attribute (die, cu);
15304   switch (accessibility)
15305     {
15306     case DW_ACCESS_public:
15307       /* The assumed value if neither private nor protected.  */
15308       break;
15309     case DW_ACCESS_private:
15310       fp->is_private = 1;
15311       break;
15312     case DW_ACCESS_protected:
15313       fp->is_protected = 1;
15314       break;
15315     default:
15316       complaint (&symfile_complaints,
15317                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15318     }
15319
15320   if (die->tag == DW_TAG_typedef)
15321     {
15322       new_field->next = fip->typedef_field_list;
15323       fip->typedef_field_list = new_field;
15324       fip->typedef_field_list_count++;
15325     }
15326   else
15327     {
15328       new_field->next = fip->nested_types_list;
15329       fip->nested_types_list = new_field;
15330       fip->nested_types_list_count++;
15331     }
15332 }
15333
15334 /* Create the vector of fields, and attach it to the type.  */
15335
15336 static void
15337 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15338                               struct dwarf2_cu *cu)
15339 {
15340   int nfields = fip->nfields;
15341
15342   /* Record the field count, allocate space for the array of fields,
15343      and create blank accessibility bitfields if necessary.  */
15344   TYPE_NFIELDS (type) = nfields;
15345   TYPE_FIELDS (type) = (struct field *)
15346     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15347   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15348
15349   if (fip->non_public_fields && cu->language != language_ada)
15350     {
15351       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15352
15353       TYPE_FIELD_PRIVATE_BITS (type) =
15354         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15355       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15356
15357       TYPE_FIELD_PROTECTED_BITS (type) =
15358         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15359       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15360
15361       TYPE_FIELD_IGNORE_BITS (type) =
15362         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15363       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15364     }
15365
15366   /* If the type has baseclasses, allocate and clear a bit vector for
15367      TYPE_FIELD_VIRTUAL_BITS.  */
15368   if (fip->nbaseclasses && cu->language != language_ada)
15369     {
15370       int num_bytes = B_BYTES (fip->nbaseclasses);
15371       unsigned char *pointer;
15372
15373       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15374       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15375       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15376       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15377       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15378     }
15379
15380   /* Copy the saved-up fields into the field vector.  Start from the head of
15381      the list, adding to the tail of the field array, so that they end up in
15382      the same order in the array in which they were added to the list.  */
15383   while (nfields-- > 0)
15384     {
15385       struct nextfield *fieldp;
15386
15387       if (fip->fields)
15388         {
15389           fieldp = fip->fields;
15390           fip->fields = fieldp->next;
15391         }
15392       else
15393         {
15394           fieldp = fip->baseclasses;
15395           fip->baseclasses = fieldp->next;
15396         }
15397
15398       TYPE_FIELD (type, nfields) = fieldp->field;
15399       switch (fieldp->accessibility)
15400         {
15401         case DW_ACCESS_private:
15402           if (cu->language != language_ada)
15403             SET_TYPE_FIELD_PRIVATE (type, nfields);
15404           break;
15405
15406         case DW_ACCESS_protected:
15407           if (cu->language != language_ada)
15408             SET_TYPE_FIELD_PROTECTED (type, nfields);
15409           break;
15410
15411         case DW_ACCESS_public:
15412           break;
15413
15414         default:
15415           /* Unknown accessibility.  Complain and treat it as public.  */
15416           {
15417             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15418                        fieldp->accessibility);
15419           }
15420           break;
15421         }
15422       if (nfields < fip->nbaseclasses)
15423         {
15424           switch (fieldp->virtuality)
15425             {
15426             case DW_VIRTUALITY_virtual:
15427             case DW_VIRTUALITY_pure_virtual:
15428               if (cu->language == language_ada)
15429                 error (_("unexpected virtuality in component of Ada type"));
15430               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15431               break;
15432             }
15433         }
15434     }
15435 }
15436
15437 /* Return true if this member function is a constructor, false
15438    otherwise.  */
15439
15440 static int
15441 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15442 {
15443   const char *fieldname;
15444   const char *type_name;
15445   int len;
15446
15447   if (die->parent == NULL)
15448     return 0;
15449
15450   if (die->parent->tag != DW_TAG_structure_type
15451       && die->parent->tag != DW_TAG_union_type
15452       && die->parent->tag != DW_TAG_class_type)
15453     return 0;
15454
15455   fieldname = dwarf2_name (die, cu);
15456   type_name = dwarf2_name (die->parent, cu);
15457   if (fieldname == NULL || type_name == NULL)
15458     return 0;
15459
15460   len = strlen (fieldname);
15461   return (strncmp (fieldname, type_name, len) == 0
15462           && (type_name[len] == '\0' || type_name[len] == '<'));
15463 }
15464
15465 /* Add a member function to the proper fieldlist.  */
15466
15467 static void
15468 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15469                       struct type *type, struct dwarf2_cu *cu)
15470 {
15471   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15472   struct attribute *attr;
15473   struct fnfieldlist *flp;
15474   int i;
15475   struct fn_field *fnp;
15476   const char *fieldname;
15477   struct nextfnfield *new_fnfield;
15478   struct type *this_type;
15479   enum dwarf_access_attribute accessibility;
15480
15481   if (cu->language == language_ada)
15482     error (_("unexpected member function in Ada type"));
15483
15484   /* Get name of member function.  */
15485   fieldname = dwarf2_name (die, cu);
15486   if (fieldname == NULL)
15487     return;
15488
15489   /* Look up member function name in fieldlist.  */
15490   for (i = 0; i < fip->nfnfields; i++)
15491     {
15492       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15493         break;
15494     }
15495
15496   /* Create new list element if necessary.  */
15497   if (i < fip->nfnfields)
15498     flp = &fip->fnfieldlists[i];
15499   else
15500     {
15501       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15502         {
15503           fip->fnfieldlists = (struct fnfieldlist *)
15504             xrealloc (fip->fnfieldlists,
15505                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15506                       * sizeof (struct fnfieldlist));
15507           if (fip->nfnfields == 0)
15508             make_cleanup (free_current_contents, &fip->fnfieldlists);
15509         }
15510       flp = &fip->fnfieldlists[fip->nfnfields];
15511       flp->name = fieldname;
15512       flp->length = 0;
15513       flp->head = NULL;
15514       i = fip->nfnfields++;
15515     }
15516
15517   /* Create a new member function field and chain it to the field list
15518      entry.  */
15519   new_fnfield = XNEW (struct nextfnfield);
15520   make_cleanup (xfree, new_fnfield);
15521   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15522   new_fnfield->next = flp->head;
15523   flp->head = new_fnfield;
15524   flp->length++;
15525
15526   /* Fill in the member function field info.  */
15527   fnp = &new_fnfield->fnfield;
15528
15529   /* Delay processing of the physname until later.  */
15530   if (cu->language == language_cplus)
15531     {
15532       add_to_method_list (type, i, flp->length - 1, fieldname,
15533                           die, cu);
15534     }
15535   else
15536     {
15537       const char *physname = dwarf2_physname (fieldname, die, cu);
15538       fnp->physname = physname ? physname : "";
15539     }
15540
15541   fnp->type = alloc_type (objfile);
15542   this_type = read_type_die (die, cu);
15543   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15544     {
15545       int nparams = TYPE_NFIELDS (this_type);
15546
15547       /* TYPE is the domain of this method, and THIS_TYPE is the type
15548            of the method itself (TYPE_CODE_METHOD).  */
15549       smash_to_method_type (fnp->type, type,
15550                             TYPE_TARGET_TYPE (this_type),
15551                             TYPE_FIELDS (this_type),
15552                             TYPE_NFIELDS (this_type),
15553                             TYPE_VARARGS (this_type));
15554
15555       /* Handle static member functions.
15556          Dwarf2 has no clean way to discern C++ static and non-static
15557          member functions.  G++ helps GDB by marking the first
15558          parameter for non-static member functions (which is the this
15559          pointer) as artificial.  We obtain this information from
15560          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15561       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15562         fnp->voffset = VOFFSET_STATIC;
15563     }
15564   else
15565     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15566                dwarf2_full_name (fieldname, die, cu));
15567
15568   /* Get fcontext from DW_AT_containing_type if present.  */
15569   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15570     fnp->fcontext = die_containing_type (die, cu);
15571
15572   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15573      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15574
15575   /* Get accessibility.  */
15576   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15577   if (attr)
15578     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15579   else
15580     accessibility = dwarf2_default_access_attribute (die, cu);
15581   switch (accessibility)
15582     {
15583     case DW_ACCESS_private:
15584       fnp->is_private = 1;
15585       break;
15586     case DW_ACCESS_protected:
15587       fnp->is_protected = 1;
15588       break;
15589     }
15590
15591   /* Check for artificial methods.  */
15592   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15593   if (attr && DW_UNSND (attr) != 0)
15594     fnp->is_artificial = 1;
15595
15596   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15597
15598   /* Get index in virtual function table if it is a virtual member
15599      function.  For older versions of GCC, this is an offset in the
15600      appropriate virtual table, as specified by DW_AT_containing_type.
15601      For everyone else, it is an expression to be evaluated relative
15602      to the object address.  */
15603
15604   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15605   if (attr)
15606     {
15607       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15608         {
15609           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15610             {
15611               /* Old-style GCC.  */
15612               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15613             }
15614           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15615                    || (DW_BLOCK (attr)->size > 1
15616                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15617                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15618             {
15619               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15620               if ((fnp->voffset % cu->header.addr_size) != 0)
15621                 dwarf2_complex_location_expr_complaint ();
15622               else
15623                 fnp->voffset /= cu->header.addr_size;
15624               fnp->voffset += 2;
15625             }
15626           else
15627             dwarf2_complex_location_expr_complaint ();
15628
15629           if (!fnp->fcontext)
15630             {
15631               /* If there is no `this' field and no DW_AT_containing_type,
15632                  we cannot actually find a base class context for the
15633                  vtable!  */
15634               if (TYPE_NFIELDS (this_type) == 0
15635                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15636                 {
15637                   complaint (&symfile_complaints,
15638                              _("cannot determine context for virtual member "
15639                                "function \"%s\" (offset %d)"),
15640                              fieldname, to_underlying (die->sect_off));
15641                 }
15642               else
15643                 {
15644                   fnp->fcontext
15645                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15646                 }
15647             }
15648         }
15649       else if (attr_form_is_section_offset (attr))
15650         {
15651           dwarf2_complex_location_expr_complaint ();
15652         }
15653       else
15654         {
15655           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15656                                                  fieldname);
15657         }
15658     }
15659   else
15660     {
15661       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15662       if (attr && DW_UNSND (attr))
15663         {
15664           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15665           complaint (&symfile_complaints,
15666                      _("Member function \"%s\" (offset %d) is virtual "
15667                        "but the vtable offset is not specified"),
15668                      fieldname, to_underlying (die->sect_off));
15669           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15670           TYPE_CPLUS_DYNAMIC (type) = 1;
15671         }
15672     }
15673 }
15674
15675 /* Create the vector of member function fields, and attach it to the type.  */
15676
15677 static void
15678 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15679                                  struct dwarf2_cu *cu)
15680 {
15681   struct fnfieldlist *flp;
15682   int i;
15683
15684   if (cu->language == language_ada)
15685     error (_("unexpected member functions in Ada type"));
15686
15687   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15688   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15689     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15690
15691   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15692     {
15693       struct nextfnfield *nfp = flp->head;
15694       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15695       int k;
15696
15697       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15698       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15699       fn_flp->fn_fields = (struct fn_field *)
15700         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15701       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15702         fn_flp->fn_fields[k] = nfp->fnfield;
15703     }
15704
15705   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15706 }
15707
15708 /* Returns non-zero if NAME is the name of a vtable member in CU's
15709    language, zero otherwise.  */
15710 static int
15711 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15712 {
15713   static const char vptr[] = "_vptr";
15714
15715   /* Look for the C++ form of the vtable.  */
15716   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15717     return 1;
15718
15719   return 0;
15720 }
15721
15722 /* GCC outputs unnamed structures that are really pointers to member
15723    functions, with the ABI-specified layout.  If TYPE describes
15724    such a structure, smash it into a member function type.
15725
15726    GCC shouldn't do this; it should just output pointer to member DIEs.
15727    This is GCC PR debug/28767.  */
15728
15729 static void
15730 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15731 {
15732   struct type *pfn_type, *self_type, *new_type;
15733
15734   /* Check for a structure with no name and two children.  */
15735   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15736     return;
15737
15738   /* Check for __pfn and __delta members.  */
15739   if (TYPE_FIELD_NAME (type, 0) == NULL
15740       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15741       || TYPE_FIELD_NAME (type, 1) == NULL
15742       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15743     return;
15744
15745   /* Find the type of the method.  */
15746   pfn_type = TYPE_FIELD_TYPE (type, 0);
15747   if (pfn_type == NULL
15748       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15749       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15750     return;
15751
15752   /* Look for the "this" argument.  */
15753   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15754   if (TYPE_NFIELDS (pfn_type) == 0
15755       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15756       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15757     return;
15758
15759   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15760   new_type = alloc_type (objfile);
15761   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15762                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15763                         TYPE_VARARGS (pfn_type));
15764   smash_to_methodptr_type (type, new_type);
15765 }
15766
15767
15768 /* Called when we find the DIE that starts a structure or union scope
15769    (definition) to create a type for the structure or union.  Fill in
15770    the type's name and general properties; the members will not be
15771    processed until process_structure_scope.  A symbol table entry for
15772    the type will also not be done until process_structure_scope (assuming
15773    the type has a name).
15774
15775    NOTE: we need to call these functions regardless of whether or not the
15776    DIE has a DW_AT_name attribute, since it might be an anonymous
15777    structure or union.  This gets the type entered into our set of
15778    user defined types.  */
15779
15780 static struct type *
15781 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15782 {
15783   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15784   struct type *type;
15785   struct attribute *attr;
15786   const char *name;
15787
15788   /* If the definition of this type lives in .debug_types, read that type.
15789      Don't follow DW_AT_specification though, that will take us back up
15790      the chain and we want to go down.  */
15791   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15792   if (attr)
15793     {
15794       type = get_DW_AT_signature_type (die, attr, cu);
15795
15796       /* The type's CU may not be the same as CU.
15797          Ensure TYPE is recorded with CU in die_type_hash.  */
15798       return set_die_type (die, type, cu);
15799     }
15800
15801   type = alloc_type (objfile);
15802   INIT_CPLUS_SPECIFIC (type);
15803
15804   name = dwarf2_name (die, cu);
15805   if (name != NULL)
15806     {
15807       if (cu->language == language_cplus
15808           || cu->language == language_d
15809           || cu->language == language_rust)
15810         {
15811           const char *full_name = dwarf2_full_name (name, die, cu);
15812
15813           /* dwarf2_full_name might have already finished building the DIE's
15814              type.  If so, there is no need to continue.  */
15815           if (get_die_type (die, cu) != NULL)
15816             return get_die_type (die, cu);
15817
15818           TYPE_TAG_NAME (type) = full_name;
15819           if (die->tag == DW_TAG_structure_type
15820               || die->tag == DW_TAG_class_type)
15821             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15822         }
15823       else
15824         {
15825           /* The name is already allocated along with this objfile, so
15826              we don't need to duplicate it for the type.  */
15827           TYPE_TAG_NAME (type) = name;
15828           if (die->tag == DW_TAG_class_type)
15829             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15830         }
15831     }
15832
15833   if (die->tag == DW_TAG_structure_type)
15834     {
15835       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15836     }
15837   else if (die->tag == DW_TAG_union_type)
15838     {
15839       TYPE_CODE (type) = TYPE_CODE_UNION;
15840     }
15841   else
15842     {
15843       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15844     }
15845
15846   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15847     TYPE_DECLARED_CLASS (type) = 1;
15848
15849   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15850   if (attr)
15851     {
15852       if (attr_form_is_constant (attr))
15853         TYPE_LENGTH (type) = DW_UNSND (attr);
15854       else
15855         {
15856           /* For the moment, dynamic type sizes are not supported
15857              by GDB's struct type.  The actual size is determined
15858              on-demand when resolving the type of a given object,
15859              so set the type's length to zero for now.  Otherwise,
15860              we record an expression as the length, and that expression
15861              could lead to a very large value, which could eventually
15862              lead to us trying to allocate that much memory when creating
15863              a value of that type.  */
15864           TYPE_LENGTH (type) = 0;
15865         }
15866     }
15867   else
15868     {
15869       TYPE_LENGTH (type) = 0;
15870     }
15871
15872   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15873     {
15874       /* ICC<14 does not output the required DW_AT_declaration on
15875          incomplete types, but gives them a size of zero.  */
15876       TYPE_STUB (type) = 1;
15877     }
15878   else
15879     TYPE_STUB_SUPPORTED (type) = 1;
15880
15881   if (die_is_declaration (die, cu))
15882     TYPE_STUB (type) = 1;
15883   else if (attr == NULL && die->child == NULL
15884            && producer_is_realview (cu->producer))
15885     /* RealView does not output the required DW_AT_declaration
15886        on incomplete types.  */
15887     TYPE_STUB (type) = 1;
15888
15889   /* We need to add the type field to the die immediately so we don't
15890      infinitely recurse when dealing with pointers to the structure
15891      type within the structure itself.  */
15892   set_die_type (die, type, cu);
15893
15894   /* set_die_type should be already done.  */
15895   set_descriptive_type (type, die, cu);
15896
15897   return type;
15898 }
15899
15900 /* Finish creating a structure or union type, including filling in
15901    its members and creating a symbol for it.  */
15902
15903 static void
15904 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15905 {
15906   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15907   struct die_info *child_die;
15908   struct type *type;
15909
15910   type = get_die_type (die, cu);
15911   if (type == NULL)
15912     type = read_structure_type (die, cu);
15913
15914   if (die->child != NULL && ! die_is_declaration (die, cu))
15915     {
15916       struct field_info fi;
15917       std::vector<struct symbol *> template_args;
15918       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15919
15920       memset (&fi, 0, sizeof (struct field_info));
15921
15922       child_die = die->child;
15923
15924       while (child_die && child_die->tag)
15925         {
15926           if (child_die->tag == DW_TAG_member
15927               || child_die->tag == DW_TAG_variable)
15928             {
15929               /* NOTE: carlton/2002-11-05: A C++ static data member
15930                  should be a DW_TAG_member that is a declaration, but
15931                  all versions of G++ as of this writing (so through at
15932                  least 3.2.1) incorrectly generate DW_TAG_variable
15933                  tags for them instead.  */
15934               dwarf2_add_field (&fi, child_die, cu);
15935             }
15936           else if (child_die->tag == DW_TAG_subprogram)
15937             {
15938               /* Rust doesn't have member functions in the C++ sense.
15939                  However, it does emit ordinary functions as children
15940                  of a struct DIE.  */
15941               if (cu->language == language_rust)
15942                 read_func_scope (child_die, cu);
15943               else
15944                 {
15945                   /* C++ member function.  */
15946                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15947                 }
15948             }
15949           else if (child_die->tag == DW_TAG_inheritance)
15950             {
15951               /* C++ base class field.  */
15952               dwarf2_add_field (&fi, child_die, cu);
15953             }
15954           else if (type_can_define_types (child_die))
15955             dwarf2_add_type_defn (&fi, child_die, cu);
15956           else if (child_die->tag == DW_TAG_template_type_param
15957                    || child_die->tag == DW_TAG_template_value_param)
15958             {
15959               struct symbol *arg = new_symbol (child_die, NULL, cu);
15960
15961               if (arg != NULL)
15962                 template_args.push_back (arg);
15963             }
15964
15965           child_die = sibling_die (child_die);
15966         }
15967
15968       /* Attach template arguments to type.  */
15969       if (!template_args.empty ())
15970         {
15971           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15972           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15973           TYPE_TEMPLATE_ARGUMENTS (type)
15974             = XOBNEWVEC (&objfile->objfile_obstack,
15975                          struct symbol *,
15976                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15977           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15978                   template_args.data (),
15979                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15980                    * sizeof (struct symbol *)));
15981         }
15982
15983       /* Attach fields and member functions to the type.  */
15984       if (fi.nfields)
15985         dwarf2_attach_fields_to_type (&fi, type, cu);
15986       if (fi.nfnfields)
15987         {
15988           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15989
15990           /* Get the type which refers to the base class (possibly this
15991              class itself) which contains the vtable pointer for the current
15992              class from the DW_AT_containing_type attribute.  This use of
15993              DW_AT_containing_type is a GNU extension.  */
15994
15995           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15996             {
15997               struct type *t = die_containing_type (die, cu);
15998
15999               set_type_vptr_basetype (type, t);
16000               if (type == t)
16001                 {
16002                   int i;
16003
16004                   /* Our own class provides vtbl ptr.  */
16005                   for (i = TYPE_NFIELDS (t) - 1;
16006                        i >= TYPE_N_BASECLASSES (t);
16007                        --i)
16008                     {
16009                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16010
16011                       if (is_vtable_name (fieldname, cu))
16012                         {
16013                           set_type_vptr_fieldno (type, i);
16014                           break;
16015                         }
16016                     }
16017
16018                   /* Complain if virtual function table field not found.  */
16019                   if (i < TYPE_N_BASECLASSES (t))
16020                     complaint (&symfile_complaints,
16021                                _("virtual function table pointer "
16022                                  "not found when defining class '%s'"),
16023                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16024                                "");
16025                 }
16026               else
16027                 {
16028                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16029                 }
16030             }
16031           else if (cu->producer
16032                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16033             {
16034               /* The IBM XLC compiler does not provide direct indication
16035                  of the containing type, but the vtable pointer is
16036                  always named __vfp.  */
16037
16038               int i;
16039
16040               for (i = TYPE_NFIELDS (type) - 1;
16041                    i >= TYPE_N_BASECLASSES (type);
16042                    --i)
16043                 {
16044                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16045                     {
16046                       set_type_vptr_fieldno (type, i);
16047                       set_type_vptr_basetype (type, type);
16048                       break;
16049                     }
16050                 }
16051             }
16052         }
16053
16054       /* Copy fi.typedef_field_list linked list elements content into the
16055          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16056       if (fi.typedef_field_list)
16057         {
16058           int i = fi.typedef_field_list_count;
16059
16060           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16061           TYPE_TYPEDEF_FIELD_ARRAY (type)
16062             = ((struct decl_field *)
16063                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16064           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16065
16066           /* Reverse the list order to keep the debug info elements order.  */
16067           while (--i >= 0)
16068             {
16069               struct decl_field *dest, *src;
16070
16071               dest = &TYPE_TYPEDEF_FIELD (type, i);
16072               src = &fi.typedef_field_list->field;
16073               fi.typedef_field_list = fi.typedef_field_list->next;
16074               *dest = *src;
16075             }
16076         }
16077
16078       /* Copy fi.nested_types_list linked list elements content into the
16079          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16080       if (fi.nested_types_list != NULL && cu->language != language_ada)
16081         {
16082           int i = fi.nested_types_list_count;
16083
16084           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16085           TYPE_NESTED_TYPES_ARRAY (type)
16086             = ((struct decl_field *)
16087                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16088           TYPE_NESTED_TYPES_COUNT (type) = i;
16089
16090           /* Reverse the list order to keep the debug info elements order.  */
16091           while (--i >= 0)
16092             {
16093               struct decl_field *dest, *src;
16094
16095               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16096               src = &fi.nested_types_list->field;
16097               fi.nested_types_list = fi.nested_types_list->next;
16098               *dest = *src;
16099             }
16100         }
16101
16102       do_cleanups (back_to);
16103     }
16104
16105   quirk_gcc_member_function_pointer (type, objfile);
16106
16107   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16108      snapshots) has been known to create a die giving a declaration
16109      for a class that has, as a child, a die giving a definition for a
16110      nested class.  So we have to process our children even if the
16111      current die is a declaration.  Normally, of course, a declaration
16112      won't have any children at all.  */
16113
16114   child_die = die->child;
16115
16116   while (child_die != NULL && child_die->tag)
16117     {
16118       if (child_die->tag == DW_TAG_member
16119           || child_die->tag == DW_TAG_variable
16120           || child_die->tag == DW_TAG_inheritance
16121           || child_die->tag == DW_TAG_template_value_param
16122           || child_die->tag == DW_TAG_template_type_param)
16123         {
16124           /* Do nothing.  */
16125         }
16126       else
16127         process_die (child_die, cu);
16128
16129       child_die = sibling_die (child_die);
16130     }
16131
16132   /* Do not consider external references.  According to the DWARF standard,
16133      these DIEs are identified by the fact that they have no byte_size
16134      attribute, and a declaration attribute.  */
16135   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16136       || !die_is_declaration (die, cu))
16137     new_symbol (die, type, cu);
16138 }
16139
16140 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16141    update TYPE using some information only available in DIE's children.  */
16142
16143 static void
16144 update_enumeration_type_from_children (struct die_info *die,
16145                                        struct type *type,
16146                                        struct dwarf2_cu *cu)
16147 {
16148   struct die_info *child_die;
16149   int unsigned_enum = 1;
16150   int flag_enum = 1;
16151   ULONGEST mask = 0;
16152
16153   auto_obstack obstack;
16154
16155   for (child_die = die->child;
16156        child_die != NULL && child_die->tag;
16157        child_die = sibling_die (child_die))
16158     {
16159       struct attribute *attr;
16160       LONGEST value;
16161       const gdb_byte *bytes;
16162       struct dwarf2_locexpr_baton *baton;
16163       const char *name;
16164
16165       if (child_die->tag != DW_TAG_enumerator)
16166         continue;
16167
16168       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16169       if (attr == NULL)
16170         continue;
16171
16172       name = dwarf2_name (child_die, cu);
16173       if (name == NULL)
16174         name = "<anonymous enumerator>";
16175
16176       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16177                                &value, &bytes, &baton);
16178       if (value < 0)
16179         {
16180           unsigned_enum = 0;
16181           flag_enum = 0;
16182         }
16183       else if ((mask & value) != 0)
16184         flag_enum = 0;
16185       else
16186         mask |= value;
16187
16188       /* If we already know that the enum type is neither unsigned, nor
16189          a flag type, no need to look at the rest of the enumerates.  */
16190       if (!unsigned_enum && !flag_enum)
16191         break;
16192     }
16193
16194   if (unsigned_enum)
16195     TYPE_UNSIGNED (type) = 1;
16196   if (flag_enum)
16197     TYPE_FLAG_ENUM (type) = 1;
16198 }
16199
16200 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16201    complete the type's fields yet, or create any symbols.  */
16202
16203 static struct type *
16204 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16205 {
16206   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16207   struct type *type;
16208   struct attribute *attr;
16209   const char *name;
16210
16211   /* If the definition of this type lives in .debug_types, read that type.
16212      Don't follow DW_AT_specification though, that will take us back up
16213      the chain and we want to go down.  */
16214   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16215   if (attr)
16216     {
16217       type = get_DW_AT_signature_type (die, attr, cu);
16218
16219       /* The type's CU may not be the same as CU.
16220          Ensure TYPE is recorded with CU in die_type_hash.  */
16221       return set_die_type (die, type, cu);
16222     }
16223
16224   type = alloc_type (objfile);
16225
16226   TYPE_CODE (type) = TYPE_CODE_ENUM;
16227   name = dwarf2_full_name (NULL, die, cu);
16228   if (name != NULL)
16229     TYPE_TAG_NAME (type) = name;
16230
16231   attr = dwarf2_attr (die, DW_AT_type, cu);
16232   if (attr != NULL)
16233     {
16234       struct type *underlying_type = die_type (die, cu);
16235
16236       TYPE_TARGET_TYPE (type) = underlying_type;
16237     }
16238
16239   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16240   if (attr)
16241     {
16242       TYPE_LENGTH (type) = DW_UNSND (attr);
16243     }
16244   else
16245     {
16246       TYPE_LENGTH (type) = 0;
16247     }
16248
16249   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16250      declared as private in the package spec, and then defined only
16251      inside the package body.  Such types are known as Taft Amendment
16252      Types.  When another package uses such a type, an incomplete DIE
16253      may be generated by the compiler.  */
16254   if (die_is_declaration (die, cu))
16255     TYPE_STUB (type) = 1;
16256
16257   /* Finish the creation of this type by using the enum's children.
16258      We must call this even when the underlying type has been provided
16259      so that we can determine if we're looking at a "flag" enum.  */
16260   update_enumeration_type_from_children (die, type, cu);
16261
16262   /* If this type has an underlying type that is not a stub, then we
16263      may use its attributes.  We always use the "unsigned" attribute
16264      in this situation, because ordinarily we guess whether the type
16265      is unsigned -- but the guess can be wrong and the underlying type
16266      can tell us the reality.  However, we defer to a local size
16267      attribute if one exists, because this lets the compiler override
16268      the underlying type if needed.  */
16269   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16270     {
16271       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16272       if (TYPE_LENGTH (type) == 0)
16273         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16274     }
16275
16276   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16277
16278   return set_die_type (die, type, cu);
16279 }
16280
16281 /* Given a pointer to a die which begins an enumeration, process all
16282    the dies that define the members of the enumeration, and create the
16283    symbol for the enumeration type.
16284
16285    NOTE: We reverse the order of the element list.  */
16286
16287 static void
16288 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16289 {
16290   struct type *this_type;
16291
16292   this_type = get_die_type (die, cu);
16293   if (this_type == NULL)
16294     this_type = read_enumeration_type (die, cu);
16295
16296   if (die->child != NULL)
16297     {
16298       struct die_info *child_die;
16299       struct symbol *sym;
16300       struct field *fields = NULL;
16301       int num_fields = 0;
16302       const char *name;
16303
16304       child_die = die->child;
16305       while (child_die && child_die->tag)
16306         {
16307           if (child_die->tag != DW_TAG_enumerator)
16308             {
16309               process_die (child_die, cu);
16310             }
16311           else
16312             {
16313               name = dwarf2_name (child_die, cu);
16314               if (name)
16315                 {
16316                   sym = new_symbol (child_die, this_type, cu);
16317
16318                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16319                     {
16320                       fields = (struct field *)
16321                         xrealloc (fields,
16322                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16323                                   * sizeof (struct field));
16324                     }
16325
16326                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16327                   FIELD_TYPE (fields[num_fields]) = NULL;
16328                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16329                   FIELD_BITSIZE (fields[num_fields]) = 0;
16330
16331                   num_fields++;
16332                 }
16333             }
16334
16335           child_die = sibling_die (child_die);
16336         }
16337
16338       if (num_fields)
16339         {
16340           TYPE_NFIELDS (this_type) = num_fields;
16341           TYPE_FIELDS (this_type) = (struct field *)
16342             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16343           memcpy (TYPE_FIELDS (this_type), fields,
16344                   sizeof (struct field) * num_fields);
16345           xfree (fields);
16346         }
16347     }
16348
16349   /* If we are reading an enum from a .debug_types unit, and the enum
16350      is a declaration, and the enum is not the signatured type in the
16351      unit, then we do not want to add a symbol for it.  Adding a
16352      symbol would in some cases obscure the true definition of the
16353      enum, giving users an incomplete type when the definition is
16354      actually available.  Note that we do not want to do this for all
16355      enums which are just declarations, because C++0x allows forward
16356      enum declarations.  */
16357   if (cu->per_cu->is_debug_types
16358       && die_is_declaration (die, cu))
16359     {
16360       struct signatured_type *sig_type;
16361
16362       sig_type = (struct signatured_type *) cu->per_cu;
16363       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16364       if (sig_type->type_offset_in_section != die->sect_off)
16365         return;
16366     }
16367
16368   new_symbol (die, this_type, cu);
16369 }
16370
16371 /* Extract all information from a DW_TAG_array_type DIE and put it in
16372    the DIE's type field.  For now, this only handles one dimensional
16373    arrays.  */
16374
16375 static struct type *
16376 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16377 {
16378   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16379   struct die_info *child_die;
16380   struct type *type;
16381   struct type *element_type, *range_type, *index_type;
16382   struct attribute *attr;
16383   const char *name;
16384   struct dynamic_prop *byte_stride_prop = NULL;
16385   unsigned int bit_stride = 0;
16386
16387   element_type = die_type (die, cu);
16388
16389   /* The die_type call above may have already set the type for this DIE.  */
16390   type = get_die_type (die, cu);
16391   if (type)
16392     return type;
16393
16394   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16395   if (attr != NULL)
16396     {
16397       int stride_ok;
16398
16399       byte_stride_prop
16400         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16401       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16402       if (!stride_ok)
16403         {
16404           complaint (&symfile_complaints,
16405                      _("unable to read array DW_AT_byte_stride "
16406                        " - DIE at 0x%x [in module %s]"),
16407                      to_underlying (die->sect_off),
16408                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16409           /* Ignore this attribute.  We will likely not be able to print
16410              arrays of this type correctly, but there is little we can do
16411              to help if we cannot read the attribute's value.  */
16412           byte_stride_prop = NULL;
16413         }
16414     }
16415
16416   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16417   if (attr != NULL)
16418     bit_stride = DW_UNSND (attr);
16419
16420   /* Irix 6.2 native cc creates array types without children for
16421      arrays with unspecified length.  */
16422   if (die->child == NULL)
16423     {
16424       index_type = objfile_type (objfile)->builtin_int;
16425       range_type = create_static_range_type (NULL, index_type, 0, -1);
16426       type = create_array_type_with_stride (NULL, element_type, range_type,
16427                                             byte_stride_prop, bit_stride);
16428       return set_die_type (die, type, cu);
16429     }
16430
16431   std::vector<struct type *> range_types;
16432   child_die = die->child;
16433   while (child_die && child_die->tag)
16434     {
16435       if (child_die->tag == DW_TAG_subrange_type)
16436         {
16437           struct type *child_type = read_type_die (child_die, cu);
16438
16439           if (child_type != NULL)
16440             {
16441               /* The range type was succesfully read.  Save it for the
16442                  array type creation.  */
16443               range_types.push_back (child_type);
16444             }
16445         }
16446       child_die = sibling_die (child_die);
16447     }
16448
16449   /* Dwarf2 dimensions are output from left to right, create the
16450      necessary array types in backwards order.  */
16451
16452   type = element_type;
16453
16454   if (read_array_order (die, cu) == DW_ORD_col_major)
16455     {
16456       int i = 0;
16457
16458       while (i < range_types.size ())
16459         type = create_array_type_with_stride (NULL, type, range_types[i++],
16460                                               byte_stride_prop, bit_stride);
16461     }
16462   else
16463     {
16464       size_t ndim = range_types.size ();
16465       while (ndim-- > 0)
16466         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16467                                               byte_stride_prop, bit_stride);
16468     }
16469
16470   /* Understand Dwarf2 support for vector types (like they occur on
16471      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16472      array type.  This is not part of the Dwarf2/3 standard yet, but a
16473      custom vendor extension.  The main difference between a regular
16474      array and the vector variant is that vectors are passed by value
16475      to functions.  */
16476   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16477   if (attr)
16478     make_vector_type (type);
16479
16480   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16481      implementation may choose to implement triple vectors using this
16482      attribute.  */
16483   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16484   if (attr)
16485     {
16486       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16487         TYPE_LENGTH (type) = DW_UNSND (attr);
16488       else
16489         complaint (&symfile_complaints,
16490                    _("DW_AT_byte_size for array type smaller "
16491                      "than the total size of elements"));
16492     }
16493
16494   name = dwarf2_name (die, cu);
16495   if (name)
16496     TYPE_NAME (type) = name;
16497
16498   /* Install the type in the die.  */
16499   set_die_type (die, type, cu);
16500
16501   /* set_die_type should be already done.  */
16502   set_descriptive_type (type, die, cu);
16503
16504   return type;
16505 }
16506
16507 static enum dwarf_array_dim_ordering
16508 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16509 {
16510   struct attribute *attr;
16511
16512   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16513
16514   if (attr)
16515     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16516
16517   /* GNU F77 is a special case, as at 08/2004 array type info is the
16518      opposite order to the dwarf2 specification, but data is still
16519      laid out as per normal fortran.
16520
16521      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16522      version checking.  */
16523
16524   if (cu->language == language_fortran
16525       && cu->producer && strstr (cu->producer, "GNU F77"))
16526     {
16527       return DW_ORD_row_major;
16528     }
16529
16530   switch (cu->language_defn->la_array_ordering)
16531     {
16532     case array_column_major:
16533       return DW_ORD_col_major;
16534     case array_row_major:
16535     default:
16536       return DW_ORD_row_major;
16537     };
16538 }
16539
16540 /* Extract all information from a DW_TAG_set_type DIE and put it in
16541    the DIE's type field.  */
16542
16543 static struct type *
16544 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16545 {
16546   struct type *domain_type, *set_type;
16547   struct attribute *attr;
16548
16549   domain_type = die_type (die, cu);
16550
16551   /* The die_type call above may have already set the type for this DIE.  */
16552   set_type = get_die_type (die, cu);
16553   if (set_type)
16554     return set_type;
16555
16556   set_type = create_set_type (NULL, domain_type);
16557
16558   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16559   if (attr)
16560     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16561
16562   return set_die_type (die, set_type, cu);
16563 }
16564
16565 /* A helper for read_common_block that creates a locexpr baton.
16566    SYM is the symbol which we are marking as computed.
16567    COMMON_DIE is the DIE for the common block.
16568    COMMON_LOC is the location expression attribute for the common
16569    block itself.
16570    MEMBER_LOC is the location expression attribute for the particular
16571    member of the common block that we are processing.
16572    CU is the CU from which the above come.  */
16573
16574 static void
16575 mark_common_block_symbol_computed (struct symbol *sym,
16576                                    struct die_info *common_die,
16577                                    struct attribute *common_loc,
16578                                    struct attribute *member_loc,
16579                                    struct dwarf2_cu *cu)
16580 {
16581   struct dwarf2_per_objfile *dwarf2_per_objfile
16582     = cu->per_cu->dwarf2_per_objfile;
16583   struct objfile *objfile = dwarf2_per_objfile->objfile;
16584   struct dwarf2_locexpr_baton *baton;
16585   gdb_byte *ptr;
16586   unsigned int cu_off;
16587   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16588   LONGEST offset = 0;
16589
16590   gdb_assert (common_loc && member_loc);
16591   gdb_assert (attr_form_is_block (common_loc));
16592   gdb_assert (attr_form_is_block (member_loc)
16593               || attr_form_is_constant (member_loc));
16594
16595   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16596   baton->per_cu = cu->per_cu;
16597   gdb_assert (baton->per_cu);
16598
16599   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16600
16601   if (attr_form_is_constant (member_loc))
16602     {
16603       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16604       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16605     }
16606   else
16607     baton->size += DW_BLOCK (member_loc)->size;
16608
16609   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16610   baton->data = ptr;
16611
16612   *ptr++ = DW_OP_call4;
16613   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16614   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16615   ptr += 4;
16616
16617   if (attr_form_is_constant (member_loc))
16618     {
16619       *ptr++ = DW_OP_addr;
16620       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16621       ptr += cu->header.addr_size;
16622     }
16623   else
16624     {
16625       /* We have to copy the data here, because DW_OP_call4 will only
16626          use a DW_AT_location attribute.  */
16627       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16628       ptr += DW_BLOCK (member_loc)->size;
16629     }
16630
16631   *ptr++ = DW_OP_plus;
16632   gdb_assert (ptr - baton->data == baton->size);
16633
16634   SYMBOL_LOCATION_BATON (sym) = baton;
16635   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16636 }
16637
16638 /* Create appropriate locally-scoped variables for all the
16639    DW_TAG_common_block entries.  Also create a struct common_block
16640    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16641    is used to sepate the common blocks name namespace from regular
16642    variable names.  */
16643
16644 static void
16645 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16646 {
16647   struct attribute *attr;
16648
16649   attr = dwarf2_attr (die, DW_AT_location, cu);
16650   if (attr)
16651     {
16652       /* Support the .debug_loc offsets.  */
16653       if (attr_form_is_block (attr))
16654         {
16655           /* Ok.  */
16656         }
16657       else if (attr_form_is_section_offset (attr))
16658         {
16659           dwarf2_complex_location_expr_complaint ();
16660           attr = NULL;
16661         }
16662       else
16663         {
16664           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16665                                                  "common block member");
16666           attr = NULL;
16667         }
16668     }
16669
16670   if (die->child != NULL)
16671     {
16672       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16673       struct die_info *child_die;
16674       size_t n_entries = 0, size;
16675       struct common_block *common_block;
16676       struct symbol *sym;
16677
16678       for (child_die = die->child;
16679            child_die && child_die->tag;
16680            child_die = sibling_die (child_die))
16681         ++n_entries;
16682
16683       size = (sizeof (struct common_block)
16684               + (n_entries - 1) * sizeof (struct symbol *));
16685       common_block
16686         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16687                                                  size);
16688       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16689       common_block->n_entries = 0;
16690
16691       for (child_die = die->child;
16692            child_die && child_die->tag;
16693            child_die = sibling_die (child_die))
16694         {
16695           /* Create the symbol in the DW_TAG_common_block block in the current
16696              symbol scope.  */
16697           sym = new_symbol (child_die, NULL, cu);
16698           if (sym != NULL)
16699             {
16700               struct attribute *member_loc;
16701
16702               common_block->contents[common_block->n_entries++] = sym;
16703
16704               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16705                                         cu);
16706               if (member_loc)
16707                 {
16708                   /* GDB has handled this for a long time, but it is
16709                      not specified by DWARF.  It seems to have been
16710                      emitted by gfortran at least as recently as:
16711                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16712                   complaint (&symfile_complaints,
16713                              _("Variable in common block has "
16714                                "DW_AT_data_member_location "
16715                                "- DIE at 0x%x [in module %s]"),
16716                              to_underlying (child_die->sect_off),
16717                              objfile_name (objfile));
16718
16719                   if (attr_form_is_section_offset (member_loc))
16720                     dwarf2_complex_location_expr_complaint ();
16721                   else if (attr_form_is_constant (member_loc)
16722                            || attr_form_is_block (member_loc))
16723                     {
16724                       if (attr)
16725                         mark_common_block_symbol_computed (sym, die, attr,
16726                                                            member_loc, cu);
16727                     }
16728                   else
16729                     dwarf2_complex_location_expr_complaint ();
16730                 }
16731             }
16732         }
16733
16734       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16735       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16736     }
16737 }
16738
16739 /* Create a type for a C++ namespace.  */
16740
16741 static struct type *
16742 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16743 {
16744   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16745   const char *previous_prefix, *name;
16746   int is_anonymous;
16747   struct type *type;
16748
16749   /* For extensions, reuse the type of the original namespace.  */
16750   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16751     {
16752       struct die_info *ext_die;
16753       struct dwarf2_cu *ext_cu = cu;
16754
16755       ext_die = dwarf2_extension (die, &ext_cu);
16756       type = read_type_die (ext_die, ext_cu);
16757
16758       /* EXT_CU may not be the same as CU.
16759          Ensure TYPE is recorded with CU in die_type_hash.  */
16760       return set_die_type (die, type, cu);
16761     }
16762
16763   name = namespace_name (die, &is_anonymous, cu);
16764
16765   /* Now build the name of the current namespace.  */
16766
16767   previous_prefix = determine_prefix (die, cu);
16768   if (previous_prefix[0] != '\0')
16769     name = typename_concat (&objfile->objfile_obstack,
16770                             previous_prefix, name, 0, cu);
16771
16772   /* Create the type.  */
16773   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16774   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16775
16776   return set_die_type (die, type, cu);
16777 }
16778
16779 /* Read a namespace scope.  */
16780
16781 static void
16782 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16783 {
16784   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16785   int is_anonymous;
16786
16787   /* Add a symbol associated to this if we haven't seen the namespace
16788      before.  Also, add a using directive if it's an anonymous
16789      namespace.  */
16790
16791   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16792     {
16793       struct type *type;
16794
16795       type = read_type_die (die, cu);
16796       new_symbol (die, type, cu);
16797
16798       namespace_name (die, &is_anonymous, cu);
16799       if (is_anonymous)
16800         {
16801           const char *previous_prefix = determine_prefix (die, cu);
16802
16803           std::vector<const char *> excludes;
16804           add_using_directive (using_directives (cu->language),
16805                                previous_prefix, TYPE_NAME (type), NULL,
16806                                NULL, excludes, 0, &objfile->objfile_obstack);
16807         }
16808     }
16809
16810   if (die->child != NULL)
16811     {
16812       struct die_info *child_die = die->child;
16813
16814       while (child_die && child_die->tag)
16815         {
16816           process_die (child_die, cu);
16817           child_die = sibling_die (child_die);
16818         }
16819     }
16820 }
16821
16822 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16823    imported module.  Still we need that type as local Fortran "use ... only"
16824    declaration imports depend on the created type in determine_prefix.  */
16825
16826 static struct type *
16827 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16828 {
16829   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16830   const char *module_name;
16831   struct type *type;
16832
16833   module_name = dwarf2_name (die, cu);
16834   if (!module_name)
16835     complaint (&symfile_complaints,
16836                _("DW_TAG_module has no name, offset 0x%x"),
16837                to_underlying (die->sect_off));
16838   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16839
16840   /* determine_prefix uses TYPE_TAG_NAME.  */
16841   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16842
16843   return set_die_type (die, type, cu);
16844 }
16845
16846 /* Read a Fortran module.  */
16847
16848 static void
16849 read_module (struct die_info *die, struct dwarf2_cu *cu)
16850 {
16851   struct die_info *child_die = die->child;
16852   struct type *type;
16853
16854   type = read_type_die (die, cu);
16855   new_symbol (die, type, cu);
16856
16857   while (child_die && child_die->tag)
16858     {
16859       process_die (child_die, cu);
16860       child_die = sibling_die (child_die);
16861     }
16862 }
16863
16864 /* Return the name of the namespace represented by DIE.  Set
16865    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16866    namespace.  */
16867
16868 static const char *
16869 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16870 {
16871   struct die_info *current_die;
16872   const char *name = NULL;
16873
16874   /* Loop through the extensions until we find a name.  */
16875
16876   for (current_die = die;
16877        current_die != NULL;
16878        current_die = dwarf2_extension (die, &cu))
16879     {
16880       /* We don't use dwarf2_name here so that we can detect the absence
16881          of a name -> anonymous namespace.  */
16882       name = dwarf2_string_attr (die, DW_AT_name, cu);
16883
16884       if (name != NULL)
16885         break;
16886     }
16887
16888   /* Is it an anonymous namespace?  */
16889
16890   *is_anonymous = (name == NULL);
16891   if (*is_anonymous)
16892     name = CP_ANONYMOUS_NAMESPACE_STR;
16893
16894   return name;
16895 }
16896
16897 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16898    the user defined type vector.  */
16899
16900 static struct type *
16901 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16902 {
16903   struct gdbarch *gdbarch
16904     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16905   struct comp_unit_head *cu_header = &cu->header;
16906   struct type *type;
16907   struct attribute *attr_byte_size;
16908   struct attribute *attr_address_class;
16909   int byte_size, addr_class;
16910   struct type *target_type;
16911
16912   target_type = die_type (die, cu);
16913
16914   /* The die_type call above may have already set the type for this DIE.  */
16915   type = get_die_type (die, cu);
16916   if (type)
16917     return type;
16918
16919   type = lookup_pointer_type (target_type);
16920
16921   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16922   if (attr_byte_size)
16923     byte_size = DW_UNSND (attr_byte_size);
16924   else
16925     byte_size = cu_header->addr_size;
16926
16927   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16928   if (attr_address_class)
16929     addr_class = DW_UNSND (attr_address_class);
16930   else
16931     addr_class = DW_ADDR_none;
16932
16933   /* If the pointer size or address class is different than the
16934      default, create a type variant marked as such and set the
16935      length accordingly.  */
16936   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16937     {
16938       if (gdbarch_address_class_type_flags_p (gdbarch))
16939         {
16940           int type_flags;
16941
16942           type_flags = gdbarch_address_class_type_flags
16943                          (gdbarch, byte_size, addr_class);
16944           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16945                       == 0);
16946           type = make_type_with_address_space (type, type_flags);
16947         }
16948       else if (TYPE_LENGTH (type) != byte_size)
16949         {
16950           complaint (&symfile_complaints,
16951                      _("invalid pointer size %d"), byte_size);
16952         }
16953       else
16954         {
16955           /* Should we also complain about unhandled address classes?  */
16956         }
16957     }
16958
16959   TYPE_LENGTH (type) = byte_size;
16960   return set_die_type (die, type, cu);
16961 }
16962
16963 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16964    the user defined type vector.  */
16965
16966 static struct type *
16967 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16968 {
16969   struct type *type;
16970   struct type *to_type;
16971   struct type *domain;
16972
16973   to_type = die_type (die, cu);
16974   domain = die_containing_type (die, cu);
16975
16976   /* The calls above may have already set the type for this DIE.  */
16977   type = get_die_type (die, cu);
16978   if (type)
16979     return type;
16980
16981   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16982     type = lookup_methodptr_type (to_type);
16983   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16984     {
16985       struct type *new_type
16986         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16987
16988       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16989                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16990                             TYPE_VARARGS (to_type));
16991       type = lookup_methodptr_type (new_type);
16992     }
16993   else
16994     type = lookup_memberptr_type (to_type, domain);
16995
16996   return set_die_type (die, type, cu);
16997 }
16998
16999 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17000    the user defined type vector.  */
17001
17002 static struct type *
17003 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17004                           enum type_code refcode)
17005 {
17006   struct comp_unit_head *cu_header = &cu->header;
17007   struct type *type, *target_type;
17008   struct attribute *attr;
17009
17010   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17011
17012   target_type = die_type (die, cu);
17013
17014   /* The die_type call above may have already set the type for this DIE.  */
17015   type = get_die_type (die, cu);
17016   if (type)
17017     return type;
17018
17019   type = lookup_reference_type (target_type, refcode);
17020   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17021   if (attr)
17022     {
17023       TYPE_LENGTH (type) = DW_UNSND (attr);
17024     }
17025   else
17026     {
17027       TYPE_LENGTH (type) = cu_header->addr_size;
17028     }
17029   return set_die_type (die, type, cu);
17030 }
17031
17032 /* Add the given cv-qualifiers to the element type of the array.  GCC
17033    outputs DWARF type qualifiers that apply to an array, not the
17034    element type.  But GDB relies on the array element type to carry
17035    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17036    specification.  */
17037
17038 static struct type *
17039 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17040                    struct type *base_type, int cnst, int voltl)
17041 {
17042   struct type *el_type, *inner_array;
17043
17044   base_type = copy_type (base_type);
17045   inner_array = base_type;
17046
17047   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17048     {
17049       TYPE_TARGET_TYPE (inner_array) =
17050         copy_type (TYPE_TARGET_TYPE (inner_array));
17051       inner_array = TYPE_TARGET_TYPE (inner_array);
17052     }
17053
17054   el_type = TYPE_TARGET_TYPE (inner_array);
17055   cnst |= TYPE_CONST (el_type);
17056   voltl |= TYPE_VOLATILE (el_type);
17057   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17058
17059   return set_die_type (die, base_type, cu);
17060 }
17061
17062 static struct type *
17063 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17064 {
17065   struct type *base_type, *cv_type;
17066
17067   base_type = die_type (die, cu);
17068
17069   /* The die_type call above may have already set the type for this DIE.  */
17070   cv_type = get_die_type (die, cu);
17071   if (cv_type)
17072     return cv_type;
17073
17074   /* In case the const qualifier is applied to an array type, the element type
17075      is so qualified, not the array type (section 6.7.3 of C99).  */
17076   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17077     return add_array_cv_type (die, cu, base_type, 1, 0);
17078
17079   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17080   return set_die_type (die, cv_type, cu);
17081 }
17082
17083 static struct type *
17084 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17085 {
17086   struct type *base_type, *cv_type;
17087
17088   base_type = die_type (die, cu);
17089
17090   /* The die_type call above may have already set the type for this DIE.  */
17091   cv_type = get_die_type (die, cu);
17092   if (cv_type)
17093     return cv_type;
17094
17095   /* In case the volatile qualifier is applied to an array type, the
17096      element type is so qualified, not the array type (section 6.7.3
17097      of C99).  */
17098   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17099     return add_array_cv_type (die, cu, base_type, 0, 1);
17100
17101   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17102   return set_die_type (die, cv_type, cu);
17103 }
17104
17105 /* Handle DW_TAG_restrict_type.  */
17106
17107 static struct type *
17108 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17109 {
17110   struct type *base_type, *cv_type;
17111
17112   base_type = die_type (die, cu);
17113
17114   /* The die_type call above may have already set the type for this DIE.  */
17115   cv_type = get_die_type (die, cu);
17116   if (cv_type)
17117     return cv_type;
17118
17119   cv_type = make_restrict_type (base_type);
17120   return set_die_type (die, cv_type, cu);
17121 }
17122
17123 /* Handle DW_TAG_atomic_type.  */
17124
17125 static struct type *
17126 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17127 {
17128   struct type *base_type, *cv_type;
17129
17130   base_type = die_type (die, cu);
17131
17132   /* The die_type call above may have already set the type for this DIE.  */
17133   cv_type = get_die_type (die, cu);
17134   if (cv_type)
17135     return cv_type;
17136
17137   cv_type = make_atomic_type (base_type);
17138   return set_die_type (die, cv_type, cu);
17139 }
17140
17141 /* Extract all information from a DW_TAG_string_type DIE and add to
17142    the user defined type vector.  It isn't really a user defined type,
17143    but it behaves like one, with other DIE's using an AT_user_def_type
17144    attribute to reference it.  */
17145
17146 static struct type *
17147 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17148 {
17149   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17150   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17151   struct type *type, *range_type, *index_type, *char_type;
17152   struct attribute *attr;
17153   unsigned int length;
17154
17155   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17156   if (attr)
17157     {
17158       length = DW_UNSND (attr);
17159     }
17160   else
17161     {
17162       /* Check for the DW_AT_byte_size attribute.  */
17163       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17164       if (attr)
17165         {
17166           length = DW_UNSND (attr);
17167         }
17168       else
17169         {
17170           length = 1;
17171         }
17172     }
17173
17174   index_type = objfile_type (objfile)->builtin_int;
17175   range_type = create_static_range_type (NULL, index_type, 1, length);
17176   char_type = language_string_char_type (cu->language_defn, gdbarch);
17177   type = create_string_type (NULL, char_type, range_type);
17178
17179   return set_die_type (die, type, cu);
17180 }
17181
17182 /* Assuming that DIE corresponds to a function, returns nonzero
17183    if the function is prototyped.  */
17184
17185 static int
17186 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17187 {
17188   struct attribute *attr;
17189
17190   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17191   if (attr && (DW_UNSND (attr) != 0))
17192     return 1;
17193
17194   /* The DWARF standard implies that the DW_AT_prototyped attribute
17195      is only meaninful for C, but the concept also extends to other
17196      languages that allow unprototyped functions (Eg: Objective C).
17197      For all other languages, assume that functions are always
17198      prototyped.  */
17199   if (cu->language != language_c
17200       && cu->language != language_objc
17201       && cu->language != language_opencl)
17202     return 1;
17203
17204   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17205      prototyped and unprototyped functions; default to prototyped,
17206      since that is more common in modern code (and RealView warns
17207      about unprototyped functions).  */
17208   if (producer_is_realview (cu->producer))
17209     return 1;
17210
17211   return 0;
17212 }
17213
17214 /* Handle DIES due to C code like:
17215
17216    struct foo
17217    {
17218    int (*funcp)(int a, long l);
17219    int b;
17220    };
17221
17222    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17223
17224 static struct type *
17225 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17226 {
17227   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17228   struct type *type;            /* Type that this function returns.  */
17229   struct type *ftype;           /* Function that returns above type.  */
17230   struct attribute *attr;
17231
17232   type = die_type (die, cu);
17233
17234   /* The die_type call above may have already set the type for this DIE.  */
17235   ftype = get_die_type (die, cu);
17236   if (ftype)
17237     return ftype;
17238
17239   ftype = lookup_function_type (type);
17240
17241   if (prototyped_function_p (die, cu))
17242     TYPE_PROTOTYPED (ftype) = 1;
17243
17244   /* Store the calling convention in the type if it's available in
17245      the subroutine die.  Otherwise set the calling convention to
17246      the default value DW_CC_normal.  */
17247   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17248   if (attr)
17249     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17250   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17251     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17252   else
17253     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17254
17255   /* Record whether the function returns normally to its caller or not
17256      if the DWARF producer set that information.  */
17257   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17258   if (attr && (DW_UNSND (attr) != 0))
17259     TYPE_NO_RETURN (ftype) = 1;
17260
17261   /* We need to add the subroutine type to the die immediately so
17262      we don't infinitely recurse when dealing with parameters
17263      declared as the same subroutine type.  */
17264   set_die_type (die, ftype, cu);
17265
17266   if (die->child != NULL)
17267     {
17268       struct type *void_type = objfile_type (objfile)->builtin_void;
17269       struct die_info *child_die;
17270       int nparams, iparams;
17271
17272       /* Count the number of parameters.
17273          FIXME: GDB currently ignores vararg functions, but knows about
17274          vararg member functions.  */
17275       nparams = 0;
17276       child_die = die->child;
17277       while (child_die && child_die->tag)
17278         {
17279           if (child_die->tag == DW_TAG_formal_parameter)
17280             nparams++;
17281           else if (child_die->tag == DW_TAG_unspecified_parameters)
17282             TYPE_VARARGS (ftype) = 1;
17283           child_die = sibling_die (child_die);
17284         }
17285
17286       /* Allocate storage for parameters and fill them in.  */
17287       TYPE_NFIELDS (ftype) = nparams;
17288       TYPE_FIELDS (ftype) = (struct field *)
17289         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17290
17291       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17292          even if we error out during the parameters reading below.  */
17293       for (iparams = 0; iparams < nparams; iparams++)
17294         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17295
17296       iparams = 0;
17297       child_die = die->child;
17298       while (child_die && child_die->tag)
17299         {
17300           if (child_die->tag == DW_TAG_formal_parameter)
17301             {
17302               struct type *arg_type;
17303
17304               /* DWARF version 2 has no clean way to discern C++
17305                  static and non-static member functions.  G++ helps
17306                  GDB by marking the first parameter for non-static
17307                  member functions (which is the this pointer) as
17308                  artificial.  We pass this information to
17309                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17310
17311                  DWARF version 3 added DW_AT_object_pointer, which GCC
17312                  4.5 does not yet generate.  */
17313               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17314               if (attr)
17315                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17316               else
17317                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17318               arg_type = die_type (child_die, cu);
17319
17320               /* RealView does not mark THIS as const, which the testsuite
17321                  expects.  GCC marks THIS as const in method definitions,
17322                  but not in the class specifications (GCC PR 43053).  */
17323               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17324                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17325                 {
17326                   int is_this = 0;
17327                   struct dwarf2_cu *arg_cu = cu;
17328                   const char *name = dwarf2_name (child_die, cu);
17329
17330                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17331                   if (attr)
17332                     {
17333                       /* If the compiler emits this, use it.  */
17334                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17335                         is_this = 1;
17336                     }
17337                   else if (name && strcmp (name, "this") == 0)
17338                     /* Function definitions will have the argument names.  */
17339                     is_this = 1;
17340                   else if (name == NULL && iparams == 0)
17341                     /* Declarations may not have the names, so like
17342                        elsewhere in GDB, assume an artificial first
17343                        argument is "this".  */
17344                     is_this = 1;
17345
17346                   if (is_this)
17347                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17348                                              arg_type, 0);
17349                 }
17350
17351               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17352               iparams++;
17353             }
17354           child_die = sibling_die (child_die);
17355         }
17356     }
17357
17358   return ftype;
17359 }
17360
17361 static struct type *
17362 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17363 {
17364   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17365   const char *name = NULL;
17366   struct type *this_type, *target_type;
17367
17368   name = dwarf2_full_name (NULL, die, cu);
17369   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17370   TYPE_TARGET_STUB (this_type) = 1;
17371   set_die_type (die, this_type, cu);
17372   target_type = die_type (die, cu);
17373   if (target_type != this_type)
17374     TYPE_TARGET_TYPE (this_type) = target_type;
17375   else
17376     {
17377       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17378          spec and cause infinite loops in GDB.  */
17379       complaint (&symfile_complaints,
17380                  _("Self-referential DW_TAG_typedef "
17381                    "- DIE at 0x%x [in module %s]"),
17382                  to_underlying (die->sect_off), objfile_name (objfile));
17383       TYPE_TARGET_TYPE (this_type) = NULL;
17384     }
17385   return this_type;
17386 }
17387
17388 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17389    (which may be different from NAME) to the architecture back-end to allow
17390    it to guess the correct format if necessary.  */
17391
17392 static struct type *
17393 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17394                         const char *name_hint)
17395 {
17396   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17397   const struct floatformat **format;
17398   struct type *type;
17399
17400   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17401   if (format)
17402     type = init_float_type (objfile, bits, name, format);
17403   else
17404     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17405
17406   return type;
17407 }
17408
17409 /* Find a representation of a given base type and install
17410    it in the TYPE field of the die.  */
17411
17412 static struct type *
17413 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17414 {
17415   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17416   struct type *type;
17417   struct attribute *attr;
17418   int encoding = 0, bits = 0;
17419   const char *name;
17420
17421   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17422   if (attr)
17423     {
17424       encoding = DW_UNSND (attr);
17425     }
17426   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17427   if (attr)
17428     {
17429       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17430     }
17431   name = dwarf2_name (die, cu);
17432   if (!name)
17433     {
17434       complaint (&symfile_complaints,
17435                  _("DW_AT_name missing from DW_TAG_base_type"));
17436     }
17437
17438   switch (encoding)
17439     {
17440       case DW_ATE_address:
17441         /* Turn DW_ATE_address into a void * pointer.  */
17442         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17443         type = init_pointer_type (objfile, bits, name, type);
17444         break;
17445       case DW_ATE_boolean:
17446         type = init_boolean_type (objfile, bits, 1, name);
17447         break;
17448       case DW_ATE_complex_float:
17449         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17450         type = init_complex_type (objfile, name, type);
17451         break;
17452       case DW_ATE_decimal_float:
17453         type = init_decfloat_type (objfile, bits, name);
17454         break;
17455       case DW_ATE_float:
17456         type = dwarf2_init_float_type (objfile, bits, name, name);
17457         break;
17458       case DW_ATE_signed:
17459         type = init_integer_type (objfile, bits, 0, name);
17460         break;
17461       case DW_ATE_unsigned:
17462         if (cu->language == language_fortran
17463             && name
17464             && startswith (name, "character("))
17465           type = init_character_type (objfile, bits, 1, name);
17466         else
17467           type = init_integer_type (objfile, bits, 1, name);
17468         break;
17469       case DW_ATE_signed_char:
17470         if (cu->language == language_ada || cu->language == language_m2
17471             || cu->language == language_pascal
17472             || cu->language == language_fortran)
17473           type = init_character_type (objfile, bits, 0, name);
17474         else
17475           type = init_integer_type (objfile, bits, 0, name);
17476         break;
17477       case DW_ATE_unsigned_char:
17478         if (cu->language == language_ada || cu->language == language_m2
17479             || cu->language == language_pascal
17480             || cu->language == language_fortran
17481             || cu->language == language_rust)
17482           type = init_character_type (objfile, bits, 1, name);
17483         else
17484           type = init_integer_type (objfile, bits, 1, name);
17485         break;
17486       case DW_ATE_UTF:
17487         {
17488           gdbarch *arch = get_objfile_arch (objfile);
17489
17490           if (bits == 16)
17491             type = builtin_type (arch)->builtin_char16;
17492           else if (bits == 32)
17493             type = builtin_type (arch)->builtin_char32;
17494           else
17495             {
17496               complaint (&symfile_complaints,
17497                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17498                          bits);
17499               type = init_integer_type (objfile, bits, 1, name);
17500             }
17501           return set_die_type (die, type, cu);
17502         }
17503         break;
17504
17505       default:
17506         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17507                    dwarf_type_encoding_name (encoding));
17508         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17509         break;
17510     }
17511
17512   if (name && strcmp (name, "char") == 0)
17513     TYPE_NOSIGN (type) = 1;
17514
17515   return set_die_type (die, type, cu);
17516 }
17517
17518 /* Parse dwarf attribute if it's a block, reference or constant and put the
17519    resulting value of the attribute into struct bound_prop.
17520    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17521
17522 static int
17523 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17524                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17525 {
17526   struct dwarf2_property_baton *baton;
17527   struct obstack *obstack
17528     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17529
17530   if (attr == NULL || prop == NULL)
17531     return 0;
17532
17533   if (attr_form_is_block (attr))
17534     {
17535       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17536       baton->referenced_type = NULL;
17537       baton->locexpr.per_cu = cu->per_cu;
17538       baton->locexpr.size = DW_BLOCK (attr)->size;
17539       baton->locexpr.data = DW_BLOCK (attr)->data;
17540       prop->data.baton = baton;
17541       prop->kind = PROP_LOCEXPR;
17542       gdb_assert (prop->data.baton != NULL);
17543     }
17544   else if (attr_form_is_ref (attr))
17545     {
17546       struct dwarf2_cu *target_cu = cu;
17547       struct die_info *target_die;
17548       struct attribute *target_attr;
17549
17550       target_die = follow_die_ref (die, attr, &target_cu);
17551       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17552       if (target_attr == NULL)
17553         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17554                                    target_cu);
17555       if (target_attr == NULL)
17556         return 0;
17557
17558       switch (target_attr->name)
17559         {
17560           case DW_AT_location:
17561             if (attr_form_is_section_offset (target_attr))
17562               {
17563                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17564                 baton->referenced_type = die_type (target_die, target_cu);
17565                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17566                 prop->data.baton = baton;
17567                 prop->kind = PROP_LOCLIST;
17568                 gdb_assert (prop->data.baton != NULL);
17569               }
17570             else if (attr_form_is_block (target_attr))
17571               {
17572                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17573                 baton->referenced_type = die_type (target_die, target_cu);
17574                 baton->locexpr.per_cu = cu->per_cu;
17575                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17576                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17577                 prop->data.baton = baton;
17578                 prop->kind = PROP_LOCEXPR;
17579                 gdb_assert (prop->data.baton != NULL);
17580               }
17581             else
17582               {
17583                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17584                                                        "dynamic property");
17585                 return 0;
17586               }
17587             break;
17588           case DW_AT_data_member_location:
17589             {
17590               LONGEST offset;
17591
17592               if (!handle_data_member_location (target_die, target_cu,
17593                                                 &offset))
17594                 return 0;
17595
17596               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17597               baton->referenced_type = read_type_die (target_die->parent,
17598                                                       target_cu);
17599               baton->offset_info.offset = offset;
17600               baton->offset_info.type = die_type (target_die, target_cu);
17601               prop->data.baton = baton;
17602               prop->kind = PROP_ADDR_OFFSET;
17603               break;
17604             }
17605         }
17606     }
17607   else if (attr_form_is_constant (attr))
17608     {
17609       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17610       prop->kind = PROP_CONST;
17611     }
17612   else
17613     {
17614       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17615                                              dwarf2_name (die, cu));
17616       return 0;
17617     }
17618
17619   return 1;
17620 }
17621
17622 /* Read the given DW_AT_subrange DIE.  */
17623
17624 static struct type *
17625 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17626 {
17627   struct type *base_type, *orig_base_type;
17628   struct type *range_type;
17629   struct attribute *attr;
17630   struct dynamic_prop low, high;
17631   int low_default_is_valid;
17632   int high_bound_is_count = 0;
17633   const char *name;
17634   LONGEST negative_mask;
17635
17636   orig_base_type = die_type (die, cu);
17637   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17638      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17639      creating the range type, but we use the result of check_typedef
17640      when examining properties of the type.  */
17641   base_type = check_typedef (orig_base_type);
17642
17643   /* The die_type call above may have already set the type for this DIE.  */
17644   range_type = get_die_type (die, cu);
17645   if (range_type)
17646     return range_type;
17647
17648   low.kind = PROP_CONST;
17649   high.kind = PROP_CONST;
17650   high.data.const_val = 0;
17651
17652   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17653      omitting DW_AT_lower_bound.  */
17654   switch (cu->language)
17655     {
17656     case language_c:
17657     case language_cplus:
17658       low.data.const_val = 0;
17659       low_default_is_valid = 1;
17660       break;
17661     case language_fortran:
17662       low.data.const_val = 1;
17663       low_default_is_valid = 1;
17664       break;
17665     case language_d:
17666     case language_objc:
17667     case language_rust:
17668       low.data.const_val = 0;
17669       low_default_is_valid = (cu->header.version >= 4);
17670       break;
17671     case language_ada:
17672     case language_m2:
17673     case language_pascal:
17674       low.data.const_val = 1;
17675       low_default_is_valid = (cu->header.version >= 4);
17676       break;
17677     default:
17678       low.data.const_val = 0;
17679       low_default_is_valid = 0;
17680       break;
17681     }
17682
17683   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17684   if (attr)
17685     attr_to_dynamic_prop (attr, die, cu, &low);
17686   else if (!low_default_is_valid)
17687     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17688                                       "- DIE at 0x%x [in module %s]"),
17689                to_underlying (die->sect_off),
17690                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17691
17692   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17693   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17694     {
17695       attr = dwarf2_attr (die, DW_AT_count, cu);
17696       if (attr_to_dynamic_prop (attr, die, cu, &high))
17697         {
17698           /* If bounds are constant do the final calculation here.  */
17699           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17700             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17701           else
17702             high_bound_is_count = 1;
17703         }
17704     }
17705
17706   /* Dwarf-2 specifications explicitly allows to create subrange types
17707      without specifying a base type.
17708      In that case, the base type must be set to the type of
17709      the lower bound, upper bound or count, in that order, if any of these
17710      three attributes references an object that has a type.
17711      If no base type is found, the Dwarf-2 specifications say that
17712      a signed integer type of size equal to the size of an address should
17713      be used.
17714      For the following C code: `extern char gdb_int [];'
17715      GCC produces an empty range DIE.
17716      FIXME: muller/2010-05-28: Possible references to object for low bound,
17717      high bound or count are not yet handled by this code.  */
17718   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17719     {
17720       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17721       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17722       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17723       struct type *int_type = objfile_type (objfile)->builtin_int;
17724
17725       /* Test "int", "long int", and "long long int" objfile types,
17726          and select the first one having a size above or equal to the
17727          architecture address size.  */
17728       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17729         base_type = int_type;
17730       else
17731         {
17732           int_type = objfile_type (objfile)->builtin_long;
17733           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17734             base_type = int_type;
17735           else
17736             {
17737               int_type = objfile_type (objfile)->builtin_long_long;
17738               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17739                 base_type = int_type;
17740             }
17741         }
17742     }
17743
17744   /* Normally, the DWARF producers are expected to use a signed
17745      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17746      But this is unfortunately not always the case, as witnessed
17747      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17748      is used instead.  To work around that ambiguity, we treat
17749      the bounds as signed, and thus sign-extend their values, when
17750      the base type is signed.  */
17751   negative_mask =
17752     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17753   if (low.kind == PROP_CONST
17754       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17755     low.data.const_val |= negative_mask;
17756   if (high.kind == PROP_CONST
17757       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17758     high.data.const_val |= negative_mask;
17759
17760   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17761
17762   if (high_bound_is_count)
17763     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17764
17765   /* Ada expects an empty array on no boundary attributes.  */
17766   if (attr == NULL && cu->language != language_ada)
17767     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17768
17769   name = dwarf2_name (die, cu);
17770   if (name)
17771     TYPE_NAME (range_type) = name;
17772
17773   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17774   if (attr)
17775     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17776
17777   set_die_type (die, range_type, cu);
17778
17779   /* set_die_type should be already done.  */
17780   set_descriptive_type (range_type, die, cu);
17781
17782   return range_type;
17783 }
17784
17785 static struct type *
17786 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17787 {
17788   struct type *type;
17789
17790   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17791                     NULL);
17792   TYPE_NAME (type) = dwarf2_name (die, cu);
17793
17794   /* In Ada, an unspecified type is typically used when the description
17795      of the type is defered to a different unit.  When encountering
17796      such a type, we treat it as a stub, and try to resolve it later on,
17797      when needed.  */
17798   if (cu->language == language_ada)
17799     TYPE_STUB (type) = 1;
17800
17801   return set_die_type (die, type, cu);
17802 }
17803
17804 /* Read a single die and all its descendents.  Set the die's sibling
17805    field to NULL; set other fields in the die correctly, and set all
17806    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17807    location of the info_ptr after reading all of those dies.  PARENT
17808    is the parent of the die in question.  */
17809
17810 static struct die_info *
17811 read_die_and_children (const struct die_reader_specs *reader,
17812                        const gdb_byte *info_ptr,
17813                        const gdb_byte **new_info_ptr,
17814                        struct die_info *parent)
17815 {
17816   struct die_info *die;
17817   const gdb_byte *cur_ptr;
17818   int has_children;
17819
17820   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17821   if (die == NULL)
17822     {
17823       *new_info_ptr = cur_ptr;
17824       return NULL;
17825     }
17826   store_in_ref_table (die, reader->cu);
17827
17828   if (has_children)
17829     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17830   else
17831     {
17832       die->child = NULL;
17833       *new_info_ptr = cur_ptr;
17834     }
17835
17836   die->sibling = NULL;
17837   die->parent = parent;
17838   return die;
17839 }
17840
17841 /* Read a die, all of its descendents, and all of its siblings; set
17842    all of the fields of all of the dies correctly.  Arguments are as
17843    in read_die_and_children.  */
17844
17845 static struct die_info *
17846 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17847                          const gdb_byte *info_ptr,
17848                          const gdb_byte **new_info_ptr,
17849                          struct die_info *parent)
17850 {
17851   struct die_info *first_die, *last_sibling;
17852   const gdb_byte *cur_ptr;
17853
17854   cur_ptr = info_ptr;
17855   first_die = last_sibling = NULL;
17856
17857   while (1)
17858     {
17859       struct die_info *die
17860         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17861
17862       if (die == NULL)
17863         {
17864           *new_info_ptr = cur_ptr;
17865           return first_die;
17866         }
17867
17868       if (!first_die)
17869         first_die = die;
17870       else
17871         last_sibling->sibling = die;
17872
17873       last_sibling = die;
17874     }
17875 }
17876
17877 /* Read a die, all of its descendents, and all of its siblings; set
17878    all of the fields of all of the dies correctly.  Arguments are as
17879    in read_die_and_children.
17880    This the main entry point for reading a DIE and all its children.  */
17881
17882 static struct die_info *
17883 read_die_and_siblings (const struct die_reader_specs *reader,
17884                        const gdb_byte *info_ptr,
17885                        const gdb_byte **new_info_ptr,
17886                        struct die_info *parent)
17887 {
17888   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17889                                                   new_info_ptr, parent);
17890
17891   if (dwarf_die_debug)
17892     {
17893       fprintf_unfiltered (gdb_stdlog,
17894                           "Read die from %s@0x%x of %s:\n",
17895                           get_section_name (reader->die_section),
17896                           (unsigned) (info_ptr - reader->die_section->buffer),
17897                           bfd_get_filename (reader->abfd));
17898       dump_die (die, dwarf_die_debug);
17899     }
17900
17901   return die;
17902 }
17903
17904 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17905    attributes.
17906    The caller is responsible for filling in the extra attributes
17907    and updating (*DIEP)->num_attrs.
17908    Set DIEP to point to a newly allocated die with its information,
17909    except for its child, sibling, and parent fields.
17910    Set HAS_CHILDREN to tell whether the die has children or not.  */
17911
17912 static const gdb_byte *
17913 read_full_die_1 (const struct die_reader_specs *reader,
17914                  struct die_info **diep, const gdb_byte *info_ptr,
17915                  int *has_children, int num_extra_attrs)
17916 {
17917   unsigned int abbrev_number, bytes_read, i;
17918   struct abbrev_info *abbrev;
17919   struct die_info *die;
17920   struct dwarf2_cu *cu = reader->cu;
17921   bfd *abfd = reader->abfd;
17922
17923   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17924   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17925   info_ptr += bytes_read;
17926   if (!abbrev_number)
17927     {
17928       *diep = NULL;
17929       *has_children = 0;
17930       return info_ptr;
17931     }
17932
17933   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17934   if (!abbrev)
17935     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17936            abbrev_number,
17937            bfd_get_filename (abfd));
17938
17939   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17940   die->sect_off = sect_off;
17941   die->tag = abbrev->tag;
17942   die->abbrev = abbrev_number;
17943
17944   /* Make the result usable.
17945      The caller needs to update num_attrs after adding the extra
17946      attributes.  */
17947   die->num_attrs = abbrev->num_attrs;
17948
17949   for (i = 0; i < abbrev->num_attrs; ++i)
17950     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17951                                info_ptr);
17952
17953   *diep = die;
17954   *has_children = abbrev->has_children;
17955   return info_ptr;
17956 }
17957
17958 /* Read a die and all its attributes.
17959    Set DIEP to point to a newly allocated die with its information,
17960    except for its child, sibling, and parent fields.
17961    Set HAS_CHILDREN to tell whether the die has children or not.  */
17962
17963 static const gdb_byte *
17964 read_full_die (const struct die_reader_specs *reader,
17965                struct die_info **diep, const gdb_byte *info_ptr,
17966                int *has_children)
17967 {
17968   const gdb_byte *result;
17969
17970   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17971
17972   if (dwarf_die_debug)
17973     {
17974       fprintf_unfiltered (gdb_stdlog,
17975                           "Read die from %s@0x%x of %s:\n",
17976                           get_section_name (reader->die_section),
17977                           (unsigned) (info_ptr - reader->die_section->buffer),
17978                           bfd_get_filename (reader->abfd));
17979       dump_die (*diep, dwarf_die_debug);
17980     }
17981
17982   return result;
17983 }
17984 \f
17985 /* Abbreviation tables.
17986
17987    In DWARF version 2, the description of the debugging information is
17988    stored in a separate .debug_abbrev section.  Before we read any
17989    dies from a section we read in all abbreviations and install them
17990    in a hash table.  */
17991
17992 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17993
17994 struct abbrev_info *
17995 abbrev_table::alloc_abbrev ()
17996 {
17997   struct abbrev_info *abbrev;
17998
17999   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18000   memset (abbrev, 0, sizeof (struct abbrev_info));
18001
18002   return abbrev;
18003 }
18004
18005 /* Add an abbreviation to the table.  */
18006
18007 void
18008 abbrev_table::add_abbrev (unsigned int abbrev_number,
18009                           struct abbrev_info *abbrev)
18010 {
18011   unsigned int hash_number;
18012
18013   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18014   abbrev->next = abbrevs[hash_number];
18015   abbrevs[hash_number] = abbrev;
18016 }
18017
18018 /* Look up an abbrev in the table.
18019    Returns NULL if the abbrev is not found.  */
18020
18021 struct abbrev_info *
18022 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18023 {
18024   unsigned int hash_number;
18025   struct abbrev_info *abbrev;
18026
18027   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18028   abbrev = abbrevs[hash_number];
18029
18030   while (abbrev)
18031     {
18032       if (abbrev->number == abbrev_number)
18033         return abbrev;
18034       abbrev = abbrev->next;
18035     }
18036   return NULL;
18037 }
18038
18039 /* Read in an abbrev table.  */
18040
18041 static abbrev_table_up
18042 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18043                          struct dwarf2_section_info *section,
18044                          sect_offset sect_off)
18045 {
18046   struct objfile *objfile = dwarf2_per_objfile->objfile;
18047   bfd *abfd = get_section_bfd_owner (section);
18048   const gdb_byte *abbrev_ptr;
18049   struct abbrev_info *cur_abbrev;
18050   unsigned int abbrev_number, bytes_read, abbrev_name;
18051   unsigned int abbrev_form;
18052   struct attr_abbrev *cur_attrs;
18053   unsigned int allocated_attrs;
18054
18055   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18056
18057   dwarf2_read_section (objfile, section);
18058   abbrev_ptr = section->buffer + to_underlying (sect_off);
18059   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18060   abbrev_ptr += bytes_read;
18061
18062   allocated_attrs = ATTR_ALLOC_CHUNK;
18063   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18064
18065   /* Loop until we reach an abbrev number of 0.  */
18066   while (abbrev_number)
18067     {
18068       cur_abbrev = abbrev_table->alloc_abbrev ();
18069
18070       /* read in abbrev header */
18071       cur_abbrev->number = abbrev_number;
18072       cur_abbrev->tag
18073         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18074       abbrev_ptr += bytes_read;
18075       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18076       abbrev_ptr += 1;
18077
18078       /* now read in declarations */
18079       for (;;)
18080         {
18081           LONGEST implicit_const;
18082
18083           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18084           abbrev_ptr += bytes_read;
18085           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18086           abbrev_ptr += bytes_read;
18087           if (abbrev_form == DW_FORM_implicit_const)
18088             {
18089               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18090                                                    &bytes_read);
18091               abbrev_ptr += bytes_read;
18092             }
18093           else
18094             {
18095               /* Initialize it due to a false compiler warning.  */
18096               implicit_const = -1;
18097             }
18098
18099           if (abbrev_name == 0)
18100             break;
18101
18102           if (cur_abbrev->num_attrs == allocated_attrs)
18103             {
18104               allocated_attrs += ATTR_ALLOC_CHUNK;
18105               cur_attrs
18106                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18107             }
18108
18109           cur_attrs[cur_abbrev->num_attrs].name
18110             = (enum dwarf_attribute) abbrev_name;
18111           cur_attrs[cur_abbrev->num_attrs].form
18112             = (enum dwarf_form) abbrev_form;
18113           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18114           ++cur_abbrev->num_attrs;
18115         }
18116
18117       cur_abbrev->attrs =
18118         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18119                    cur_abbrev->num_attrs);
18120       memcpy (cur_abbrev->attrs, cur_attrs,
18121               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18122
18123       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18124
18125       /* Get next abbreviation.
18126          Under Irix6 the abbreviations for a compilation unit are not
18127          always properly terminated with an abbrev number of 0.
18128          Exit loop if we encounter an abbreviation which we have
18129          already read (which means we are about to read the abbreviations
18130          for the next compile unit) or if the end of the abbreviation
18131          table is reached.  */
18132       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18133         break;
18134       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18135       abbrev_ptr += bytes_read;
18136       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18137         break;
18138     }
18139
18140   xfree (cur_attrs);
18141   return abbrev_table;
18142 }
18143
18144 /* Returns nonzero if TAG represents a type that we might generate a partial
18145    symbol for.  */
18146
18147 static int
18148 is_type_tag_for_partial (int tag)
18149 {
18150   switch (tag)
18151     {
18152 #if 0
18153     /* Some types that would be reasonable to generate partial symbols for,
18154        that we don't at present.  */
18155     case DW_TAG_array_type:
18156     case DW_TAG_file_type:
18157     case DW_TAG_ptr_to_member_type:
18158     case DW_TAG_set_type:
18159     case DW_TAG_string_type:
18160     case DW_TAG_subroutine_type:
18161 #endif
18162     case DW_TAG_base_type:
18163     case DW_TAG_class_type:
18164     case DW_TAG_interface_type:
18165     case DW_TAG_enumeration_type:
18166     case DW_TAG_structure_type:
18167     case DW_TAG_subrange_type:
18168     case DW_TAG_typedef:
18169     case DW_TAG_union_type:
18170       return 1;
18171     default:
18172       return 0;
18173     }
18174 }
18175
18176 /* Load all DIEs that are interesting for partial symbols into memory.  */
18177
18178 static struct partial_die_info *
18179 load_partial_dies (const struct die_reader_specs *reader,
18180                    const gdb_byte *info_ptr, int building_psymtab)
18181 {
18182   struct dwarf2_cu *cu = reader->cu;
18183   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18184   struct partial_die_info *part_die;
18185   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18186   unsigned int bytes_read;
18187   unsigned int load_all = 0;
18188   int nesting_level = 1;
18189
18190   parent_die = NULL;
18191   last_die = NULL;
18192
18193   gdb_assert (cu->per_cu != NULL);
18194   if (cu->per_cu->load_all_dies)
18195     load_all = 1;
18196
18197   cu->partial_dies
18198     = htab_create_alloc_ex (cu->header.length / 12,
18199                             partial_die_hash,
18200                             partial_die_eq,
18201                             NULL,
18202                             &cu->comp_unit_obstack,
18203                             hashtab_obstack_allocate,
18204                             dummy_obstack_deallocate);
18205
18206   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18207
18208   while (1)
18209     {
18210       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18211
18212       /* A NULL abbrev means the end of a series of children.  */
18213       if (abbrev == NULL)
18214         {
18215           if (--nesting_level == 0)
18216             {
18217               /* PART_DIE was probably the last thing allocated on the
18218                  comp_unit_obstack, so we could call obstack_free
18219                  here.  We don't do that because the waste is small,
18220                  and will be cleaned up when we're done with this
18221                  compilation unit.  This way, we're also more robust
18222                  against other users of the comp_unit_obstack.  */
18223               return first_die;
18224             }
18225           info_ptr += bytes_read;
18226           last_die = parent_die;
18227           parent_die = parent_die->die_parent;
18228           continue;
18229         }
18230
18231       /* Check for template arguments.  We never save these; if
18232          they're seen, we just mark the parent, and go on our way.  */
18233       if (parent_die != NULL
18234           && cu->language == language_cplus
18235           && (abbrev->tag == DW_TAG_template_type_param
18236               || abbrev->tag == DW_TAG_template_value_param))
18237         {
18238           parent_die->has_template_arguments = 1;
18239
18240           if (!load_all)
18241             {
18242               /* We don't need a partial DIE for the template argument.  */
18243               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18244               continue;
18245             }
18246         }
18247
18248       /* We only recurse into c++ subprograms looking for template arguments.
18249          Skip their other children.  */
18250       if (!load_all
18251           && cu->language == language_cplus
18252           && parent_die != NULL
18253           && parent_die->tag == DW_TAG_subprogram)
18254         {
18255           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18256           continue;
18257         }
18258
18259       /* Check whether this DIE is interesting enough to save.  Normally
18260          we would not be interested in members here, but there may be
18261          later variables referencing them via DW_AT_specification (for
18262          static members).  */
18263       if (!load_all
18264           && !is_type_tag_for_partial (abbrev->tag)
18265           && abbrev->tag != DW_TAG_constant
18266           && abbrev->tag != DW_TAG_enumerator
18267           && abbrev->tag != DW_TAG_subprogram
18268           && abbrev->tag != DW_TAG_inlined_subroutine
18269           && abbrev->tag != DW_TAG_lexical_block
18270           && abbrev->tag != DW_TAG_variable
18271           && abbrev->tag != DW_TAG_namespace
18272           && abbrev->tag != DW_TAG_module
18273           && abbrev->tag != DW_TAG_member
18274           && abbrev->tag != DW_TAG_imported_unit
18275           && abbrev->tag != DW_TAG_imported_declaration)
18276         {
18277           /* Otherwise we skip to the next sibling, if any.  */
18278           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18279           continue;
18280         }
18281
18282       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18283                                    info_ptr);
18284
18285       /* This two-pass algorithm for processing partial symbols has a
18286          high cost in cache pressure.  Thus, handle some simple cases
18287          here which cover the majority of C partial symbols.  DIEs
18288          which neither have specification tags in them, nor could have
18289          specification tags elsewhere pointing at them, can simply be
18290          processed and discarded.
18291
18292          This segment is also optional; scan_partial_symbols and
18293          add_partial_symbol will handle these DIEs if we chain
18294          them in normally.  When compilers which do not emit large
18295          quantities of duplicate debug information are more common,
18296          this code can probably be removed.  */
18297
18298       /* Any complete simple types at the top level (pretty much all
18299          of them, for a language without namespaces), can be processed
18300          directly.  */
18301       if (parent_die == NULL
18302           && part_die->has_specification == 0
18303           && part_die->is_declaration == 0
18304           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18305               || part_die->tag == DW_TAG_base_type
18306               || part_die->tag == DW_TAG_subrange_type))
18307         {
18308           if (building_psymtab && part_die->name != NULL)
18309             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18310                                  VAR_DOMAIN, LOC_TYPEDEF,
18311                                  &objfile->static_psymbols,
18312                                  0, cu->language, objfile);
18313           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18314           continue;
18315         }
18316
18317       /* The exception for DW_TAG_typedef with has_children above is
18318          a workaround of GCC PR debug/47510.  In the case of this complaint
18319          type_name_no_tag_or_error will error on such types later.
18320
18321          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18322          it could not find the child DIEs referenced later, this is checked
18323          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18324
18325       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18326         complaint (&symfile_complaints,
18327                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18328                      "- DIE at 0x%x [in module %s]"),
18329                    to_underlying (part_die->sect_off), objfile_name (objfile));
18330
18331       /* If we're at the second level, and we're an enumerator, and
18332          our parent has no specification (meaning possibly lives in a
18333          namespace elsewhere), then we can add the partial symbol now
18334          instead of queueing it.  */
18335       if (part_die->tag == DW_TAG_enumerator
18336           && parent_die != NULL
18337           && parent_die->die_parent == NULL
18338           && parent_die->tag == DW_TAG_enumeration_type
18339           && parent_die->has_specification == 0)
18340         {
18341           if (part_die->name == NULL)
18342             complaint (&symfile_complaints,
18343                        _("malformed enumerator DIE ignored"));
18344           else if (building_psymtab)
18345             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18346                                  VAR_DOMAIN, LOC_CONST,
18347                                  cu->language == language_cplus
18348                                  ? &objfile->global_psymbols
18349                                  : &objfile->static_psymbols,
18350                                  0, cu->language, objfile);
18351
18352           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18353           continue;
18354         }
18355
18356       /* We'll save this DIE so link it in.  */
18357       part_die->die_parent = parent_die;
18358       part_die->die_sibling = NULL;
18359       part_die->die_child = NULL;
18360
18361       if (last_die && last_die == parent_die)
18362         last_die->die_child = part_die;
18363       else if (last_die)
18364         last_die->die_sibling = part_die;
18365
18366       last_die = part_die;
18367
18368       if (first_die == NULL)
18369         first_die = part_die;
18370
18371       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18372          find interesting need to be in the hash table, because we
18373          also have the parent/sibling/child chains; only those that we
18374          might refer to by offset later during partial symbol reading.
18375
18376          For now this means things that might have be the target of a
18377          DW_AT_specification, DW_AT_abstract_origin, or
18378          DW_AT_extension.  DW_AT_extension will refer only to
18379          namespaces; DW_AT_abstract_origin refers to functions (and
18380          many things under the function DIE, but we do not recurse
18381          into function DIEs during partial symbol reading) and
18382          possibly variables as well; DW_AT_specification refers to
18383          declarations.  Declarations ought to have the DW_AT_declaration
18384          flag.  It happens that GCC forgets to put it in sometimes, but
18385          only for functions, not for types.
18386
18387          Adding more things than necessary to the hash table is harmless
18388          except for the performance cost.  Adding too few will result in
18389          wasted time in find_partial_die, when we reread the compilation
18390          unit with load_all_dies set.  */
18391
18392       if (load_all
18393           || abbrev->tag == DW_TAG_constant
18394           || abbrev->tag == DW_TAG_subprogram
18395           || abbrev->tag == DW_TAG_variable
18396           || abbrev->tag == DW_TAG_namespace
18397           || part_die->is_declaration)
18398         {
18399           void **slot;
18400
18401           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18402                                            to_underlying (part_die->sect_off),
18403                                            INSERT);
18404           *slot = part_die;
18405         }
18406
18407       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18408
18409       /* For some DIEs we want to follow their children (if any).  For C
18410          we have no reason to follow the children of structures; for other
18411          languages we have to, so that we can get at method physnames
18412          to infer fully qualified class names, for DW_AT_specification,
18413          and for C++ template arguments.  For C++, we also look one level
18414          inside functions to find template arguments (if the name of the
18415          function does not already contain the template arguments).
18416
18417          For Ada, we need to scan the children of subprograms and lexical
18418          blocks as well because Ada allows the definition of nested
18419          entities that could be interesting for the debugger, such as
18420          nested subprograms for instance.  */
18421       if (last_die->has_children
18422           && (load_all
18423               || last_die->tag == DW_TAG_namespace
18424               || last_die->tag == DW_TAG_module
18425               || last_die->tag == DW_TAG_enumeration_type
18426               || (cu->language == language_cplus
18427                   && last_die->tag == DW_TAG_subprogram
18428                   && (last_die->name == NULL
18429                       || strchr (last_die->name, '<') == NULL))
18430               || (cu->language != language_c
18431                   && (last_die->tag == DW_TAG_class_type
18432                       || last_die->tag == DW_TAG_interface_type
18433                       || last_die->tag == DW_TAG_structure_type
18434                       || last_die->tag == DW_TAG_union_type))
18435               || (cu->language == language_ada
18436                   && (last_die->tag == DW_TAG_subprogram
18437                       || last_die->tag == DW_TAG_lexical_block))))
18438         {
18439           nesting_level++;
18440           parent_die = last_die;
18441           continue;
18442         }
18443
18444       /* Otherwise we skip to the next sibling, if any.  */
18445       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18446
18447       /* Back to the top, do it again.  */
18448     }
18449 }
18450
18451 /* Read a minimal amount of information into the minimal die structure.  */
18452
18453 static const gdb_byte *
18454 read_partial_die (const struct die_reader_specs *reader,
18455                   struct partial_die_info *part_die,
18456                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18457                   const gdb_byte *info_ptr)
18458 {
18459   struct dwarf2_cu *cu = reader->cu;
18460   struct dwarf2_per_objfile *dwarf2_per_objfile
18461     = cu->per_cu->dwarf2_per_objfile;
18462   struct objfile *objfile = dwarf2_per_objfile->objfile;
18463   const gdb_byte *buffer = reader->buffer;
18464   unsigned int i;
18465   struct attribute attr;
18466   int has_low_pc_attr = 0;
18467   int has_high_pc_attr = 0;
18468   int high_pc_relative = 0;
18469
18470   memset (part_die, 0, sizeof (struct partial_die_info));
18471
18472   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18473
18474   info_ptr += abbrev_len;
18475
18476   if (abbrev == NULL)
18477     return info_ptr;
18478
18479   part_die->tag = abbrev->tag;
18480   part_die->has_children = abbrev->has_children;
18481
18482   for (i = 0; i < abbrev->num_attrs; ++i)
18483     {
18484       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18485
18486       /* Store the data if it is of an attribute we want to keep in a
18487          partial symbol table.  */
18488       switch (attr.name)
18489         {
18490         case DW_AT_name:
18491           switch (part_die->tag)
18492             {
18493             case DW_TAG_compile_unit:
18494             case DW_TAG_partial_unit:
18495             case DW_TAG_type_unit:
18496               /* Compilation units have a DW_AT_name that is a filename, not
18497                  a source language identifier.  */
18498             case DW_TAG_enumeration_type:
18499             case DW_TAG_enumerator:
18500               /* These tags always have simple identifiers already; no need
18501                  to canonicalize them.  */
18502               part_die->name = DW_STRING (&attr);
18503               break;
18504             default:
18505               part_die->name
18506                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18507                                             &objfile->per_bfd->storage_obstack);
18508               break;
18509             }
18510           break;
18511         case DW_AT_linkage_name:
18512         case DW_AT_MIPS_linkage_name:
18513           /* Note that both forms of linkage name might appear.  We
18514              assume they will be the same, and we only store the last
18515              one we see.  */
18516           if (cu->language == language_ada)
18517             part_die->name = DW_STRING (&attr);
18518           part_die->linkage_name = DW_STRING (&attr);
18519           break;
18520         case DW_AT_low_pc:
18521           has_low_pc_attr = 1;
18522           part_die->lowpc = attr_value_as_address (&attr);
18523           break;
18524         case DW_AT_high_pc:
18525           has_high_pc_attr = 1;
18526           part_die->highpc = attr_value_as_address (&attr);
18527           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18528                 high_pc_relative = 1;
18529           break;
18530         case DW_AT_location:
18531           /* Support the .debug_loc offsets.  */
18532           if (attr_form_is_block (&attr))
18533             {
18534                part_die->d.locdesc = DW_BLOCK (&attr);
18535             }
18536           else if (attr_form_is_section_offset (&attr))
18537             {
18538               dwarf2_complex_location_expr_complaint ();
18539             }
18540           else
18541             {
18542               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18543                                                      "partial symbol information");
18544             }
18545           break;
18546         case DW_AT_external:
18547           part_die->is_external = DW_UNSND (&attr);
18548           break;
18549         case DW_AT_declaration:
18550           part_die->is_declaration = DW_UNSND (&attr);
18551           break;
18552         case DW_AT_type:
18553           part_die->has_type = 1;
18554           break;
18555         case DW_AT_abstract_origin:
18556         case DW_AT_specification:
18557         case DW_AT_extension:
18558           part_die->has_specification = 1;
18559           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18560           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18561                                    || cu->per_cu->is_dwz);
18562           break;
18563         case DW_AT_sibling:
18564           /* Ignore absolute siblings, they might point outside of
18565              the current compile unit.  */
18566           if (attr.form == DW_FORM_ref_addr)
18567             complaint (&symfile_complaints,
18568                        _("ignoring absolute DW_AT_sibling"));
18569           else
18570             {
18571               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18572               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18573
18574               if (sibling_ptr < info_ptr)
18575                 complaint (&symfile_complaints,
18576                            _("DW_AT_sibling points backwards"));
18577               else if (sibling_ptr > reader->buffer_end)
18578                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18579               else
18580                 part_die->sibling = sibling_ptr;
18581             }
18582           break;
18583         case DW_AT_byte_size:
18584           part_die->has_byte_size = 1;
18585           break;
18586         case DW_AT_const_value:
18587           part_die->has_const_value = 1;
18588           break;
18589         case DW_AT_calling_convention:
18590           /* DWARF doesn't provide a way to identify a program's source-level
18591              entry point.  DW_AT_calling_convention attributes are only meant
18592              to describe functions' calling conventions.
18593
18594              However, because it's a necessary piece of information in
18595              Fortran, and before DWARF 4 DW_CC_program was the only
18596              piece of debugging information whose definition refers to
18597              a 'main program' at all, several compilers marked Fortran
18598              main programs with DW_CC_program --- even when those
18599              functions use the standard calling conventions.
18600
18601              Although DWARF now specifies a way to provide this
18602              information, we support this practice for backward
18603              compatibility.  */
18604           if (DW_UNSND (&attr) == DW_CC_program
18605               && cu->language == language_fortran)
18606             part_die->main_subprogram = 1;
18607           break;
18608         case DW_AT_inline:
18609           if (DW_UNSND (&attr) == DW_INL_inlined
18610               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18611             part_die->may_be_inlined = 1;
18612           break;
18613
18614         case DW_AT_import:
18615           if (part_die->tag == DW_TAG_imported_unit)
18616             {
18617               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18618               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18619                                   || cu->per_cu->is_dwz);
18620             }
18621           break;
18622
18623         case DW_AT_main_subprogram:
18624           part_die->main_subprogram = DW_UNSND (&attr);
18625           break;
18626
18627         default:
18628           break;
18629         }
18630     }
18631
18632   if (high_pc_relative)
18633     part_die->highpc += part_die->lowpc;
18634
18635   if (has_low_pc_attr && has_high_pc_attr)
18636     {
18637       /* When using the GNU linker, .gnu.linkonce. sections are used to
18638          eliminate duplicate copies of functions and vtables and such.
18639          The linker will arbitrarily choose one and discard the others.
18640          The AT_*_pc values for such functions refer to local labels in
18641          these sections.  If the section from that file was discarded, the
18642          labels are not in the output, so the relocs get a value of 0.
18643          If this is a discarded function, mark the pc bounds as invalid,
18644          so that GDB will ignore it.  */
18645       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18646         {
18647           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18648
18649           complaint (&symfile_complaints,
18650                      _("DW_AT_low_pc %s is zero "
18651                        "for DIE at 0x%x [in module %s]"),
18652                      paddress (gdbarch, part_die->lowpc),
18653                      to_underlying (part_die->sect_off), objfile_name (objfile));
18654         }
18655       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18656       else if (part_die->lowpc >= part_die->highpc)
18657         {
18658           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18659
18660           complaint (&symfile_complaints,
18661                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18662                        "for DIE at 0x%x [in module %s]"),
18663                      paddress (gdbarch, part_die->lowpc),
18664                      paddress (gdbarch, part_die->highpc),
18665                      to_underlying (part_die->sect_off),
18666                      objfile_name (objfile));
18667         }
18668       else
18669         part_die->has_pc_info = 1;
18670     }
18671
18672   return info_ptr;
18673 }
18674
18675 /* Find a cached partial DIE at OFFSET in CU.  */
18676
18677 static struct partial_die_info *
18678 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18679 {
18680   struct partial_die_info *lookup_die = NULL;
18681   struct partial_die_info part_die;
18682
18683   part_die.sect_off = sect_off;
18684   lookup_die = ((struct partial_die_info *)
18685                 htab_find_with_hash (cu->partial_dies, &part_die,
18686                                      to_underlying (sect_off)));
18687
18688   return lookup_die;
18689 }
18690
18691 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18692    except in the case of .debug_types DIEs which do not reference
18693    outside their CU (they do however referencing other types via
18694    DW_FORM_ref_sig8).  */
18695
18696 static struct partial_die_info *
18697 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18698 {
18699   struct dwarf2_per_objfile *dwarf2_per_objfile
18700     = cu->per_cu->dwarf2_per_objfile;
18701   struct objfile *objfile = dwarf2_per_objfile->objfile;
18702   struct dwarf2_per_cu_data *per_cu = NULL;
18703   struct partial_die_info *pd = NULL;
18704
18705   if (offset_in_dwz == cu->per_cu->is_dwz
18706       && offset_in_cu_p (&cu->header, sect_off))
18707     {
18708       pd = find_partial_die_in_comp_unit (sect_off, cu);
18709       if (pd != NULL)
18710         return pd;
18711       /* We missed recording what we needed.
18712          Load all dies and try again.  */
18713       per_cu = cu->per_cu;
18714     }
18715   else
18716     {
18717       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18718       if (cu->per_cu->is_debug_types)
18719         {
18720           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18721                    " external reference to offset 0x%x [in module %s].\n"),
18722                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18723                  bfd_get_filename (objfile->obfd));
18724         }
18725       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18726                                                  dwarf2_per_objfile);
18727
18728       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18729         load_partial_comp_unit (per_cu);
18730
18731       per_cu->cu->last_used = 0;
18732       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18733     }
18734
18735   /* If we didn't find it, and not all dies have been loaded,
18736      load them all and try again.  */
18737
18738   if (pd == NULL && per_cu->load_all_dies == 0)
18739     {
18740       per_cu->load_all_dies = 1;
18741
18742       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18743          THIS_CU->cu may already be in use.  So we can't just free it and
18744          replace its DIEs with the ones we read in.  Instead, we leave those
18745          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18746          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18747          set.  */
18748       load_partial_comp_unit (per_cu);
18749
18750       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18751     }
18752
18753   if (pd == NULL)
18754     internal_error (__FILE__, __LINE__,
18755                     _("could not find partial DIE 0x%x "
18756                       "in cache [from module %s]\n"),
18757                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18758   return pd;
18759 }
18760
18761 /* See if we can figure out if the class lives in a namespace.  We do
18762    this by looking for a member function; its demangled name will
18763    contain namespace info, if there is any.  */
18764
18765 static void
18766 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18767                                   struct dwarf2_cu *cu)
18768 {
18769   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18770      what template types look like, because the demangler
18771      frequently doesn't give the same name as the debug info.  We
18772      could fix this by only using the demangled name to get the
18773      prefix (but see comment in read_structure_type).  */
18774
18775   struct partial_die_info *real_pdi;
18776   struct partial_die_info *child_pdi;
18777
18778   /* If this DIE (this DIE's specification, if any) has a parent, then
18779      we should not do this.  We'll prepend the parent's fully qualified
18780      name when we create the partial symbol.  */
18781
18782   real_pdi = struct_pdi;
18783   while (real_pdi->has_specification)
18784     real_pdi = find_partial_die (real_pdi->spec_offset,
18785                                  real_pdi->spec_is_dwz, cu);
18786
18787   if (real_pdi->die_parent != NULL)
18788     return;
18789
18790   for (child_pdi = struct_pdi->die_child;
18791        child_pdi != NULL;
18792        child_pdi = child_pdi->die_sibling)
18793     {
18794       if (child_pdi->tag == DW_TAG_subprogram
18795           && child_pdi->linkage_name != NULL)
18796         {
18797           char *actual_class_name
18798             = language_class_name_from_physname (cu->language_defn,
18799                                                  child_pdi->linkage_name);
18800           if (actual_class_name != NULL)
18801             {
18802               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18803               struct_pdi->name
18804                 = ((const char *)
18805                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18806                                   actual_class_name,
18807                                   strlen (actual_class_name)));
18808               xfree (actual_class_name);
18809             }
18810           break;
18811         }
18812     }
18813 }
18814
18815 /* Adjust PART_DIE before generating a symbol for it.  This function
18816    may set the is_external flag or change the DIE's name.  */
18817
18818 static void
18819 fixup_partial_die (struct partial_die_info *part_die,
18820                    struct dwarf2_cu *cu)
18821 {
18822   /* Once we've fixed up a die, there's no point in doing so again.
18823      This also avoids a memory leak if we were to call
18824      guess_partial_die_structure_name multiple times.  */
18825   if (part_die->fixup_called)
18826     return;
18827
18828   /* If we found a reference attribute and the DIE has no name, try
18829      to find a name in the referred to DIE.  */
18830
18831   if (part_die->name == NULL && part_die->has_specification)
18832     {
18833       struct partial_die_info *spec_die;
18834
18835       spec_die = find_partial_die (part_die->spec_offset,
18836                                    part_die->spec_is_dwz, cu);
18837
18838       fixup_partial_die (spec_die, cu);
18839
18840       if (spec_die->name)
18841         {
18842           part_die->name = spec_die->name;
18843
18844           /* Copy DW_AT_external attribute if it is set.  */
18845           if (spec_die->is_external)
18846             part_die->is_external = spec_die->is_external;
18847         }
18848     }
18849
18850   /* Set default names for some unnamed DIEs.  */
18851
18852   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18853     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18854
18855   /* If there is no parent die to provide a namespace, and there are
18856      children, see if we can determine the namespace from their linkage
18857      name.  */
18858   if (cu->language == language_cplus
18859       && !VEC_empty (dwarf2_section_info_def,
18860                      cu->per_cu->dwarf2_per_objfile->types)
18861       && part_die->die_parent == NULL
18862       && part_die->has_children
18863       && (part_die->tag == DW_TAG_class_type
18864           || part_die->tag == DW_TAG_structure_type
18865           || part_die->tag == DW_TAG_union_type))
18866     guess_partial_die_structure_name (part_die, cu);
18867
18868   /* GCC might emit a nameless struct or union that has a linkage
18869      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18870   if (part_die->name == NULL
18871       && (part_die->tag == DW_TAG_class_type
18872           || part_die->tag == DW_TAG_interface_type
18873           || part_die->tag == DW_TAG_structure_type
18874           || part_die->tag == DW_TAG_union_type)
18875       && part_die->linkage_name != NULL)
18876     {
18877       char *demangled;
18878
18879       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18880       if (demangled)
18881         {
18882           const char *base;
18883
18884           /* Strip any leading namespaces/classes, keep only the base name.
18885              DW_AT_name for named DIEs does not contain the prefixes.  */
18886           base = strrchr (demangled, ':');
18887           if (base && base > demangled && base[-1] == ':')
18888             base++;
18889           else
18890             base = demangled;
18891
18892           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18893           part_die->name
18894             = ((const char *)
18895                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18896                               base, strlen (base)));
18897           xfree (demangled);
18898         }
18899     }
18900
18901   part_die->fixup_called = 1;
18902 }
18903
18904 /* Read an attribute value described by an attribute form.  */
18905
18906 static const gdb_byte *
18907 read_attribute_value (const struct die_reader_specs *reader,
18908                       struct attribute *attr, unsigned form,
18909                       LONGEST implicit_const, const gdb_byte *info_ptr)
18910 {
18911   struct dwarf2_cu *cu = reader->cu;
18912   struct dwarf2_per_objfile *dwarf2_per_objfile
18913     = cu->per_cu->dwarf2_per_objfile;
18914   struct objfile *objfile = dwarf2_per_objfile->objfile;
18915   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18916   bfd *abfd = reader->abfd;
18917   struct comp_unit_head *cu_header = &cu->header;
18918   unsigned int bytes_read;
18919   struct dwarf_block *blk;
18920
18921   attr->form = (enum dwarf_form) form;
18922   switch (form)
18923     {
18924     case DW_FORM_ref_addr:
18925       if (cu->header.version == 2)
18926         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18927       else
18928         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18929                                        &cu->header, &bytes_read);
18930       info_ptr += bytes_read;
18931       break;
18932     case DW_FORM_GNU_ref_alt:
18933       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18934       info_ptr += bytes_read;
18935       break;
18936     case DW_FORM_addr:
18937       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18938       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18939       info_ptr += bytes_read;
18940       break;
18941     case DW_FORM_block2:
18942       blk = dwarf_alloc_block (cu);
18943       blk->size = read_2_bytes (abfd, info_ptr);
18944       info_ptr += 2;
18945       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18946       info_ptr += blk->size;
18947       DW_BLOCK (attr) = blk;
18948       break;
18949     case DW_FORM_block4:
18950       blk = dwarf_alloc_block (cu);
18951       blk->size = read_4_bytes (abfd, info_ptr);
18952       info_ptr += 4;
18953       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18954       info_ptr += blk->size;
18955       DW_BLOCK (attr) = blk;
18956       break;
18957     case DW_FORM_data2:
18958       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18959       info_ptr += 2;
18960       break;
18961     case DW_FORM_data4:
18962       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18963       info_ptr += 4;
18964       break;
18965     case DW_FORM_data8:
18966       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18967       info_ptr += 8;
18968       break;
18969     case DW_FORM_data16:
18970       blk = dwarf_alloc_block (cu);
18971       blk->size = 16;
18972       blk->data = read_n_bytes (abfd, info_ptr, 16);
18973       info_ptr += 16;
18974       DW_BLOCK (attr) = blk;
18975       break;
18976     case DW_FORM_sec_offset:
18977       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18978       info_ptr += bytes_read;
18979       break;
18980     case DW_FORM_string:
18981       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18982       DW_STRING_IS_CANONICAL (attr) = 0;
18983       info_ptr += bytes_read;
18984       break;
18985     case DW_FORM_strp:
18986       if (!cu->per_cu->is_dwz)
18987         {
18988           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18989                                                    abfd, info_ptr, cu_header,
18990                                                    &bytes_read);
18991           DW_STRING_IS_CANONICAL (attr) = 0;
18992           info_ptr += bytes_read;
18993           break;
18994         }
18995       /* FALLTHROUGH */
18996     case DW_FORM_line_strp:
18997       if (!cu->per_cu->is_dwz)
18998         {
18999           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19000                                                         abfd, info_ptr,
19001                                                         cu_header, &bytes_read);
19002           DW_STRING_IS_CANONICAL (attr) = 0;
19003           info_ptr += bytes_read;
19004           break;
19005         }
19006       /* FALLTHROUGH */
19007     case DW_FORM_GNU_strp_alt:
19008       {
19009         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19010         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19011                                           &bytes_read);
19012
19013         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19014                                                           dwz, str_offset);
19015         DW_STRING_IS_CANONICAL (attr) = 0;
19016         info_ptr += bytes_read;
19017       }
19018       break;
19019     case DW_FORM_exprloc:
19020     case DW_FORM_block:
19021       blk = dwarf_alloc_block (cu);
19022       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19023       info_ptr += bytes_read;
19024       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19025       info_ptr += blk->size;
19026       DW_BLOCK (attr) = blk;
19027       break;
19028     case DW_FORM_block1:
19029       blk = dwarf_alloc_block (cu);
19030       blk->size = read_1_byte (abfd, info_ptr);
19031       info_ptr += 1;
19032       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19033       info_ptr += blk->size;
19034       DW_BLOCK (attr) = blk;
19035       break;
19036     case DW_FORM_data1:
19037       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19038       info_ptr += 1;
19039       break;
19040     case DW_FORM_flag:
19041       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19042       info_ptr += 1;
19043       break;
19044     case DW_FORM_flag_present:
19045       DW_UNSND (attr) = 1;
19046       break;
19047     case DW_FORM_sdata:
19048       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19049       info_ptr += bytes_read;
19050       break;
19051     case DW_FORM_udata:
19052       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19053       info_ptr += bytes_read;
19054       break;
19055     case DW_FORM_ref1:
19056       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19057                          + read_1_byte (abfd, info_ptr));
19058       info_ptr += 1;
19059       break;
19060     case DW_FORM_ref2:
19061       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19062                          + read_2_bytes (abfd, info_ptr));
19063       info_ptr += 2;
19064       break;
19065     case DW_FORM_ref4:
19066       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19067                          + read_4_bytes (abfd, info_ptr));
19068       info_ptr += 4;
19069       break;
19070     case DW_FORM_ref8:
19071       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19072                          + read_8_bytes (abfd, info_ptr));
19073       info_ptr += 8;
19074       break;
19075     case DW_FORM_ref_sig8:
19076       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19077       info_ptr += 8;
19078       break;
19079     case DW_FORM_ref_udata:
19080       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19081                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19082       info_ptr += bytes_read;
19083       break;
19084     case DW_FORM_indirect:
19085       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19086       info_ptr += bytes_read;
19087       if (form == DW_FORM_implicit_const)
19088         {
19089           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19090           info_ptr += bytes_read;
19091         }
19092       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19093                                        info_ptr);
19094       break;
19095     case DW_FORM_implicit_const:
19096       DW_SND (attr) = implicit_const;
19097       break;
19098     case DW_FORM_GNU_addr_index:
19099       if (reader->dwo_file == NULL)
19100         {
19101           /* For now flag a hard error.
19102              Later we can turn this into a complaint.  */
19103           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19104                  dwarf_form_name (form),
19105                  bfd_get_filename (abfd));
19106         }
19107       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19108       info_ptr += bytes_read;
19109       break;
19110     case DW_FORM_GNU_str_index:
19111       if (reader->dwo_file == NULL)
19112         {
19113           /* For now flag a hard error.
19114              Later we can turn this into a complaint if warranted.  */
19115           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19116                  dwarf_form_name (form),
19117                  bfd_get_filename (abfd));
19118         }
19119       {
19120         ULONGEST str_index =
19121           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19122
19123         DW_STRING (attr) = read_str_index (reader, str_index);
19124         DW_STRING_IS_CANONICAL (attr) = 0;
19125         info_ptr += bytes_read;
19126       }
19127       break;
19128     default:
19129       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19130              dwarf_form_name (form),
19131              bfd_get_filename (abfd));
19132     }
19133
19134   /* Super hack.  */
19135   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19136     attr->form = DW_FORM_GNU_ref_alt;
19137
19138   /* We have seen instances where the compiler tried to emit a byte
19139      size attribute of -1 which ended up being encoded as an unsigned
19140      0xffffffff.  Although 0xffffffff is technically a valid size value,
19141      an object of this size seems pretty unlikely so we can relatively
19142      safely treat these cases as if the size attribute was invalid and
19143      treat them as zero by default.  */
19144   if (attr->name == DW_AT_byte_size
19145       && form == DW_FORM_data4
19146       && DW_UNSND (attr) >= 0xffffffff)
19147     {
19148       complaint
19149         (&symfile_complaints,
19150          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19151          hex_string (DW_UNSND (attr)));
19152       DW_UNSND (attr) = 0;
19153     }
19154
19155   return info_ptr;
19156 }
19157
19158 /* Read an attribute described by an abbreviated attribute.  */
19159
19160 static const gdb_byte *
19161 read_attribute (const struct die_reader_specs *reader,
19162                 struct attribute *attr, struct attr_abbrev *abbrev,
19163                 const gdb_byte *info_ptr)
19164 {
19165   attr->name = abbrev->name;
19166   return read_attribute_value (reader, attr, abbrev->form,
19167                                abbrev->implicit_const, info_ptr);
19168 }
19169
19170 /* Read dwarf information from a buffer.  */
19171
19172 static unsigned int
19173 read_1_byte (bfd *abfd, const gdb_byte *buf)
19174 {
19175   return bfd_get_8 (abfd, buf);
19176 }
19177
19178 static int
19179 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19180 {
19181   return bfd_get_signed_8 (abfd, buf);
19182 }
19183
19184 static unsigned int
19185 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19186 {
19187   return bfd_get_16 (abfd, buf);
19188 }
19189
19190 static int
19191 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19192 {
19193   return bfd_get_signed_16 (abfd, buf);
19194 }
19195
19196 static unsigned int
19197 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19198 {
19199   return bfd_get_32 (abfd, buf);
19200 }
19201
19202 static int
19203 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19204 {
19205   return bfd_get_signed_32 (abfd, buf);
19206 }
19207
19208 static ULONGEST
19209 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19210 {
19211   return bfd_get_64 (abfd, buf);
19212 }
19213
19214 static CORE_ADDR
19215 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19216               unsigned int *bytes_read)
19217 {
19218   struct comp_unit_head *cu_header = &cu->header;
19219   CORE_ADDR retval = 0;
19220
19221   if (cu_header->signed_addr_p)
19222     {
19223       switch (cu_header->addr_size)
19224         {
19225         case 2:
19226           retval = bfd_get_signed_16 (abfd, buf);
19227           break;
19228         case 4:
19229           retval = bfd_get_signed_32 (abfd, buf);
19230           break;
19231         case 8:
19232           retval = bfd_get_signed_64 (abfd, buf);
19233           break;
19234         default:
19235           internal_error (__FILE__, __LINE__,
19236                           _("read_address: bad switch, signed [in module %s]"),
19237                           bfd_get_filename (abfd));
19238         }
19239     }
19240   else
19241     {
19242       switch (cu_header->addr_size)
19243         {
19244         case 2:
19245           retval = bfd_get_16 (abfd, buf);
19246           break;
19247         case 4:
19248           retval = bfd_get_32 (abfd, buf);
19249           break;
19250         case 8:
19251           retval = bfd_get_64 (abfd, buf);
19252           break;
19253         default:
19254           internal_error (__FILE__, __LINE__,
19255                           _("read_address: bad switch, "
19256                             "unsigned [in module %s]"),
19257                           bfd_get_filename (abfd));
19258         }
19259     }
19260
19261   *bytes_read = cu_header->addr_size;
19262   return retval;
19263 }
19264
19265 /* Read the initial length from a section.  The (draft) DWARF 3
19266    specification allows the initial length to take up either 4 bytes
19267    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19268    bytes describe the length and all offsets will be 8 bytes in length
19269    instead of 4.
19270
19271    An older, non-standard 64-bit format is also handled by this
19272    function.  The older format in question stores the initial length
19273    as an 8-byte quantity without an escape value.  Lengths greater
19274    than 2^32 aren't very common which means that the initial 4 bytes
19275    is almost always zero.  Since a length value of zero doesn't make
19276    sense for the 32-bit format, this initial zero can be considered to
19277    be an escape value which indicates the presence of the older 64-bit
19278    format.  As written, the code can't detect (old format) lengths
19279    greater than 4GB.  If it becomes necessary to handle lengths
19280    somewhat larger than 4GB, we could allow other small values (such
19281    as the non-sensical values of 1, 2, and 3) to also be used as
19282    escape values indicating the presence of the old format.
19283
19284    The value returned via bytes_read should be used to increment the
19285    relevant pointer after calling read_initial_length().
19286
19287    [ Note:  read_initial_length() and read_offset() are based on the
19288      document entitled "DWARF Debugging Information Format", revision
19289      3, draft 8, dated November 19, 2001.  This document was obtained
19290      from:
19291
19292         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19293
19294      This document is only a draft and is subject to change.  (So beware.)
19295
19296      Details regarding the older, non-standard 64-bit format were
19297      determined empirically by examining 64-bit ELF files produced by
19298      the SGI toolchain on an IRIX 6.5 machine.
19299
19300      - Kevin, July 16, 2002
19301    ] */
19302
19303 static LONGEST
19304 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19305 {
19306   LONGEST length = bfd_get_32 (abfd, buf);
19307
19308   if (length == 0xffffffff)
19309     {
19310       length = bfd_get_64 (abfd, buf + 4);
19311       *bytes_read = 12;
19312     }
19313   else if (length == 0)
19314     {
19315       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19316       length = bfd_get_64 (abfd, buf);
19317       *bytes_read = 8;
19318     }
19319   else
19320     {
19321       *bytes_read = 4;
19322     }
19323
19324   return length;
19325 }
19326
19327 /* Cover function for read_initial_length.
19328    Returns the length of the object at BUF, and stores the size of the
19329    initial length in *BYTES_READ and stores the size that offsets will be in
19330    *OFFSET_SIZE.
19331    If the initial length size is not equivalent to that specified in
19332    CU_HEADER then issue a complaint.
19333    This is useful when reading non-comp-unit headers.  */
19334
19335 static LONGEST
19336 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19337                                         const struct comp_unit_head *cu_header,
19338                                         unsigned int *bytes_read,
19339                                         unsigned int *offset_size)
19340 {
19341   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19342
19343   gdb_assert (cu_header->initial_length_size == 4
19344               || cu_header->initial_length_size == 8
19345               || cu_header->initial_length_size == 12);
19346
19347   if (cu_header->initial_length_size != *bytes_read)
19348     complaint (&symfile_complaints,
19349                _("intermixed 32-bit and 64-bit DWARF sections"));
19350
19351   *offset_size = (*bytes_read == 4) ? 4 : 8;
19352   return length;
19353 }
19354
19355 /* Read an offset from the data stream.  The size of the offset is
19356    given by cu_header->offset_size.  */
19357
19358 static LONGEST
19359 read_offset (bfd *abfd, const gdb_byte *buf,
19360              const struct comp_unit_head *cu_header,
19361              unsigned int *bytes_read)
19362 {
19363   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19364
19365   *bytes_read = cu_header->offset_size;
19366   return offset;
19367 }
19368
19369 /* Read an offset from the data stream.  */
19370
19371 static LONGEST
19372 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19373 {
19374   LONGEST retval = 0;
19375
19376   switch (offset_size)
19377     {
19378     case 4:
19379       retval = bfd_get_32 (abfd, buf);
19380       break;
19381     case 8:
19382       retval = bfd_get_64 (abfd, buf);
19383       break;
19384     default:
19385       internal_error (__FILE__, __LINE__,
19386                       _("read_offset_1: bad switch [in module %s]"),
19387                       bfd_get_filename (abfd));
19388     }
19389
19390   return retval;
19391 }
19392
19393 static const gdb_byte *
19394 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19395 {
19396   /* If the size of a host char is 8 bits, we can return a pointer
19397      to the buffer, otherwise we have to copy the data to a buffer
19398      allocated on the temporary obstack.  */
19399   gdb_assert (HOST_CHAR_BIT == 8);
19400   return buf;
19401 }
19402
19403 static const char *
19404 read_direct_string (bfd *abfd, const gdb_byte *buf,
19405                     unsigned int *bytes_read_ptr)
19406 {
19407   /* If the size of a host char is 8 bits, we can return a pointer
19408      to the string, otherwise we have to copy the string to a buffer
19409      allocated on the temporary obstack.  */
19410   gdb_assert (HOST_CHAR_BIT == 8);
19411   if (*buf == '\0')
19412     {
19413       *bytes_read_ptr = 1;
19414       return NULL;
19415     }
19416   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19417   return (const char *) buf;
19418 }
19419
19420 /* Return pointer to string at section SECT offset STR_OFFSET with error
19421    reporting strings FORM_NAME and SECT_NAME.  */
19422
19423 static const char *
19424 read_indirect_string_at_offset_from (struct objfile *objfile,
19425                                      bfd *abfd, LONGEST str_offset,
19426                                      struct dwarf2_section_info *sect,
19427                                      const char *form_name,
19428                                      const char *sect_name)
19429 {
19430   dwarf2_read_section (objfile, sect);
19431   if (sect->buffer == NULL)
19432     error (_("%s used without %s section [in module %s]"),
19433            form_name, sect_name, bfd_get_filename (abfd));
19434   if (str_offset >= sect->size)
19435     error (_("%s pointing outside of %s section [in module %s]"),
19436            form_name, sect_name, bfd_get_filename (abfd));
19437   gdb_assert (HOST_CHAR_BIT == 8);
19438   if (sect->buffer[str_offset] == '\0')
19439     return NULL;
19440   return (const char *) (sect->buffer + str_offset);
19441 }
19442
19443 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19444
19445 static const char *
19446 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19447                                 bfd *abfd, LONGEST str_offset)
19448 {
19449   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19450                                               abfd, str_offset,
19451                                               &dwarf2_per_objfile->str,
19452                                               "DW_FORM_strp", ".debug_str");
19453 }
19454
19455 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19456
19457 static const char *
19458 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19459                                      bfd *abfd, LONGEST str_offset)
19460 {
19461   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19462                                               abfd, str_offset,
19463                                               &dwarf2_per_objfile->line_str,
19464                                               "DW_FORM_line_strp",
19465                                               ".debug_line_str");
19466 }
19467
19468 /* Read a string at offset STR_OFFSET in the .debug_str section from
19469    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19470    the string consists of a single NUL byte, return NULL; otherwise
19471    return a pointer to the string.  */
19472
19473 static const char *
19474 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19475                                LONGEST str_offset)
19476 {
19477   dwarf2_read_section (objfile, &dwz->str);
19478
19479   if (dwz->str.buffer == NULL)
19480     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19481              "section [in module %s]"),
19482            bfd_get_filename (dwz->dwz_bfd));
19483   if (str_offset >= dwz->str.size)
19484     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19485              ".debug_str section [in module %s]"),
19486            bfd_get_filename (dwz->dwz_bfd));
19487   gdb_assert (HOST_CHAR_BIT == 8);
19488   if (dwz->str.buffer[str_offset] == '\0')
19489     return NULL;
19490   return (const char *) (dwz->str.buffer + str_offset);
19491 }
19492
19493 /* Return pointer to string at .debug_str offset as read from BUF.
19494    BUF is assumed to be in a compilation unit described by CU_HEADER.
19495    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19496
19497 static const char *
19498 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19499                       const gdb_byte *buf,
19500                       const struct comp_unit_head *cu_header,
19501                       unsigned int *bytes_read_ptr)
19502 {
19503   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19504
19505   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19506 }
19507
19508 /* Return pointer to string at .debug_line_str offset as read from BUF.
19509    BUF is assumed to be in a compilation unit described by CU_HEADER.
19510    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19511
19512 static const char *
19513 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19514                            bfd *abfd, const gdb_byte *buf,
19515                            const struct comp_unit_head *cu_header,
19516                            unsigned int *bytes_read_ptr)
19517 {
19518   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19519
19520   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19521                                               str_offset);
19522 }
19523
19524 ULONGEST
19525 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19526                           unsigned int *bytes_read_ptr)
19527 {
19528   ULONGEST result;
19529   unsigned int num_read;
19530   int shift;
19531   unsigned char byte;
19532
19533   result = 0;
19534   shift = 0;
19535   num_read = 0;
19536   while (1)
19537     {
19538       byte = bfd_get_8 (abfd, buf);
19539       buf++;
19540       num_read++;
19541       result |= ((ULONGEST) (byte & 127) << shift);
19542       if ((byte & 128) == 0)
19543         {
19544           break;
19545         }
19546       shift += 7;
19547     }
19548   *bytes_read_ptr = num_read;
19549   return result;
19550 }
19551
19552 static LONGEST
19553 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19554                     unsigned int *bytes_read_ptr)
19555 {
19556   LONGEST result;
19557   int shift, num_read;
19558   unsigned char byte;
19559
19560   result = 0;
19561   shift = 0;
19562   num_read = 0;
19563   while (1)
19564     {
19565       byte = bfd_get_8 (abfd, buf);
19566       buf++;
19567       num_read++;
19568       result |= ((LONGEST) (byte & 127) << shift);
19569       shift += 7;
19570       if ((byte & 128) == 0)
19571         {
19572           break;
19573         }
19574     }
19575   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19576     result |= -(((LONGEST) 1) << shift);
19577   *bytes_read_ptr = num_read;
19578   return result;
19579 }
19580
19581 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19582    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19583    ADDR_SIZE is the size of addresses from the CU header.  */
19584
19585 static CORE_ADDR
19586 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19587                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19588 {
19589   struct objfile *objfile = dwarf2_per_objfile->objfile;
19590   bfd *abfd = objfile->obfd;
19591   const gdb_byte *info_ptr;
19592
19593   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19594   if (dwarf2_per_objfile->addr.buffer == NULL)
19595     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19596            objfile_name (objfile));
19597   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19598     error (_("DW_FORM_addr_index pointing outside of "
19599              ".debug_addr section [in module %s]"),
19600            objfile_name (objfile));
19601   info_ptr = (dwarf2_per_objfile->addr.buffer
19602               + addr_base + addr_index * addr_size);
19603   if (addr_size == 4)
19604     return bfd_get_32 (abfd, info_ptr);
19605   else
19606     return bfd_get_64 (abfd, info_ptr);
19607 }
19608
19609 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19610
19611 static CORE_ADDR
19612 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19613 {
19614   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19615                             cu->addr_base, cu->header.addr_size);
19616 }
19617
19618 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19619
19620 static CORE_ADDR
19621 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19622                              unsigned int *bytes_read)
19623 {
19624   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19625   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19626
19627   return read_addr_index (cu, addr_index);
19628 }
19629
19630 /* Data structure to pass results from dwarf2_read_addr_index_reader
19631    back to dwarf2_read_addr_index.  */
19632
19633 struct dwarf2_read_addr_index_data
19634 {
19635   ULONGEST addr_base;
19636   int addr_size;
19637 };
19638
19639 /* die_reader_func for dwarf2_read_addr_index.  */
19640
19641 static void
19642 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19643                                const gdb_byte *info_ptr,
19644                                struct die_info *comp_unit_die,
19645                                int has_children,
19646                                void *data)
19647 {
19648   struct dwarf2_cu *cu = reader->cu;
19649   struct dwarf2_read_addr_index_data *aidata =
19650     (struct dwarf2_read_addr_index_data *) data;
19651
19652   aidata->addr_base = cu->addr_base;
19653   aidata->addr_size = cu->header.addr_size;
19654 }
19655
19656 /* Given an index in .debug_addr, fetch the value.
19657    NOTE: This can be called during dwarf expression evaluation,
19658    long after the debug information has been read, and thus per_cu->cu
19659    may no longer exist.  */
19660
19661 CORE_ADDR
19662 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19663                         unsigned int addr_index)
19664 {
19665   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19666   struct objfile *objfile = dwarf2_per_objfile->objfile;
19667   struct dwarf2_cu *cu = per_cu->cu;
19668   ULONGEST addr_base;
19669   int addr_size;
19670
19671   /* We need addr_base and addr_size.
19672      If we don't have PER_CU->cu, we have to get it.
19673      Nasty, but the alternative is storing the needed info in PER_CU,
19674      which at this point doesn't seem justified: it's not clear how frequently
19675      it would get used and it would increase the size of every PER_CU.
19676      Entry points like dwarf2_per_cu_addr_size do a similar thing
19677      so we're not in uncharted territory here.
19678      Alas we need to be a bit more complicated as addr_base is contained
19679      in the DIE.
19680
19681      We don't need to read the entire CU(/TU).
19682      We just need the header and top level die.
19683
19684      IWBN to use the aging mechanism to let us lazily later discard the CU.
19685      For now we skip this optimization.  */
19686
19687   if (cu != NULL)
19688     {
19689       addr_base = cu->addr_base;
19690       addr_size = cu->header.addr_size;
19691     }
19692   else
19693     {
19694       struct dwarf2_read_addr_index_data aidata;
19695
19696       /* Note: We can't use init_cutu_and_read_dies_simple here,
19697          we need addr_base.  */
19698       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19699                                dwarf2_read_addr_index_reader, &aidata);
19700       addr_base = aidata.addr_base;
19701       addr_size = aidata.addr_size;
19702     }
19703
19704   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19705                             addr_size);
19706 }
19707
19708 /* Given a DW_FORM_GNU_str_index, fetch the string.
19709    This is only used by the Fission support.  */
19710
19711 static const char *
19712 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19713 {
19714   struct dwarf2_cu *cu = reader->cu;
19715   struct dwarf2_per_objfile *dwarf2_per_objfile
19716     = cu->per_cu->dwarf2_per_objfile;
19717   struct objfile *objfile = dwarf2_per_objfile->objfile;
19718   const char *objf_name = objfile_name (objfile);
19719   bfd *abfd = objfile->obfd;
19720   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19721   struct dwarf2_section_info *str_offsets_section =
19722     &reader->dwo_file->sections.str_offsets;
19723   const gdb_byte *info_ptr;
19724   ULONGEST str_offset;
19725   static const char form_name[] = "DW_FORM_GNU_str_index";
19726
19727   dwarf2_read_section (objfile, str_section);
19728   dwarf2_read_section (objfile, str_offsets_section);
19729   if (str_section->buffer == NULL)
19730     error (_("%s used without .debug_str.dwo section"
19731              " in CU at offset 0x%x [in module %s]"),
19732            form_name, to_underlying (cu->header.sect_off), objf_name);
19733   if (str_offsets_section->buffer == NULL)
19734     error (_("%s used without .debug_str_offsets.dwo section"
19735              " in CU at offset 0x%x [in module %s]"),
19736            form_name, to_underlying (cu->header.sect_off), objf_name);
19737   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19738     error (_("%s pointing outside of .debug_str_offsets.dwo"
19739              " section in CU at offset 0x%x [in module %s]"),
19740            form_name, to_underlying (cu->header.sect_off), objf_name);
19741   info_ptr = (str_offsets_section->buffer
19742               + str_index * cu->header.offset_size);
19743   if (cu->header.offset_size == 4)
19744     str_offset = bfd_get_32 (abfd, info_ptr);
19745   else
19746     str_offset = bfd_get_64 (abfd, info_ptr);
19747   if (str_offset >= str_section->size)
19748     error (_("Offset from %s pointing outside of"
19749              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19750            form_name, to_underlying (cu->header.sect_off), objf_name);
19751   return (const char *) (str_section->buffer + str_offset);
19752 }
19753
19754 /* Return the length of an LEB128 number in BUF.  */
19755
19756 static int
19757 leb128_size (const gdb_byte *buf)
19758 {
19759   const gdb_byte *begin = buf;
19760   gdb_byte byte;
19761
19762   while (1)
19763     {
19764       byte = *buf++;
19765       if ((byte & 128) == 0)
19766         return buf - begin;
19767     }
19768 }
19769
19770 static void
19771 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19772 {
19773   switch (lang)
19774     {
19775     case DW_LANG_C89:
19776     case DW_LANG_C99:
19777     case DW_LANG_C11:
19778     case DW_LANG_C:
19779     case DW_LANG_UPC:
19780       cu->language = language_c;
19781       break;
19782     case DW_LANG_Java:
19783     case DW_LANG_C_plus_plus:
19784     case DW_LANG_C_plus_plus_11:
19785     case DW_LANG_C_plus_plus_14:
19786       cu->language = language_cplus;
19787       break;
19788     case DW_LANG_D:
19789       cu->language = language_d;
19790       break;
19791     case DW_LANG_Fortran77:
19792     case DW_LANG_Fortran90:
19793     case DW_LANG_Fortran95:
19794     case DW_LANG_Fortran03:
19795     case DW_LANG_Fortran08:
19796       cu->language = language_fortran;
19797       break;
19798     case DW_LANG_Go:
19799       cu->language = language_go;
19800       break;
19801     case DW_LANG_Mips_Assembler:
19802       cu->language = language_asm;
19803       break;
19804     case DW_LANG_Ada83:
19805     case DW_LANG_Ada95:
19806       cu->language = language_ada;
19807       break;
19808     case DW_LANG_Modula2:
19809       cu->language = language_m2;
19810       break;
19811     case DW_LANG_Pascal83:
19812       cu->language = language_pascal;
19813       break;
19814     case DW_LANG_ObjC:
19815       cu->language = language_objc;
19816       break;
19817     case DW_LANG_Rust:
19818     case DW_LANG_Rust_old:
19819       cu->language = language_rust;
19820       break;
19821     case DW_LANG_Cobol74:
19822     case DW_LANG_Cobol85:
19823     default:
19824       cu->language = language_minimal;
19825       break;
19826     }
19827   cu->language_defn = language_def (cu->language);
19828 }
19829
19830 /* Return the named attribute or NULL if not there.  */
19831
19832 static struct attribute *
19833 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19834 {
19835   for (;;)
19836     {
19837       unsigned int i;
19838       struct attribute *spec = NULL;
19839
19840       for (i = 0; i < die->num_attrs; ++i)
19841         {
19842           if (die->attrs[i].name == name)
19843             return &die->attrs[i];
19844           if (die->attrs[i].name == DW_AT_specification
19845               || die->attrs[i].name == DW_AT_abstract_origin)
19846             spec = &die->attrs[i];
19847         }
19848
19849       if (!spec)
19850         break;
19851
19852       die = follow_die_ref (die, spec, &cu);
19853     }
19854
19855   return NULL;
19856 }
19857
19858 /* Return the named attribute or NULL if not there,
19859    but do not follow DW_AT_specification, etc.
19860    This is for use in contexts where we're reading .debug_types dies.
19861    Following DW_AT_specification, DW_AT_abstract_origin will take us
19862    back up the chain, and we want to go down.  */
19863
19864 static struct attribute *
19865 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19866 {
19867   unsigned int i;
19868
19869   for (i = 0; i < die->num_attrs; ++i)
19870     if (die->attrs[i].name == name)
19871       return &die->attrs[i];
19872
19873   return NULL;
19874 }
19875
19876 /* Return the string associated with a string-typed attribute, or NULL if it
19877    is either not found or is of an incorrect type.  */
19878
19879 static const char *
19880 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19881 {
19882   struct attribute *attr;
19883   const char *str = NULL;
19884
19885   attr = dwarf2_attr (die, name, cu);
19886
19887   if (attr != NULL)
19888     {
19889       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19890           || attr->form == DW_FORM_string
19891           || attr->form == DW_FORM_GNU_str_index
19892           || attr->form == DW_FORM_GNU_strp_alt)
19893         str = DW_STRING (attr);
19894       else
19895         complaint (&symfile_complaints,
19896                    _("string type expected for attribute %s for "
19897                      "DIE at 0x%x in module %s"),
19898                    dwarf_attr_name (name), to_underlying (die->sect_off),
19899                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19900     }
19901
19902   return str;
19903 }
19904
19905 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19906    and holds a non-zero value.  This function should only be used for
19907    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19908
19909 static int
19910 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19911 {
19912   struct attribute *attr = dwarf2_attr (die, name, cu);
19913
19914   return (attr && DW_UNSND (attr));
19915 }
19916
19917 static int
19918 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19919 {
19920   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19921      which value is non-zero.  However, we have to be careful with
19922      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19923      (via dwarf2_flag_true_p) follows this attribute.  So we may
19924      end up accidently finding a declaration attribute that belongs
19925      to a different DIE referenced by the specification attribute,
19926      even though the given DIE does not have a declaration attribute.  */
19927   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19928           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19929 }
19930
19931 /* Return the die giving the specification for DIE, if there is
19932    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19933    containing the return value on output.  If there is no
19934    specification, but there is an abstract origin, that is
19935    returned.  */
19936
19937 static struct die_info *
19938 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19939 {
19940   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19941                                              *spec_cu);
19942
19943   if (spec_attr == NULL)
19944     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19945
19946   if (spec_attr == NULL)
19947     return NULL;
19948   else
19949     return follow_die_ref (die, spec_attr, spec_cu);
19950 }
19951
19952 /* Stub for free_line_header to match void * callback types.  */
19953
19954 static void
19955 free_line_header_voidp (void *arg)
19956 {
19957   struct line_header *lh = (struct line_header *) arg;
19958
19959   delete lh;
19960 }
19961
19962 void
19963 line_header::add_include_dir (const char *include_dir)
19964 {
19965   if (dwarf_line_debug >= 2)
19966     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19967                         include_dirs.size () + 1, include_dir);
19968
19969   include_dirs.push_back (include_dir);
19970 }
19971
19972 void
19973 line_header::add_file_name (const char *name,
19974                             dir_index d_index,
19975                             unsigned int mod_time,
19976                             unsigned int length)
19977 {
19978   if (dwarf_line_debug >= 2)
19979     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19980                         (unsigned) file_names.size () + 1, name);
19981
19982   file_names.emplace_back (name, d_index, mod_time, length);
19983 }
19984
19985 /* A convenience function to find the proper .debug_line section for a CU.  */
19986
19987 static struct dwarf2_section_info *
19988 get_debug_line_section (struct dwarf2_cu *cu)
19989 {
19990   struct dwarf2_section_info *section;
19991   struct dwarf2_per_objfile *dwarf2_per_objfile
19992     = cu->per_cu->dwarf2_per_objfile;
19993
19994   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19995      DWO file.  */
19996   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19997     section = &cu->dwo_unit->dwo_file->sections.line;
19998   else if (cu->per_cu->is_dwz)
19999     {
20000       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20001
20002       section = &dwz->line;
20003     }
20004   else
20005     section = &dwarf2_per_objfile->line;
20006
20007   return section;
20008 }
20009
20010 /* Read directory or file name entry format, starting with byte of
20011    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20012    entries count and the entries themselves in the described entry
20013    format.  */
20014
20015 static void
20016 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20017                         bfd *abfd, const gdb_byte **bufp,
20018                         struct line_header *lh,
20019                         const struct comp_unit_head *cu_header,
20020                         void (*callback) (struct line_header *lh,
20021                                           const char *name,
20022                                           dir_index d_index,
20023                                           unsigned int mod_time,
20024                                           unsigned int length))
20025 {
20026   gdb_byte format_count, formati;
20027   ULONGEST data_count, datai;
20028   const gdb_byte *buf = *bufp;
20029   const gdb_byte *format_header_data;
20030   unsigned int bytes_read;
20031
20032   format_count = read_1_byte (abfd, buf);
20033   buf += 1;
20034   format_header_data = buf;
20035   for (formati = 0; formati < format_count; formati++)
20036     {
20037       read_unsigned_leb128 (abfd, buf, &bytes_read);
20038       buf += bytes_read;
20039       read_unsigned_leb128 (abfd, buf, &bytes_read);
20040       buf += bytes_read;
20041     }
20042
20043   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20044   buf += bytes_read;
20045   for (datai = 0; datai < data_count; datai++)
20046     {
20047       const gdb_byte *format = format_header_data;
20048       struct file_entry fe;
20049
20050       for (formati = 0; formati < format_count; formati++)
20051         {
20052           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20053           format += bytes_read;
20054
20055           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20056           format += bytes_read;
20057
20058           gdb::optional<const char *> string;
20059           gdb::optional<unsigned int> uint;
20060
20061           switch (form)
20062             {
20063             case DW_FORM_string:
20064               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20065               buf += bytes_read;
20066               break;
20067
20068             case DW_FORM_line_strp:
20069               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20070                                                          abfd, buf,
20071                                                          cu_header,
20072                                                          &bytes_read));
20073               buf += bytes_read;
20074               break;
20075
20076             case DW_FORM_data1:
20077               uint.emplace (read_1_byte (abfd, buf));
20078               buf += 1;
20079               break;
20080
20081             case DW_FORM_data2:
20082               uint.emplace (read_2_bytes (abfd, buf));
20083               buf += 2;
20084               break;
20085
20086             case DW_FORM_data4:
20087               uint.emplace (read_4_bytes (abfd, buf));
20088               buf += 4;
20089               break;
20090
20091             case DW_FORM_data8:
20092               uint.emplace (read_8_bytes (abfd, buf));
20093               buf += 8;
20094               break;
20095
20096             case DW_FORM_udata:
20097               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20098               buf += bytes_read;
20099               break;
20100
20101             case DW_FORM_block:
20102               /* It is valid only for DW_LNCT_timestamp which is ignored by
20103                  current GDB.  */
20104               break;
20105             }
20106
20107           switch (content_type)
20108             {
20109             case DW_LNCT_path:
20110               if (string.has_value ())
20111                 fe.name = *string;
20112               break;
20113             case DW_LNCT_directory_index:
20114               if (uint.has_value ())
20115                 fe.d_index = (dir_index) *uint;
20116               break;
20117             case DW_LNCT_timestamp:
20118               if (uint.has_value ())
20119                 fe.mod_time = *uint;
20120               break;
20121             case DW_LNCT_size:
20122               if (uint.has_value ())
20123                 fe.length = *uint;
20124               break;
20125             case DW_LNCT_MD5:
20126               break;
20127             default:
20128               complaint (&symfile_complaints,
20129                          _("Unknown format content type %s"),
20130                          pulongest (content_type));
20131             }
20132         }
20133
20134       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20135     }
20136
20137   *bufp = buf;
20138 }
20139
20140 /* Read the statement program header starting at OFFSET in
20141    .debug_line, or .debug_line.dwo.  Return a pointer
20142    to a struct line_header, allocated using xmalloc.
20143    Returns NULL if there is a problem reading the header, e.g., if it
20144    has a version we don't understand.
20145
20146    NOTE: the strings in the include directory and file name tables of
20147    the returned object point into the dwarf line section buffer,
20148    and must not be freed.  */
20149
20150 static line_header_up
20151 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20152 {
20153   const gdb_byte *line_ptr;
20154   unsigned int bytes_read, offset_size;
20155   int i;
20156   const char *cur_dir, *cur_file;
20157   struct dwarf2_section_info *section;
20158   bfd *abfd;
20159   struct dwarf2_per_objfile *dwarf2_per_objfile
20160     = cu->per_cu->dwarf2_per_objfile;
20161
20162   section = get_debug_line_section (cu);
20163   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20164   if (section->buffer == NULL)
20165     {
20166       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20167         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20168       else
20169         complaint (&symfile_complaints, _("missing .debug_line section"));
20170       return 0;
20171     }
20172
20173   /* We can't do this until we know the section is non-empty.
20174      Only then do we know we have such a section.  */
20175   abfd = get_section_bfd_owner (section);
20176
20177   /* Make sure that at least there's room for the total_length field.
20178      That could be 12 bytes long, but we're just going to fudge that.  */
20179   if (to_underlying (sect_off) + 4 >= section->size)
20180     {
20181       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20182       return 0;
20183     }
20184
20185   line_header_up lh (new line_header ());
20186
20187   lh->sect_off = sect_off;
20188   lh->offset_in_dwz = cu->per_cu->is_dwz;
20189
20190   line_ptr = section->buffer + to_underlying (sect_off);
20191
20192   /* Read in the header.  */
20193   lh->total_length =
20194     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20195                                             &bytes_read, &offset_size);
20196   line_ptr += bytes_read;
20197   if (line_ptr + lh->total_length > (section->buffer + section->size))
20198     {
20199       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20200       return 0;
20201     }
20202   lh->statement_program_end = line_ptr + lh->total_length;
20203   lh->version = read_2_bytes (abfd, line_ptr);
20204   line_ptr += 2;
20205   if (lh->version > 5)
20206     {
20207       /* This is a version we don't understand.  The format could have
20208          changed in ways we don't handle properly so just punt.  */
20209       complaint (&symfile_complaints,
20210                  _("unsupported version in .debug_line section"));
20211       return NULL;
20212     }
20213   if (lh->version >= 5)
20214     {
20215       gdb_byte segment_selector_size;
20216
20217       /* Skip address size.  */
20218       read_1_byte (abfd, line_ptr);
20219       line_ptr += 1;
20220
20221       segment_selector_size = read_1_byte (abfd, line_ptr);
20222       line_ptr += 1;
20223       if (segment_selector_size != 0)
20224         {
20225           complaint (&symfile_complaints,
20226                      _("unsupported segment selector size %u "
20227                        "in .debug_line section"),
20228                      segment_selector_size);
20229           return NULL;
20230         }
20231     }
20232   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20233   line_ptr += offset_size;
20234   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20235   line_ptr += 1;
20236   if (lh->version >= 4)
20237     {
20238       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20239       line_ptr += 1;
20240     }
20241   else
20242     lh->maximum_ops_per_instruction = 1;
20243
20244   if (lh->maximum_ops_per_instruction == 0)
20245     {
20246       lh->maximum_ops_per_instruction = 1;
20247       complaint (&symfile_complaints,
20248                  _("invalid maximum_ops_per_instruction "
20249                    "in `.debug_line' section"));
20250     }
20251
20252   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20253   line_ptr += 1;
20254   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20255   line_ptr += 1;
20256   lh->line_range = read_1_byte (abfd, line_ptr);
20257   line_ptr += 1;
20258   lh->opcode_base = read_1_byte (abfd, line_ptr);
20259   line_ptr += 1;
20260   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20261
20262   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20263   for (i = 1; i < lh->opcode_base; ++i)
20264     {
20265       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20266       line_ptr += 1;
20267     }
20268
20269   if (lh->version >= 5)
20270     {
20271       /* Read directory table.  */
20272       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20273                               &cu->header,
20274                               [] (struct line_header *lh, const char *name,
20275                                   dir_index d_index, unsigned int mod_time,
20276                                   unsigned int length)
20277         {
20278           lh->add_include_dir (name);
20279         });
20280
20281       /* Read file name table.  */
20282       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20283                               &cu->header,
20284                               [] (struct line_header *lh, const char *name,
20285                                   dir_index d_index, unsigned int mod_time,
20286                                   unsigned int length)
20287         {
20288           lh->add_file_name (name, d_index, mod_time, length);
20289         });
20290     }
20291   else
20292     {
20293       /* Read directory table.  */
20294       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20295         {
20296           line_ptr += bytes_read;
20297           lh->add_include_dir (cur_dir);
20298         }
20299       line_ptr += bytes_read;
20300
20301       /* Read file name table.  */
20302       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20303         {
20304           unsigned int mod_time, length;
20305           dir_index d_index;
20306
20307           line_ptr += bytes_read;
20308           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20309           line_ptr += bytes_read;
20310           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20311           line_ptr += bytes_read;
20312           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20313           line_ptr += bytes_read;
20314
20315           lh->add_file_name (cur_file, d_index, mod_time, length);
20316         }
20317       line_ptr += bytes_read;
20318     }
20319   lh->statement_program_start = line_ptr;
20320
20321   if (line_ptr > (section->buffer + section->size))
20322     complaint (&symfile_complaints,
20323                _("line number info header doesn't "
20324                  "fit in `.debug_line' section"));
20325
20326   return lh;
20327 }
20328
20329 /* Subroutine of dwarf_decode_lines to simplify it.
20330    Return the file name of the psymtab for included file FILE_INDEX
20331    in line header LH of PST.
20332    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20333    If space for the result is malloc'd, *NAME_HOLDER will be set.
20334    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20335
20336 static const char *
20337 psymtab_include_file_name (const struct line_header *lh, int file_index,
20338                            const struct partial_symtab *pst,
20339                            const char *comp_dir,
20340                            gdb::unique_xmalloc_ptr<char> *name_holder)
20341 {
20342   const file_entry &fe = lh->file_names[file_index];
20343   const char *include_name = fe.name;
20344   const char *include_name_to_compare = include_name;
20345   const char *pst_filename;
20346   int file_is_pst;
20347
20348   const char *dir_name = fe.include_dir (lh);
20349
20350   gdb::unique_xmalloc_ptr<char> hold_compare;
20351   if (!IS_ABSOLUTE_PATH (include_name)
20352       && (dir_name != NULL || comp_dir != NULL))
20353     {
20354       /* Avoid creating a duplicate psymtab for PST.
20355          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20356          Before we do the comparison, however, we need to account
20357          for DIR_NAME and COMP_DIR.
20358          First prepend dir_name (if non-NULL).  If we still don't
20359          have an absolute path prepend comp_dir (if non-NULL).
20360          However, the directory we record in the include-file's
20361          psymtab does not contain COMP_DIR (to match the
20362          corresponding symtab(s)).
20363
20364          Example:
20365
20366          bash$ cd /tmp
20367          bash$ gcc -g ./hello.c
20368          include_name = "hello.c"
20369          dir_name = "."
20370          DW_AT_comp_dir = comp_dir = "/tmp"
20371          DW_AT_name = "./hello.c"
20372
20373       */
20374
20375       if (dir_name != NULL)
20376         {
20377           name_holder->reset (concat (dir_name, SLASH_STRING,
20378                                       include_name, (char *) NULL));
20379           include_name = name_holder->get ();
20380           include_name_to_compare = include_name;
20381         }
20382       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20383         {
20384           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20385                                       include_name, (char *) NULL));
20386           include_name_to_compare = hold_compare.get ();
20387         }
20388     }
20389
20390   pst_filename = pst->filename;
20391   gdb::unique_xmalloc_ptr<char> copied_name;
20392   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20393     {
20394       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20395                                  pst_filename, (char *) NULL));
20396       pst_filename = copied_name.get ();
20397     }
20398
20399   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20400
20401   if (file_is_pst)
20402     return NULL;
20403   return include_name;
20404 }
20405
20406 /* State machine to track the state of the line number program.  */
20407
20408 class lnp_state_machine
20409 {
20410 public:
20411   /* Initialize a machine state for the start of a line number
20412      program.  */
20413   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20414
20415   file_entry *current_file ()
20416   {
20417     /* lh->file_names is 0-based, but the file name numbers in the
20418        statement program are 1-based.  */
20419     return m_line_header->file_name_at (m_file);
20420   }
20421
20422   /* Record the line in the state machine.  END_SEQUENCE is true if
20423      we're processing the end of a sequence.  */
20424   void record_line (bool end_sequence);
20425
20426   /* Check address and if invalid nop-out the rest of the lines in this
20427      sequence.  */
20428   void check_line_address (struct dwarf2_cu *cu,
20429                            const gdb_byte *line_ptr,
20430                            CORE_ADDR lowpc, CORE_ADDR address);
20431
20432   void handle_set_discriminator (unsigned int discriminator)
20433   {
20434     m_discriminator = discriminator;
20435     m_line_has_non_zero_discriminator |= discriminator != 0;
20436   }
20437
20438   /* Handle DW_LNE_set_address.  */
20439   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20440   {
20441     m_op_index = 0;
20442     address += baseaddr;
20443     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20444   }
20445
20446   /* Handle DW_LNS_advance_pc.  */
20447   void handle_advance_pc (CORE_ADDR adjust);
20448
20449   /* Handle a special opcode.  */
20450   void handle_special_opcode (unsigned char op_code);
20451
20452   /* Handle DW_LNS_advance_line.  */
20453   void handle_advance_line (int line_delta)
20454   {
20455     advance_line (line_delta);
20456   }
20457
20458   /* Handle DW_LNS_set_file.  */
20459   void handle_set_file (file_name_index file);
20460
20461   /* Handle DW_LNS_negate_stmt.  */
20462   void handle_negate_stmt ()
20463   {
20464     m_is_stmt = !m_is_stmt;
20465   }
20466
20467   /* Handle DW_LNS_const_add_pc.  */
20468   void handle_const_add_pc ();
20469
20470   /* Handle DW_LNS_fixed_advance_pc.  */
20471   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20472   {
20473     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20474     m_op_index = 0;
20475   }
20476
20477   /* Handle DW_LNS_copy.  */
20478   void handle_copy ()
20479   {
20480     record_line (false);
20481     m_discriminator = 0;
20482   }
20483
20484   /* Handle DW_LNE_end_sequence.  */
20485   void handle_end_sequence ()
20486   {
20487     m_record_line_callback = ::record_line;
20488   }
20489
20490 private:
20491   /* Advance the line by LINE_DELTA.  */
20492   void advance_line (int line_delta)
20493   {
20494     m_line += line_delta;
20495
20496     if (line_delta != 0)
20497       m_line_has_non_zero_discriminator = m_discriminator != 0;
20498   }
20499
20500   gdbarch *m_gdbarch;
20501
20502   /* True if we're recording lines.
20503      Otherwise we're building partial symtabs and are just interested in
20504      finding include files mentioned by the line number program.  */
20505   bool m_record_lines_p;
20506
20507   /* The line number header.  */
20508   line_header *m_line_header;
20509
20510   /* These are part of the standard DWARF line number state machine,
20511      and initialized according to the DWARF spec.  */
20512
20513   unsigned char m_op_index = 0;
20514   /* The line table index (1-based) of the current file.  */
20515   file_name_index m_file = (file_name_index) 1;
20516   unsigned int m_line = 1;
20517
20518   /* These are initialized in the constructor.  */
20519
20520   CORE_ADDR m_address;
20521   bool m_is_stmt;
20522   unsigned int m_discriminator;
20523
20524   /* Additional bits of state we need to track.  */
20525
20526   /* The last file that we called dwarf2_start_subfile for.
20527      This is only used for TLLs.  */
20528   unsigned int m_last_file = 0;
20529   /* The last file a line number was recorded for.  */
20530   struct subfile *m_last_subfile = NULL;
20531
20532   /* The function to call to record a line.  */
20533   record_line_ftype *m_record_line_callback = NULL;
20534
20535   /* The last line number that was recorded, used to coalesce
20536      consecutive entries for the same line.  This can happen, for
20537      example, when discriminators are present.  PR 17276.  */
20538   unsigned int m_last_line = 0;
20539   bool m_line_has_non_zero_discriminator = false;
20540 };
20541
20542 void
20543 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20544 {
20545   CORE_ADDR addr_adj = (((m_op_index + adjust)
20546                          / m_line_header->maximum_ops_per_instruction)
20547                         * m_line_header->minimum_instruction_length);
20548   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20549   m_op_index = ((m_op_index + adjust)
20550                 % m_line_header->maximum_ops_per_instruction);
20551 }
20552
20553 void
20554 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20555 {
20556   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20557   CORE_ADDR addr_adj = (((m_op_index
20558                           + (adj_opcode / m_line_header->line_range))
20559                          / m_line_header->maximum_ops_per_instruction)
20560                         * m_line_header->minimum_instruction_length);
20561   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20562   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20563                 % m_line_header->maximum_ops_per_instruction);
20564
20565   int line_delta = (m_line_header->line_base
20566                     + (adj_opcode % m_line_header->line_range));
20567   advance_line (line_delta);
20568   record_line (false);
20569   m_discriminator = 0;
20570 }
20571
20572 void
20573 lnp_state_machine::handle_set_file (file_name_index file)
20574 {
20575   m_file = file;
20576
20577   const file_entry *fe = current_file ();
20578   if (fe == NULL)
20579     dwarf2_debug_line_missing_file_complaint ();
20580   else if (m_record_lines_p)
20581     {
20582       const char *dir = fe->include_dir (m_line_header);
20583
20584       m_last_subfile = current_subfile;
20585       m_line_has_non_zero_discriminator = m_discriminator != 0;
20586       dwarf2_start_subfile (fe->name, dir);
20587     }
20588 }
20589
20590 void
20591 lnp_state_machine::handle_const_add_pc ()
20592 {
20593   CORE_ADDR adjust
20594     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20595
20596   CORE_ADDR addr_adj
20597     = (((m_op_index + adjust)
20598         / m_line_header->maximum_ops_per_instruction)
20599        * m_line_header->minimum_instruction_length);
20600
20601   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20602   m_op_index = ((m_op_index + adjust)
20603                 % m_line_header->maximum_ops_per_instruction);
20604 }
20605
20606 /* Ignore this record_line request.  */
20607
20608 static void
20609 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20610 {
20611   return;
20612 }
20613
20614 /* Return non-zero if we should add LINE to the line number table.
20615    LINE is the line to add, LAST_LINE is the last line that was added,
20616    LAST_SUBFILE is the subfile for LAST_LINE.
20617    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20618    had a non-zero discriminator.
20619
20620    We have to be careful in the presence of discriminators.
20621    E.g., for this line:
20622
20623      for (i = 0; i < 100000; i++);
20624
20625    clang can emit four line number entries for that one line,
20626    each with a different discriminator.
20627    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20628
20629    However, we want gdb to coalesce all four entries into one.
20630    Otherwise the user could stepi into the middle of the line and
20631    gdb would get confused about whether the pc really was in the
20632    middle of the line.
20633
20634    Things are further complicated by the fact that two consecutive
20635    line number entries for the same line is a heuristic used by gcc
20636    to denote the end of the prologue.  So we can't just discard duplicate
20637    entries, we have to be selective about it.  The heuristic we use is
20638    that we only collapse consecutive entries for the same line if at least
20639    one of those entries has a non-zero discriminator.  PR 17276.
20640
20641    Note: Addresses in the line number state machine can never go backwards
20642    within one sequence, thus this coalescing is ok.  */
20643
20644 static int
20645 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20646                      int line_has_non_zero_discriminator,
20647                      struct subfile *last_subfile)
20648 {
20649   if (current_subfile != last_subfile)
20650     return 1;
20651   if (line != last_line)
20652     return 1;
20653   /* Same line for the same file that we've seen already.
20654      As a last check, for pr 17276, only record the line if the line
20655      has never had a non-zero discriminator.  */
20656   if (!line_has_non_zero_discriminator)
20657     return 1;
20658   return 0;
20659 }
20660
20661 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20662    in the line table of subfile SUBFILE.  */
20663
20664 static void
20665 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20666                      unsigned int line, CORE_ADDR address,
20667                      record_line_ftype p_record_line)
20668 {
20669   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20670
20671   if (dwarf_line_debug)
20672     {
20673       fprintf_unfiltered (gdb_stdlog,
20674                           "Recording line %u, file %s, address %s\n",
20675                           line, lbasename (subfile->name),
20676                           paddress (gdbarch, address));
20677     }
20678
20679   (*p_record_line) (subfile, line, addr);
20680 }
20681
20682 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20683    Mark the end of a set of line number records.
20684    The arguments are the same as for dwarf_record_line_1.
20685    If SUBFILE is NULL the request is ignored.  */
20686
20687 static void
20688 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20689                    CORE_ADDR address, record_line_ftype p_record_line)
20690 {
20691   if (subfile == NULL)
20692     return;
20693
20694   if (dwarf_line_debug)
20695     {
20696       fprintf_unfiltered (gdb_stdlog,
20697                           "Finishing current line, file %s, address %s\n",
20698                           lbasename (subfile->name),
20699                           paddress (gdbarch, address));
20700     }
20701
20702   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20703 }
20704
20705 void
20706 lnp_state_machine::record_line (bool end_sequence)
20707 {
20708   if (dwarf_line_debug)
20709     {
20710       fprintf_unfiltered (gdb_stdlog,
20711                           "Processing actual line %u: file %u,"
20712                           " address %s, is_stmt %u, discrim %u\n",
20713                           m_line, to_underlying (m_file),
20714                           paddress (m_gdbarch, m_address),
20715                           m_is_stmt, m_discriminator);
20716     }
20717
20718   file_entry *fe = current_file ();
20719
20720   if (fe == NULL)
20721     dwarf2_debug_line_missing_file_complaint ();
20722   /* For now we ignore lines not starting on an instruction boundary.
20723      But not when processing end_sequence for compatibility with the
20724      previous version of the code.  */
20725   else if (m_op_index == 0 || end_sequence)
20726     {
20727       fe->included_p = 1;
20728       if (m_record_lines_p && m_is_stmt)
20729         {
20730           if (m_last_subfile != current_subfile || end_sequence)
20731             {
20732               dwarf_finish_line (m_gdbarch, m_last_subfile,
20733                                  m_address, m_record_line_callback);
20734             }
20735
20736           if (!end_sequence)
20737             {
20738               if (dwarf_record_line_p (m_line, m_last_line,
20739                                        m_line_has_non_zero_discriminator,
20740                                        m_last_subfile))
20741                 {
20742                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20743                                        m_line, m_address,
20744                                        m_record_line_callback);
20745                 }
20746               m_last_subfile = current_subfile;
20747               m_last_line = m_line;
20748             }
20749         }
20750     }
20751 }
20752
20753 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20754                                       bool record_lines_p)
20755 {
20756   m_gdbarch = arch;
20757   m_record_lines_p = record_lines_p;
20758   m_line_header = lh;
20759
20760   m_record_line_callback = ::record_line;
20761
20762   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20763      was a line entry for it so that the backend has a chance to adjust it
20764      and also record it in case it needs it.  This is currently used by MIPS
20765      code, cf. `mips_adjust_dwarf2_line'.  */
20766   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20767   m_is_stmt = lh->default_is_stmt;
20768   m_discriminator = 0;
20769 }
20770
20771 void
20772 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20773                                        const gdb_byte *line_ptr,
20774                                        CORE_ADDR lowpc, CORE_ADDR address)
20775 {
20776   /* If address < lowpc then it's not a usable value, it's outside the
20777      pc range of the CU.  However, we restrict the test to only address
20778      values of zero to preserve GDB's previous behaviour which is to
20779      handle the specific case of a function being GC'd by the linker.  */
20780
20781   if (address == 0 && address < lowpc)
20782     {
20783       /* This line table is for a function which has been
20784          GCd by the linker.  Ignore it.  PR gdb/12528 */
20785
20786       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20787       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20788
20789       complaint (&symfile_complaints,
20790                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20791                  line_offset, objfile_name (objfile));
20792       m_record_line_callback = noop_record_line;
20793       /* Note: record_line_callback is left as noop_record_line until
20794          we see DW_LNE_end_sequence.  */
20795     }
20796 }
20797
20798 /* Subroutine of dwarf_decode_lines to simplify it.
20799    Process the line number information in LH.
20800    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20801    program in order to set included_p for every referenced header.  */
20802
20803 static void
20804 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20805                       const int decode_for_pst_p, CORE_ADDR lowpc)
20806 {
20807   const gdb_byte *line_ptr, *extended_end;
20808   const gdb_byte *line_end;
20809   unsigned int bytes_read, extended_len;
20810   unsigned char op_code, extended_op;
20811   CORE_ADDR baseaddr;
20812   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20813   bfd *abfd = objfile->obfd;
20814   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20815   /* True if we're recording line info (as opposed to building partial
20816      symtabs and just interested in finding include files mentioned by
20817      the line number program).  */
20818   bool record_lines_p = !decode_for_pst_p;
20819
20820   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20821
20822   line_ptr = lh->statement_program_start;
20823   line_end = lh->statement_program_end;
20824
20825   /* Read the statement sequences until there's nothing left.  */
20826   while (line_ptr < line_end)
20827     {
20828       /* The DWARF line number program state machine.  Reset the state
20829          machine at the start of each sequence.  */
20830       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20831       bool end_sequence = false;
20832
20833       if (record_lines_p)
20834         {
20835           /* Start a subfile for the current file of the state
20836              machine.  */
20837           const file_entry *fe = state_machine.current_file ();
20838
20839           if (fe != NULL)
20840             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20841         }
20842
20843       /* Decode the table.  */
20844       while (line_ptr < line_end && !end_sequence)
20845         {
20846           op_code = read_1_byte (abfd, line_ptr);
20847           line_ptr += 1;
20848
20849           if (op_code >= lh->opcode_base)
20850             {
20851               /* Special opcode.  */
20852               state_machine.handle_special_opcode (op_code);
20853             }
20854           else switch (op_code)
20855             {
20856             case DW_LNS_extended_op:
20857               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20858                                                    &bytes_read);
20859               line_ptr += bytes_read;
20860               extended_end = line_ptr + extended_len;
20861               extended_op = read_1_byte (abfd, line_ptr);
20862               line_ptr += 1;
20863               switch (extended_op)
20864                 {
20865                 case DW_LNE_end_sequence:
20866                   state_machine.handle_end_sequence ();
20867                   end_sequence = true;
20868                   break;
20869                 case DW_LNE_set_address:
20870                   {
20871                     CORE_ADDR address
20872                       = read_address (abfd, line_ptr, cu, &bytes_read);
20873                     line_ptr += bytes_read;
20874
20875                     state_machine.check_line_address (cu, line_ptr,
20876                                                       lowpc, address);
20877                     state_machine.handle_set_address (baseaddr, address);
20878                   }
20879                   break;
20880                 case DW_LNE_define_file:
20881                   {
20882                     const char *cur_file;
20883                     unsigned int mod_time, length;
20884                     dir_index dindex;
20885
20886                     cur_file = read_direct_string (abfd, line_ptr,
20887                                                    &bytes_read);
20888                     line_ptr += bytes_read;
20889                     dindex = (dir_index)
20890                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20891                     line_ptr += bytes_read;
20892                     mod_time =
20893                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20894                     line_ptr += bytes_read;
20895                     length =
20896                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20897                     line_ptr += bytes_read;
20898                     lh->add_file_name (cur_file, dindex, mod_time, length);
20899                   }
20900                   break;
20901                 case DW_LNE_set_discriminator:
20902                   {
20903                     /* The discriminator is not interesting to the
20904                        debugger; just ignore it.  We still need to
20905                        check its value though:
20906                        if there are consecutive entries for the same
20907                        (non-prologue) line we want to coalesce them.
20908                        PR 17276.  */
20909                     unsigned int discr
20910                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20911                     line_ptr += bytes_read;
20912
20913                     state_machine.handle_set_discriminator (discr);
20914                   }
20915                   break;
20916                 default:
20917                   complaint (&symfile_complaints,
20918                              _("mangled .debug_line section"));
20919                   return;
20920                 }
20921               /* Make sure that we parsed the extended op correctly.  If e.g.
20922                  we expected a different address size than the producer used,
20923                  we may have read the wrong number of bytes.  */
20924               if (line_ptr != extended_end)
20925                 {
20926                   complaint (&symfile_complaints,
20927                              _("mangled .debug_line section"));
20928                   return;
20929                 }
20930               break;
20931             case DW_LNS_copy:
20932               state_machine.handle_copy ();
20933               break;
20934             case DW_LNS_advance_pc:
20935               {
20936                 CORE_ADDR adjust
20937                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20938                 line_ptr += bytes_read;
20939
20940                 state_machine.handle_advance_pc (adjust);
20941               }
20942               break;
20943             case DW_LNS_advance_line:
20944               {
20945                 int line_delta
20946                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20947                 line_ptr += bytes_read;
20948
20949                 state_machine.handle_advance_line (line_delta);
20950               }
20951               break;
20952             case DW_LNS_set_file:
20953               {
20954                 file_name_index file
20955                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20956                                                             &bytes_read);
20957                 line_ptr += bytes_read;
20958
20959                 state_machine.handle_set_file (file);
20960               }
20961               break;
20962             case DW_LNS_set_column:
20963               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20964               line_ptr += bytes_read;
20965               break;
20966             case DW_LNS_negate_stmt:
20967               state_machine.handle_negate_stmt ();
20968               break;
20969             case DW_LNS_set_basic_block:
20970               break;
20971             /* Add to the address register of the state machine the
20972                address increment value corresponding to special opcode
20973                255.  I.e., this value is scaled by the minimum
20974                instruction length since special opcode 255 would have
20975                scaled the increment.  */
20976             case DW_LNS_const_add_pc:
20977               state_machine.handle_const_add_pc ();
20978               break;
20979             case DW_LNS_fixed_advance_pc:
20980               {
20981                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20982                 line_ptr += 2;
20983
20984                 state_machine.handle_fixed_advance_pc (addr_adj);
20985               }
20986               break;
20987             default:
20988               {
20989                 /* Unknown standard opcode, ignore it.  */
20990                 int i;
20991
20992                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20993                   {
20994                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20995                     line_ptr += bytes_read;
20996                   }
20997               }
20998             }
20999         }
21000
21001       if (!end_sequence)
21002         dwarf2_debug_line_missing_end_sequence_complaint ();
21003
21004       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21005          in which case we still finish recording the last line).  */
21006       state_machine.record_line (true);
21007     }
21008 }
21009
21010 /* Decode the Line Number Program (LNP) for the given line_header
21011    structure and CU.  The actual information extracted and the type
21012    of structures created from the LNP depends on the value of PST.
21013
21014    1. If PST is NULL, then this procedure uses the data from the program
21015       to create all necessary symbol tables, and their linetables.
21016
21017    2. If PST is not NULL, this procedure reads the program to determine
21018       the list of files included by the unit represented by PST, and
21019       builds all the associated partial symbol tables.
21020
21021    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21022    It is used for relative paths in the line table.
21023    NOTE: When processing partial symtabs (pst != NULL),
21024    comp_dir == pst->dirname.
21025
21026    NOTE: It is important that psymtabs have the same file name (via strcmp)
21027    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21028    symtab we don't use it in the name of the psymtabs we create.
21029    E.g. expand_line_sal requires this when finding psymtabs to expand.
21030    A good testcase for this is mb-inline.exp.
21031
21032    LOWPC is the lowest address in CU (or 0 if not known).
21033
21034    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21035    for its PC<->lines mapping information.  Otherwise only the filename
21036    table is read in.  */
21037
21038 static void
21039 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21040                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21041                     CORE_ADDR lowpc, int decode_mapping)
21042 {
21043   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21044   const int decode_for_pst_p = (pst != NULL);
21045
21046   if (decode_mapping)
21047     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21048
21049   if (decode_for_pst_p)
21050     {
21051       int file_index;
21052
21053       /* Now that we're done scanning the Line Header Program, we can
21054          create the psymtab of each included file.  */
21055       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21056         if (lh->file_names[file_index].included_p == 1)
21057           {
21058             gdb::unique_xmalloc_ptr<char> name_holder;
21059             const char *include_name =
21060               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21061                                          &name_holder);
21062             if (include_name != NULL)
21063               dwarf2_create_include_psymtab (include_name, pst, objfile);
21064           }
21065     }
21066   else
21067     {
21068       /* Make sure a symtab is created for every file, even files
21069          which contain only variables (i.e. no code with associated
21070          line numbers).  */
21071       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21072       int i;
21073
21074       for (i = 0; i < lh->file_names.size (); i++)
21075         {
21076           file_entry &fe = lh->file_names[i];
21077
21078           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21079
21080           if (current_subfile->symtab == NULL)
21081             {
21082               current_subfile->symtab
21083                 = allocate_symtab (cust, current_subfile->name);
21084             }
21085           fe.symtab = current_subfile->symtab;
21086         }
21087     }
21088 }
21089
21090 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21091    DIRNAME the name of the source directory which contains FILENAME
21092    or NULL if not known.
21093    This routine tries to keep line numbers from identical absolute and
21094    relative file names in a common subfile.
21095
21096    Using the `list' example from the GDB testsuite, which resides in
21097    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21098    of /srcdir/list0.c yields the following debugging information for list0.c:
21099
21100    DW_AT_name:          /srcdir/list0.c
21101    DW_AT_comp_dir:      /compdir
21102    files.files[0].name: list0.h
21103    files.files[0].dir:  /srcdir
21104    files.files[1].name: list0.c
21105    files.files[1].dir:  /srcdir
21106
21107    The line number information for list0.c has to end up in a single
21108    subfile, so that `break /srcdir/list0.c:1' works as expected.
21109    start_subfile will ensure that this happens provided that we pass the
21110    concatenation of files.files[1].dir and files.files[1].name as the
21111    subfile's name.  */
21112
21113 static void
21114 dwarf2_start_subfile (const char *filename, const char *dirname)
21115 {
21116   char *copy = NULL;
21117
21118   /* In order not to lose the line information directory,
21119      we concatenate it to the filename when it makes sense.
21120      Note that the Dwarf3 standard says (speaking of filenames in line
21121      information): ``The directory index is ignored for file names
21122      that represent full path names''.  Thus ignoring dirname in the
21123      `else' branch below isn't an issue.  */
21124
21125   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21126     {
21127       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21128       filename = copy;
21129     }
21130
21131   start_subfile (filename);
21132
21133   if (copy != NULL)
21134     xfree (copy);
21135 }
21136
21137 /* Start a symtab for DWARF.
21138    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21139
21140 static struct compunit_symtab *
21141 dwarf2_start_symtab (struct dwarf2_cu *cu,
21142                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21143 {
21144   struct compunit_symtab *cust
21145     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21146                     low_pc, cu->language);
21147
21148   record_debugformat ("DWARF 2");
21149   record_producer (cu->producer);
21150
21151   /* We assume that we're processing GCC output.  */
21152   processing_gcc_compilation = 2;
21153
21154   cu->processing_has_namespace_info = 0;
21155
21156   return cust;
21157 }
21158
21159 static void
21160 var_decode_location (struct attribute *attr, struct symbol *sym,
21161                      struct dwarf2_cu *cu)
21162 {
21163   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21164   struct comp_unit_head *cu_header = &cu->header;
21165
21166   /* NOTE drow/2003-01-30: There used to be a comment and some special
21167      code here to turn a symbol with DW_AT_external and a
21168      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21169      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21170      with some versions of binutils) where shared libraries could have
21171      relocations against symbols in their debug information - the
21172      minimal symbol would have the right address, but the debug info
21173      would not.  It's no longer necessary, because we will explicitly
21174      apply relocations when we read in the debug information now.  */
21175
21176   /* A DW_AT_location attribute with no contents indicates that a
21177      variable has been optimized away.  */
21178   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21179     {
21180       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21181       return;
21182     }
21183
21184   /* Handle one degenerate form of location expression specially, to
21185      preserve GDB's previous behavior when section offsets are
21186      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21187      then mark this symbol as LOC_STATIC.  */
21188
21189   if (attr_form_is_block (attr)
21190       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21191            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21192           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21193               && (DW_BLOCK (attr)->size
21194                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21195     {
21196       unsigned int dummy;
21197
21198       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21199         SYMBOL_VALUE_ADDRESS (sym) =
21200           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21201       else
21202         SYMBOL_VALUE_ADDRESS (sym) =
21203           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21204       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21205       fixup_symbol_section (sym, objfile);
21206       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21207                                               SYMBOL_SECTION (sym));
21208       return;
21209     }
21210
21211   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21212      expression evaluator, and use LOC_COMPUTED only when necessary
21213      (i.e. when the value of a register or memory location is
21214      referenced, or a thread-local block, etc.).  Then again, it might
21215      not be worthwhile.  I'm assuming that it isn't unless performance
21216      or memory numbers show me otherwise.  */
21217
21218   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21219
21220   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21221     cu->has_loclist = 1;
21222 }
21223
21224 /* Given a pointer to a DWARF information entry, figure out if we need
21225    to make a symbol table entry for it, and if so, create a new entry
21226    and return a pointer to it.
21227    If TYPE is NULL, determine symbol type from the die, otherwise
21228    used the passed type.
21229    If SPACE is not NULL, use it to hold the new symbol.  If it is
21230    NULL, allocate a new symbol on the objfile's obstack.  */
21231
21232 static struct symbol *
21233 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21234             struct symbol *space)
21235 {
21236   struct dwarf2_per_objfile *dwarf2_per_objfile
21237     = cu->per_cu->dwarf2_per_objfile;
21238   struct objfile *objfile = dwarf2_per_objfile->objfile;
21239   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21240   struct symbol *sym = NULL;
21241   const char *name;
21242   struct attribute *attr = NULL;
21243   struct attribute *attr2 = NULL;
21244   CORE_ADDR baseaddr;
21245   struct pending **list_to_add = NULL;
21246
21247   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21248
21249   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21250
21251   name = dwarf2_name (die, cu);
21252   if (name)
21253     {
21254       const char *linkagename;
21255       int suppress_add = 0;
21256
21257       if (space)
21258         sym = space;
21259       else
21260         sym = allocate_symbol (objfile);
21261       OBJSTAT (objfile, n_syms++);
21262
21263       /* Cache this symbol's name and the name's demangled form (if any).  */
21264       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21265       linkagename = dwarf2_physname (name, die, cu);
21266       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21267
21268       /* Fortran does not have mangling standard and the mangling does differ
21269          between gfortran, iFort etc.  */
21270       if (cu->language == language_fortran
21271           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21272         symbol_set_demangled_name (&(sym->ginfo),
21273                                    dwarf2_full_name (name, die, cu),
21274                                    NULL);
21275
21276       /* Default assumptions.
21277          Use the passed type or decode it from the die.  */
21278       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21279       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21280       if (type != NULL)
21281         SYMBOL_TYPE (sym) = type;
21282       else
21283         SYMBOL_TYPE (sym) = die_type (die, cu);
21284       attr = dwarf2_attr (die,
21285                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21286                           cu);
21287       if (attr)
21288         {
21289           SYMBOL_LINE (sym) = DW_UNSND (attr);
21290         }
21291
21292       attr = dwarf2_attr (die,
21293                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21294                           cu);
21295       if (attr)
21296         {
21297           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21298           struct file_entry *fe;
21299
21300           if (cu->line_header != NULL)
21301             fe = cu->line_header->file_name_at (file_index);
21302           else
21303             fe = NULL;
21304
21305           if (fe == NULL)
21306             complaint (&symfile_complaints,
21307                        _("file index out of range"));
21308           else
21309             symbol_set_symtab (sym, fe->symtab);
21310         }
21311
21312       switch (die->tag)
21313         {
21314         case DW_TAG_label:
21315           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21316           if (attr)
21317             {
21318               CORE_ADDR addr;
21319
21320               addr = attr_value_as_address (attr);
21321               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21322               SYMBOL_VALUE_ADDRESS (sym) = addr;
21323             }
21324           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21325           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21326           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21327           add_symbol_to_list (sym, cu->list_in_scope);
21328           break;
21329         case DW_TAG_subprogram:
21330           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21331              finish_block.  */
21332           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21333           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21334           if ((attr2 && (DW_UNSND (attr2) != 0))
21335               || cu->language == language_ada)
21336             {
21337               /* Subprograms marked external are stored as a global symbol.
21338                  Ada subprograms, whether marked external or not, are always
21339                  stored as a global symbol, because we want to be able to
21340                  access them globally.  For instance, we want to be able
21341                  to break on a nested subprogram without having to
21342                  specify the context.  */
21343               list_to_add = &global_symbols;
21344             }
21345           else
21346             {
21347               list_to_add = cu->list_in_scope;
21348             }
21349           break;
21350         case DW_TAG_inlined_subroutine:
21351           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21352              finish_block.  */
21353           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21354           SYMBOL_INLINED (sym) = 1;
21355           list_to_add = cu->list_in_scope;
21356           break;
21357         case DW_TAG_template_value_param:
21358           suppress_add = 1;
21359           /* Fall through.  */
21360         case DW_TAG_constant:
21361         case DW_TAG_variable:
21362         case DW_TAG_member:
21363           /* Compilation with minimal debug info may result in
21364              variables with missing type entries.  Change the
21365              misleading `void' type to something sensible.  */
21366           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21367             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21368
21369           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21370           /* In the case of DW_TAG_member, we should only be called for
21371              static const members.  */
21372           if (die->tag == DW_TAG_member)
21373             {
21374               /* dwarf2_add_field uses die_is_declaration,
21375                  so we do the same.  */
21376               gdb_assert (die_is_declaration (die, cu));
21377               gdb_assert (attr);
21378             }
21379           if (attr)
21380             {
21381               dwarf2_const_value (attr, sym, cu);
21382               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21383               if (!suppress_add)
21384                 {
21385                   if (attr2 && (DW_UNSND (attr2) != 0))
21386                     list_to_add = &global_symbols;
21387                   else
21388                     list_to_add = cu->list_in_scope;
21389                 }
21390               break;
21391             }
21392           attr = dwarf2_attr (die, DW_AT_location, cu);
21393           if (attr)
21394             {
21395               var_decode_location (attr, sym, cu);
21396               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21397
21398               /* Fortran explicitly imports any global symbols to the local
21399                  scope by DW_TAG_common_block.  */
21400               if (cu->language == language_fortran && die->parent
21401                   && die->parent->tag == DW_TAG_common_block)
21402                 attr2 = NULL;
21403
21404               if (SYMBOL_CLASS (sym) == LOC_STATIC
21405                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21406                   && !dwarf2_per_objfile->has_section_at_zero)
21407                 {
21408                   /* When a static variable is eliminated by the linker,
21409                      the corresponding debug information is not stripped
21410                      out, but the variable address is set to null;
21411                      do not add such variables into symbol table.  */
21412                 }
21413               else if (attr2 && (DW_UNSND (attr2) != 0))
21414                 {
21415                   /* Workaround gfortran PR debug/40040 - it uses
21416                      DW_AT_location for variables in -fPIC libraries which may
21417                      get overriden by other libraries/executable and get
21418                      a different address.  Resolve it by the minimal symbol
21419                      which may come from inferior's executable using copy
21420                      relocation.  Make this workaround only for gfortran as for
21421                      other compilers GDB cannot guess the minimal symbol
21422                      Fortran mangling kind.  */
21423                   if (cu->language == language_fortran && die->parent
21424                       && die->parent->tag == DW_TAG_module
21425                       && cu->producer
21426                       && startswith (cu->producer, "GNU Fortran"))
21427                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21428
21429                   /* A variable with DW_AT_external is never static,
21430                      but it may be block-scoped.  */
21431                   list_to_add = (cu->list_in_scope == &file_symbols
21432                                  ? &global_symbols : cu->list_in_scope);
21433                 }
21434               else
21435                 list_to_add = cu->list_in_scope;
21436             }
21437           else
21438             {
21439               /* We do not know the address of this symbol.
21440                  If it is an external symbol and we have type information
21441                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21442                  The address of the variable will then be determined from
21443                  the minimal symbol table whenever the variable is
21444                  referenced.  */
21445               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21446
21447               /* Fortran explicitly imports any global symbols to the local
21448                  scope by DW_TAG_common_block.  */
21449               if (cu->language == language_fortran && die->parent
21450                   && die->parent->tag == DW_TAG_common_block)
21451                 {
21452                   /* SYMBOL_CLASS doesn't matter here because
21453                      read_common_block is going to reset it.  */
21454                   if (!suppress_add)
21455                     list_to_add = cu->list_in_scope;
21456                 }
21457               else if (attr2 && (DW_UNSND (attr2) != 0)
21458                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21459                 {
21460                   /* A variable with DW_AT_external is never static, but it
21461                      may be block-scoped.  */
21462                   list_to_add = (cu->list_in_scope == &file_symbols
21463                                  ? &global_symbols : cu->list_in_scope);
21464
21465                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21466                 }
21467               else if (!die_is_declaration (die, cu))
21468                 {
21469                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21470                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21471                   if (!suppress_add)
21472                     list_to_add = cu->list_in_scope;
21473                 }
21474             }
21475           break;
21476         case DW_TAG_formal_parameter:
21477           /* If we are inside a function, mark this as an argument.  If
21478              not, we might be looking at an argument to an inlined function
21479              when we do not have enough information to show inlined frames;
21480              pretend it's a local variable in that case so that the user can
21481              still see it.  */
21482           if (context_stack_depth > 0
21483               && context_stack[context_stack_depth - 1].name != NULL)
21484             SYMBOL_IS_ARGUMENT (sym) = 1;
21485           attr = dwarf2_attr (die, DW_AT_location, cu);
21486           if (attr)
21487             {
21488               var_decode_location (attr, sym, cu);
21489             }
21490           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21491           if (attr)
21492             {
21493               dwarf2_const_value (attr, sym, cu);
21494             }
21495
21496           list_to_add = cu->list_in_scope;
21497           break;
21498         case DW_TAG_unspecified_parameters:
21499           /* From varargs functions; gdb doesn't seem to have any
21500              interest in this information, so just ignore it for now.
21501              (FIXME?) */
21502           break;
21503         case DW_TAG_template_type_param:
21504           suppress_add = 1;
21505           /* Fall through.  */
21506         case DW_TAG_class_type:
21507         case DW_TAG_interface_type:
21508         case DW_TAG_structure_type:
21509         case DW_TAG_union_type:
21510         case DW_TAG_set_type:
21511         case DW_TAG_enumeration_type:
21512           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21513           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21514
21515           {
21516             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21517                really ever be static objects: otherwise, if you try
21518                to, say, break of a class's method and you're in a file
21519                which doesn't mention that class, it won't work unless
21520                the check for all static symbols in lookup_symbol_aux
21521                saves you.  See the OtherFileClass tests in
21522                gdb.c++/namespace.exp.  */
21523
21524             if (!suppress_add)
21525               {
21526                 list_to_add = (cu->list_in_scope == &file_symbols
21527                                && cu->language == language_cplus
21528                                ? &global_symbols : cu->list_in_scope);
21529
21530                 /* The semantics of C++ state that "struct foo {
21531                    ... }" also defines a typedef for "foo".  */
21532                 if (cu->language == language_cplus
21533                     || cu->language == language_ada
21534                     || cu->language == language_d
21535                     || cu->language == language_rust)
21536                   {
21537                     /* The symbol's name is already allocated along
21538                        with this objfile, so we don't need to
21539                        duplicate it for the type.  */
21540                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21541                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21542                   }
21543               }
21544           }
21545           break;
21546         case DW_TAG_typedef:
21547           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21548           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21549           list_to_add = cu->list_in_scope;
21550           break;
21551         case DW_TAG_base_type:
21552         case DW_TAG_subrange_type:
21553           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21554           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21555           list_to_add = cu->list_in_scope;
21556           break;
21557         case DW_TAG_enumerator:
21558           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21559           if (attr)
21560             {
21561               dwarf2_const_value (attr, sym, cu);
21562             }
21563           {
21564             /* NOTE: carlton/2003-11-10: See comment above in the
21565                DW_TAG_class_type, etc. block.  */
21566
21567             list_to_add = (cu->list_in_scope == &file_symbols
21568                            && cu->language == language_cplus
21569                            ? &global_symbols : cu->list_in_scope);
21570           }
21571           break;
21572         case DW_TAG_imported_declaration:
21573         case DW_TAG_namespace:
21574           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21575           list_to_add = &global_symbols;
21576           break;
21577         case DW_TAG_module:
21578           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21579           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21580           list_to_add = &global_symbols;
21581           break;
21582         case DW_TAG_common_block:
21583           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21584           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21585           add_symbol_to_list (sym, cu->list_in_scope);
21586           break;
21587         default:
21588           /* Not a tag we recognize.  Hopefully we aren't processing
21589              trash data, but since we must specifically ignore things
21590              we don't recognize, there is nothing else we should do at
21591              this point.  */
21592           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21593                      dwarf_tag_name (die->tag));
21594           break;
21595         }
21596
21597       if (suppress_add)
21598         {
21599           sym->hash_next = objfile->template_symbols;
21600           objfile->template_symbols = sym;
21601           list_to_add = NULL;
21602         }
21603
21604       if (list_to_add != NULL)
21605         add_symbol_to_list (sym, list_to_add);
21606
21607       /* For the benefit of old versions of GCC, check for anonymous
21608          namespaces based on the demangled name.  */
21609       if (!cu->processing_has_namespace_info
21610           && cu->language == language_cplus)
21611         cp_scan_for_anonymous_namespaces (sym, objfile);
21612     }
21613   return (sym);
21614 }
21615
21616 /* Given an attr with a DW_FORM_dataN value in host byte order,
21617    zero-extend it as appropriate for the symbol's type.  The DWARF
21618    standard (v4) is not entirely clear about the meaning of using
21619    DW_FORM_dataN for a constant with a signed type, where the type is
21620    wider than the data.  The conclusion of a discussion on the DWARF
21621    list was that this is unspecified.  We choose to always zero-extend
21622    because that is the interpretation long in use by GCC.  */
21623
21624 static gdb_byte *
21625 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21626                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21627 {
21628   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21629   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21630                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21631   LONGEST l = DW_UNSND (attr);
21632
21633   if (bits < sizeof (*value) * 8)
21634     {
21635       l &= ((LONGEST) 1 << bits) - 1;
21636       *value = l;
21637     }
21638   else if (bits == sizeof (*value) * 8)
21639     *value = l;
21640   else
21641     {
21642       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21643       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21644       return bytes;
21645     }
21646
21647   return NULL;
21648 }
21649
21650 /* Read a constant value from an attribute.  Either set *VALUE, or if
21651    the value does not fit in *VALUE, set *BYTES - either already
21652    allocated on the objfile obstack, or newly allocated on OBSTACK,
21653    or, set *BATON, if we translated the constant to a location
21654    expression.  */
21655
21656 static void
21657 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21658                          const char *name, struct obstack *obstack,
21659                          struct dwarf2_cu *cu,
21660                          LONGEST *value, const gdb_byte **bytes,
21661                          struct dwarf2_locexpr_baton **baton)
21662 {
21663   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21664   struct comp_unit_head *cu_header = &cu->header;
21665   struct dwarf_block *blk;
21666   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21667                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21668
21669   *value = 0;
21670   *bytes = NULL;
21671   *baton = NULL;
21672
21673   switch (attr->form)
21674     {
21675     case DW_FORM_addr:
21676     case DW_FORM_GNU_addr_index:
21677       {
21678         gdb_byte *data;
21679
21680         if (TYPE_LENGTH (type) != cu_header->addr_size)
21681           dwarf2_const_value_length_mismatch_complaint (name,
21682                                                         cu_header->addr_size,
21683                                                         TYPE_LENGTH (type));
21684         /* Symbols of this form are reasonably rare, so we just
21685            piggyback on the existing location code rather than writing
21686            a new implementation of symbol_computed_ops.  */
21687         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21688         (*baton)->per_cu = cu->per_cu;
21689         gdb_assert ((*baton)->per_cu);
21690
21691         (*baton)->size = 2 + cu_header->addr_size;
21692         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21693         (*baton)->data = data;
21694
21695         data[0] = DW_OP_addr;
21696         store_unsigned_integer (&data[1], cu_header->addr_size,
21697                                 byte_order, DW_ADDR (attr));
21698         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21699       }
21700       break;
21701     case DW_FORM_string:
21702     case DW_FORM_strp:
21703     case DW_FORM_GNU_str_index:
21704     case DW_FORM_GNU_strp_alt:
21705       /* DW_STRING is already allocated on the objfile obstack, point
21706          directly to it.  */
21707       *bytes = (const gdb_byte *) DW_STRING (attr);
21708       break;
21709     case DW_FORM_block1:
21710     case DW_FORM_block2:
21711     case DW_FORM_block4:
21712     case DW_FORM_block:
21713     case DW_FORM_exprloc:
21714     case DW_FORM_data16:
21715       blk = DW_BLOCK (attr);
21716       if (TYPE_LENGTH (type) != blk->size)
21717         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21718                                                       TYPE_LENGTH (type));
21719       *bytes = blk->data;
21720       break;
21721
21722       /* The DW_AT_const_value attributes are supposed to carry the
21723          symbol's value "represented as it would be on the target
21724          architecture."  By the time we get here, it's already been
21725          converted to host endianness, so we just need to sign- or
21726          zero-extend it as appropriate.  */
21727     case DW_FORM_data1:
21728       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21729       break;
21730     case DW_FORM_data2:
21731       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21732       break;
21733     case DW_FORM_data4:
21734       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21735       break;
21736     case DW_FORM_data8:
21737       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21738       break;
21739
21740     case DW_FORM_sdata:
21741     case DW_FORM_implicit_const:
21742       *value = DW_SND (attr);
21743       break;
21744
21745     case DW_FORM_udata:
21746       *value = DW_UNSND (attr);
21747       break;
21748
21749     default:
21750       complaint (&symfile_complaints,
21751                  _("unsupported const value attribute form: '%s'"),
21752                  dwarf_form_name (attr->form));
21753       *value = 0;
21754       break;
21755     }
21756 }
21757
21758
21759 /* Copy constant value from an attribute to a symbol.  */
21760
21761 static void
21762 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21763                     struct dwarf2_cu *cu)
21764 {
21765   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21766   LONGEST value;
21767   const gdb_byte *bytes;
21768   struct dwarf2_locexpr_baton *baton;
21769
21770   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21771                            SYMBOL_PRINT_NAME (sym),
21772                            &objfile->objfile_obstack, cu,
21773                            &value, &bytes, &baton);
21774
21775   if (baton != NULL)
21776     {
21777       SYMBOL_LOCATION_BATON (sym) = baton;
21778       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21779     }
21780   else if (bytes != NULL)
21781      {
21782       SYMBOL_VALUE_BYTES (sym) = bytes;
21783       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21784     }
21785   else
21786     {
21787       SYMBOL_VALUE (sym) = value;
21788       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21789     }
21790 }
21791
21792 /* Return the type of the die in question using its DW_AT_type attribute.  */
21793
21794 static struct type *
21795 die_type (struct die_info *die, struct dwarf2_cu *cu)
21796 {
21797   struct attribute *type_attr;
21798
21799   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21800   if (!type_attr)
21801     {
21802       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21803       /* A missing DW_AT_type represents a void type.  */
21804       return objfile_type (objfile)->builtin_void;
21805     }
21806
21807   return lookup_die_type (die, type_attr, cu);
21808 }
21809
21810 /* True iff CU's producer generates GNAT Ada auxiliary information
21811    that allows to find parallel types through that information instead
21812    of having to do expensive parallel lookups by type name.  */
21813
21814 static int
21815 need_gnat_info (struct dwarf2_cu *cu)
21816 {
21817   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21818      of GNAT produces this auxiliary information, without any indication
21819      that it is produced.  Part of enhancing the FSF version of GNAT
21820      to produce that information will be to put in place an indicator
21821      that we can use in order to determine whether the descriptive type
21822      info is available or not.  One suggestion that has been made is
21823      to use a new attribute, attached to the CU die.  For now, assume
21824      that the descriptive type info is not available.  */
21825   return 0;
21826 }
21827
21828 /* Return the auxiliary type of the die in question using its
21829    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21830    attribute is not present.  */
21831
21832 static struct type *
21833 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21834 {
21835   struct attribute *type_attr;
21836
21837   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21838   if (!type_attr)
21839     return NULL;
21840
21841   return lookup_die_type (die, type_attr, cu);
21842 }
21843
21844 /* If DIE has a descriptive_type attribute, then set the TYPE's
21845    descriptive type accordingly.  */
21846
21847 static void
21848 set_descriptive_type (struct type *type, struct die_info *die,
21849                       struct dwarf2_cu *cu)
21850 {
21851   struct type *descriptive_type = die_descriptive_type (die, cu);
21852
21853   if (descriptive_type)
21854     {
21855       ALLOCATE_GNAT_AUX_TYPE (type);
21856       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21857     }
21858 }
21859
21860 /* Return the containing type of the die in question using its
21861    DW_AT_containing_type attribute.  */
21862
21863 static struct type *
21864 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21865 {
21866   struct attribute *type_attr;
21867   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21868
21869   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21870   if (!type_attr)
21871     error (_("Dwarf Error: Problem turning containing type into gdb type "
21872              "[in module %s]"), objfile_name (objfile));
21873
21874   return lookup_die_type (die, type_attr, cu);
21875 }
21876
21877 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21878
21879 static struct type *
21880 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21881 {
21882   struct dwarf2_per_objfile *dwarf2_per_objfile
21883     = cu->per_cu->dwarf2_per_objfile;
21884   struct objfile *objfile = dwarf2_per_objfile->objfile;
21885   char *message, *saved;
21886
21887   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21888                         objfile_name (objfile),
21889                         to_underlying (cu->header.sect_off),
21890                         to_underlying (die->sect_off));
21891   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21892                                   message, strlen (message));
21893   xfree (message);
21894
21895   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21896 }
21897
21898 /* Look up the type of DIE in CU using its type attribute ATTR.
21899    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21900    DW_AT_containing_type.
21901    If there is no type substitute an error marker.  */
21902
21903 static struct type *
21904 lookup_die_type (struct die_info *die, const struct attribute *attr,
21905                  struct dwarf2_cu *cu)
21906 {
21907   struct dwarf2_per_objfile *dwarf2_per_objfile
21908     = cu->per_cu->dwarf2_per_objfile;
21909   struct objfile *objfile = dwarf2_per_objfile->objfile;
21910   struct type *this_type;
21911
21912   gdb_assert (attr->name == DW_AT_type
21913               || attr->name == DW_AT_GNAT_descriptive_type
21914               || attr->name == DW_AT_containing_type);
21915
21916   /* First see if we have it cached.  */
21917
21918   if (attr->form == DW_FORM_GNU_ref_alt)
21919     {
21920       struct dwarf2_per_cu_data *per_cu;
21921       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21922
21923       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21924                                                  dwarf2_per_objfile);
21925       this_type = get_die_type_at_offset (sect_off, per_cu);
21926     }
21927   else if (attr_form_is_ref (attr))
21928     {
21929       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21930
21931       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21932     }
21933   else if (attr->form == DW_FORM_ref_sig8)
21934     {
21935       ULONGEST signature = DW_SIGNATURE (attr);
21936
21937       return get_signatured_type (die, signature, cu);
21938     }
21939   else
21940     {
21941       complaint (&symfile_complaints,
21942                  _("Dwarf Error: Bad type attribute %s in DIE"
21943                    " at 0x%x [in module %s]"),
21944                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21945                  objfile_name (objfile));
21946       return build_error_marker_type (cu, die);
21947     }
21948
21949   /* If not cached we need to read it in.  */
21950
21951   if (this_type == NULL)
21952     {
21953       struct die_info *type_die = NULL;
21954       struct dwarf2_cu *type_cu = cu;
21955
21956       if (attr_form_is_ref (attr))
21957         type_die = follow_die_ref (die, attr, &type_cu);
21958       if (type_die == NULL)
21959         return build_error_marker_type (cu, die);
21960       /* If we find the type now, it's probably because the type came
21961          from an inter-CU reference and the type's CU got expanded before
21962          ours.  */
21963       this_type = read_type_die (type_die, type_cu);
21964     }
21965
21966   /* If we still don't have a type use an error marker.  */
21967
21968   if (this_type == NULL)
21969     return build_error_marker_type (cu, die);
21970
21971   return this_type;
21972 }
21973
21974 /* Return the type in DIE, CU.
21975    Returns NULL for invalid types.
21976
21977    This first does a lookup in die_type_hash,
21978    and only reads the die in if necessary.
21979
21980    NOTE: This can be called when reading in partial or full symbols.  */
21981
21982 static struct type *
21983 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21984 {
21985   struct type *this_type;
21986
21987   this_type = get_die_type (die, cu);
21988   if (this_type)
21989     return this_type;
21990
21991   return read_type_die_1 (die, cu);
21992 }
21993
21994 /* Read the type in DIE, CU.
21995    Returns NULL for invalid types.  */
21996
21997 static struct type *
21998 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21999 {
22000   struct type *this_type = NULL;
22001
22002   switch (die->tag)
22003     {
22004     case DW_TAG_class_type:
22005     case DW_TAG_interface_type:
22006     case DW_TAG_structure_type:
22007     case DW_TAG_union_type:
22008       this_type = read_structure_type (die, cu);
22009       break;
22010     case DW_TAG_enumeration_type:
22011       this_type = read_enumeration_type (die, cu);
22012       break;
22013     case DW_TAG_subprogram:
22014     case DW_TAG_subroutine_type:
22015     case DW_TAG_inlined_subroutine:
22016       this_type = read_subroutine_type (die, cu);
22017       break;
22018     case DW_TAG_array_type:
22019       this_type = read_array_type (die, cu);
22020       break;
22021     case DW_TAG_set_type:
22022       this_type = read_set_type (die, cu);
22023       break;
22024     case DW_TAG_pointer_type:
22025       this_type = read_tag_pointer_type (die, cu);
22026       break;
22027     case DW_TAG_ptr_to_member_type:
22028       this_type = read_tag_ptr_to_member_type (die, cu);
22029       break;
22030     case DW_TAG_reference_type:
22031       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22032       break;
22033     case DW_TAG_rvalue_reference_type:
22034       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22035       break;
22036     case DW_TAG_const_type:
22037       this_type = read_tag_const_type (die, cu);
22038       break;
22039     case DW_TAG_volatile_type:
22040       this_type = read_tag_volatile_type (die, cu);
22041       break;
22042     case DW_TAG_restrict_type:
22043       this_type = read_tag_restrict_type (die, cu);
22044       break;
22045     case DW_TAG_string_type:
22046       this_type = read_tag_string_type (die, cu);
22047       break;
22048     case DW_TAG_typedef:
22049       this_type = read_typedef (die, cu);
22050       break;
22051     case DW_TAG_subrange_type:
22052       this_type = read_subrange_type (die, cu);
22053       break;
22054     case DW_TAG_base_type:
22055       this_type = read_base_type (die, cu);
22056       break;
22057     case DW_TAG_unspecified_type:
22058       this_type = read_unspecified_type (die, cu);
22059       break;
22060     case DW_TAG_namespace:
22061       this_type = read_namespace_type (die, cu);
22062       break;
22063     case DW_TAG_module:
22064       this_type = read_module_type (die, cu);
22065       break;
22066     case DW_TAG_atomic_type:
22067       this_type = read_tag_atomic_type (die, cu);
22068       break;
22069     default:
22070       complaint (&symfile_complaints,
22071                  _("unexpected tag in read_type_die: '%s'"),
22072                  dwarf_tag_name (die->tag));
22073       break;
22074     }
22075
22076   return this_type;
22077 }
22078
22079 /* See if we can figure out if the class lives in a namespace.  We do
22080    this by looking for a member function; its demangled name will
22081    contain namespace info, if there is any.
22082    Return the computed name or NULL.
22083    Space for the result is allocated on the objfile's obstack.
22084    This is the full-die version of guess_partial_die_structure_name.
22085    In this case we know DIE has no useful parent.  */
22086
22087 static char *
22088 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22089 {
22090   struct die_info *spec_die;
22091   struct dwarf2_cu *spec_cu;
22092   struct die_info *child;
22093   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22094
22095   spec_cu = cu;
22096   spec_die = die_specification (die, &spec_cu);
22097   if (spec_die != NULL)
22098     {
22099       die = spec_die;
22100       cu = spec_cu;
22101     }
22102
22103   for (child = die->child;
22104        child != NULL;
22105        child = child->sibling)
22106     {
22107       if (child->tag == DW_TAG_subprogram)
22108         {
22109           const char *linkage_name = dw2_linkage_name (child, cu);
22110
22111           if (linkage_name != NULL)
22112             {
22113               char *actual_name
22114                 = language_class_name_from_physname (cu->language_defn,
22115                                                      linkage_name);
22116               char *name = NULL;
22117
22118               if (actual_name != NULL)
22119                 {
22120                   const char *die_name = dwarf2_name (die, cu);
22121
22122                   if (die_name != NULL
22123                       && strcmp (die_name, actual_name) != 0)
22124                     {
22125                       /* Strip off the class name from the full name.
22126                          We want the prefix.  */
22127                       int die_name_len = strlen (die_name);
22128                       int actual_name_len = strlen (actual_name);
22129
22130                       /* Test for '::' as a sanity check.  */
22131                       if (actual_name_len > die_name_len + 2
22132                           && actual_name[actual_name_len
22133                                          - die_name_len - 1] == ':')
22134                         name = (char *) obstack_copy0 (
22135                           &objfile->per_bfd->storage_obstack,
22136                           actual_name, actual_name_len - die_name_len - 2);
22137                     }
22138                 }
22139               xfree (actual_name);
22140               return name;
22141             }
22142         }
22143     }
22144
22145   return NULL;
22146 }
22147
22148 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22149    prefix part in such case.  See
22150    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22151
22152 static const char *
22153 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22154 {
22155   struct attribute *attr;
22156   const char *base;
22157
22158   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22159       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22160     return NULL;
22161
22162   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22163     return NULL;
22164
22165   attr = dw2_linkage_name_attr (die, cu);
22166   if (attr == NULL || DW_STRING (attr) == NULL)
22167     return NULL;
22168
22169   /* dwarf2_name had to be already called.  */
22170   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22171
22172   /* Strip the base name, keep any leading namespaces/classes.  */
22173   base = strrchr (DW_STRING (attr), ':');
22174   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22175     return "";
22176
22177   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22178   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22179                                  DW_STRING (attr),
22180                                  &base[-1] - DW_STRING (attr));
22181 }
22182
22183 /* Return the name of the namespace/class that DIE is defined within,
22184    or "" if we can't tell.  The caller should not xfree the result.
22185
22186    For example, if we're within the method foo() in the following
22187    code:
22188
22189    namespace N {
22190      class C {
22191        void foo () {
22192        }
22193      };
22194    }
22195
22196    then determine_prefix on foo's die will return "N::C".  */
22197
22198 static const char *
22199 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22200 {
22201   struct dwarf2_per_objfile *dwarf2_per_objfile
22202     = cu->per_cu->dwarf2_per_objfile;
22203   struct die_info *parent, *spec_die;
22204   struct dwarf2_cu *spec_cu;
22205   struct type *parent_type;
22206   const char *retval;
22207
22208   if (cu->language != language_cplus
22209       && cu->language != language_fortran && cu->language != language_d
22210       && cu->language != language_rust)
22211     return "";
22212
22213   retval = anonymous_struct_prefix (die, cu);
22214   if (retval)
22215     return retval;
22216
22217   /* We have to be careful in the presence of DW_AT_specification.
22218      For example, with GCC 3.4, given the code
22219
22220      namespace N {
22221        void foo() {
22222          // Definition of N::foo.
22223        }
22224      }
22225
22226      then we'll have a tree of DIEs like this:
22227
22228      1: DW_TAG_compile_unit
22229        2: DW_TAG_namespace        // N
22230          3: DW_TAG_subprogram     // declaration of N::foo
22231        4: DW_TAG_subprogram       // definition of N::foo
22232             DW_AT_specification   // refers to die #3
22233
22234      Thus, when processing die #4, we have to pretend that we're in
22235      the context of its DW_AT_specification, namely the contex of die
22236      #3.  */
22237   spec_cu = cu;
22238   spec_die = die_specification (die, &spec_cu);
22239   if (spec_die == NULL)
22240     parent = die->parent;
22241   else
22242     {
22243       parent = spec_die->parent;
22244       cu = spec_cu;
22245     }
22246
22247   if (parent == NULL)
22248     return "";
22249   else if (parent->building_fullname)
22250     {
22251       const char *name;
22252       const char *parent_name;
22253
22254       /* It has been seen on RealView 2.2 built binaries,
22255          DW_TAG_template_type_param types actually _defined_ as
22256          children of the parent class:
22257
22258          enum E {};
22259          template class <class Enum> Class{};
22260          Class<enum E> class_e;
22261
22262          1: DW_TAG_class_type (Class)
22263            2: DW_TAG_enumeration_type (E)
22264              3: DW_TAG_enumerator (enum1:0)
22265              3: DW_TAG_enumerator (enum2:1)
22266              ...
22267            2: DW_TAG_template_type_param
22268               DW_AT_type  DW_FORM_ref_udata (E)
22269
22270          Besides being broken debug info, it can put GDB into an
22271          infinite loop.  Consider:
22272
22273          When we're building the full name for Class<E>, we'll start
22274          at Class, and go look over its template type parameters,
22275          finding E.  We'll then try to build the full name of E, and
22276          reach here.  We're now trying to build the full name of E,
22277          and look over the parent DIE for containing scope.  In the
22278          broken case, if we followed the parent DIE of E, we'd again
22279          find Class, and once again go look at its template type
22280          arguments, etc., etc.  Simply don't consider such parent die
22281          as source-level parent of this die (it can't be, the language
22282          doesn't allow it), and break the loop here.  */
22283       name = dwarf2_name (die, cu);
22284       parent_name = dwarf2_name (parent, cu);
22285       complaint (&symfile_complaints,
22286                  _("template param type '%s' defined within parent '%s'"),
22287                  name ? name : "<unknown>",
22288                  parent_name ? parent_name : "<unknown>");
22289       return "";
22290     }
22291   else
22292     switch (parent->tag)
22293       {
22294       case DW_TAG_namespace:
22295         parent_type = read_type_die (parent, cu);
22296         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22297            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22298            Work around this problem here.  */
22299         if (cu->language == language_cplus
22300             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22301           return "";
22302         /* We give a name to even anonymous namespaces.  */
22303         return TYPE_TAG_NAME (parent_type);
22304       case DW_TAG_class_type:
22305       case DW_TAG_interface_type:
22306       case DW_TAG_structure_type:
22307       case DW_TAG_union_type:
22308       case DW_TAG_module:
22309         parent_type = read_type_die (parent, cu);
22310         if (TYPE_TAG_NAME (parent_type) != NULL)
22311           return TYPE_TAG_NAME (parent_type);
22312         else
22313           /* An anonymous structure is only allowed non-static data
22314              members; no typedefs, no member functions, et cetera.
22315              So it does not need a prefix.  */
22316           return "";
22317       case DW_TAG_compile_unit:
22318       case DW_TAG_partial_unit:
22319         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22320         if (cu->language == language_cplus
22321             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22322             && die->child != NULL
22323             && (die->tag == DW_TAG_class_type
22324                 || die->tag == DW_TAG_structure_type
22325                 || die->tag == DW_TAG_union_type))
22326           {
22327             char *name = guess_full_die_structure_name (die, cu);
22328             if (name != NULL)
22329               return name;
22330           }
22331         return "";
22332       case DW_TAG_enumeration_type:
22333         parent_type = read_type_die (parent, cu);
22334         if (TYPE_DECLARED_CLASS (parent_type))
22335           {
22336             if (TYPE_TAG_NAME (parent_type) != NULL)
22337               return TYPE_TAG_NAME (parent_type);
22338             return "";
22339           }
22340         /* Fall through.  */
22341       default:
22342         return determine_prefix (parent, cu);
22343       }
22344 }
22345
22346 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22347    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22348    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22349    an obconcat, otherwise allocate storage for the result.  The CU argument is
22350    used to determine the language and hence, the appropriate separator.  */
22351
22352 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22353
22354 static char *
22355 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22356                  int physname, struct dwarf2_cu *cu)
22357 {
22358   const char *lead = "";
22359   const char *sep;
22360
22361   if (suffix == NULL || suffix[0] == '\0'
22362       || prefix == NULL || prefix[0] == '\0')
22363     sep = "";
22364   else if (cu->language == language_d)
22365     {
22366       /* For D, the 'main' function could be defined in any module, but it
22367          should never be prefixed.  */
22368       if (strcmp (suffix, "D main") == 0)
22369         {
22370           prefix = "";
22371           sep = "";
22372         }
22373       else
22374         sep = ".";
22375     }
22376   else if (cu->language == language_fortran && physname)
22377     {
22378       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22379          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22380
22381       lead = "__";
22382       sep = "_MOD_";
22383     }
22384   else
22385     sep = "::";
22386
22387   if (prefix == NULL)
22388     prefix = "";
22389   if (suffix == NULL)
22390     suffix = "";
22391
22392   if (obs == NULL)
22393     {
22394       char *retval
22395         = ((char *)
22396            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22397
22398       strcpy (retval, lead);
22399       strcat (retval, prefix);
22400       strcat (retval, sep);
22401       strcat (retval, suffix);
22402       return retval;
22403     }
22404   else
22405     {
22406       /* We have an obstack.  */
22407       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22408     }
22409 }
22410
22411 /* Return sibling of die, NULL if no sibling.  */
22412
22413 static struct die_info *
22414 sibling_die (struct die_info *die)
22415 {
22416   return die->sibling;
22417 }
22418
22419 /* Get name of a die, return NULL if not found.  */
22420
22421 static const char *
22422 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22423                           struct obstack *obstack)
22424 {
22425   if (name && cu->language == language_cplus)
22426     {
22427       std::string canon_name = cp_canonicalize_string (name);
22428
22429       if (!canon_name.empty ())
22430         {
22431           if (canon_name != name)
22432             name = (const char *) obstack_copy0 (obstack,
22433                                                  canon_name.c_str (),
22434                                                  canon_name.length ());
22435         }
22436     }
22437
22438   return name;
22439 }
22440
22441 /* Get name of a die, return NULL if not found.
22442    Anonymous namespaces are converted to their magic string.  */
22443
22444 static const char *
22445 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22446 {
22447   struct attribute *attr;
22448   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22449
22450   attr = dwarf2_attr (die, DW_AT_name, cu);
22451   if ((!attr || !DW_STRING (attr))
22452       && die->tag != DW_TAG_namespace
22453       && die->tag != DW_TAG_class_type
22454       && die->tag != DW_TAG_interface_type
22455       && die->tag != DW_TAG_structure_type
22456       && die->tag != DW_TAG_union_type)
22457     return NULL;
22458
22459   switch (die->tag)
22460     {
22461     case DW_TAG_compile_unit:
22462     case DW_TAG_partial_unit:
22463       /* Compilation units have a DW_AT_name that is a filename, not
22464          a source language identifier.  */
22465     case DW_TAG_enumeration_type:
22466     case DW_TAG_enumerator:
22467       /* These tags always have simple identifiers already; no need
22468          to canonicalize them.  */
22469       return DW_STRING (attr);
22470
22471     case DW_TAG_namespace:
22472       if (attr != NULL && DW_STRING (attr) != NULL)
22473         return DW_STRING (attr);
22474       return CP_ANONYMOUS_NAMESPACE_STR;
22475
22476     case DW_TAG_class_type:
22477     case DW_TAG_interface_type:
22478     case DW_TAG_structure_type:
22479     case DW_TAG_union_type:
22480       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22481          structures or unions.  These were of the form "._%d" in GCC 4.1,
22482          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22483          and GCC 4.4.  We work around this problem by ignoring these.  */
22484       if (attr && DW_STRING (attr)
22485           && (startswith (DW_STRING (attr), "._")
22486               || startswith (DW_STRING (attr), "<anonymous")))
22487         return NULL;
22488
22489       /* GCC might emit a nameless typedef that has a linkage name.  See
22490          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22491       if (!attr || DW_STRING (attr) == NULL)
22492         {
22493           char *demangled = NULL;
22494
22495           attr = dw2_linkage_name_attr (die, cu);
22496           if (attr == NULL || DW_STRING (attr) == NULL)
22497             return NULL;
22498
22499           /* Avoid demangling DW_STRING (attr) the second time on a second
22500              call for the same DIE.  */
22501           if (!DW_STRING_IS_CANONICAL (attr))
22502             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22503
22504           if (demangled)
22505             {
22506               const char *base;
22507
22508               /* FIXME: we already did this for the partial symbol... */
22509               DW_STRING (attr)
22510                 = ((const char *)
22511                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22512                                   demangled, strlen (demangled)));
22513               DW_STRING_IS_CANONICAL (attr) = 1;
22514               xfree (demangled);
22515
22516               /* Strip any leading namespaces/classes, keep only the base name.
22517                  DW_AT_name for named DIEs does not contain the prefixes.  */
22518               base = strrchr (DW_STRING (attr), ':');
22519               if (base && base > DW_STRING (attr) && base[-1] == ':')
22520                 return &base[1];
22521               else
22522                 return DW_STRING (attr);
22523             }
22524         }
22525       break;
22526
22527     default:
22528       break;
22529     }
22530
22531   if (!DW_STRING_IS_CANONICAL (attr))
22532     {
22533       DW_STRING (attr)
22534         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22535                                     &objfile->per_bfd->storage_obstack);
22536       DW_STRING_IS_CANONICAL (attr) = 1;
22537     }
22538   return DW_STRING (attr);
22539 }
22540
22541 /* Return the die that this die in an extension of, or NULL if there
22542    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22543    containing the return value on output.  */
22544
22545 static struct die_info *
22546 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22547 {
22548   struct attribute *attr;
22549
22550   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22551   if (attr == NULL)
22552     return NULL;
22553
22554   return follow_die_ref (die, attr, ext_cu);
22555 }
22556
22557 /* Convert a DIE tag into its string name.  */
22558
22559 static const char *
22560 dwarf_tag_name (unsigned tag)
22561 {
22562   const char *name = get_DW_TAG_name (tag);
22563
22564   if (name == NULL)
22565     return "DW_TAG_<unknown>";
22566
22567   return name;
22568 }
22569
22570 /* Convert a DWARF attribute code into its string name.  */
22571
22572 static const char *
22573 dwarf_attr_name (unsigned attr)
22574 {
22575   const char *name;
22576
22577 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22578   if (attr == DW_AT_MIPS_fde)
22579     return "DW_AT_MIPS_fde";
22580 #else
22581   if (attr == DW_AT_HP_block_index)
22582     return "DW_AT_HP_block_index";
22583 #endif
22584
22585   name = get_DW_AT_name (attr);
22586
22587   if (name == NULL)
22588     return "DW_AT_<unknown>";
22589
22590   return name;
22591 }
22592
22593 /* Convert a DWARF value form code into its string name.  */
22594
22595 static const char *
22596 dwarf_form_name (unsigned form)
22597 {
22598   const char *name = get_DW_FORM_name (form);
22599
22600   if (name == NULL)
22601     return "DW_FORM_<unknown>";
22602
22603   return name;
22604 }
22605
22606 static const char *
22607 dwarf_bool_name (unsigned mybool)
22608 {
22609   if (mybool)
22610     return "TRUE";
22611   else
22612     return "FALSE";
22613 }
22614
22615 /* Convert a DWARF type code into its string name.  */
22616
22617 static const char *
22618 dwarf_type_encoding_name (unsigned enc)
22619 {
22620   const char *name = get_DW_ATE_name (enc);
22621
22622   if (name == NULL)
22623     return "DW_ATE_<unknown>";
22624
22625   return name;
22626 }
22627
22628 static void
22629 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22630 {
22631   unsigned int i;
22632
22633   print_spaces (indent, f);
22634   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22635                       dwarf_tag_name (die->tag), die->abbrev,
22636                       to_underlying (die->sect_off));
22637
22638   if (die->parent != NULL)
22639     {
22640       print_spaces (indent, f);
22641       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22642                           to_underlying (die->parent->sect_off));
22643     }
22644
22645   print_spaces (indent, f);
22646   fprintf_unfiltered (f, "  has children: %s\n",
22647            dwarf_bool_name (die->child != NULL));
22648
22649   print_spaces (indent, f);
22650   fprintf_unfiltered (f, "  attributes:\n");
22651
22652   for (i = 0; i < die->num_attrs; ++i)
22653     {
22654       print_spaces (indent, f);
22655       fprintf_unfiltered (f, "    %s (%s) ",
22656                dwarf_attr_name (die->attrs[i].name),
22657                dwarf_form_name (die->attrs[i].form));
22658
22659       switch (die->attrs[i].form)
22660         {
22661         case DW_FORM_addr:
22662         case DW_FORM_GNU_addr_index:
22663           fprintf_unfiltered (f, "address: ");
22664           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22665           break;
22666         case DW_FORM_block2:
22667         case DW_FORM_block4:
22668         case DW_FORM_block:
22669         case DW_FORM_block1:
22670           fprintf_unfiltered (f, "block: size %s",
22671                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22672           break;
22673         case DW_FORM_exprloc:
22674           fprintf_unfiltered (f, "expression: size %s",
22675                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22676           break;
22677         case DW_FORM_data16:
22678           fprintf_unfiltered (f, "constant of 16 bytes");
22679           break;
22680         case DW_FORM_ref_addr:
22681           fprintf_unfiltered (f, "ref address: ");
22682           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22683           break;
22684         case DW_FORM_GNU_ref_alt:
22685           fprintf_unfiltered (f, "alt ref address: ");
22686           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22687           break;
22688         case DW_FORM_ref1:
22689         case DW_FORM_ref2:
22690         case DW_FORM_ref4:
22691         case DW_FORM_ref8:
22692         case DW_FORM_ref_udata:
22693           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22694                               (long) (DW_UNSND (&die->attrs[i])));
22695           break;
22696         case DW_FORM_data1:
22697         case DW_FORM_data2:
22698         case DW_FORM_data4:
22699         case DW_FORM_data8:
22700         case DW_FORM_udata:
22701         case DW_FORM_sdata:
22702           fprintf_unfiltered (f, "constant: %s",
22703                               pulongest (DW_UNSND (&die->attrs[i])));
22704           break;
22705         case DW_FORM_sec_offset:
22706           fprintf_unfiltered (f, "section offset: %s",
22707                               pulongest (DW_UNSND (&die->attrs[i])));
22708           break;
22709         case DW_FORM_ref_sig8:
22710           fprintf_unfiltered (f, "signature: %s",
22711                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22712           break;
22713         case DW_FORM_string:
22714         case DW_FORM_strp:
22715         case DW_FORM_line_strp:
22716         case DW_FORM_GNU_str_index:
22717         case DW_FORM_GNU_strp_alt:
22718           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22719                    DW_STRING (&die->attrs[i])
22720                    ? DW_STRING (&die->attrs[i]) : "",
22721                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22722           break;
22723         case DW_FORM_flag:
22724           if (DW_UNSND (&die->attrs[i]))
22725             fprintf_unfiltered (f, "flag: TRUE");
22726           else
22727             fprintf_unfiltered (f, "flag: FALSE");
22728           break;
22729         case DW_FORM_flag_present:
22730           fprintf_unfiltered (f, "flag: TRUE");
22731           break;
22732         case DW_FORM_indirect:
22733           /* The reader will have reduced the indirect form to
22734              the "base form" so this form should not occur.  */
22735           fprintf_unfiltered (f, 
22736                               "unexpected attribute form: DW_FORM_indirect");
22737           break;
22738         case DW_FORM_implicit_const:
22739           fprintf_unfiltered (f, "constant: %s",
22740                               plongest (DW_SND (&die->attrs[i])));
22741           break;
22742         default:
22743           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22744                    die->attrs[i].form);
22745           break;
22746         }
22747       fprintf_unfiltered (f, "\n");
22748     }
22749 }
22750
22751 static void
22752 dump_die_for_error (struct die_info *die)
22753 {
22754   dump_die_shallow (gdb_stderr, 0, die);
22755 }
22756
22757 static void
22758 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22759 {
22760   int indent = level * 4;
22761
22762   gdb_assert (die != NULL);
22763
22764   if (level >= max_level)
22765     return;
22766
22767   dump_die_shallow (f, indent, die);
22768
22769   if (die->child != NULL)
22770     {
22771       print_spaces (indent, f);
22772       fprintf_unfiltered (f, "  Children:");
22773       if (level + 1 < max_level)
22774         {
22775           fprintf_unfiltered (f, "\n");
22776           dump_die_1 (f, level + 1, max_level, die->child);
22777         }
22778       else
22779         {
22780           fprintf_unfiltered (f,
22781                               " [not printed, max nesting level reached]\n");
22782         }
22783     }
22784
22785   if (die->sibling != NULL && level > 0)
22786     {
22787       dump_die_1 (f, level, max_level, die->sibling);
22788     }
22789 }
22790
22791 /* This is called from the pdie macro in gdbinit.in.
22792    It's not static so gcc will keep a copy callable from gdb.  */
22793
22794 void
22795 dump_die (struct die_info *die, int max_level)
22796 {
22797   dump_die_1 (gdb_stdlog, 0, max_level, die);
22798 }
22799
22800 static void
22801 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22802 {
22803   void **slot;
22804
22805   slot = htab_find_slot_with_hash (cu->die_hash, die,
22806                                    to_underlying (die->sect_off),
22807                                    INSERT);
22808
22809   *slot = die;
22810 }
22811
22812 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22813    required kind.  */
22814
22815 static sect_offset
22816 dwarf2_get_ref_die_offset (const struct attribute *attr)
22817 {
22818   if (attr_form_is_ref (attr))
22819     return (sect_offset) DW_UNSND (attr);
22820
22821   complaint (&symfile_complaints,
22822              _("unsupported die ref attribute form: '%s'"),
22823              dwarf_form_name (attr->form));
22824   return {};
22825 }
22826
22827 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22828  * the value held by the attribute is not constant.  */
22829
22830 static LONGEST
22831 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22832 {
22833   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22834     return DW_SND (attr);
22835   else if (attr->form == DW_FORM_udata
22836            || attr->form == DW_FORM_data1
22837            || attr->form == DW_FORM_data2
22838            || attr->form == DW_FORM_data4
22839            || attr->form == DW_FORM_data8)
22840     return DW_UNSND (attr);
22841   else
22842     {
22843       /* For DW_FORM_data16 see attr_form_is_constant.  */
22844       complaint (&symfile_complaints,
22845                  _("Attribute value is not a constant (%s)"),
22846                  dwarf_form_name (attr->form));
22847       return default_value;
22848     }
22849 }
22850
22851 /* Follow reference or signature attribute ATTR of SRC_DIE.
22852    On entry *REF_CU is the CU of SRC_DIE.
22853    On exit *REF_CU is the CU of the result.  */
22854
22855 static struct die_info *
22856 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22857                        struct dwarf2_cu **ref_cu)
22858 {
22859   struct die_info *die;
22860
22861   if (attr_form_is_ref (attr))
22862     die = follow_die_ref (src_die, attr, ref_cu);
22863   else if (attr->form == DW_FORM_ref_sig8)
22864     die = follow_die_sig (src_die, attr, ref_cu);
22865   else
22866     {
22867       dump_die_for_error (src_die);
22868       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22869              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22870     }
22871
22872   return die;
22873 }
22874
22875 /* Follow reference OFFSET.
22876    On entry *REF_CU is the CU of the source die referencing OFFSET.
22877    On exit *REF_CU is the CU of the result.
22878    Returns NULL if OFFSET is invalid.  */
22879
22880 static struct die_info *
22881 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22882                    struct dwarf2_cu **ref_cu)
22883 {
22884   struct die_info temp_die;
22885   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22886   struct dwarf2_per_objfile *dwarf2_per_objfile
22887     = cu->per_cu->dwarf2_per_objfile;
22888   struct objfile *objfile = dwarf2_per_objfile->objfile;
22889
22890   gdb_assert (cu->per_cu != NULL);
22891
22892   target_cu = cu;
22893
22894   if (cu->per_cu->is_debug_types)
22895     {
22896       /* .debug_types CUs cannot reference anything outside their CU.
22897          If they need to, they have to reference a signatured type via
22898          DW_FORM_ref_sig8.  */
22899       if (!offset_in_cu_p (&cu->header, sect_off))
22900         return NULL;
22901     }
22902   else if (offset_in_dwz != cu->per_cu->is_dwz
22903            || !offset_in_cu_p (&cu->header, sect_off))
22904     {
22905       struct dwarf2_per_cu_data *per_cu;
22906
22907       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22908                                                  dwarf2_per_objfile);
22909
22910       /* If necessary, add it to the queue and load its DIEs.  */
22911       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22912         load_full_comp_unit (per_cu, cu->language);
22913
22914       target_cu = per_cu->cu;
22915     }
22916   else if (cu->dies == NULL)
22917     {
22918       /* We're loading full DIEs during partial symbol reading.  */
22919       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22920       load_full_comp_unit (cu->per_cu, language_minimal);
22921     }
22922
22923   *ref_cu = target_cu;
22924   temp_die.sect_off = sect_off;
22925   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22926                                                   &temp_die,
22927                                                   to_underlying (sect_off));
22928 }
22929
22930 /* Follow reference attribute ATTR of SRC_DIE.
22931    On entry *REF_CU is the CU of SRC_DIE.
22932    On exit *REF_CU is the CU of the result.  */
22933
22934 static struct die_info *
22935 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22936                 struct dwarf2_cu **ref_cu)
22937 {
22938   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22939   struct dwarf2_cu *cu = *ref_cu;
22940   struct die_info *die;
22941
22942   die = follow_die_offset (sect_off,
22943                            (attr->form == DW_FORM_GNU_ref_alt
22944                             || cu->per_cu->is_dwz),
22945                            ref_cu);
22946   if (!die)
22947     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22948            "at 0x%x [in module %s]"),
22949            to_underlying (sect_off), to_underlying (src_die->sect_off),
22950            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22951
22952   return die;
22953 }
22954
22955 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22956    Returned value is intended for DW_OP_call*.  Returned
22957    dwarf2_locexpr_baton->data has lifetime of
22958    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22959
22960 struct dwarf2_locexpr_baton
22961 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22962                                struct dwarf2_per_cu_data *per_cu,
22963                                CORE_ADDR (*get_frame_pc) (void *baton),
22964                                void *baton)
22965 {
22966   struct dwarf2_cu *cu;
22967   struct die_info *die;
22968   struct attribute *attr;
22969   struct dwarf2_locexpr_baton retval;
22970   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22971   struct dwarf2_per_objfile *dwarf2_per_objfile
22972     = get_dwarf2_per_objfile (objfile);
22973
22974   if (per_cu->cu == NULL)
22975     load_cu (per_cu);
22976   cu = per_cu->cu;
22977   if (cu == NULL)
22978     {
22979       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22980          Instead just throw an error, not much else we can do.  */
22981       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22982              to_underlying (sect_off), objfile_name (objfile));
22983     }
22984
22985   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22986   if (!die)
22987     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22988            to_underlying (sect_off), objfile_name (objfile));
22989
22990   attr = dwarf2_attr (die, DW_AT_location, cu);
22991   if (!attr)
22992     {
22993       /* DWARF: "If there is no such attribute, then there is no effect.".
22994          DATA is ignored if SIZE is 0.  */
22995
22996       retval.data = NULL;
22997       retval.size = 0;
22998     }
22999   else if (attr_form_is_section_offset (attr))
23000     {
23001       struct dwarf2_loclist_baton loclist_baton;
23002       CORE_ADDR pc = (*get_frame_pc) (baton);
23003       size_t size;
23004
23005       fill_in_loclist_baton (cu, &loclist_baton, attr);
23006
23007       retval.data = dwarf2_find_location_expression (&loclist_baton,
23008                                                      &size, pc);
23009       retval.size = size;
23010     }
23011   else
23012     {
23013       if (!attr_form_is_block (attr))
23014         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
23015                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23016                to_underlying (sect_off), objfile_name (objfile));
23017
23018       retval.data = DW_BLOCK (attr)->data;
23019       retval.size = DW_BLOCK (attr)->size;
23020     }
23021   retval.per_cu = cu->per_cu;
23022
23023   age_cached_comp_units (dwarf2_per_objfile);
23024
23025   return retval;
23026 }
23027
23028 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23029    offset.  */
23030
23031 struct dwarf2_locexpr_baton
23032 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23033                              struct dwarf2_per_cu_data *per_cu,
23034                              CORE_ADDR (*get_frame_pc) (void *baton),
23035                              void *baton)
23036 {
23037   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23038
23039   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23040 }
23041
23042 /* Write a constant of a given type as target-ordered bytes into
23043    OBSTACK.  */
23044
23045 static const gdb_byte *
23046 write_constant_as_bytes (struct obstack *obstack,
23047                          enum bfd_endian byte_order,
23048                          struct type *type,
23049                          ULONGEST value,
23050                          LONGEST *len)
23051 {
23052   gdb_byte *result;
23053
23054   *len = TYPE_LENGTH (type);
23055   result = (gdb_byte *) obstack_alloc (obstack, *len);
23056   store_unsigned_integer (result, *len, byte_order, value);
23057
23058   return result;
23059 }
23060
23061 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23062    pointer to the constant bytes and set LEN to the length of the
23063    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23064    does not have a DW_AT_const_value, return NULL.  */
23065
23066 const gdb_byte *
23067 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23068                              struct dwarf2_per_cu_data *per_cu,
23069                              struct obstack *obstack,
23070                              LONGEST *len)
23071 {
23072   struct dwarf2_cu *cu;
23073   struct die_info *die;
23074   struct attribute *attr;
23075   const gdb_byte *result = NULL;
23076   struct type *type;
23077   LONGEST value;
23078   enum bfd_endian byte_order;
23079   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23080
23081   if (per_cu->cu == NULL)
23082     load_cu (per_cu);
23083   cu = per_cu->cu;
23084   if (cu == NULL)
23085     {
23086       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23087          Instead just throw an error, not much else we can do.  */
23088       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23089              to_underlying (sect_off), objfile_name (objfile));
23090     }
23091
23092   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23093   if (!die)
23094     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23095            to_underlying (sect_off), objfile_name (objfile));
23096
23097
23098   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23099   if (attr == NULL)
23100     return NULL;
23101
23102   byte_order = (bfd_big_endian (objfile->obfd)
23103                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23104
23105   switch (attr->form)
23106     {
23107     case DW_FORM_addr:
23108     case DW_FORM_GNU_addr_index:
23109       {
23110         gdb_byte *tem;
23111
23112         *len = cu->header.addr_size;
23113         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23114         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23115         result = tem;
23116       }
23117       break;
23118     case DW_FORM_string:
23119     case DW_FORM_strp:
23120     case DW_FORM_GNU_str_index:
23121     case DW_FORM_GNU_strp_alt:
23122       /* DW_STRING is already allocated on the objfile obstack, point
23123          directly to it.  */
23124       result = (const gdb_byte *) DW_STRING (attr);
23125       *len = strlen (DW_STRING (attr));
23126       break;
23127     case DW_FORM_block1:
23128     case DW_FORM_block2:
23129     case DW_FORM_block4:
23130     case DW_FORM_block:
23131     case DW_FORM_exprloc:
23132     case DW_FORM_data16:
23133       result = DW_BLOCK (attr)->data;
23134       *len = DW_BLOCK (attr)->size;
23135       break;
23136
23137       /* The DW_AT_const_value attributes are supposed to carry the
23138          symbol's value "represented as it would be on the target
23139          architecture."  By the time we get here, it's already been
23140          converted to host endianness, so we just need to sign- or
23141          zero-extend it as appropriate.  */
23142     case DW_FORM_data1:
23143       type = die_type (die, cu);
23144       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23145       if (result == NULL)
23146         result = write_constant_as_bytes (obstack, byte_order,
23147                                           type, value, len);
23148       break;
23149     case DW_FORM_data2:
23150       type = die_type (die, cu);
23151       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23152       if (result == NULL)
23153         result = write_constant_as_bytes (obstack, byte_order,
23154                                           type, value, len);
23155       break;
23156     case DW_FORM_data4:
23157       type = die_type (die, cu);
23158       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23159       if (result == NULL)
23160         result = write_constant_as_bytes (obstack, byte_order,
23161                                           type, value, len);
23162       break;
23163     case DW_FORM_data8:
23164       type = die_type (die, cu);
23165       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23166       if (result == NULL)
23167         result = write_constant_as_bytes (obstack, byte_order,
23168                                           type, value, len);
23169       break;
23170
23171     case DW_FORM_sdata:
23172     case DW_FORM_implicit_const:
23173       type = die_type (die, cu);
23174       result = write_constant_as_bytes (obstack, byte_order,
23175                                         type, DW_SND (attr), len);
23176       break;
23177
23178     case DW_FORM_udata:
23179       type = die_type (die, cu);
23180       result = write_constant_as_bytes (obstack, byte_order,
23181                                         type, DW_UNSND (attr), len);
23182       break;
23183
23184     default:
23185       complaint (&symfile_complaints,
23186                  _("unsupported const value attribute form: '%s'"),
23187                  dwarf_form_name (attr->form));
23188       break;
23189     }
23190
23191   return result;
23192 }
23193
23194 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23195    valid type for this die is found.  */
23196
23197 struct type *
23198 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23199                                 struct dwarf2_per_cu_data *per_cu)
23200 {
23201   struct dwarf2_cu *cu;
23202   struct die_info *die;
23203
23204   if (per_cu->cu == NULL)
23205     load_cu (per_cu);
23206   cu = per_cu->cu;
23207   if (!cu)
23208     return NULL;
23209
23210   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23211   if (!die)
23212     return NULL;
23213
23214   return die_type (die, cu);
23215 }
23216
23217 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23218    PER_CU.  */
23219
23220 struct type *
23221 dwarf2_get_die_type (cu_offset die_offset,
23222                      struct dwarf2_per_cu_data *per_cu)
23223 {
23224   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23225   return get_die_type_at_offset (die_offset_sect, per_cu);
23226 }
23227
23228 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23229    On entry *REF_CU is the CU of SRC_DIE.
23230    On exit *REF_CU is the CU of the result.
23231    Returns NULL if the referenced DIE isn't found.  */
23232
23233 static struct die_info *
23234 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23235                   struct dwarf2_cu **ref_cu)
23236 {
23237   struct die_info temp_die;
23238   struct dwarf2_cu *sig_cu;
23239   struct die_info *die;
23240
23241   /* While it might be nice to assert sig_type->type == NULL here,
23242      we can get here for DW_AT_imported_declaration where we need
23243      the DIE not the type.  */
23244
23245   /* If necessary, add it to the queue and load its DIEs.  */
23246
23247   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23248     read_signatured_type (sig_type);
23249
23250   sig_cu = sig_type->per_cu.cu;
23251   gdb_assert (sig_cu != NULL);
23252   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23253   temp_die.sect_off = sig_type->type_offset_in_section;
23254   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23255                                                  to_underlying (temp_die.sect_off));
23256   if (die)
23257     {
23258       struct dwarf2_per_objfile *dwarf2_per_objfile
23259         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23260
23261       /* For .gdb_index version 7 keep track of included TUs.
23262          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23263       if (dwarf2_per_objfile->index_table != NULL
23264           && dwarf2_per_objfile->index_table->version <= 7)
23265         {
23266           VEC_safe_push (dwarf2_per_cu_ptr,
23267                          (*ref_cu)->per_cu->imported_symtabs,
23268                          sig_cu->per_cu);
23269         }
23270
23271       *ref_cu = sig_cu;
23272       return die;
23273     }
23274
23275   return NULL;
23276 }
23277
23278 /* Follow signatured type referenced by ATTR in SRC_DIE.
23279    On entry *REF_CU is the CU of SRC_DIE.
23280    On exit *REF_CU is the CU of the result.
23281    The result is the DIE of the type.
23282    If the referenced type cannot be found an error is thrown.  */
23283
23284 static struct die_info *
23285 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23286                 struct dwarf2_cu **ref_cu)
23287 {
23288   ULONGEST signature = DW_SIGNATURE (attr);
23289   struct signatured_type *sig_type;
23290   struct die_info *die;
23291
23292   gdb_assert (attr->form == DW_FORM_ref_sig8);
23293
23294   sig_type = lookup_signatured_type (*ref_cu, signature);
23295   /* sig_type will be NULL if the signatured type is missing from
23296      the debug info.  */
23297   if (sig_type == NULL)
23298     {
23299       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23300                " from DIE at 0x%x [in module %s]"),
23301              hex_string (signature), to_underlying (src_die->sect_off),
23302              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23303     }
23304
23305   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23306   if (die == NULL)
23307     {
23308       dump_die_for_error (src_die);
23309       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23310                " from DIE at 0x%x [in module %s]"),
23311              hex_string (signature), to_underlying (src_die->sect_off),
23312              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23313     }
23314
23315   return die;
23316 }
23317
23318 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23319    reading in and processing the type unit if necessary.  */
23320
23321 static struct type *
23322 get_signatured_type (struct die_info *die, ULONGEST signature,
23323                      struct dwarf2_cu *cu)
23324 {
23325   struct dwarf2_per_objfile *dwarf2_per_objfile
23326     = cu->per_cu->dwarf2_per_objfile;
23327   struct signatured_type *sig_type;
23328   struct dwarf2_cu *type_cu;
23329   struct die_info *type_die;
23330   struct type *type;
23331
23332   sig_type = lookup_signatured_type (cu, signature);
23333   /* sig_type will be NULL if the signatured type is missing from
23334      the debug info.  */
23335   if (sig_type == NULL)
23336     {
23337       complaint (&symfile_complaints,
23338                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23339                    " from DIE at 0x%x [in module %s]"),
23340                  hex_string (signature), to_underlying (die->sect_off),
23341                  objfile_name (dwarf2_per_objfile->objfile));
23342       return build_error_marker_type (cu, die);
23343     }
23344
23345   /* If we already know the type we're done.  */
23346   if (sig_type->type != NULL)
23347     return sig_type->type;
23348
23349   type_cu = cu;
23350   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23351   if (type_die != NULL)
23352     {
23353       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23354          is created.  This is important, for example, because for c++ classes
23355          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23356       type = read_type_die (type_die, type_cu);
23357       if (type == NULL)
23358         {
23359           complaint (&symfile_complaints,
23360                      _("Dwarf Error: Cannot build signatured type %s"
23361                        " referenced from DIE at 0x%x [in module %s]"),
23362                      hex_string (signature), to_underlying (die->sect_off),
23363                      objfile_name (dwarf2_per_objfile->objfile));
23364           type = build_error_marker_type (cu, die);
23365         }
23366     }
23367   else
23368     {
23369       complaint (&symfile_complaints,
23370                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23371                    " from DIE at 0x%x [in module %s]"),
23372                  hex_string (signature), to_underlying (die->sect_off),
23373                  objfile_name (dwarf2_per_objfile->objfile));
23374       type = build_error_marker_type (cu, die);
23375     }
23376   sig_type->type = type;
23377
23378   return type;
23379 }
23380
23381 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23382    reading in and processing the type unit if necessary.  */
23383
23384 static struct type *
23385 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23386                           struct dwarf2_cu *cu) /* ARI: editCase function */
23387 {
23388   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23389   if (attr_form_is_ref (attr))
23390     {
23391       struct dwarf2_cu *type_cu = cu;
23392       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23393
23394       return read_type_die (type_die, type_cu);
23395     }
23396   else if (attr->form == DW_FORM_ref_sig8)
23397     {
23398       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23399     }
23400   else
23401     {
23402       struct dwarf2_per_objfile *dwarf2_per_objfile
23403         = cu->per_cu->dwarf2_per_objfile;
23404
23405       complaint (&symfile_complaints,
23406                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23407                    " at 0x%x [in module %s]"),
23408                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23409                  objfile_name (dwarf2_per_objfile->objfile));
23410       return build_error_marker_type (cu, die);
23411     }
23412 }
23413
23414 /* Load the DIEs associated with type unit PER_CU into memory.  */
23415
23416 static void
23417 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23418 {
23419   struct signatured_type *sig_type;
23420
23421   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23422   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23423
23424   /* We have the per_cu, but we need the signatured_type.
23425      Fortunately this is an easy translation.  */
23426   gdb_assert (per_cu->is_debug_types);
23427   sig_type = (struct signatured_type *) per_cu;
23428
23429   gdb_assert (per_cu->cu == NULL);
23430
23431   read_signatured_type (sig_type);
23432
23433   gdb_assert (per_cu->cu != NULL);
23434 }
23435
23436 /* die_reader_func for read_signatured_type.
23437    This is identical to load_full_comp_unit_reader,
23438    but is kept separate for now.  */
23439
23440 static void
23441 read_signatured_type_reader (const struct die_reader_specs *reader,
23442                              const gdb_byte *info_ptr,
23443                              struct die_info *comp_unit_die,
23444                              int has_children,
23445                              void *data)
23446 {
23447   struct dwarf2_cu *cu = reader->cu;
23448
23449   gdb_assert (cu->die_hash == NULL);
23450   cu->die_hash =
23451     htab_create_alloc_ex (cu->header.length / 12,
23452                           die_hash,
23453                           die_eq,
23454                           NULL,
23455                           &cu->comp_unit_obstack,
23456                           hashtab_obstack_allocate,
23457                           dummy_obstack_deallocate);
23458
23459   if (has_children)
23460     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23461                                                   &info_ptr, comp_unit_die);
23462   cu->dies = comp_unit_die;
23463   /* comp_unit_die is not stored in die_hash, no need.  */
23464
23465   /* We try not to read any attributes in this function, because not
23466      all CUs needed for references have been loaded yet, and symbol
23467      table processing isn't initialized.  But we have to set the CU language,
23468      or we won't be able to build types correctly.
23469      Similarly, if we do not read the producer, we can not apply
23470      producer-specific interpretation.  */
23471   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23472 }
23473
23474 /* Read in a signatured type and build its CU and DIEs.
23475    If the type is a stub for the real type in a DWO file,
23476    read in the real type from the DWO file as well.  */
23477
23478 static void
23479 read_signatured_type (struct signatured_type *sig_type)
23480 {
23481   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23482
23483   gdb_assert (per_cu->is_debug_types);
23484   gdb_assert (per_cu->cu == NULL);
23485
23486   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23487                            read_signatured_type_reader, NULL);
23488   sig_type->per_cu.tu_read = 1;
23489 }
23490
23491 /* Decode simple location descriptions.
23492    Given a pointer to a dwarf block that defines a location, compute
23493    the location and return the value.
23494
23495    NOTE drow/2003-11-18: This function is called in two situations
23496    now: for the address of static or global variables (partial symbols
23497    only) and for offsets into structures which are expected to be
23498    (more or less) constant.  The partial symbol case should go away,
23499    and only the constant case should remain.  That will let this
23500    function complain more accurately.  A few special modes are allowed
23501    without complaint for global variables (for instance, global
23502    register values and thread-local values).
23503
23504    A location description containing no operations indicates that the
23505    object is optimized out.  The return value is 0 for that case.
23506    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23507    callers will only want a very basic result and this can become a
23508    complaint.
23509
23510    Note that stack[0] is unused except as a default error return.  */
23511
23512 static CORE_ADDR
23513 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23514 {
23515   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23516   size_t i;
23517   size_t size = blk->size;
23518   const gdb_byte *data = blk->data;
23519   CORE_ADDR stack[64];
23520   int stacki;
23521   unsigned int bytes_read, unsnd;
23522   gdb_byte op;
23523
23524   i = 0;
23525   stacki = 0;
23526   stack[stacki] = 0;
23527   stack[++stacki] = 0;
23528
23529   while (i < size)
23530     {
23531       op = data[i++];
23532       switch (op)
23533         {
23534         case DW_OP_lit0:
23535         case DW_OP_lit1:
23536         case DW_OP_lit2:
23537         case DW_OP_lit3:
23538         case DW_OP_lit4:
23539         case DW_OP_lit5:
23540         case DW_OP_lit6:
23541         case DW_OP_lit7:
23542         case DW_OP_lit8:
23543         case DW_OP_lit9:
23544         case DW_OP_lit10:
23545         case DW_OP_lit11:
23546         case DW_OP_lit12:
23547         case DW_OP_lit13:
23548         case DW_OP_lit14:
23549         case DW_OP_lit15:
23550         case DW_OP_lit16:
23551         case DW_OP_lit17:
23552         case DW_OP_lit18:
23553         case DW_OP_lit19:
23554         case DW_OP_lit20:
23555         case DW_OP_lit21:
23556         case DW_OP_lit22:
23557         case DW_OP_lit23:
23558         case DW_OP_lit24:
23559         case DW_OP_lit25:
23560         case DW_OP_lit26:
23561         case DW_OP_lit27:
23562         case DW_OP_lit28:
23563         case DW_OP_lit29:
23564         case DW_OP_lit30:
23565         case DW_OP_lit31:
23566           stack[++stacki] = op - DW_OP_lit0;
23567           break;
23568
23569         case DW_OP_reg0:
23570         case DW_OP_reg1:
23571         case DW_OP_reg2:
23572         case DW_OP_reg3:
23573         case DW_OP_reg4:
23574         case DW_OP_reg5:
23575         case DW_OP_reg6:
23576         case DW_OP_reg7:
23577         case DW_OP_reg8:
23578         case DW_OP_reg9:
23579         case DW_OP_reg10:
23580         case DW_OP_reg11:
23581         case DW_OP_reg12:
23582         case DW_OP_reg13:
23583         case DW_OP_reg14:
23584         case DW_OP_reg15:
23585         case DW_OP_reg16:
23586         case DW_OP_reg17:
23587         case DW_OP_reg18:
23588         case DW_OP_reg19:
23589         case DW_OP_reg20:
23590         case DW_OP_reg21:
23591         case DW_OP_reg22:
23592         case DW_OP_reg23:
23593         case DW_OP_reg24:
23594         case DW_OP_reg25:
23595         case DW_OP_reg26:
23596         case DW_OP_reg27:
23597         case DW_OP_reg28:
23598         case DW_OP_reg29:
23599         case DW_OP_reg30:
23600         case DW_OP_reg31:
23601           stack[++stacki] = op - DW_OP_reg0;
23602           if (i < size)
23603             dwarf2_complex_location_expr_complaint ();
23604           break;
23605
23606         case DW_OP_regx:
23607           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23608           i += bytes_read;
23609           stack[++stacki] = unsnd;
23610           if (i < size)
23611             dwarf2_complex_location_expr_complaint ();
23612           break;
23613
23614         case DW_OP_addr:
23615           stack[++stacki] = read_address (objfile->obfd, &data[i],
23616                                           cu, &bytes_read);
23617           i += bytes_read;
23618           break;
23619
23620         case DW_OP_const1u:
23621           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23622           i += 1;
23623           break;
23624
23625         case DW_OP_const1s:
23626           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23627           i += 1;
23628           break;
23629
23630         case DW_OP_const2u:
23631           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23632           i += 2;
23633           break;
23634
23635         case DW_OP_const2s:
23636           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23637           i += 2;
23638           break;
23639
23640         case DW_OP_const4u:
23641           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23642           i += 4;
23643           break;
23644
23645         case DW_OP_const4s:
23646           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23647           i += 4;
23648           break;
23649
23650         case DW_OP_const8u:
23651           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23652           i += 8;
23653           break;
23654
23655         case DW_OP_constu:
23656           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23657                                                   &bytes_read);
23658           i += bytes_read;
23659           break;
23660
23661         case DW_OP_consts:
23662           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23663           i += bytes_read;
23664           break;
23665
23666         case DW_OP_dup:
23667           stack[stacki + 1] = stack[stacki];
23668           stacki++;
23669           break;
23670
23671         case DW_OP_plus:
23672           stack[stacki - 1] += stack[stacki];
23673           stacki--;
23674           break;
23675
23676         case DW_OP_plus_uconst:
23677           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23678                                                  &bytes_read);
23679           i += bytes_read;
23680           break;
23681
23682         case DW_OP_minus:
23683           stack[stacki - 1] -= stack[stacki];
23684           stacki--;
23685           break;
23686
23687         case DW_OP_deref:
23688           /* If we're not the last op, then we definitely can't encode
23689              this using GDB's address_class enum.  This is valid for partial
23690              global symbols, although the variable's address will be bogus
23691              in the psymtab.  */
23692           if (i < size)
23693             dwarf2_complex_location_expr_complaint ();
23694           break;
23695
23696         case DW_OP_GNU_push_tls_address:
23697         case DW_OP_form_tls_address:
23698           /* The top of the stack has the offset from the beginning
23699              of the thread control block at which the variable is located.  */
23700           /* Nothing should follow this operator, so the top of stack would
23701              be returned.  */
23702           /* This is valid for partial global symbols, but the variable's
23703              address will be bogus in the psymtab.  Make it always at least
23704              non-zero to not look as a variable garbage collected by linker
23705              which have DW_OP_addr 0.  */
23706           if (i < size)
23707             dwarf2_complex_location_expr_complaint ();
23708           stack[stacki]++;
23709           break;
23710
23711         case DW_OP_GNU_uninit:
23712           break;
23713
23714         case DW_OP_GNU_addr_index:
23715         case DW_OP_GNU_const_index:
23716           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23717                                                          &bytes_read);
23718           i += bytes_read;
23719           break;
23720
23721         default:
23722           {
23723             const char *name = get_DW_OP_name (op);
23724
23725             if (name)
23726               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23727                          name);
23728             else
23729               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23730                          op);
23731           }
23732
23733           return (stack[stacki]);
23734         }
23735
23736       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23737          outside of the allocated space.  Also enforce minimum>0.  */
23738       if (stacki >= ARRAY_SIZE (stack) - 1)
23739         {
23740           complaint (&symfile_complaints,
23741                      _("location description stack overflow"));
23742           return 0;
23743         }
23744
23745       if (stacki <= 0)
23746         {
23747           complaint (&symfile_complaints,
23748                      _("location description stack underflow"));
23749           return 0;
23750         }
23751     }
23752   return (stack[stacki]);
23753 }
23754
23755 /* memory allocation interface */
23756
23757 static struct dwarf_block *
23758 dwarf_alloc_block (struct dwarf2_cu *cu)
23759 {
23760   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23761 }
23762
23763 static struct die_info *
23764 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23765 {
23766   struct die_info *die;
23767   size_t size = sizeof (struct die_info);
23768
23769   if (num_attrs > 1)
23770     size += (num_attrs - 1) * sizeof (struct attribute);
23771
23772   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23773   memset (die, 0, sizeof (struct die_info));
23774   return (die);
23775 }
23776
23777 \f
23778 /* Macro support.  */
23779
23780 /* Return file name relative to the compilation directory of file number I in
23781    *LH's file name table.  The result is allocated using xmalloc; the caller is
23782    responsible for freeing it.  */
23783
23784 static char *
23785 file_file_name (int file, struct line_header *lh)
23786 {
23787   /* Is the file number a valid index into the line header's file name
23788      table?  Remember that file numbers start with one, not zero.  */
23789   if (1 <= file && file <= lh->file_names.size ())
23790     {
23791       const file_entry &fe = lh->file_names[file - 1];
23792
23793       if (!IS_ABSOLUTE_PATH (fe.name))
23794         {
23795           const char *dir = fe.include_dir (lh);
23796           if (dir != NULL)
23797             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23798         }
23799       return xstrdup (fe.name);
23800     }
23801   else
23802     {
23803       /* The compiler produced a bogus file number.  We can at least
23804          record the macro definitions made in the file, even if we
23805          won't be able to find the file by name.  */
23806       char fake_name[80];
23807
23808       xsnprintf (fake_name, sizeof (fake_name),
23809                  "<bad macro file number %d>", file);
23810
23811       complaint (&symfile_complaints,
23812                  _("bad file number in macro information (%d)"),
23813                  file);
23814
23815       return xstrdup (fake_name);
23816     }
23817 }
23818
23819 /* Return the full name of file number I in *LH's file name table.
23820    Use COMP_DIR as the name of the current directory of the
23821    compilation.  The result is allocated using xmalloc; the caller is
23822    responsible for freeing it.  */
23823 static char *
23824 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23825 {
23826   /* Is the file number a valid index into the line header's file name
23827      table?  Remember that file numbers start with one, not zero.  */
23828   if (1 <= file && file <= lh->file_names.size ())
23829     {
23830       char *relative = file_file_name (file, lh);
23831
23832       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23833         return relative;
23834       return reconcat (relative, comp_dir, SLASH_STRING,
23835                        relative, (char *) NULL);
23836     }
23837   else
23838     return file_file_name (file, lh);
23839 }
23840
23841
23842 static struct macro_source_file *
23843 macro_start_file (int file, int line,
23844                   struct macro_source_file *current_file,
23845                   struct line_header *lh)
23846 {
23847   /* File name relative to the compilation directory of this source file.  */
23848   char *file_name = file_file_name (file, lh);
23849
23850   if (! current_file)
23851     {
23852       /* Note: We don't create a macro table for this compilation unit
23853          at all until we actually get a filename.  */
23854       struct macro_table *macro_table = get_macro_table ();
23855
23856       /* If we have no current file, then this must be the start_file
23857          directive for the compilation unit's main source file.  */
23858       current_file = macro_set_main (macro_table, file_name);
23859       macro_define_special (macro_table);
23860     }
23861   else
23862     current_file = macro_include (current_file, line, file_name);
23863
23864   xfree (file_name);
23865
23866   return current_file;
23867 }
23868
23869 static const char *
23870 consume_improper_spaces (const char *p, const char *body)
23871 {
23872   if (*p == ' ')
23873     {
23874       complaint (&symfile_complaints,
23875                  _("macro definition contains spaces "
23876                    "in formal argument list:\n`%s'"),
23877                  body);
23878
23879       while (*p == ' ')
23880         p++;
23881     }
23882
23883   return p;
23884 }
23885
23886
23887 static void
23888 parse_macro_definition (struct macro_source_file *file, int line,
23889                         const char *body)
23890 {
23891   const char *p;
23892
23893   /* The body string takes one of two forms.  For object-like macro
23894      definitions, it should be:
23895
23896         <macro name> " " <definition>
23897
23898      For function-like macro definitions, it should be:
23899
23900         <macro name> "() " <definition>
23901      or
23902         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23903
23904      Spaces may appear only where explicitly indicated, and in the
23905      <definition>.
23906
23907      The Dwarf 2 spec says that an object-like macro's name is always
23908      followed by a space, but versions of GCC around March 2002 omit
23909      the space when the macro's definition is the empty string.
23910
23911      The Dwarf 2 spec says that there should be no spaces between the
23912      formal arguments in a function-like macro's formal argument list,
23913      but versions of GCC around March 2002 include spaces after the
23914      commas.  */
23915
23916
23917   /* Find the extent of the macro name.  The macro name is terminated
23918      by either a space or null character (for an object-like macro) or
23919      an opening paren (for a function-like macro).  */
23920   for (p = body; *p; p++)
23921     if (*p == ' ' || *p == '(')
23922       break;
23923
23924   if (*p == ' ' || *p == '\0')
23925     {
23926       /* It's an object-like macro.  */
23927       int name_len = p - body;
23928       char *name = savestring (body, name_len);
23929       const char *replacement;
23930
23931       if (*p == ' ')
23932         replacement = body + name_len + 1;
23933       else
23934         {
23935           dwarf2_macro_malformed_definition_complaint (body);
23936           replacement = body + name_len;
23937         }
23938
23939       macro_define_object (file, line, name, replacement);
23940
23941       xfree (name);
23942     }
23943   else if (*p == '(')
23944     {
23945       /* It's a function-like macro.  */
23946       char *name = savestring (body, p - body);
23947       int argc = 0;
23948       int argv_size = 1;
23949       char **argv = XNEWVEC (char *, argv_size);
23950
23951       p++;
23952
23953       p = consume_improper_spaces (p, body);
23954
23955       /* Parse the formal argument list.  */
23956       while (*p && *p != ')')
23957         {
23958           /* Find the extent of the current argument name.  */
23959           const char *arg_start = p;
23960
23961           while (*p && *p != ',' && *p != ')' && *p != ' ')
23962             p++;
23963
23964           if (! *p || p == arg_start)
23965             dwarf2_macro_malformed_definition_complaint (body);
23966           else
23967             {
23968               /* Make sure argv has room for the new argument.  */
23969               if (argc >= argv_size)
23970                 {
23971                   argv_size *= 2;
23972                   argv = XRESIZEVEC (char *, argv, argv_size);
23973                 }
23974
23975               argv[argc++] = savestring (arg_start, p - arg_start);
23976             }
23977
23978           p = consume_improper_spaces (p, body);
23979
23980           /* Consume the comma, if present.  */
23981           if (*p == ',')
23982             {
23983               p++;
23984
23985               p = consume_improper_spaces (p, body);
23986             }
23987         }
23988
23989       if (*p == ')')
23990         {
23991           p++;
23992
23993           if (*p == ' ')
23994             /* Perfectly formed definition, no complaints.  */
23995             macro_define_function (file, line, name,
23996                                    argc, (const char **) argv,
23997                                    p + 1);
23998           else if (*p == '\0')
23999             {
24000               /* Complain, but do define it.  */
24001               dwarf2_macro_malformed_definition_complaint (body);
24002               macro_define_function (file, line, name,
24003                                      argc, (const char **) argv,
24004                                      p);
24005             }
24006           else
24007             /* Just complain.  */
24008             dwarf2_macro_malformed_definition_complaint (body);
24009         }
24010       else
24011         /* Just complain.  */
24012         dwarf2_macro_malformed_definition_complaint (body);
24013
24014       xfree (name);
24015       {
24016         int i;
24017
24018         for (i = 0; i < argc; i++)
24019           xfree (argv[i]);
24020       }
24021       xfree (argv);
24022     }
24023   else
24024     dwarf2_macro_malformed_definition_complaint (body);
24025 }
24026
24027 /* Skip some bytes from BYTES according to the form given in FORM.
24028    Returns the new pointer.  */
24029
24030 static const gdb_byte *
24031 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24032                  enum dwarf_form form,
24033                  unsigned int offset_size,
24034                  struct dwarf2_section_info *section)
24035 {
24036   unsigned int bytes_read;
24037
24038   switch (form)
24039     {
24040     case DW_FORM_data1:
24041     case DW_FORM_flag:
24042       ++bytes;
24043       break;
24044
24045     case DW_FORM_data2:
24046       bytes += 2;
24047       break;
24048
24049     case DW_FORM_data4:
24050       bytes += 4;
24051       break;
24052
24053     case DW_FORM_data8:
24054       bytes += 8;
24055       break;
24056
24057     case DW_FORM_data16:
24058       bytes += 16;
24059       break;
24060
24061     case DW_FORM_string:
24062       read_direct_string (abfd, bytes, &bytes_read);
24063       bytes += bytes_read;
24064       break;
24065
24066     case DW_FORM_sec_offset:
24067     case DW_FORM_strp:
24068     case DW_FORM_GNU_strp_alt:
24069       bytes += offset_size;
24070       break;
24071
24072     case DW_FORM_block:
24073       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24074       bytes += bytes_read;
24075       break;
24076
24077     case DW_FORM_block1:
24078       bytes += 1 + read_1_byte (abfd, bytes);
24079       break;
24080     case DW_FORM_block2:
24081       bytes += 2 + read_2_bytes (abfd, bytes);
24082       break;
24083     case DW_FORM_block4:
24084       bytes += 4 + read_4_bytes (abfd, bytes);
24085       break;
24086
24087     case DW_FORM_sdata:
24088     case DW_FORM_udata:
24089     case DW_FORM_GNU_addr_index:
24090     case DW_FORM_GNU_str_index:
24091       bytes = gdb_skip_leb128 (bytes, buffer_end);
24092       if (bytes == NULL)
24093         {
24094           dwarf2_section_buffer_overflow_complaint (section);
24095           return NULL;
24096         }
24097       break;
24098
24099     case DW_FORM_implicit_const:
24100       break;
24101
24102     default:
24103       {
24104         complaint (&symfile_complaints,
24105                    _("invalid form 0x%x in `%s'"),
24106                    form, get_section_name (section));
24107         return NULL;
24108       }
24109     }
24110
24111   return bytes;
24112 }
24113
24114 /* A helper for dwarf_decode_macros that handles skipping an unknown
24115    opcode.  Returns an updated pointer to the macro data buffer; or,
24116    on error, issues a complaint and returns NULL.  */
24117
24118 static const gdb_byte *
24119 skip_unknown_opcode (unsigned int opcode,
24120                      const gdb_byte **opcode_definitions,
24121                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24122                      bfd *abfd,
24123                      unsigned int offset_size,
24124                      struct dwarf2_section_info *section)
24125 {
24126   unsigned int bytes_read, i;
24127   unsigned long arg;
24128   const gdb_byte *defn;
24129
24130   if (opcode_definitions[opcode] == NULL)
24131     {
24132       complaint (&symfile_complaints,
24133                  _("unrecognized DW_MACFINO opcode 0x%x"),
24134                  opcode);
24135       return NULL;
24136     }
24137
24138   defn = opcode_definitions[opcode];
24139   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24140   defn += bytes_read;
24141
24142   for (i = 0; i < arg; ++i)
24143     {
24144       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24145                                  (enum dwarf_form) defn[i], offset_size,
24146                                  section);
24147       if (mac_ptr == NULL)
24148         {
24149           /* skip_form_bytes already issued the complaint.  */
24150           return NULL;
24151         }
24152     }
24153
24154   return mac_ptr;
24155 }
24156
24157 /* A helper function which parses the header of a macro section.
24158    If the macro section is the extended (for now called "GNU") type,
24159    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24160    the header, or issues a complaint and returns NULL on error.  */
24161
24162 static const gdb_byte *
24163 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24164                           bfd *abfd,
24165                           const gdb_byte *mac_ptr,
24166                           unsigned int *offset_size,
24167                           int section_is_gnu)
24168 {
24169   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24170
24171   if (section_is_gnu)
24172     {
24173       unsigned int version, flags;
24174
24175       version = read_2_bytes (abfd, mac_ptr);
24176       if (version != 4 && version != 5)
24177         {
24178           complaint (&symfile_complaints,
24179                      _("unrecognized version `%d' in .debug_macro section"),
24180                      version);
24181           return NULL;
24182         }
24183       mac_ptr += 2;
24184
24185       flags = read_1_byte (abfd, mac_ptr);
24186       ++mac_ptr;
24187       *offset_size = (flags & 1) ? 8 : 4;
24188
24189       if ((flags & 2) != 0)
24190         /* We don't need the line table offset.  */
24191         mac_ptr += *offset_size;
24192
24193       /* Vendor opcode descriptions.  */
24194       if ((flags & 4) != 0)
24195         {
24196           unsigned int i, count;
24197
24198           count = read_1_byte (abfd, mac_ptr);
24199           ++mac_ptr;
24200           for (i = 0; i < count; ++i)
24201             {
24202               unsigned int opcode, bytes_read;
24203               unsigned long arg;
24204
24205               opcode = read_1_byte (abfd, mac_ptr);
24206               ++mac_ptr;
24207               opcode_definitions[opcode] = mac_ptr;
24208               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24209               mac_ptr += bytes_read;
24210               mac_ptr += arg;
24211             }
24212         }
24213     }
24214
24215   return mac_ptr;
24216 }
24217
24218 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24219    including DW_MACRO_import.  */
24220
24221 static void
24222 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24223                           bfd *abfd,
24224                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24225                           struct macro_source_file *current_file,
24226                           struct line_header *lh,
24227                           struct dwarf2_section_info *section,
24228                           int section_is_gnu, int section_is_dwz,
24229                           unsigned int offset_size,
24230                           htab_t include_hash)
24231 {
24232   struct objfile *objfile = dwarf2_per_objfile->objfile;
24233   enum dwarf_macro_record_type macinfo_type;
24234   int at_commandline;
24235   const gdb_byte *opcode_definitions[256];
24236
24237   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24238                                       &offset_size, section_is_gnu);
24239   if (mac_ptr == NULL)
24240     {
24241       /* We already issued a complaint.  */
24242       return;
24243     }
24244
24245   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24246      GDB is still reading the definitions from command line.  First
24247      DW_MACINFO_start_file will need to be ignored as it was already executed
24248      to create CURRENT_FILE for the main source holding also the command line
24249      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24250      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24251
24252   at_commandline = 1;
24253
24254   do
24255     {
24256       /* Do we at least have room for a macinfo type byte?  */
24257       if (mac_ptr >= mac_end)
24258         {
24259           dwarf2_section_buffer_overflow_complaint (section);
24260           break;
24261         }
24262
24263       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24264       mac_ptr++;
24265
24266       /* Note that we rely on the fact that the corresponding GNU and
24267          DWARF constants are the same.  */
24268       DIAGNOSTIC_PUSH
24269       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24270       switch (macinfo_type)
24271         {
24272           /* A zero macinfo type indicates the end of the macro
24273              information.  */
24274         case 0:
24275           break;
24276
24277         case DW_MACRO_define:
24278         case DW_MACRO_undef:
24279         case DW_MACRO_define_strp:
24280         case DW_MACRO_undef_strp:
24281         case DW_MACRO_define_sup:
24282         case DW_MACRO_undef_sup:
24283           {
24284             unsigned int bytes_read;
24285             int line;
24286             const char *body;
24287             int is_define;
24288
24289             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24290             mac_ptr += bytes_read;
24291
24292             if (macinfo_type == DW_MACRO_define
24293                 || macinfo_type == DW_MACRO_undef)
24294               {
24295                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24296                 mac_ptr += bytes_read;
24297               }
24298             else
24299               {
24300                 LONGEST str_offset;
24301
24302                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24303                 mac_ptr += offset_size;
24304
24305                 if (macinfo_type == DW_MACRO_define_sup
24306                     || macinfo_type == DW_MACRO_undef_sup
24307                     || section_is_dwz)
24308                   {
24309                     struct dwz_file *dwz
24310                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24311
24312                     body = read_indirect_string_from_dwz (objfile,
24313                                                           dwz, str_offset);
24314                   }
24315                 else
24316                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24317                                                          abfd, str_offset);
24318               }
24319
24320             is_define = (macinfo_type == DW_MACRO_define
24321                          || macinfo_type == DW_MACRO_define_strp
24322                          || macinfo_type == DW_MACRO_define_sup);
24323             if (! current_file)
24324               {
24325                 /* DWARF violation as no main source is present.  */
24326                 complaint (&symfile_complaints,
24327                            _("debug info with no main source gives macro %s "
24328                              "on line %d: %s"),
24329                            is_define ? _("definition") : _("undefinition"),
24330                            line, body);
24331                 break;
24332               }
24333             if ((line == 0 && !at_commandline)
24334                 || (line != 0 && at_commandline))
24335               complaint (&symfile_complaints,
24336                          _("debug info gives %s macro %s with %s line %d: %s"),
24337                          at_commandline ? _("command-line") : _("in-file"),
24338                          is_define ? _("definition") : _("undefinition"),
24339                          line == 0 ? _("zero") : _("non-zero"), line, body);
24340
24341             if (is_define)
24342               parse_macro_definition (current_file, line, body);
24343             else
24344               {
24345                 gdb_assert (macinfo_type == DW_MACRO_undef
24346                             || macinfo_type == DW_MACRO_undef_strp
24347                             || macinfo_type == DW_MACRO_undef_sup);
24348                 macro_undef (current_file, line, body);
24349               }
24350           }
24351           break;
24352
24353         case DW_MACRO_start_file:
24354           {
24355             unsigned int bytes_read;
24356             int line, file;
24357
24358             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24359             mac_ptr += bytes_read;
24360             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24361             mac_ptr += bytes_read;
24362
24363             if ((line == 0 && !at_commandline)
24364                 || (line != 0 && at_commandline))
24365               complaint (&symfile_complaints,
24366                          _("debug info gives source %d included "
24367                            "from %s at %s line %d"),
24368                          file, at_commandline ? _("command-line") : _("file"),
24369                          line == 0 ? _("zero") : _("non-zero"), line);
24370
24371             if (at_commandline)
24372               {
24373                 /* This DW_MACRO_start_file was executed in the
24374                    pass one.  */
24375                 at_commandline = 0;
24376               }
24377             else
24378               current_file = macro_start_file (file, line, current_file, lh);
24379           }
24380           break;
24381
24382         case DW_MACRO_end_file:
24383           if (! current_file)
24384             complaint (&symfile_complaints,
24385                        _("macro debug info has an unmatched "
24386                          "`close_file' directive"));
24387           else
24388             {
24389               current_file = current_file->included_by;
24390               if (! current_file)
24391                 {
24392                   enum dwarf_macro_record_type next_type;
24393
24394                   /* GCC circa March 2002 doesn't produce the zero
24395                      type byte marking the end of the compilation
24396                      unit.  Complain if it's not there, but exit no
24397                      matter what.  */
24398
24399                   /* Do we at least have room for a macinfo type byte?  */
24400                   if (mac_ptr >= mac_end)
24401                     {
24402                       dwarf2_section_buffer_overflow_complaint (section);
24403                       return;
24404                     }
24405
24406                   /* We don't increment mac_ptr here, so this is just
24407                      a look-ahead.  */
24408                   next_type
24409                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24410                                                                   mac_ptr);
24411                   if (next_type != 0)
24412                     complaint (&symfile_complaints,
24413                                _("no terminating 0-type entry for "
24414                                  "macros in `.debug_macinfo' section"));
24415
24416                   return;
24417                 }
24418             }
24419           break;
24420
24421         case DW_MACRO_import:
24422         case DW_MACRO_import_sup:
24423           {
24424             LONGEST offset;
24425             void **slot;
24426             bfd *include_bfd = abfd;
24427             struct dwarf2_section_info *include_section = section;
24428             const gdb_byte *include_mac_end = mac_end;
24429             int is_dwz = section_is_dwz;
24430             const gdb_byte *new_mac_ptr;
24431
24432             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24433             mac_ptr += offset_size;
24434
24435             if (macinfo_type == DW_MACRO_import_sup)
24436               {
24437                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24438
24439                 dwarf2_read_section (objfile, &dwz->macro);
24440
24441                 include_section = &dwz->macro;
24442                 include_bfd = get_section_bfd_owner (include_section);
24443                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24444                 is_dwz = 1;
24445               }
24446
24447             new_mac_ptr = include_section->buffer + offset;
24448             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24449
24450             if (*slot != NULL)
24451               {
24452                 /* This has actually happened; see
24453                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24454                 complaint (&symfile_complaints,
24455                            _("recursive DW_MACRO_import in "
24456                              ".debug_macro section"));
24457               }
24458             else
24459               {
24460                 *slot = (void *) new_mac_ptr;
24461
24462                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24463                                           include_bfd, new_mac_ptr,
24464                                           include_mac_end, current_file, lh,
24465                                           section, section_is_gnu, is_dwz,
24466                                           offset_size, include_hash);
24467
24468                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24469               }
24470           }
24471           break;
24472
24473         case DW_MACINFO_vendor_ext:
24474           if (!section_is_gnu)
24475             {
24476               unsigned int bytes_read;
24477
24478               /* This reads the constant, but since we don't recognize
24479                  any vendor extensions, we ignore it.  */
24480               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24481               mac_ptr += bytes_read;
24482               read_direct_string (abfd, mac_ptr, &bytes_read);
24483               mac_ptr += bytes_read;
24484
24485               /* We don't recognize any vendor extensions.  */
24486               break;
24487             }
24488           /* FALLTHROUGH */
24489
24490         default:
24491           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24492                                          mac_ptr, mac_end, abfd, offset_size,
24493                                          section);
24494           if (mac_ptr == NULL)
24495             return;
24496           break;
24497         }
24498       DIAGNOSTIC_POP
24499     } while (macinfo_type != 0);
24500 }
24501
24502 static void
24503 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24504                      int section_is_gnu)
24505 {
24506   struct dwarf2_per_objfile *dwarf2_per_objfile
24507     = cu->per_cu->dwarf2_per_objfile;
24508   struct objfile *objfile = dwarf2_per_objfile->objfile;
24509   struct line_header *lh = cu->line_header;
24510   bfd *abfd;
24511   const gdb_byte *mac_ptr, *mac_end;
24512   struct macro_source_file *current_file = 0;
24513   enum dwarf_macro_record_type macinfo_type;
24514   unsigned int offset_size = cu->header.offset_size;
24515   const gdb_byte *opcode_definitions[256];
24516   void **slot;
24517   struct dwarf2_section_info *section;
24518   const char *section_name;
24519
24520   if (cu->dwo_unit != NULL)
24521     {
24522       if (section_is_gnu)
24523         {
24524           section = &cu->dwo_unit->dwo_file->sections.macro;
24525           section_name = ".debug_macro.dwo";
24526         }
24527       else
24528         {
24529           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24530           section_name = ".debug_macinfo.dwo";
24531         }
24532     }
24533   else
24534     {
24535       if (section_is_gnu)
24536         {
24537           section = &dwarf2_per_objfile->macro;
24538           section_name = ".debug_macro";
24539         }
24540       else
24541         {
24542           section = &dwarf2_per_objfile->macinfo;
24543           section_name = ".debug_macinfo";
24544         }
24545     }
24546
24547   dwarf2_read_section (objfile, section);
24548   if (section->buffer == NULL)
24549     {
24550       complaint (&symfile_complaints, _("missing %s section"), section_name);
24551       return;
24552     }
24553   abfd = get_section_bfd_owner (section);
24554
24555   /* First pass: Find the name of the base filename.
24556      This filename is needed in order to process all macros whose definition
24557      (or undefinition) comes from the command line.  These macros are defined
24558      before the first DW_MACINFO_start_file entry, and yet still need to be
24559      associated to the base file.
24560
24561      To determine the base file name, we scan the macro definitions until we
24562      reach the first DW_MACINFO_start_file entry.  We then initialize
24563      CURRENT_FILE accordingly so that any macro definition found before the
24564      first DW_MACINFO_start_file can still be associated to the base file.  */
24565
24566   mac_ptr = section->buffer + offset;
24567   mac_end = section->buffer + section->size;
24568
24569   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24570                                       &offset_size, section_is_gnu);
24571   if (mac_ptr == NULL)
24572     {
24573       /* We already issued a complaint.  */
24574       return;
24575     }
24576
24577   do
24578     {
24579       /* Do we at least have room for a macinfo type byte?  */
24580       if (mac_ptr >= mac_end)
24581         {
24582           /* Complaint is printed during the second pass as GDB will probably
24583              stop the first pass earlier upon finding
24584              DW_MACINFO_start_file.  */
24585           break;
24586         }
24587
24588       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24589       mac_ptr++;
24590
24591       /* Note that we rely on the fact that the corresponding GNU and
24592          DWARF constants are the same.  */
24593       DIAGNOSTIC_PUSH
24594       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24595       switch (macinfo_type)
24596         {
24597           /* A zero macinfo type indicates the end of the macro
24598              information.  */
24599         case 0:
24600           break;
24601
24602         case DW_MACRO_define:
24603         case DW_MACRO_undef:
24604           /* Only skip the data by MAC_PTR.  */
24605           {
24606             unsigned int bytes_read;
24607
24608             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24609             mac_ptr += bytes_read;
24610             read_direct_string (abfd, mac_ptr, &bytes_read);
24611             mac_ptr += bytes_read;
24612           }
24613           break;
24614
24615         case DW_MACRO_start_file:
24616           {
24617             unsigned int bytes_read;
24618             int line, file;
24619
24620             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24621             mac_ptr += bytes_read;
24622             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24623             mac_ptr += bytes_read;
24624
24625             current_file = macro_start_file (file, line, current_file, lh);
24626           }
24627           break;
24628
24629         case DW_MACRO_end_file:
24630           /* No data to skip by MAC_PTR.  */
24631           break;
24632
24633         case DW_MACRO_define_strp:
24634         case DW_MACRO_undef_strp:
24635         case DW_MACRO_define_sup:
24636         case DW_MACRO_undef_sup:
24637           {
24638             unsigned int bytes_read;
24639
24640             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24641             mac_ptr += bytes_read;
24642             mac_ptr += offset_size;
24643           }
24644           break;
24645
24646         case DW_MACRO_import:
24647         case DW_MACRO_import_sup:
24648           /* Note that, according to the spec, a transparent include
24649              chain cannot call DW_MACRO_start_file.  So, we can just
24650              skip this opcode.  */
24651           mac_ptr += offset_size;
24652           break;
24653
24654         case DW_MACINFO_vendor_ext:
24655           /* Only skip the data by MAC_PTR.  */
24656           if (!section_is_gnu)
24657             {
24658               unsigned int bytes_read;
24659
24660               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24661               mac_ptr += bytes_read;
24662               read_direct_string (abfd, mac_ptr, &bytes_read);
24663               mac_ptr += bytes_read;
24664             }
24665           /* FALLTHROUGH */
24666
24667         default:
24668           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24669                                          mac_ptr, mac_end, abfd, offset_size,
24670                                          section);
24671           if (mac_ptr == NULL)
24672             return;
24673           break;
24674         }
24675       DIAGNOSTIC_POP
24676     } while (macinfo_type != 0 && current_file == NULL);
24677
24678   /* Second pass: Process all entries.
24679
24680      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24681      command-line macro definitions/undefinitions.  This flag is unset when we
24682      reach the first DW_MACINFO_start_file entry.  */
24683
24684   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24685                                            htab_eq_pointer,
24686                                            NULL, xcalloc, xfree));
24687   mac_ptr = section->buffer + offset;
24688   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24689   *slot = (void *) mac_ptr;
24690   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24691                             abfd, mac_ptr, mac_end,
24692                             current_file, lh, section,
24693                             section_is_gnu, 0, offset_size,
24694                             include_hash.get ());
24695 }
24696
24697 /* Check if the attribute's form is a DW_FORM_block*
24698    if so return true else false.  */
24699
24700 static int
24701 attr_form_is_block (const struct attribute *attr)
24702 {
24703   return (attr == NULL ? 0 :
24704       attr->form == DW_FORM_block1
24705       || attr->form == DW_FORM_block2
24706       || attr->form == DW_FORM_block4
24707       || attr->form == DW_FORM_block
24708       || attr->form == DW_FORM_exprloc);
24709 }
24710
24711 /* Return non-zero if ATTR's value is a section offset --- classes
24712    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24713    You may use DW_UNSND (attr) to retrieve such offsets.
24714
24715    Section 7.5.4, "Attribute Encodings", explains that no attribute
24716    may have a value that belongs to more than one of these classes; it
24717    would be ambiguous if we did, because we use the same forms for all
24718    of them.  */
24719
24720 static int
24721 attr_form_is_section_offset (const struct attribute *attr)
24722 {
24723   return (attr->form == DW_FORM_data4
24724           || attr->form == DW_FORM_data8
24725           || attr->form == DW_FORM_sec_offset);
24726 }
24727
24728 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24729    zero otherwise.  When this function returns true, you can apply
24730    dwarf2_get_attr_constant_value to it.
24731
24732    However, note that for some attributes you must check
24733    attr_form_is_section_offset before using this test.  DW_FORM_data4
24734    and DW_FORM_data8 are members of both the constant class, and of
24735    the classes that contain offsets into other debug sections
24736    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24737    that, if an attribute's can be either a constant or one of the
24738    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24739    taken as section offsets, not constants.
24740
24741    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24742    cannot handle that.  */
24743
24744 static int
24745 attr_form_is_constant (const struct attribute *attr)
24746 {
24747   switch (attr->form)
24748     {
24749     case DW_FORM_sdata:
24750     case DW_FORM_udata:
24751     case DW_FORM_data1:
24752     case DW_FORM_data2:
24753     case DW_FORM_data4:
24754     case DW_FORM_data8:
24755     case DW_FORM_implicit_const:
24756       return 1;
24757     default:
24758       return 0;
24759     }
24760 }
24761
24762
24763 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24764    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24765
24766 static int
24767 attr_form_is_ref (const struct attribute *attr)
24768 {
24769   switch (attr->form)
24770     {
24771     case DW_FORM_ref_addr:
24772     case DW_FORM_ref1:
24773     case DW_FORM_ref2:
24774     case DW_FORM_ref4:
24775     case DW_FORM_ref8:
24776     case DW_FORM_ref_udata:
24777     case DW_FORM_GNU_ref_alt:
24778       return 1;
24779     default:
24780       return 0;
24781     }
24782 }
24783
24784 /* Return the .debug_loc section to use for CU.
24785    For DWO files use .debug_loc.dwo.  */
24786
24787 static struct dwarf2_section_info *
24788 cu_debug_loc_section (struct dwarf2_cu *cu)
24789 {
24790   struct dwarf2_per_objfile *dwarf2_per_objfile
24791     = cu->per_cu->dwarf2_per_objfile;
24792
24793   if (cu->dwo_unit)
24794     {
24795       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24796       
24797       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24798     }
24799   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24800                                   : &dwarf2_per_objfile->loc);
24801 }
24802
24803 /* A helper function that fills in a dwarf2_loclist_baton.  */
24804
24805 static void
24806 fill_in_loclist_baton (struct dwarf2_cu *cu,
24807                        struct dwarf2_loclist_baton *baton,
24808                        const struct attribute *attr)
24809 {
24810   struct dwarf2_per_objfile *dwarf2_per_objfile
24811     = cu->per_cu->dwarf2_per_objfile;
24812   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24813
24814   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24815
24816   baton->per_cu = cu->per_cu;
24817   gdb_assert (baton->per_cu);
24818   /* We don't know how long the location list is, but make sure we
24819      don't run off the edge of the section.  */
24820   baton->size = section->size - DW_UNSND (attr);
24821   baton->data = section->buffer + DW_UNSND (attr);
24822   baton->base_address = cu->base_address;
24823   baton->from_dwo = cu->dwo_unit != NULL;
24824 }
24825
24826 static void
24827 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24828                              struct dwarf2_cu *cu, int is_block)
24829 {
24830   struct dwarf2_per_objfile *dwarf2_per_objfile
24831     = cu->per_cu->dwarf2_per_objfile;
24832   struct objfile *objfile = dwarf2_per_objfile->objfile;
24833   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24834
24835   if (attr_form_is_section_offset (attr)
24836       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24837          the section.  If so, fall through to the complaint in the
24838          other branch.  */
24839       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24840     {
24841       struct dwarf2_loclist_baton *baton;
24842
24843       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24844
24845       fill_in_loclist_baton (cu, baton, attr);
24846
24847       if (cu->base_known == 0)
24848         complaint (&symfile_complaints,
24849                    _("Location list used without "
24850                      "specifying the CU base address."));
24851
24852       SYMBOL_ACLASS_INDEX (sym) = (is_block
24853                                    ? dwarf2_loclist_block_index
24854                                    : dwarf2_loclist_index);
24855       SYMBOL_LOCATION_BATON (sym) = baton;
24856     }
24857   else
24858     {
24859       struct dwarf2_locexpr_baton *baton;
24860
24861       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24862       baton->per_cu = cu->per_cu;
24863       gdb_assert (baton->per_cu);
24864
24865       if (attr_form_is_block (attr))
24866         {
24867           /* Note that we're just copying the block's data pointer
24868              here, not the actual data.  We're still pointing into the
24869              info_buffer for SYM's objfile; right now we never release
24870              that buffer, but when we do clean up properly this may
24871              need to change.  */
24872           baton->size = DW_BLOCK (attr)->size;
24873           baton->data = DW_BLOCK (attr)->data;
24874         }
24875       else
24876         {
24877           dwarf2_invalid_attrib_class_complaint ("location description",
24878                                                  SYMBOL_NATURAL_NAME (sym));
24879           baton->size = 0;
24880         }
24881
24882       SYMBOL_ACLASS_INDEX (sym) = (is_block
24883                                    ? dwarf2_locexpr_block_index
24884                                    : dwarf2_locexpr_index);
24885       SYMBOL_LOCATION_BATON (sym) = baton;
24886     }
24887 }
24888
24889 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24890    came from a separate debuginfo file, then the master objfile is
24891    returned.  */
24892
24893 struct objfile *
24894 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24895 {
24896   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24897
24898   /* Return the master objfile, so that we can report and look up the
24899      correct file containing this variable.  */
24900   if (objfile->separate_debug_objfile_backlink)
24901     objfile = objfile->separate_debug_objfile_backlink;
24902
24903   return objfile;
24904 }
24905
24906 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24907    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24908    CU_HEADERP first.  */
24909
24910 static const struct comp_unit_head *
24911 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24912                        struct dwarf2_per_cu_data *per_cu)
24913 {
24914   const gdb_byte *info_ptr;
24915
24916   if (per_cu->cu)
24917     return &per_cu->cu->header;
24918
24919   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24920
24921   memset (cu_headerp, 0, sizeof (*cu_headerp));
24922   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24923                        rcuh_kind::COMPILE);
24924
24925   return cu_headerp;
24926 }
24927
24928 /* Return the address size given in the compilation unit header for CU.  */
24929
24930 int
24931 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24932 {
24933   struct comp_unit_head cu_header_local;
24934   const struct comp_unit_head *cu_headerp;
24935
24936   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24937
24938   return cu_headerp->addr_size;
24939 }
24940
24941 /* Return the offset size given in the compilation unit header for CU.  */
24942
24943 int
24944 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24945 {
24946   struct comp_unit_head cu_header_local;
24947   const struct comp_unit_head *cu_headerp;
24948
24949   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24950
24951   return cu_headerp->offset_size;
24952 }
24953
24954 /* See its dwarf2loc.h declaration.  */
24955
24956 int
24957 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24958 {
24959   struct comp_unit_head cu_header_local;
24960   const struct comp_unit_head *cu_headerp;
24961
24962   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24963
24964   if (cu_headerp->version == 2)
24965     return cu_headerp->addr_size;
24966   else
24967     return cu_headerp->offset_size;
24968 }
24969
24970 /* Return the text offset of the CU.  The returned offset comes from
24971    this CU's objfile.  If this objfile came from a separate debuginfo
24972    file, then the offset may be different from the corresponding
24973    offset in the parent objfile.  */
24974
24975 CORE_ADDR
24976 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24977 {
24978   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24979
24980   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24981 }
24982
24983 /* Return DWARF version number of PER_CU.  */
24984
24985 short
24986 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24987 {
24988   return per_cu->dwarf_version;
24989 }
24990
24991 /* Locate the .debug_info compilation unit from CU's objfile which contains
24992    the DIE at OFFSET.  Raises an error on failure.  */
24993
24994 static struct dwarf2_per_cu_data *
24995 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24996                                   unsigned int offset_in_dwz,
24997                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24998 {
24999   struct dwarf2_per_cu_data *this_cu;
25000   int low, high;
25001   const sect_offset *cu_off;
25002
25003   low = 0;
25004   high = dwarf2_per_objfile->n_comp_units - 1;
25005   while (high > low)
25006     {
25007       struct dwarf2_per_cu_data *mid_cu;
25008       int mid = low + (high - low) / 2;
25009
25010       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25011       cu_off = &mid_cu->sect_off;
25012       if (mid_cu->is_dwz > offset_in_dwz
25013           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25014         high = mid;
25015       else
25016         low = mid + 1;
25017     }
25018   gdb_assert (low == high);
25019   this_cu = dwarf2_per_objfile->all_comp_units[low];
25020   cu_off = &this_cu->sect_off;
25021   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25022     {
25023       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25024         error (_("Dwarf Error: could not find partial DIE containing "
25025                "offset 0x%x [in module %s]"),
25026                to_underlying (sect_off),
25027                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25028
25029       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25030                   <= sect_off);
25031       return dwarf2_per_objfile->all_comp_units[low-1];
25032     }
25033   else
25034     {
25035       this_cu = dwarf2_per_objfile->all_comp_units[low];
25036       if (low == dwarf2_per_objfile->n_comp_units - 1
25037           && sect_off >= this_cu->sect_off + this_cu->length)
25038         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
25039       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25040       return this_cu;
25041     }
25042 }
25043
25044 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25045
25046 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25047   : per_cu (per_cu_),
25048     mark (0),
25049     has_loclist (0),
25050     checked_producer (0),
25051     producer_is_gxx_lt_4_6 (0),
25052     producer_is_gcc_lt_4_3 (0),
25053     producer_is_icc_lt_14 (0),
25054     processing_has_namespace_info (0)
25055 {
25056   per_cu->cu = this;
25057 }
25058
25059 /* Destroy a dwarf2_cu.  */
25060
25061 dwarf2_cu::~dwarf2_cu ()
25062 {
25063   per_cu->cu = NULL;
25064 }
25065
25066 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25067
25068 static void
25069 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25070                        enum language pretend_language)
25071 {
25072   struct attribute *attr;
25073
25074   /* Set the language we're debugging.  */
25075   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25076   if (attr)
25077     set_cu_language (DW_UNSND (attr), cu);
25078   else
25079     {
25080       cu->language = pretend_language;
25081       cu->language_defn = language_def (cu->language);
25082     }
25083
25084   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25085 }
25086
25087 /* Free all cached compilation units.  */
25088
25089 static void
25090 free_cached_comp_units (void *data)
25091 {
25092   struct dwarf2_per_objfile *dwarf2_per_objfile
25093     = (struct dwarf2_per_objfile *) data;
25094
25095   dwarf2_per_objfile->free_cached_comp_units ();
25096 }
25097
25098 /* Increase the age counter on each cached compilation unit, and free
25099    any that are too old.  */
25100
25101 static void
25102 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25103 {
25104   struct dwarf2_per_cu_data *per_cu, **last_chain;
25105
25106   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25107   per_cu = dwarf2_per_objfile->read_in_chain;
25108   while (per_cu != NULL)
25109     {
25110       per_cu->cu->last_used ++;
25111       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25112         dwarf2_mark (per_cu->cu);
25113       per_cu = per_cu->cu->read_in_chain;
25114     }
25115
25116   per_cu = dwarf2_per_objfile->read_in_chain;
25117   last_chain = &dwarf2_per_objfile->read_in_chain;
25118   while (per_cu != NULL)
25119     {
25120       struct dwarf2_per_cu_data *next_cu;
25121
25122       next_cu = per_cu->cu->read_in_chain;
25123
25124       if (!per_cu->cu->mark)
25125         {
25126           delete per_cu->cu;
25127           *last_chain = next_cu;
25128         }
25129       else
25130         last_chain = &per_cu->cu->read_in_chain;
25131
25132       per_cu = next_cu;
25133     }
25134 }
25135
25136 /* Remove a single compilation unit from the cache.  */
25137
25138 static void
25139 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25140 {
25141   struct dwarf2_per_cu_data *per_cu, **last_chain;
25142   struct dwarf2_per_objfile *dwarf2_per_objfile
25143     = target_per_cu->dwarf2_per_objfile;
25144
25145   per_cu = dwarf2_per_objfile->read_in_chain;
25146   last_chain = &dwarf2_per_objfile->read_in_chain;
25147   while (per_cu != NULL)
25148     {
25149       struct dwarf2_per_cu_data *next_cu;
25150
25151       next_cu = per_cu->cu->read_in_chain;
25152
25153       if (per_cu == target_per_cu)
25154         {
25155           delete per_cu->cu;
25156           per_cu->cu = NULL;
25157           *last_chain = next_cu;
25158           break;
25159         }
25160       else
25161         last_chain = &per_cu->cu->read_in_chain;
25162
25163       per_cu = next_cu;
25164     }
25165 }
25166
25167 /* Release all extra memory associated with OBJFILE.  */
25168
25169 void
25170 dwarf2_free_objfile (struct objfile *objfile)
25171 {
25172   struct dwarf2_per_objfile *dwarf2_per_objfile
25173     = get_dwarf2_per_objfile (objfile);
25174
25175   if (dwarf2_per_objfile == NULL)
25176     return;
25177
25178   dwarf2_per_objfile->~dwarf2_per_objfile ();
25179 }
25180
25181 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25182    We store these in a hash table separate from the DIEs, and preserve them
25183    when the DIEs are flushed out of cache.
25184
25185    The CU "per_cu" pointer is needed because offset alone is not enough to
25186    uniquely identify the type.  A file may have multiple .debug_types sections,
25187    or the type may come from a DWO file.  Furthermore, while it's more logical
25188    to use per_cu->section+offset, with Fission the section with the data is in
25189    the DWO file but we don't know that section at the point we need it.
25190    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25191    because we can enter the lookup routine, get_die_type_at_offset, from
25192    outside this file, and thus won't necessarily have PER_CU->cu.
25193    Fortunately, PER_CU is stable for the life of the objfile.  */
25194
25195 struct dwarf2_per_cu_offset_and_type
25196 {
25197   const struct dwarf2_per_cu_data *per_cu;
25198   sect_offset sect_off;
25199   struct type *type;
25200 };
25201
25202 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25203
25204 static hashval_t
25205 per_cu_offset_and_type_hash (const void *item)
25206 {
25207   const struct dwarf2_per_cu_offset_and_type *ofs
25208     = (const struct dwarf2_per_cu_offset_and_type *) item;
25209
25210   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25211 }
25212
25213 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25214
25215 static int
25216 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25217 {
25218   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25219     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25220   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25221     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25222
25223   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25224           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25225 }
25226
25227 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25228    table if necessary.  For convenience, return TYPE.
25229
25230    The DIEs reading must have careful ordering to:
25231     * Not cause infite loops trying to read in DIEs as a prerequisite for
25232       reading current DIE.
25233     * Not trying to dereference contents of still incompletely read in types
25234       while reading in other DIEs.
25235     * Enable referencing still incompletely read in types just by a pointer to
25236       the type without accessing its fields.
25237
25238    Therefore caller should follow these rules:
25239      * Try to fetch any prerequisite types we may need to build this DIE type
25240        before building the type and calling set_die_type.
25241      * After building type call set_die_type for current DIE as soon as
25242        possible before fetching more types to complete the current type.
25243      * Make the type as complete as possible before fetching more types.  */
25244
25245 static struct type *
25246 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25247 {
25248   struct dwarf2_per_objfile *dwarf2_per_objfile
25249     = cu->per_cu->dwarf2_per_objfile;
25250   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25251   struct objfile *objfile = dwarf2_per_objfile->objfile;
25252   struct attribute *attr;
25253   struct dynamic_prop prop;
25254
25255   /* For Ada types, make sure that the gnat-specific data is always
25256      initialized (if not already set).  There are a few types where
25257      we should not be doing so, because the type-specific area is
25258      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25259      where the type-specific area is used to store the floatformat).
25260      But this is not a problem, because the gnat-specific information
25261      is actually not needed for these types.  */
25262   if (need_gnat_info (cu)
25263       && TYPE_CODE (type) != TYPE_CODE_FUNC
25264       && TYPE_CODE (type) != TYPE_CODE_FLT
25265       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25266       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25267       && TYPE_CODE (type) != TYPE_CODE_METHOD
25268       && !HAVE_GNAT_AUX_INFO (type))
25269     INIT_GNAT_SPECIFIC (type);
25270
25271   /* Read DW_AT_allocated and set in type.  */
25272   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25273   if (attr_form_is_block (attr))
25274     {
25275       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25276         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25277     }
25278   else if (attr != NULL)
25279     {
25280       complaint (&symfile_complaints,
25281                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25282                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25283                  to_underlying (die->sect_off));
25284     }
25285
25286   /* Read DW_AT_associated and set in type.  */
25287   attr = dwarf2_attr (die, DW_AT_associated, cu);
25288   if (attr_form_is_block (attr))
25289     {
25290       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25291         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25292     }
25293   else if (attr != NULL)
25294     {
25295       complaint (&symfile_complaints,
25296                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25297                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25298                  to_underlying (die->sect_off));
25299     }
25300
25301   /* Read DW_AT_data_location and set in type.  */
25302   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25303   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25304     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25305
25306   if (dwarf2_per_objfile->die_type_hash == NULL)
25307     {
25308       dwarf2_per_objfile->die_type_hash =
25309         htab_create_alloc_ex (127,
25310                               per_cu_offset_and_type_hash,
25311                               per_cu_offset_and_type_eq,
25312                               NULL,
25313                               &objfile->objfile_obstack,
25314                               hashtab_obstack_allocate,
25315                               dummy_obstack_deallocate);
25316     }
25317
25318   ofs.per_cu = cu->per_cu;
25319   ofs.sect_off = die->sect_off;
25320   ofs.type = type;
25321   slot = (struct dwarf2_per_cu_offset_and_type **)
25322     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25323   if (*slot)
25324     complaint (&symfile_complaints,
25325                _("A problem internal to GDB: DIE 0x%x has type already set"),
25326                to_underlying (die->sect_off));
25327   *slot = XOBNEW (&objfile->objfile_obstack,
25328                   struct dwarf2_per_cu_offset_and_type);
25329   **slot = ofs;
25330   return type;
25331 }
25332
25333 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25334    or return NULL if the die does not have a saved type.  */
25335
25336 static struct type *
25337 get_die_type_at_offset (sect_offset sect_off,
25338                         struct dwarf2_per_cu_data *per_cu)
25339 {
25340   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25341   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25342
25343   if (dwarf2_per_objfile->die_type_hash == NULL)
25344     return NULL;
25345
25346   ofs.per_cu = per_cu;
25347   ofs.sect_off = sect_off;
25348   slot = ((struct dwarf2_per_cu_offset_and_type *)
25349           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25350   if (slot)
25351     return slot->type;
25352   else
25353     return NULL;
25354 }
25355
25356 /* Look up the type for DIE in CU in die_type_hash,
25357    or return NULL if DIE does not have a saved type.  */
25358
25359 static struct type *
25360 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25361 {
25362   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25363 }
25364
25365 /* Add a dependence relationship from CU to REF_PER_CU.  */
25366
25367 static void
25368 dwarf2_add_dependence (struct dwarf2_cu *cu,
25369                        struct dwarf2_per_cu_data *ref_per_cu)
25370 {
25371   void **slot;
25372
25373   if (cu->dependencies == NULL)
25374     cu->dependencies
25375       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25376                               NULL, &cu->comp_unit_obstack,
25377                               hashtab_obstack_allocate,
25378                               dummy_obstack_deallocate);
25379
25380   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25381   if (*slot == NULL)
25382     *slot = ref_per_cu;
25383 }
25384
25385 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25386    Set the mark field in every compilation unit in the
25387    cache that we must keep because we are keeping CU.  */
25388
25389 static int
25390 dwarf2_mark_helper (void **slot, void *data)
25391 {
25392   struct dwarf2_per_cu_data *per_cu;
25393
25394   per_cu = (struct dwarf2_per_cu_data *) *slot;
25395
25396   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25397      reading of the chain.  As such dependencies remain valid it is not much
25398      useful to track and undo them during QUIT cleanups.  */
25399   if (per_cu->cu == NULL)
25400     return 1;
25401
25402   if (per_cu->cu->mark)
25403     return 1;
25404   per_cu->cu->mark = 1;
25405
25406   if (per_cu->cu->dependencies != NULL)
25407     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25408
25409   return 1;
25410 }
25411
25412 /* Set the mark field in CU and in every other compilation unit in the
25413    cache that we must keep because we are keeping CU.  */
25414
25415 static void
25416 dwarf2_mark (struct dwarf2_cu *cu)
25417 {
25418   if (cu->mark)
25419     return;
25420   cu->mark = 1;
25421   if (cu->dependencies != NULL)
25422     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25423 }
25424
25425 static void
25426 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25427 {
25428   while (per_cu)
25429     {
25430       per_cu->cu->mark = 0;
25431       per_cu = per_cu->cu->read_in_chain;
25432     }
25433 }
25434
25435 /* Trivial hash function for partial_die_info: the hash value of a DIE
25436    is its offset in .debug_info for this objfile.  */
25437
25438 static hashval_t
25439 partial_die_hash (const void *item)
25440 {
25441   const struct partial_die_info *part_die
25442     = (const struct partial_die_info *) item;
25443
25444   return to_underlying (part_die->sect_off);
25445 }
25446
25447 /* Trivial comparison function for partial_die_info structures: two DIEs
25448    are equal if they have the same offset.  */
25449
25450 static int
25451 partial_die_eq (const void *item_lhs, const void *item_rhs)
25452 {
25453   const struct partial_die_info *part_die_lhs
25454     = (const struct partial_die_info *) item_lhs;
25455   const struct partial_die_info *part_die_rhs
25456     = (const struct partial_die_info *) item_rhs;
25457
25458   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25459 }
25460
25461 static struct cmd_list_element *set_dwarf_cmdlist;
25462 static struct cmd_list_element *show_dwarf_cmdlist;
25463
25464 static void
25465 set_dwarf_cmd (const char *args, int from_tty)
25466 {
25467   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25468              gdb_stdout);
25469 }
25470
25471 static void
25472 show_dwarf_cmd (const char *args, int from_tty)
25473 {
25474   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25475 }
25476
25477 /* Free data associated with OBJFILE, if necessary.  */
25478
25479 static void
25480 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25481 {
25482   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25483   int ix;
25484
25485   for (ix = 0; ix < data->n_comp_units; ++ix)
25486    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25487
25488   for (ix = 0; ix < data->n_type_units; ++ix)
25489     VEC_free (dwarf2_per_cu_ptr,
25490               data->all_type_units[ix]->per_cu.imported_symtabs);
25491   xfree (data->all_type_units);
25492
25493   VEC_free (dwarf2_section_info_def, data->types);
25494
25495   if (data->dwo_files)
25496     free_dwo_files (data->dwo_files, objfile);
25497   if (data->dwp_file)
25498     gdb_bfd_unref (data->dwp_file->dbfd);
25499
25500   if (data->dwz_file && data->dwz_file->dwz_bfd)
25501     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25502
25503   if (data->index_table != NULL)
25504     data->index_table->~mapped_index ();
25505 }
25506
25507 \f
25508 /* The "save gdb-index" command.  */
25509
25510 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25511    error checking.  */
25512
25513 static void
25514 file_write (FILE *file, const void *data, size_t size)
25515 {
25516   if (fwrite (data, 1, size, file) != size)
25517     error (_("couldn't data write to file"));
25518 }
25519
25520 /* Write the contents of VEC to FILE, with error checking.  */
25521
25522 template<typename Elem, typename Alloc>
25523 static void
25524 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25525 {
25526   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25527 }
25528
25529 /* In-memory buffer to prepare data to be written later to a file.  */
25530 class data_buf
25531 {
25532 public:
25533   /* Copy DATA to the end of the buffer.  */
25534   template<typename T>
25535   void append_data (const T &data)
25536   {
25537     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25538                reinterpret_cast<const gdb_byte *> (&data + 1),
25539                grow (sizeof (data)));
25540   }
25541
25542   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25543      terminating zero is appended too.  */
25544   void append_cstr0 (const char *cstr)
25545   {
25546     const size_t size = strlen (cstr) + 1;
25547     std::copy (cstr, cstr + size, grow (size));
25548   }
25549
25550   /* Store INPUT as ULEB128 to the end of buffer.  */
25551   void append_unsigned_leb128 (ULONGEST input)
25552   {
25553     for (;;)
25554       {
25555         gdb_byte output = input & 0x7f;
25556         input >>= 7;
25557         if (input)
25558           output |= 0x80;
25559         append_data (output);
25560         if (input == 0)
25561           break;
25562       }
25563   }
25564
25565   /* Accept a host-format integer in VAL and append it to the buffer
25566      as a target-format integer which is LEN bytes long.  */
25567   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25568   {
25569     ::store_unsigned_integer (grow (len), len, byte_order, val);
25570   }
25571
25572   /* Return the size of the buffer.  */
25573   size_t size () const
25574   {
25575     return m_vec.size ();
25576   }
25577
25578   /* Return true iff the buffer is empty.  */
25579   bool empty () const
25580   {
25581     return m_vec.empty ();
25582   }
25583
25584   /* Write the buffer to FILE.  */
25585   void file_write (FILE *file) const
25586   {
25587     ::file_write (file, m_vec);
25588   }
25589
25590 private:
25591   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25592      the start of the new block.  */
25593   gdb_byte *grow (size_t size)
25594   {
25595     m_vec.resize (m_vec.size () + size);
25596     return &*m_vec.end () - size;
25597   }
25598
25599   gdb::byte_vector m_vec;
25600 };
25601
25602 /* An entry in the symbol table.  */
25603 struct symtab_index_entry
25604 {
25605   /* The name of the symbol.  */
25606   const char *name;
25607   /* The offset of the name in the constant pool.  */
25608   offset_type index_offset;
25609   /* A sorted vector of the indices of all the CUs that hold an object
25610      of this name.  */
25611   std::vector<offset_type> cu_indices;
25612 };
25613
25614 /* The symbol table.  This is a power-of-2-sized hash table.  */
25615 struct mapped_symtab
25616 {
25617   mapped_symtab ()
25618   {
25619     data.resize (1024);
25620   }
25621
25622   offset_type n_elements = 0;
25623   std::vector<symtab_index_entry> data;
25624 };
25625
25626 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25627    the slot.
25628    
25629    Function is used only during write_hash_table so no index format backward
25630    compatibility is needed.  */
25631
25632 static symtab_index_entry &
25633 find_slot (struct mapped_symtab *symtab, const char *name)
25634 {
25635   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25636
25637   index = hash & (symtab->data.size () - 1);
25638   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25639
25640   for (;;)
25641     {
25642       if (symtab->data[index].name == NULL
25643           || strcmp (name, symtab->data[index].name) == 0)
25644         return symtab->data[index];
25645       index = (index + step) & (symtab->data.size () - 1);
25646     }
25647 }
25648
25649 /* Expand SYMTAB's hash table.  */
25650
25651 static void
25652 hash_expand (struct mapped_symtab *symtab)
25653 {
25654   auto old_entries = std::move (symtab->data);
25655
25656   symtab->data.clear ();
25657   symtab->data.resize (old_entries.size () * 2);
25658
25659   for (auto &it : old_entries)
25660     if (it.name != NULL)
25661       {
25662         auto &ref = find_slot (symtab, it.name);
25663         ref = std::move (it);
25664       }
25665 }
25666
25667 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25668    CU_INDEX is the index of the CU in which the symbol appears.
25669    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25670
25671 static void
25672 add_index_entry (struct mapped_symtab *symtab, const char *name,
25673                  int is_static, gdb_index_symbol_kind kind,
25674                  offset_type cu_index)
25675 {
25676   offset_type cu_index_and_attrs;
25677
25678   ++symtab->n_elements;
25679   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25680     hash_expand (symtab);
25681
25682   symtab_index_entry &slot = find_slot (symtab, name);
25683   if (slot.name == NULL)
25684     {
25685       slot.name = name;
25686       /* index_offset is set later.  */
25687     }
25688
25689   cu_index_and_attrs = 0;
25690   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25691   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25692   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25693
25694   /* We don't want to record an index value twice as we want to avoid the
25695      duplication.
25696      We process all global symbols and then all static symbols
25697      (which would allow us to avoid the duplication by only having to check
25698      the last entry pushed), but a symbol could have multiple kinds in one CU.
25699      To keep things simple we don't worry about the duplication here and
25700      sort and uniqufy the list after we've processed all symbols.  */
25701   slot.cu_indices.push_back (cu_index_and_attrs);
25702 }
25703
25704 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25705
25706 static void
25707 uniquify_cu_indices (struct mapped_symtab *symtab)
25708 {
25709   for (auto &entry : symtab->data)
25710     {
25711       if (entry.name != NULL && !entry.cu_indices.empty ())
25712         {
25713           auto &cu_indices = entry.cu_indices;
25714           std::sort (cu_indices.begin (), cu_indices.end ());
25715           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25716           cu_indices.erase (from, cu_indices.end ());
25717         }
25718     }
25719 }
25720
25721 /* A form of 'const char *' suitable for container keys.  Only the
25722    pointer is stored.  The strings themselves are compared, not the
25723    pointers.  */
25724 class c_str_view
25725 {
25726 public:
25727   c_str_view (const char *cstr)
25728     : m_cstr (cstr)
25729   {}
25730
25731   bool operator== (const c_str_view &other) const
25732   {
25733     return strcmp (m_cstr, other.m_cstr) == 0;
25734   }
25735
25736   /* Return the underlying C string.  Note, the returned string is
25737      only a reference with lifetime of this object.  */
25738   const char *c_str () const
25739   {
25740     return m_cstr;
25741   }
25742
25743 private:
25744   friend class c_str_view_hasher;
25745   const char *const m_cstr;
25746 };
25747
25748 /* A std::unordered_map::hasher for c_str_view that uses the right
25749    hash function for strings in a mapped index.  */
25750 class c_str_view_hasher
25751 {
25752 public:
25753   size_t operator () (const c_str_view &x) const
25754   {
25755     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25756   }
25757 };
25758
25759 /* A std::unordered_map::hasher for std::vector<>.  */
25760 template<typename T>
25761 class vector_hasher
25762 {
25763 public:
25764   size_t operator () (const std::vector<T> &key) const
25765   {
25766     return iterative_hash (key.data (),
25767                            sizeof (key.front ()) * key.size (), 0);
25768   }
25769 };
25770
25771 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25772    constant pool entries going into the data buffer CPOOL.  */
25773
25774 static void
25775 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25776 {
25777   {
25778     /* Elements are sorted vectors of the indices of all the CUs that
25779        hold an object of this name.  */
25780     std::unordered_map<std::vector<offset_type>, offset_type,
25781                        vector_hasher<offset_type>>
25782       symbol_hash_table;
25783
25784     /* We add all the index vectors to the constant pool first, to
25785        ensure alignment is ok.  */
25786     for (symtab_index_entry &entry : symtab->data)
25787       {
25788         if (entry.name == NULL)
25789           continue;
25790         gdb_assert (entry.index_offset == 0);
25791
25792         /* Finding before inserting is faster than always trying to
25793            insert, because inserting always allocates a node, does the
25794            lookup, and then destroys the new node if another node
25795            already had the same key.  C++17 try_emplace will avoid
25796            this.  */
25797         const auto found
25798           = symbol_hash_table.find (entry.cu_indices);
25799         if (found != symbol_hash_table.end ())
25800           {
25801             entry.index_offset = found->second;
25802             continue;
25803           }
25804
25805         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25806         entry.index_offset = cpool.size ();
25807         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25808         for (const auto index : entry.cu_indices)
25809           cpool.append_data (MAYBE_SWAP (index));
25810       }
25811   }
25812
25813   /* Now write out the hash table.  */
25814   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25815   for (const auto &entry : symtab->data)
25816     {
25817       offset_type str_off, vec_off;
25818
25819       if (entry.name != NULL)
25820         {
25821           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25822           if (insertpair.second)
25823             cpool.append_cstr0 (entry.name);
25824           str_off = insertpair.first->second;
25825           vec_off = entry.index_offset;
25826         }
25827       else
25828         {
25829           /* While 0 is a valid constant pool index, it is not valid
25830              to have 0 for both offsets.  */
25831           str_off = 0;
25832           vec_off = 0;
25833         }
25834
25835       output.append_data (MAYBE_SWAP (str_off));
25836       output.append_data (MAYBE_SWAP (vec_off));
25837     }
25838 }
25839
25840 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25841
25842 /* Helper struct for building the address table.  */
25843 struct addrmap_index_data
25844 {
25845   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25846     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25847   {}
25848
25849   struct objfile *objfile;
25850   data_buf &addr_vec;
25851   psym_index_map &cu_index_htab;
25852
25853   /* Non-zero if the previous_* fields are valid.
25854      We can't write an entry until we see the next entry (since it is only then
25855      that we know the end of the entry).  */
25856   int previous_valid;
25857   /* Index of the CU in the table of all CUs in the index file.  */
25858   unsigned int previous_cu_index;
25859   /* Start address of the CU.  */
25860   CORE_ADDR previous_cu_start;
25861 };
25862
25863 /* Write an address entry to ADDR_VEC.  */
25864
25865 static void
25866 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25867                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25868 {
25869   CORE_ADDR baseaddr;
25870
25871   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25872
25873   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25874   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25875   addr_vec.append_data (MAYBE_SWAP (cu_index));
25876 }
25877
25878 /* Worker function for traversing an addrmap to build the address table.  */
25879
25880 static int
25881 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25882 {
25883   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25884   struct partial_symtab *pst = (struct partial_symtab *) obj;
25885
25886   if (data->previous_valid)
25887     add_address_entry (data->objfile, data->addr_vec,
25888                        data->previous_cu_start, start_addr,
25889                        data->previous_cu_index);
25890
25891   data->previous_cu_start = start_addr;
25892   if (pst != NULL)
25893     {
25894       const auto it = data->cu_index_htab.find (pst);
25895       gdb_assert (it != data->cu_index_htab.cend ());
25896       data->previous_cu_index = it->second;
25897       data->previous_valid = 1;
25898     }
25899   else
25900     data->previous_valid = 0;
25901
25902   return 0;
25903 }
25904
25905 /* Write OBJFILE's address map to ADDR_VEC.
25906    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25907    in the index file.  */
25908
25909 static void
25910 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25911                    psym_index_map &cu_index_htab)
25912 {
25913   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25914
25915   /* When writing the address table, we have to cope with the fact that
25916      the addrmap iterator only provides the start of a region; we have to
25917      wait until the next invocation to get the start of the next region.  */
25918
25919   addrmap_index_data.objfile = objfile;
25920   addrmap_index_data.previous_valid = 0;
25921
25922   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25923                    &addrmap_index_data);
25924
25925   /* It's highly unlikely the last entry (end address = 0xff...ff)
25926      is valid, but we should still handle it.
25927      The end address is recorded as the start of the next region, but that
25928      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25929      anyway.  */
25930   if (addrmap_index_data.previous_valid)
25931     add_address_entry (objfile, addr_vec,
25932                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25933                        addrmap_index_data.previous_cu_index);
25934 }
25935
25936 /* Return the symbol kind of PSYM.  */
25937
25938 static gdb_index_symbol_kind
25939 symbol_kind (struct partial_symbol *psym)
25940 {
25941   domain_enum domain = PSYMBOL_DOMAIN (psym);
25942   enum address_class aclass = PSYMBOL_CLASS (psym);
25943
25944   switch (domain)
25945     {
25946     case VAR_DOMAIN:
25947       switch (aclass)
25948         {
25949         case LOC_BLOCK:
25950           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25951         case LOC_TYPEDEF:
25952           return GDB_INDEX_SYMBOL_KIND_TYPE;
25953         case LOC_COMPUTED:
25954         case LOC_CONST_BYTES:
25955         case LOC_OPTIMIZED_OUT:
25956         case LOC_STATIC:
25957           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25958         case LOC_CONST:
25959           /* Note: It's currently impossible to recognize psyms as enum values
25960              short of reading the type info.  For now punt.  */
25961           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25962         default:
25963           /* There are other LOC_FOO values that one might want to classify
25964              as variables, but dwarf2read.c doesn't currently use them.  */
25965           return GDB_INDEX_SYMBOL_KIND_OTHER;
25966         }
25967     case STRUCT_DOMAIN:
25968       return GDB_INDEX_SYMBOL_KIND_TYPE;
25969     default:
25970       return GDB_INDEX_SYMBOL_KIND_OTHER;
25971     }
25972 }
25973
25974 /* Add a list of partial symbols to SYMTAB.  */
25975
25976 static void
25977 write_psymbols (struct mapped_symtab *symtab,
25978                 std::unordered_set<partial_symbol *> &psyms_seen,
25979                 struct partial_symbol **psymp,
25980                 int count,
25981                 offset_type cu_index,
25982                 int is_static)
25983 {
25984   for (; count-- > 0; ++psymp)
25985     {
25986       struct partial_symbol *psym = *psymp;
25987
25988       if (SYMBOL_LANGUAGE (psym) == language_ada)
25989         error (_("Ada is not currently supported by the index"));
25990
25991       /* Only add a given psymbol once.  */
25992       if (psyms_seen.insert (psym).second)
25993         {
25994           gdb_index_symbol_kind kind = symbol_kind (psym);
25995
25996           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25997                            is_static, kind, cu_index);
25998         }
25999     }
26000 }
26001
26002 /* A helper struct used when iterating over debug_types.  */
26003 struct signatured_type_index_data
26004 {
26005   signatured_type_index_data (data_buf &types_list_,
26006                               std::unordered_set<partial_symbol *> &psyms_seen_)
26007     : types_list (types_list_), psyms_seen (psyms_seen_)
26008   {}
26009
26010   struct objfile *objfile;
26011   struct mapped_symtab *symtab;
26012   data_buf &types_list;
26013   std::unordered_set<partial_symbol *> &psyms_seen;
26014   int cu_index;
26015 };
26016
26017 /* A helper function that writes a single signatured_type to an
26018    obstack.  */
26019
26020 static int
26021 write_one_signatured_type (void **slot, void *d)
26022 {
26023   struct signatured_type_index_data *info
26024     = (struct signatured_type_index_data *) d;
26025   struct signatured_type *entry = (struct signatured_type *) *slot;
26026   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26027
26028   write_psymbols (info->symtab,
26029                   info->psyms_seen,
26030                   &info->objfile->global_psymbols[psymtab->globals_offset],
26031                   psymtab->n_global_syms, info->cu_index,
26032                   0);
26033   write_psymbols (info->symtab,
26034                   info->psyms_seen,
26035                   &info->objfile->static_psymbols[psymtab->statics_offset],
26036                   psymtab->n_static_syms, info->cu_index,
26037                   1);
26038
26039   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26040                                 to_underlying (entry->per_cu.sect_off));
26041   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26042                                 to_underlying (entry->type_offset_in_tu));
26043   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26044
26045   ++info->cu_index;
26046
26047   return 1;
26048 }
26049
26050 /* Recurse into all "included" dependencies and count their symbols as
26051    if they appeared in this psymtab.  */
26052
26053 static void
26054 recursively_count_psymbols (struct partial_symtab *psymtab,
26055                             size_t &psyms_seen)
26056 {
26057   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26058     if (psymtab->dependencies[i]->user != NULL)
26059       recursively_count_psymbols (psymtab->dependencies[i],
26060                                   psyms_seen);
26061
26062   psyms_seen += psymtab->n_global_syms;
26063   psyms_seen += psymtab->n_static_syms;
26064 }
26065
26066 /* Recurse into all "included" dependencies and write their symbols as
26067    if they appeared in this psymtab.  */
26068
26069 static void
26070 recursively_write_psymbols (struct objfile *objfile,
26071                             struct partial_symtab *psymtab,
26072                             struct mapped_symtab *symtab,
26073                             std::unordered_set<partial_symbol *> &psyms_seen,
26074                             offset_type cu_index)
26075 {
26076   int i;
26077
26078   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26079     if (psymtab->dependencies[i]->user != NULL)
26080       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26081                                   symtab, psyms_seen, cu_index);
26082
26083   write_psymbols (symtab,
26084                   psyms_seen,
26085                   &objfile->global_psymbols[psymtab->globals_offset],
26086                   psymtab->n_global_syms, cu_index,
26087                   0);
26088   write_psymbols (symtab,
26089                   psyms_seen,
26090                   &objfile->static_psymbols[psymtab->statics_offset],
26091                   psymtab->n_static_syms, cu_index,
26092                   1);
26093 }
26094
26095 /* DWARF-5 .debug_names builder.  */
26096 class debug_names
26097 {
26098 public:
26099   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26100                bfd_endian dwarf5_byte_order)
26101     : m_dwarf5_byte_order (dwarf5_byte_order),
26102       m_dwarf32 (dwarf5_byte_order),
26103       m_dwarf64 (dwarf5_byte_order),
26104       m_dwarf (is_dwarf64
26105                ? static_cast<dwarf &> (m_dwarf64)
26106                : static_cast<dwarf &> (m_dwarf32)),
26107       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26108       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26109       m_debugstrlookup (dwarf2_per_objfile)
26110   {}
26111
26112   int dwarf5_offset_size () const
26113   {
26114     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26115     return dwarf5_is_dwarf64 ? 8 : 4;
26116   }
26117
26118   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26119   enum class unit_kind { cu, tu };
26120
26121   /* Insert one symbol.  */
26122   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26123                unit_kind kind)
26124   {
26125     const int dwarf_tag = psymbol_tag (psym);
26126     if (dwarf_tag == 0)
26127       return;
26128     const char *const name = SYMBOL_SEARCH_NAME (psym);
26129     const auto insertpair
26130       = m_name_to_value_set.emplace (c_str_view (name),
26131                                      std::set<symbol_value> ());
26132     std::set<symbol_value> &value_set = insertpair.first->second;
26133     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26134   }
26135
26136   /* Build all the tables.  All symbols must be already inserted.
26137      This function does not call file_write, caller has to do it
26138      afterwards.  */
26139   void build ()
26140   {
26141     /* Verify the build method has not be called twice.  */
26142     gdb_assert (m_abbrev_table.empty ());
26143     const size_t name_count = m_name_to_value_set.size ();
26144     m_bucket_table.resize
26145       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26146     m_hash_table.reserve (name_count);
26147     m_name_table_string_offs.reserve (name_count);
26148     m_name_table_entry_offs.reserve (name_count);
26149
26150     /* Map each hash of symbol to its name and value.  */
26151     struct hash_it_pair
26152     {
26153       uint32_t hash;
26154       decltype (m_name_to_value_set)::const_iterator it;
26155     };
26156     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26157     bucket_hash.resize (m_bucket_table.size ());
26158     for (decltype (m_name_to_value_set)::const_iterator it
26159            = m_name_to_value_set.cbegin ();
26160          it != m_name_to_value_set.cend ();
26161          ++it)
26162       {
26163         const char *const name = it->first.c_str ();
26164         const uint32_t hash = dwarf5_djb_hash (name);
26165         hash_it_pair hashitpair;
26166         hashitpair.hash = hash;
26167         hashitpair.it = it;
26168         auto &slot = bucket_hash[hash % bucket_hash.size()];
26169         slot.push_front (std::move (hashitpair));
26170       }
26171     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26172       {
26173         const std::forward_list<hash_it_pair> &hashitlist
26174           = bucket_hash[bucket_ix];
26175         if (hashitlist.empty ())
26176           continue;
26177         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26178         /* The hashes array is indexed starting at 1.  */
26179         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26180                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26181                                 m_hash_table.size () + 1);
26182         for (const hash_it_pair &hashitpair : hashitlist)
26183           {
26184             m_hash_table.push_back (0);
26185             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26186                                                         (&m_hash_table.back ()),
26187                                     sizeof (m_hash_table.back ()),
26188                                     m_dwarf5_byte_order, hashitpair.hash);
26189             const c_str_view &name = hashitpair.it->first;
26190             const std::set<symbol_value> &value_set = hashitpair.it->second;
26191             m_name_table_string_offs.push_back_reorder
26192               (m_debugstrlookup.lookup (name.c_str ()));
26193             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26194             gdb_assert (!value_set.empty ());
26195             for (const symbol_value &value : value_set)
26196               {
26197                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26198                                                         value.is_static,
26199                                                         value.kind)];
26200                 if (idx == 0)
26201                   {
26202                     idx = m_idx_next++;
26203                     m_abbrev_table.append_unsigned_leb128 (idx);
26204                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26205                     m_abbrev_table.append_unsigned_leb128
26206                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26207                                                            : DW_IDX_type_unit);
26208                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26209                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26210                                                            ? DW_IDX_GNU_internal
26211                                                            : DW_IDX_GNU_external);
26212                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26213
26214                     /* Terminate attributes list.  */
26215                     m_abbrev_table.append_unsigned_leb128 (0);
26216                     m_abbrev_table.append_unsigned_leb128 (0);
26217                   }
26218
26219                 m_entry_pool.append_unsigned_leb128 (idx);
26220                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26221               }
26222
26223             /* Terminate the list of CUs.  */
26224             m_entry_pool.append_unsigned_leb128 (0);
26225           }
26226       }
26227     gdb_assert (m_hash_table.size () == name_count);
26228
26229     /* Terminate tags list.  */
26230     m_abbrev_table.append_unsigned_leb128 (0);
26231   }
26232
26233   /* Return .debug_names bucket count.  This must be called only after
26234      calling the build method.  */
26235   uint32_t bucket_count () const
26236   {
26237     /* Verify the build method has been already called.  */
26238     gdb_assert (!m_abbrev_table.empty ());
26239     const uint32_t retval = m_bucket_table.size ();
26240
26241     /* Check for overflow.  */
26242     gdb_assert (retval == m_bucket_table.size ());
26243     return retval;
26244   }
26245
26246   /* Return .debug_names names count.  This must be called only after
26247      calling the build method.  */
26248   uint32_t name_count () const
26249   {
26250     /* Verify the build method has been already called.  */
26251     gdb_assert (!m_abbrev_table.empty ());
26252     const uint32_t retval = m_hash_table.size ();
26253
26254     /* Check for overflow.  */
26255     gdb_assert (retval == m_hash_table.size ());
26256     return retval;
26257   }
26258
26259   /* Return number of bytes of .debug_names abbreviation table.  This
26260      must be called only after calling the build method.  */
26261   uint32_t abbrev_table_bytes () const
26262   {
26263     gdb_assert (!m_abbrev_table.empty ());
26264     return m_abbrev_table.size ();
26265   }
26266
26267   /* Recurse into all "included" dependencies and store their symbols
26268      as if they appeared in this psymtab.  */
26269   void recursively_write_psymbols
26270     (struct objfile *objfile,
26271      struct partial_symtab *psymtab,
26272      std::unordered_set<partial_symbol *> &psyms_seen,
26273      int cu_index)
26274   {
26275     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26276       if (psymtab->dependencies[i]->user != NULL)
26277         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26278                                     psyms_seen, cu_index);
26279
26280     write_psymbols (psyms_seen,
26281                     &objfile->global_psymbols[psymtab->globals_offset],
26282                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26283     write_psymbols (psyms_seen,
26284                     &objfile->static_psymbols[psymtab->statics_offset],
26285                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26286   }
26287
26288   /* Return number of bytes the .debug_names section will have.  This
26289      must be called only after calling the build method.  */
26290   size_t bytes () const
26291   {
26292     /* Verify the build method has been already called.  */
26293     gdb_assert (!m_abbrev_table.empty ());
26294     size_t expected_bytes = 0;
26295     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26296     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26297     expected_bytes += m_name_table_string_offs.bytes ();
26298     expected_bytes += m_name_table_entry_offs.bytes ();
26299     expected_bytes += m_abbrev_table.size ();
26300     expected_bytes += m_entry_pool.size ();
26301     return expected_bytes;
26302   }
26303
26304   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26305      FILE_STR.  This must be called only after calling the build
26306      method.  */
26307   void file_write (FILE *file_names, FILE *file_str) const
26308   {
26309     /* Verify the build method has been already called.  */
26310     gdb_assert (!m_abbrev_table.empty ());
26311     ::file_write (file_names, m_bucket_table);
26312     ::file_write (file_names, m_hash_table);
26313     m_name_table_string_offs.file_write (file_names);
26314     m_name_table_entry_offs.file_write (file_names);
26315     m_abbrev_table.file_write (file_names);
26316     m_entry_pool.file_write (file_names);
26317     m_debugstrlookup.file_write (file_str);
26318   }
26319
26320   /* A helper user data for write_one_signatured_type.  */
26321   class write_one_signatured_type_data
26322   {
26323   public:
26324     write_one_signatured_type_data (debug_names &nametable_,
26325                                     signatured_type_index_data &&info_)
26326     : nametable (nametable_), info (std::move (info_))
26327     {}
26328     debug_names &nametable;
26329     struct signatured_type_index_data info;
26330   };
26331
26332   /* A helper function to pass write_one_signatured_type to
26333      htab_traverse_noresize.  */
26334   static int
26335   write_one_signatured_type (void **slot, void *d)
26336   {
26337     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26338     struct signatured_type_index_data *info = &data->info;
26339     struct signatured_type *entry = (struct signatured_type *) *slot;
26340
26341     data->nametable.write_one_signatured_type (entry, info);
26342
26343     return 1;
26344   }
26345
26346 private:
26347
26348   /* Storage for symbol names mapping them to their .debug_str section
26349      offsets.  */
26350   class debug_str_lookup
26351   {
26352   public:
26353
26354     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26355        All .debug_str section strings are automatically stored.  */
26356     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26357       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26358         m_dwarf2_per_objfile (dwarf2_per_objfile)
26359     {
26360       dwarf2_read_section (dwarf2_per_objfile->objfile,
26361                            &dwarf2_per_objfile->str);
26362       if (dwarf2_per_objfile->str.buffer == NULL)
26363         return;
26364       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26365            data < (dwarf2_per_objfile->str.buffer
26366                    + dwarf2_per_objfile->str.size);)
26367         {
26368           const char *const s = reinterpret_cast<const char *> (data);
26369           const auto insertpair
26370             = m_str_table.emplace (c_str_view (s),
26371                                    data - dwarf2_per_objfile->str.buffer);
26372           if (!insertpair.second)
26373             complaint (&symfile_complaints,
26374                        _("Duplicate string \"%s\" in "
26375                          ".debug_str section [in module %s]"),
26376                        s, bfd_get_filename (m_abfd));
26377           data += strlen (s) + 1;
26378         }
26379     }
26380
26381     /* Return offset of symbol name S in the .debug_str section.  Add
26382        such symbol to the section's end if it does not exist there
26383        yet.  */
26384     size_t lookup (const char *s)
26385     {
26386       const auto it = m_str_table.find (c_str_view (s));
26387       if (it != m_str_table.end ())
26388         return it->second;
26389       const size_t offset = (m_dwarf2_per_objfile->str.size
26390                              + m_str_add_buf.size ());
26391       m_str_table.emplace (c_str_view (s), offset);
26392       m_str_add_buf.append_cstr0 (s);
26393       return offset;
26394     }
26395
26396     /* Append the end of the .debug_str section to FILE.  */
26397     void file_write (FILE *file) const
26398     {
26399       m_str_add_buf.file_write (file);
26400     }
26401
26402   private:
26403     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26404     bfd *const m_abfd;
26405     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26406
26407     /* Data to add at the end of .debug_str for new needed symbol names.  */
26408     data_buf m_str_add_buf;
26409   };
26410
26411   /* Container to map used DWARF tags to their .debug_names abbreviation
26412      tags.  */
26413   class index_key
26414   {
26415   public:
26416     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26417       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26418     {
26419     }
26420
26421     bool
26422     operator== (const index_key &other) const
26423     {
26424       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26425               && kind == other.kind);
26426     }
26427
26428     const int dwarf_tag;
26429     const bool is_static;
26430     const unit_kind kind;
26431   };
26432
26433   /* Provide std::unordered_map::hasher for index_key.  */
26434   class index_key_hasher
26435   {
26436   public:
26437     size_t
26438     operator () (const index_key &key) const
26439     {
26440       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26441     }
26442   };
26443
26444   /* Parameters of one symbol entry.  */
26445   class symbol_value
26446   {
26447   public:
26448     const int dwarf_tag, cu_index;
26449     const bool is_static;
26450     const unit_kind kind;
26451
26452     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26453                   unit_kind kind_)
26454       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26455         kind (kind_)
26456     {}
26457
26458     bool
26459     operator< (const symbol_value &other) const
26460     {
26461 #define X(n) \
26462   do \
26463     { \
26464       if (n < other.n) \
26465         return true; \
26466       if (n > other.n) \
26467         return false; \
26468     } \
26469   while (0)
26470       X (dwarf_tag);
26471       X (is_static);
26472       X (kind);
26473       X (cu_index);
26474 #undef X
26475       return false;
26476     }
26477   };
26478
26479   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26480      output.  */
26481   class offset_vec
26482   {
26483   protected:
26484     const bfd_endian dwarf5_byte_order;
26485   public:
26486     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26487       : dwarf5_byte_order (dwarf5_byte_order_)
26488     {}
26489
26490     /* Call std::vector::reserve for NELEM elements.  */
26491     virtual void reserve (size_t nelem) = 0;
26492
26493     /* Call std::vector::push_back with store_unsigned_integer byte
26494        reordering for ELEM.  */
26495     virtual void push_back_reorder (size_t elem) = 0;
26496
26497     /* Return expected output size in bytes.  */
26498     virtual size_t bytes () const = 0;
26499
26500     /* Write name table to FILE.  */
26501     virtual void file_write (FILE *file) const = 0;
26502   };
26503
26504   /* Template to unify DWARF-32 and DWARF-64 output.  */
26505   template<typename OffsetSize>
26506   class offset_vec_tmpl : public offset_vec
26507   {
26508   public:
26509     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26510       : offset_vec (dwarf5_byte_order_)
26511     {}
26512
26513     /* Implement offset_vec::reserve.  */
26514     void reserve (size_t nelem) override
26515     {
26516       m_vec.reserve (nelem);
26517     }
26518
26519     /* Implement offset_vec::push_back_reorder.  */
26520     void push_back_reorder (size_t elem) override
26521     {
26522       m_vec.push_back (elem);
26523       /* Check for overflow.  */
26524       gdb_assert (m_vec.back () == elem);
26525       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26526                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26527     }
26528
26529     /* Implement offset_vec::bytes.  */
26530     size_t bytes () const override
26531     {
26532       return m_vec.size () * sizeof (m_vec[0]);
26533     }
26534
26535     /* Implement offset_vec::file_write.  */
26536     void file_write (FILE *file) const override
26537     {
26538       ::file_write (file, m_vec);
26539     }
26540
26541   private:
26542     std::vector<OffsetSize> m_vec;
26543   };
26544
26545   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26546      respecting name table width.  */
26547   class dwarf
26548   {
26549   public:
26550     offset_vec &name_table_string_offs, &name_table_entry_offs;
26551
26552     dwarf (offset_vec &name_table_string_offs_,
26553            offset_vec &name_table_entry_offs_)
26554       : name_table_string_offs (name_table_string_offs_),
26555         name_table_entry_offs (name_table_entry_offs_)
26556     {
26557     }
26558   };
26559
26560   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26561      respecting name table width.  */
26562   template<typename OffsetSize>
26563   class dwarf_tmpl : public dwarf
26564   {
26565   public:
26566     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26567       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26568         m_name_table_string_offs (dwarf5_byte_order_),
26569         m_name_table_entry_offs (dwarf5_byte_order_)
26570     {}
26571
26572   private:
26573     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26574     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26575   };
26576
26577   /* Try to reconstruct original DWARF tag for given partial_symbol.
26578      This function is not DWARF-5 compliant but it is sufficient for
26579      GDB as a DWARF-5 index consumer.  */
26580   static int psymbol_tag (const struct partial_symbol *psym)
26581   {
26582     domain_enum domain = PSYMBOL_DOMAIN (psym);
26583     enum address_class aclass = PSYMBOL_CLASS (psym);
26584
26585     switch (domain)
26586       {
26587       case VAR_DOMAIN:
26588         switch (aclass)
26589           {
26590           case LOC_BLOCK:
26591             return DW_TAG_subprogram;
26592           case LOC_TYPEDEF:
26593             return DW_TAG_typedef;
26594           case LOC_COMPUTED:
26595           case LOC_CONST_BYTES:
26596           case LOC_OPTIMIZED_OUT:
26597           case LOC_STATIC:
26598             return DW_TAG_variable;
26599           case LOC_CONST:
26600             /* Note: It's currently impossible to recognize psyms as enum values
26601                short of reading the type info.  For now punt.  */
26602             return DW_TAG_variable;
26603           default:
26604             /* There are other LOC_FOO values that one might want to classify
26605                as variables, but dwarf2read.c doesn't currently use them.  */
26606             return DW_TAG_variable;
26607           }
26608       case STRUCT_DOMAIN:
26609         return DW_TAG_structure_type;
26610       default:
26611         return 0;
26612       }
26613   }
26614
26615   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26616   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26617                        struct partial_symbol **psymp, int count, int cu_index,
26618                        bool is_static, unit_kind kind)
26619   {
26620     for (; count-- > 0; ++psymp)
26621       {
26622         struct partial_symbol *psym = *psymp;
26623
26624         if (SYMBOL_LANGUAGE (psym) == language_ada)
26625           error (_("Ada is not currently supported by the index"));
26626
26627         /* Only add a given psymbol once.  */
26628         if (psyms_seen.insert (psym).second)
26629           insert (psym, cu_index, is_static, kind);
26630       }
26631   }
26632
26633   /* A helper function that writes a single signatured_type
26634      to a debug_names.  */
26635   void
26636   write_one_signatured_type (struct signatured_type *entry,
26637                              struct signatured_type_index_data *info)
26638   {
26639     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26640
26641     write_psymbols (info->psyms_seen,
26642                     &info->objfile->global_psymbols[psymtab->globals_offset],
26643                     psymtab->n_global_syms, info->cu_index, false,
26644                     unit_kind::tu);
26645     write_psymbols (info->psyms_seen,
26646                     &info->objfile->static_psymbols[psymtab->statics_offset],
26647                     psymtab->n_static_syms, info->cu_index, true,
26648                     unit_kind::tu);
26649
26650     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26651                                   to_underlying (entry->per_cu.sect_off));
26652
26653     ++info->cu_index;
26654   }
26655
26656   /* Store value of each symbol.  */
26657   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26658     m_name_to_value_set;
26659
26660   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26661      order.  */
26662   std::vector<uint32_t> m_bucket_table;
26663   std::vector<uint32_t> m_hash_table;
26664
26665   const bfd_endian m_dwarf5_byte_order;
26666   dwarf_tmpl<uint32_t> m_dwarf32;
26667   dwarf_tmpl<uint64_t> m_dwarf64;
26668   dwarf &m_dwarf;
26669   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26670   debug_str_lookup m_debugstrlookup;
26671
26672   /* Map each used .debug_names abbreviation tag parameter to its
26673      index value.  */
26674   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26675
26676   /* Next unused .debug_names abbreviation tag for
26677      m_indexkey_to_idx.  */
26678   int m_idx_next = 1;
26679
26680   /* .debug_names abbreviation table.  */
26681   data_buf m_abbrev_table;
26682
26683   /* .debug_names entry pool.  */
26684   data_buf m_entry_pool;
26685 };
26686
26687 /* Return iff any of the needed offsets does not fit into 32-bit
26688    .debug_names section.  */
26689
26690 static bool
26691 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26692 {
26693   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26694     {
26695       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26696
26697       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26698         return true;
26699     }
26700   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26701     {
26702       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26703       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26704
26705       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26706         return true;
26707     }
26708   return false;
26709 }
26710
26711 /* The psyms_seen set is potentially going to be largish (~40k
26712    elements when indexing a -g3 build of GDB itself).  Estimate the
26713    number of elements in order to avoid too many rehashes, which
26714    require rebuilding buckets and thus many trips to
26715    malloc/free.  */
26716
26717 static size_t
26718 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26719 {
26720   size_t psyms_count = 0;
26721   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26722     {
26723       struct dwarf2_per_cu_data *per_cu
26724         = dwarf2_per_objfile->all_comp_units[i];
26725       struct partial_symtab *psymtab = per_cu->v.psymtab;
26726
26727       if (psymtab != NULL && psymtab->user == NULL)
26728         recursively_count_psymbols (psymtab, psyms_count);
26729     }
26730   /* Generating an index for gdb itself shows a ratio of
26731      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26732   return psyms_count / 4;
26733 }
26734
26735 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26736    Return how many bytes were expected to be written into OUT_FILE.  */
26737
26738 static size_t
26739 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26740 {
26741   struct objfile *objfile = dwarf2_per_objfile->objfile;
26742   mapped_symtab symtab;
26743   data_buf cu_list;
26744
26745   /* While we're scanning CU's create a table that maps a psymtab pointer
26746      (which is what addrmap records) to its index (which is what is recorded
26747      in the index file).  This will later be needed to write the address
26748      table.  */
26749   psym_index_map cu_index_htab;
26750   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26751
26752   /* The CU list is already sorted, so we don't need to do additional
26753      work here.  Also, the debug_types entries do not appear in
26754      all_comp_units, but only in their own hash table.  */
26755
26756   std::unordered_set<partial_symbol *> psyms_seen
26757     (psyms_seen_size (dwarf2_per_objfile));
26758   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26759     {
26760       struct dwarf2_per_cu_data *per_cu
26761         = dwarf2_per_objfile->all_comp_units[i];
26762       struct partial_symtab *psymtab = per_cu->v.psymtab;
26763
26764       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26765          It may be referenced from a local scope but in such case it does not
26766          need to be present in .gdb_index.  */
26767       if (psymtab == NULL)
26768         continue;
26769
26770       if (psymtab->user == NULL)
26771         recursively_write_psymbols (objfile, psymtab, &symtab,
26772                                     psyms_seen, i);
26773
26774       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26775       gdb_assert (insertpair.second);
26776
26777       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26778                            to_underlying (per_cu->sect_off));
26779       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26780     }
26781
26782   /* Dump the address map.  */
26783   data_buf addr_vec;
26784   write_address_map (objfile, addr_vec, cu_index_htab);
26785
26786   /* Write out the .debug_type entries, if any.  */
26787   data_buf types_cu_list;
26788   if (dwarf2_per_objfile->signatured_types)
26789     {
26790       signatured_type_index_data sig_data (types_cu_list,
26791                                            psyms_seen);
26792
26793       sig_data.objfile = objfile;
26794       sig_data.symtab = &symtab;
26795       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26796       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26797                               write_one_signatured_type, &sig_data);
26798     }
26799
26800   /* Now that we've processed all symbols we can shrink their cu_indices
26801      lists.  */
26802   uniquify_cu_indices (&symtab);
26803
26804   data_buf symtab_vec, constant_pool;
26805   write_hash_table (&symtab, symtab_vec, constant_pool);
26806
26807   data_buf contents;
26808   const offset_type size_of_contents = 6 * sizeof (offset_type);
26809   offset_type total_len = size_of_contents;
26810
26811   /* The version number.  */
26812   contents.append_data (MAYBE_SWAP (8));
26813
26814   /* The offset of the CU list from the start of the file.  */
26815   contents.append_data (MAYBE_SWAP (total_len));
26816   total_len += cu_list.size ();
26817
26818   /* The offset of the types CU list from the start of the file.  */
26819   contents.append_data (MAYBE_SWAP (total_len));
26820   total_len += types_cu_list.size ();
26821
26822   /* The offset of the address table from the start of the file.  */
26823   contents.append_data (MAYBE_SWAP (total_len));
26824   total_len += addr_vec.size ();
26825
26826   /* The offset of the symbol table from the start of the file.  */
26827   contents.append_data (MAYBE_SWAP (total_len));
26828   total_len += symtab_vec.size ();
26829
26830   /* The offset of the constant pool from the start of the file.  */
26831   contents.append_data (MAYBE_SWAP (total_len));
26832   total_len += constant_pool.size ();
26833
26834   gdb_assert (contents.size () == size_of_contents);
26835
26836   contents.file_write (out_file);
26837   cu_list.file_write (out_file);
26838   types_cu_list.file_write (out_file);
26839   addr_vec.file_write (out_file);
26840   symtab_vec.file_write (out_file);
26841   constant_pool.file_write (out_file);
26842
26843   return total_len;
26844 }
26845
26846 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26847 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26848
26849 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26850    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26851    many bytes were expected to be written into OUT_FILE.  */
26852
26853 static size_t
26854 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26855                    FILE *out_file, FILE *out_file_str)
26856 {
26857   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26858   struct objfile *objfile = dwarf2_per_objfile->objfile;
26859   const enum bfd_endian dwarf5_byte_order
26860     = gdbarch_byte_order (get_objfile_arch (objfile));
26861
26862   /* The CU list is already sorted, so we don't need to do additional
26863      work here.  Also, the debug_types entries do not appear in
26864      all_comp_units, but only in their own hash table.  */
26865   data_buf cu_list;
26866   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26867                          dwarf5_byte_order);
26868   std::unordered_set<partial_symbol *>
26869     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26870   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26871     {
26872       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26873       partial_symtab *psymtab = per_cu->v.psymtab;
26874
26875       /* CU of a shared file from 'dwz -m' may be unused by this main
26876          file.  It may be referenced from a local scope but in such
26877          case it does not need to be present in .debug_names.  */
26878       if (psymtab == NULL)
26879         continue;
26880
26881       if (psymtab->user == NULL)
26882         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26883
26884       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26885                            to_underlying (per_cu->sect_off));
26886     }
26887
26888   /* Write out the .debug_type entries, if any.  */
26889   data_buf types_cu_list;
26890   if (dwarf2_per_objfile->signatured_types)
26891     {
26892       debug_names::write_one_signatured_type_data sig_data (nametable,
26893                         signatured_type_index_data (types_cu_list, psyms_seen));
26894
26895       sig_data.info.objfile = objfile;
26896       /* It is used only for gdb_index.  */
26897       sig_data.info.symtab = nullptr;
26898       sig_data.info.cu_index = 0;
26899       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26900                               debug_names::write_one_signatured_type,
26901                               &sig_data);
26902     }
26903
26904   nametable.build ();
26905
26906   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26907
26908   const offset_type bytes_of_header
26909     = ((dwarf5_is_dwarf64 ? 12 : 4)
26910        + 2 + 2 + 7 * 4
26911        + sizeof (dwarf5_gdb_augmentation));
26912   size_t expected_bytes = 0;
26913   expected_bytes += bytes_of_header;
26914   expected_bytes += cu_list.size ();
26915   expected_bytes += types_cu_list.size ();
26916   expected_bytes += nametable.bytes ();
26917   data_buf header;
26918
26919   if (!dwarf5_is_dwarf64)
26920     {
26921       const uint64_t size64 = expected_bytes - 4;
26922       gdb_assert (size64 < 0xfffffff0);
26923       header.append_uint (4, dwarf5_byte_order, size64);
26924     }
26925   else
26926     {
26927       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26928       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26929     }
26930
26931   /* The version number.  */
26932   header.append_uint (2, dwarf5_byte_order, 5);
26933
26934   /* Padding.  */
26935   header.append_uint (2, dwarf5_byte_order, 0);
26936
26937   /* comp_unit_count - The number of CUs in the CU list.  */
26938   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26939
26940   /* local_type_unit_count - The number of TUs in the local TU
26941      list.  */
26942   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26943
26944   /* foreign_type_unit_count - The number of TUs in the foreign TU
26945      list.  */
26946   header.append_uint (4, dwarf5_byte_order, 0);
26947
26948   /* bucket_count - The number of hash buckets in the hash lookup
26949      table.  */
26950   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26951
26952   /* name_count - The number of unique names in the index.  */
26953   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26954
26955   /* abbrev_table_size - The size in bytes of the abbreviations
26956      table.  */
26957   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26958
26959   /* augmentation_string_size - The size in bytes of the augmentation
26960      string.  This value is rounded up to a multiple of 4.  */
26961   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26962   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26963   header.append_data (dwarf5_gdb_augmentation);
26964
26965   gdb_assert (header.size () == bytes_of_header);
26966
26967   header.file_write (out_file);
26968   cu_list.file_write (out_file);
26969   types_cu_list.file_write (out_file);
26970   nametable.file_write (out_file, out_file_str);
26971
26972   return expected_bytes;
26973 }
26974
26975 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26976    position is at the end of the file.  */
26977
26978 static void
26979 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26980 {
26981   const auto file_size = ftell (file);
26982   if (file_size == -1)
26983     error (_("Can't get `%s' size"), filename);
26984   gdb_assert (file_size == expected_size);
26985 }
26986
26987 /* Create an index file for OBJFILE in the directory DIR.  */
26988
26989 static void
26990 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
26991                          const char *dir,
26992                          dw_index_kind index_kind)
26993 {
26994   struct objfile *objfile = dwarf2_per_objfile->objfile;
26995
26996   if (dwarf2_per_objfile->using_index)
26997     error (_("Cannot use an index to create the index"));
26998
26999   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27000     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27001
27002   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27003     return;
27004
27005   struct stat st;
27006   if (stat (objfile_name (objfile), &st) < 0)
27007     perror_with_name (objfile_name (objfile));
27008
27009   std::string filename (std::string (dir) + SLASH_STRING
27010                         + lbasename (objfile_name (objfile))
27011                         + (index_kind == dw_index_kind::DEBUG_NAMES
27012                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27013
27014   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27015   if (!out_file)
27016     error (_("Can't open `%s' for writing"), filename.c_str ());
27017
27018   /* Order matters here; we want FILE to be closed before FILENAME is
27019      unlinked, because on MS-Windows one cannot delete a file that is
27020      still open.  (Don't call anything here that might throw until
27021      file_closer is created.)  */
27022   gdb::unlinker unlink_file (filename.c_str ());
27023   gdb_file_up close_out_file (out_file);
27024
27025   if (index_kind == dw_index_kind::DEBUG_NAMES)
27026     {
27027       std::string filename_str (std::string (dir) + SLASH_STRING
27028                                 + lbasename (objfile_name (objfile))
27029                                 + DEBUG_STR_SUFFIX);
27030       FILE *out_file_str
27031         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27032       if (!out_file_str)
27033         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27034       gdb::unlinker unlink_file_str (filename_str.c_str ());
27035       gdb_file_up close_out_file_str (out_file_str);
27036
27037       const size_t total_len
27038         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27039       assert_file_size (out_file, filename.c_str (), total_len);
27040
27041       /* We want to keep the file .debug_str file too.  */
27042       unlink_file_str.keep ();
27043     }
27044   else
27045     {
27046       const size_t total_len
27047         = write_gdbindex (dwarf2_per_objfile, out_file);
27048       assert_file_size (out_file, filename.c_str (), total_len);
27049     }
27050
27051   /* We want to keep the file.  */
27052   unlink_file.keep ();
27053 }
27054
27055 /* Implementation of the `save gdb-index' command.
27056    
27057    Note that the .gdb_index file format used by this command is
27058    documented in the GDB manual.  Any changes here must be documented
27059    there.  */
27060
27061 static void
27062 save_gdb_index_command (const char *arg, int from_tty)
27063 {
27064   struct objfile *objfile;
27065   const char dwarf5space[] = "-dwarf-5 ";
27066   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27067
27068   if (!arg)
27069     arg = "";
27070
27071   arg = skip_spaces (arg);
27072   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27073     {
27074       index_kind = dw_index_kind::DEBUG_NAMES;
27075       arg += strlen (dwarf5space);
27076       arg = skip_spaces (arg);
27077     }
27078
27079   if (!*arg)
27080     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27081
27082   ALL_OBJFILES (objfile)
27083   {
27084     struct stat st;
27085
27086     /* If the objfile does not correspond to an actual file, skip it.  */
27087     if (stat (objfile_name (objfile), &st) < 0)
27088       continue;
27089
27090     struct dwarf2_per_objfile *dwarf2_per_objfile
27091       = get_dwarf2_per_objfile (objfile);
27092
27093     if (dwarf2_per_objfile != NULL)
27094       {
27095         TRY
27096           {
27097             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27098           }
27099         CATCH (except, RETURN_MASK_ERROR)
27100           {
27101             exception_fprintf (gdb_stderr, except,
27102                                _("Error while writing index for `%s': "),
27103                                objfile_name (objfile));
27104           }
27105         END_CATCH
27106       }
27107
27108   }
27109 }
27110
27111 \f
27112
27113 int dwarf_always_disassemble;
27114
27115 static void
27116 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27117                                struct cmd_list_element *c, const char *value)
27118 {
27119   fprintf_filtered (file,
27120                     _("Whether to always disassemble "
27121                       "DWARF expressions is %s.\n"),
27122                     value);
27123 }
27124
27125 static void
27126 show_check_physname (struct ui_file *file, int from_tty,
27127                      struct cmd_list_element *c, const char *value)
27128 {
27129   fprintf_filtered (file,
27130                     _("Whether to check \"physname\" is %s.\n"),
27131                     value);
27132 }
27133
27134 void
27135 _initialize_dwarf2_read (void)
27136 {
27137   struct cmd_list_element *c;
27138
27139   dwarf2_objfile_data_key
27140     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
27141
27142   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27143 Set DWARF specific variables.\n\
27144 Configure DWARF variables such as the cache size"),
27145                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27146                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27147
27148   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27149 Show DWARF specific variables\n\
27150 Show DWARF variables such as the cache size"),
27151                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27152                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27153
27154   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27155                             &dwarf_max_cache_age, _("\
27156 Set the upper bound on the age of cached DWARF compilation units."), _("\
27157 Show the upper bound on the age of cached DWARF compilation units."), _("\
27158 A higher limit means that cached compilation units will be stored\n\
27159 in memory longer, and more total memory will be used.  Zero disables\n\
27160 caching, which can slow down startup."),
27161                             NULL,
27162                             show_dwarf_max_cache_age,
27163                             &set_dwarf_cmdlist,
27164                             &show_dwarf_cmdlist);
27165
27166   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27167                            &dwarf_always_disassemble, _("\
27168 Set whether `info address' always disassembles DWARF expressions."), _("\
27169 Show whether `info address' always disassembles DWARF expressions."), _("\
27170 When enabled, DWARF expressions are always printed in an assembly-like\n\
27171 syntax.  When disabled, expressions will be printed in a more\n\
27172 conversational style, when possible."),
27173                            NULL,
27174                            show_dwarf_always_disassemble,
27175                            &set_dwarf_cmdlist,
27176                            &show_dwarf_cmdlist);
27177
27178   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27179 Set debugging of the DWARF reader."), _("\
27180 Show debugging of the DWARF reader."), _("\
27181 When enabled (non-zero), debugging messages are printed during DWARF\n\
27182 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27183 information.  A value greater than 1 provides more verbose information."),
27184                             NULL,
27185                             NULL,
27186                             &setdebuglist, &showdebuglist);
27187
27188   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27189 Set debugging of the DWARF DIE reader."), _("\
27190 Show debugging of the DWARF DIE reader."), _("\
27191 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27192 The value is the maximum depth to print."),
27193                              NULL,
27194                              NULL,
27195                              &setdebuglist, &showdebuglist);
27196
27197   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27198 Set debugging of the dwarf line reader."), _("\
27199 Show debugging of the dwarf line reader."), _("\
27200 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27201 A value of 1 (one) provides basic information.\n\
27202 A value greater than 1 provides more verbose information."),
27203                              NULL,
27204                              NULL,
27205                              &setdebuglist, &showdebuglist);
27206
27207   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27208 Set cross-checking of \"physname\" code against demangler."), _("\
27209 Show cross-checking of \"physname\" code against demangler."), _("\
27210 When enabled, GDB's internal \"physname\" code is checked against\n\
27211 the demangler."),
27212                            NULL, show_check_physname,
27213                            &setdebuglist, &showdebuglist);
27214
27215   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27216                            no_class, &use_deprecated_index_sections, _("\
27217 Set whether to use deprecated gdb_index sections."), _("\
27218 Show whether to use deprecated gdb_index sections."), _("\
27219 When enabled, deprecated .gdb_index sections are used anyway.\n\
27220 Normally they are ignored either because of a missing feature or\n\
27221 performance issue.\n\
27222 Warning: This option must be enabled before gdb reads the file."),
27223                            NULL,
27224                            NULL,
27225                            &setlist, &showlist);
27226
27227   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27228                _("\
27229 Save a gdb-index file.\n\
27230 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27231 \n\
27232 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27233 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27234 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27235                &save_cmdlist);
27236   set_cmd_completer (c, filename_completer);
27237
27238   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27239                                                         &dwarf2_locexpr_funcs);
27240   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27241                                                         &dwarf2_loclist_funcs);
27242
27243   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27244                                         &dwarf2_block_frame_base_locexpr_funcs);
27245   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27246                                         &dwarf2_block_frame_base_loclist_funcs);
27247
27248 #if GDB_SELF_TEST
27249   selftests::register_test ("dw2_expand_symtabs_matching",
27250                             selftests::dw2_expand_symtabs_matching::run_test);
27251 #endif
27252 }