Change find_partial_die_in_comp_unit to dwarf2_cu::find_partial_die
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 /* When == 1, print basic high level tracing messages.
91    When > 1, be more verbose.
92    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
93 static unsigned int dwarf_read_debug = 0;
94
95 /* When non-zero, dump DIEs after they are read in.  */
96 static unsigned int dwarf_die_debug = 0;
97
98 /* When non-zero, dump line number entries as they are read in.  */
99 static unsigned int dwarf_line_debug = 0;
100
101 /* When non-zero, cross-check physname against demangler.  */
102 static int check_physname = 0;
103
104 /* When non-zero, do not reject deprecated .gdb_index sections.  */
105 static int use_deprecated_index_sections = 0;
106
107 static const struct objfile_data *dwarf2_objfile_data_key;
108
109 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
110
111 static int dwarf2_locexpr_index;
112 static int dwarf2_loclist_index;
113 static int dwarf2_locexpr_block_index;
114 static int dwarf2_loclist_block_index;
115
116 /* A descriptor for dwarf sections.
117
118    S.ASECTION, SIZE are typically initialized when the objfile is first
119    scanned.  BUFFER, READIN are filled in later when the section is read.
120    If the section contained compressed data then SIZE is updated to record
121    the uncompressed size of the section.
122
123    DWP file format V2 introduces a wrinkle that is easiest to handle by
124    creating the concept of virtual sections contained within a real section.
125    In DWP V2 the sections of the input DWO files are concatenated together
126    into one section, but section offsets are kept relative to the original
127    input section.
128    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
129    the real section this "virtual" section is contained in, and BUFFER,SIZE
130    describe the virtual section.  */
131
132 struct dwarf2_section_info
133 {
134   union
135   {
136     /* If this is a real section, the bfd section.  */
137     asection *section;
138     /* If this is a virtual section, pointer to the containing ("real")
139        section.  */
140     struct dwarf2_section_info *containing_section;
141   } s;
142   /* Pointer to section data, only valid if readin.  */
143   const gdb_byte *buffer;
144   /* The size of the section, real or virtual.  */
145   bfd_size_type size;
146   /* If this is a virtual section, the offset in the real section.
147      Only valid if is_virtual.  */
148   bfd_size_type virtual_offset;
149   /* True if we have tried to read this section.  */
150   char readin;
151   /* True if this is a virtual section, False otherwise.
152      This specifies which of s.section and s.containing_section to use.  */
153   char is_virtual;
154 };
155
156 typedef struct dwarf2_section_info dwarf2_section_info_def;
157 DEF_VEC_O (dwarf2_section_info_def);
158
159 /* All offsets in the index are of this type.  It must be
160    architecture-independent.  */
161 typedef uint32_t offset_type;
162
163 DEF_VEC_I (offset_type);
164
165 /* Ensure only legit values are used.  */
166 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
167   do { \
168     gdb_assert ((unsigned int) (value) <= 1); \
169     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
170   } while (0)
171
172 /* Ensure only legit values are used.  */
173 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
174   do { \
175     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
176                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
177     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
178   } while (0)
179
180 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
181 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
182   do { \
183     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
184     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
185   } while (0)
186
187 #if WORDS_BIGENDIAN
188
189 /* Convert VALUE between big- and little-endian.  */
190
191 static offset_type
192 byte_swap (offset_type value)
193 {
194   offset_type result;
195
196   result = (value & 0xff) << 24;
197   result |= (value & 0xff00) << 8;
198   result |= (value & 0xff0000) >> 8;
199   result |= (value & 0xff000000) >> 24;
200   return result;
201 }
202
203 #define MAYBE_SWAP(V)  byte_swap (V)
204
205 #else
206 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
207 #endif /* WORDS_BIGENDIAN */
208
209 /* An index into a (C++) symbol name component in a symbol name as
210    recorded in the mapped_index's symbol table.  For each C++ symbol
211    in the symbol table, we record one entry for the start of each
212    component in the symbol in a table of name components, and then
213    sort the table, in order to be able to binary search symbol names,
214    ignoring leading namespaces, both completion and regular look up.
215    For example, for symbol "A::B::C", we'll have an entry that points
216    to "A::B::C", another that points to "B::C", and another for "C".
217    Note that function symbols in GDB index have no parameter
218    information, just the function/method names.  You can convert a
219    name_component to a "const char *" using the
220    'mapped_index::symbol_name_at(offset_type)' method.  */
221
222 struct name_component
223 {
224   /* Offset in the symbol name where the component starts.  Stored as
225      a (32-bit) offset instead of a pointer to save memory and improve
226      locality on 64-bit architectures.  */
227   offset_type name_offset;
228
229   /* The symbol's index in the symbol and constant pool tables of a
230      mapped_index.  */
231   offset_type idx;
232 };
233
234 /* Base class containing bits shared by both .gdb_index and
235    .debug_name indexes.  */
236
237 struct mapped_index_base
238 {
239   /* The name_component table (a sorted vector).  See name_component's
240      description above.  */
241   std::vector<name_component> name_components;
242
243   /* How NAME_COMPONENTS is sorted.  */
244   enum case_sensitivity name_components_casing;
245
246   /* Return the number of names in the symbol table.  */
247   virtual size_t symbol_name_count () const = 0;
248
249   /* Get the name of the symbol at IDX in the symbol table.  */
250   virtual const char *symbol_name_at (offset_type idx) const = 0;
251
252   /* Return whether the name at IDX in the symbol table should be
253      ignored.  */
254   virtual bool symbol_name_slot_invalid (offset_type idx) const
255   {
256     return false;
257   }
258
259   /* Build the symbol name component sorted vector, if we haven't
260      yet.  */
261   void build_name_components ();
262
263   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
264      possible matches for LN_NO_PARAMS in the name component
265      vector.  */
266   std::pair<std::vector<name_component>::const_iterator,
267             std::vector<name_component>::const_iterator>
268     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
269
270   /* Prevent deleting/destroying via a base class pointer.  */
271 protected:
272   ~mapped_index_base() = default;
273 };
274
275 /* A description of the mapped index.  The file format is described in
276    a comment by the code that writes the index.  */
277 struct mapped_index final : public mapped_index_base
278 {
279   /* A slot/bucket in the symbol table hash.  */
280   struct symbol_table_slot
281   {
282     const offset_type name;
283     const offset_type vec;
284   };
285
286   /* Index data format version.  */
287   int version;
288
289   /* The total length of the buffer.  */
290   off_t total_size;
291
292   /* The address table data.  */
293   gdb::array_view<const gdb_byte> address_table;
294
295   /* The symbol table, implemented as a hash table.  */
296   gdb::array_view<symbol_table_slot> symbol_table;
297
298   /* A pointer to the constant pool.  */
299   const char *constant_pool;
300
301   bool symbol_name_slot_invalid (offset_type idx) const override
302   {
303     const auto &bucket = this->symbol_table[idx];
304     return bucket.name == 0 && bucket.vec;
305   }
306
307   /* Convenience method to get at the name of the symbol at IDX in the
308      symbol table.  */
309   const char *symbol_name_at (offset_type idx) const override
310   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
311
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size (); }
314 };
315
316 /* A description of the mapped .debug_names.
317    Uninitialized map has CU_COUNT 0.  */
318 struct mapped_debug_names final : public mapped_index_base
319 {
320   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
321   : dwarf2_per_objfile (dwarf2_per_objfile_)
322   {}
323
324   struct dwarf2_per_objfile *dwarf2_per_objfile;
325   bfd_endian dwarf5_byte_order;
326   bool dwarf5_is_dwarf64;
327   bool augmentation_is_gdb;
328   uint8_t offset_size;
329   uint32_t cu_count = 0;
330   uint32_t tu_count, bucket_count, name_count;
331   const gdb_byte *cu_table_reordered, *tu_table_reordered;
332   const uint32_t *bucket_table_reordered, *hash_table_reordered;
333   const gdb_byte *name_table_string_offs_reordered;
334   const gdb_byte *name_table_entry_offs_reordered;
335   const gdb_byte *entry_pool;
336
337   struct index_val
338   {
339     ULONGEST dwarf_tag;
340     struct attr
341     {
342       /* Attribute name DW_IDX_*.  */
343       ULONGEST dw_idx;
344
345       /* Attribute form DW_FORM_*.  */
346       ULONGEST form;
347
348       /* Value if FORM is DW_FORM_implicit_const.  */
349       LONGEST implicit_const;
350     };
351     std::vector<attr> attr_vec;
352   };
353
354   std::unordered_map<ULONGEST, index_val> abbrev_map;
355
356   const char *namei_to_name (uint32_t namei) const;
357
358   /* Implementation of the mapped_index_base virtual interface, for
359      the name_components cache.  */
360
361   const char *symbol_name_at (offset_type idx) const override
362   { return namei_to_name (idx); }
363
364   size_t symbol_name_count () const override
365   { return this->name_count; }
366 };
367
368 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
369 DEF_VEC_P (dwarf2_per_cu_ptr);
370
371 struct tu_stats
372 {
373   int nr_uniq_abbrev_tables;
374   int nr_symtabs;
375   int nr_symtab_sharers;
376   int nr_stmt_less_type_units;
377   int nr_all_type_units_reallocs;
378 };
379
380 /* Collection of data recorded per objfile.
381    This hangs off of dwarf2_objfile_data_key.  */
382
383 struct dwarf2_per_objfile : public allocate_on_obstack
384 {
385   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
386      dwarf2 section names, or is NULL if the standard ELF names are
387      used.  */
388   dwarf2_per_objfile (struct objfile *objfile,
389                       const dwarf2_debug_sections *names);
390
391   ~dwarf2_per_objfile ();
392
393   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
394
395   /* Free all cached compilation units.  */
396   void free_cached_comp_units ();
397 private:
398   /* This function is mapped across the sections and remembers the
399      offset and size of each of the debugging sections we are
400      interested in.  */
401   void locate_sections (bfd *abfd, asection *sectp,
402                         const dwarf2_debug_sections &names);
403
404 public:
405   dwarf2_section_info info {};
406   dwarf2_section_info abbrev {};
407   dwarf2_section_info line {};
408   dwarf2_section_info loc {};
409   dwarf2_section_info loclists {};
410   dwarf2_section_info macinfo {};
411   dwarf2_section_info macro {};
412   dwarf2_section_info str {};
413   dwarf2_section_info line_str {};
414   dwarf2_section_info ranges {};
415   dwarf2_section_info rnglists {};
416   dwarf2_section_info addr {};
417   dwarf2_section_info frame {};
418   dwarf2_section_info eh_frame {};
419   dwarf2_section_info gdb_index {};
420   dwarf2_section_info debug_names {};
421   dwarf2_section_info debug_aranges {};
422
423   VEC (dwarf2_section_info_def) *types = NULL;
424
425   /* Back link.  */
426   struct objfile *objfile = NULL;
427
428   /* Table of all the compilation units.  This is used to locate
429      the target compilation unit of a particular reference.  */
430   struct dwarf2_per_cu_data **all_comp_units = NULL;
431
432   /* The number of compilation units in ALL_COMP_UNITS.  */
433   int n_comp_units = 0;
434
435   /* The number of .debug_types-related CUs.  */
436   int n_type_units = 0;
437
438   /* The number of elements allocated in all_type_units.
439      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
440   int n_allocated_type_units = 0;
441
442   /* The .debug_types-related CUs (TUs).
443      This is stored in malloc space because we may realloc it.  */
444   struct signatured_type **all_type_units = NULL;
445
446   /* Table of struct type_unit_group objects.
447      The hash key is the DW_AT_stmt_list value.  */
448   htab_t type_unit_groups {};
449
450   /* A table mapping .debug_types signatures to its signatured_type entry.
451      This is NULL if the .debug_types section hasn't been read in yet.  */
452   htab_t signatured_types {};
453
454   /* Type unit statistics, to see how well the scaling improvements
455      are doing.  */
456   struct tu_stats tu_stats {};
457
458   /* A chain of compilation units that are currently read in, so that
459      they can be freed later.  */
460   dwarf2_per_cu_data *read_in_chain = NULL;
461
462   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
463      This is NULL if the table hasn't been allocated yet.  */
464   htab_t dwo_files {};
465
466   /* True if we've checked for whether there is a DWP file.  */
467   bool dwp_checked = false;
468
469   /* The DWP file if there is one, or NULL.  */
470   struct dwp_file *dwp_file = NULL;
471
472   /* The shared '.dwz' file, if one exists.  This is used when the
473      original data was compressed using 'dwz -m'.  */
474   struct dwz_file *dwz_file = NULL;
475
476   /* A flag indicating whether this objfile has a section loaded at a
477      VMA of 0.  */
478   bool has_section_at_zero = false;
479
480   /* True if we are using the mapped index,
481      or we are faking it for OBJF_READNOW's sake.  */
482   bool using_index = false;
483
484   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
485   mapped_index *index_table = NULL;
486
487   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
488   std::unique_ptr<mapped_debug_names> debug_names_table;
489
490   /* When using index_table, this keeps track of all quick_file_names entries.
491      TUs typically share line table entries with a CU, so we maintain a
492      separate table of all line table entries to support the sharing.
493      Note that while there can be way more TUs than CUs, we've already
494      sorted all the TUs into "type unit groups", grouped by their
495      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
496      CU and its associated TU group if there is one.  */
497   htab_t quick_file_names_table {};
498
499   /* Set during partial symbol reading, to prevent queueing of full
500      symbols.  */
501   bool reading_partial_symbols = false;
502
503   /* Table mapping type DIEs to their struct type *.
504      This is NULL if not allocated yet.
505      The mapping is done via (CU/TU + DIE offset) -> type.  */
506   htab_t die_type_hash {};
507
508   /* The CUs we recently read.  */
509   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
510
511   /* Table containing line_header indexed by offset and offset_in_dwz.  */
512   htab_t line_header_hash {};
513
514   /* Table containing all filenames.  This is an optional because the
515      table is lazily constructed on first access.  */
516   gdb::optional<filename_seen_cache> filenames_cache;
517 };
518
519 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
520
521 struct dwarf2_per_objfile *
522 get_dwarf2_per_objfile (struct objfile *objfile)
523 {
524   return ((struct dwarf2_per_objfile *)
525           objfile_data (objfile, dwarf2_objfile_data_key));
526 }
527
528 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
529
530 void
531 set_dwarf2_per_objfile (struct objfile *objfile,
532                         struct dwarf2_per_objfile *dwarf2_per_objfile)
533 {
534   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
535   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
536 }
537
538 /* Default names of the debugging sections.  */
539
540 /* Note that if the debugging section has been compressed, it might
541    have a name like .zdebug_info.  */
542
543 static const struct dwarf2_debug_sections dwarf2_elf_names =
544 {
545   { ".debug_info", ".zdebug_info" },
546   { ".debug_abbrev", ".zdebug_abbrev" },
547   { ".debug_line", ".zdebug_line" },
548   { ".debug_loc", ".zdebug_loc" },
549   { ".debug_loclists", ".zdebug_loclists" },
550   { ".debug_macinfo", ".zdebug_macinfo" },
551   { ".debug_macro", ".zdebug_macro" },
552   { ".debug_str", ".zdebug_str" },
553   { ".debug_line_str", ".zdebug_line_str" },
554   { ".debug_ranges", ".zdebug_ranges" },
555   { ".debug_rnglists", ".zdebug_rnglists" },
556   { ".debug_types", ".zdebug_types" },
557   { ".debug_addr", ".zdebug_addr" },
558   { ".debug_frame", ".zdebug_frame" },
559   { ".eh_frame", NULL },
560   { ".gdb_index", ".zgdb_index" },
561   { ".debug_names", ".zdebug_names" },
562   { ".debug_aranges", ".zdebug_aranges" },
563   23
564 };
565
566 /* List of DWO/DWP sections.  */
567
568 static const struct dwop_section_names
569 {
570   struct dwarf2_section_names abbrev_dwo;
571   struct dwarf2_section_names info_dwo;
572   struct dwarf2_section_names line_dwo;
573   struct dwarf2_section_names loc_dwo;
574   struct dwarf2_section_names loclists_dwo;
575   struct dwarf2_section_names macinfo_dwo;
576   struct dwarf2_section_names macro_dwo;
577   struct dwarf2_section_names str_dwo;
578   struct dwarf2_section_names str_offsets_dwo;
579   struct dwarf2_section_names types_dwo;
580   struct dwarf2_section_names cu_index;
581   struct dwarf2_section_names tu_index;
582 }
583 dwop_section_names =
584 {
585   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
586   { ".debug_info.dwo", ".zdebug_info.dwo" },
587   { ".debug_line.dwo", ".zdebug_line.dwo" },
588   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
589   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
590   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
591   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
592   { ".debug_str.dwo", ".zdebug_str.dwo" },
593   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
594   { ".debug_types.dwo", ".zdebug_types.dwo" },
595   { ".debug_cu_index", ".zdebug_cu_index" },
596   { ".debug_tu_index", ".zdebug_tu_index" },
597 };
598
599 /* local data types */
600
601 /* The data in a compilation unit header, after target2host
602    translation, looks like this.  */
603 struct comp_unit_head
604 {
605   unsigned int length;
606   short version;
607   unsigned char addr_size;
608   unsigned char signed_addr_p;
609   sect_offset abbrev_sect_off;
610
611   /* Size of file offsets; either 4 or 8.  */
612   unsigned int offset_size;
613
614   /* Size of the length field; either 4 or 12.  */
615   unsigned int initial_length_size;
616
617   enum dwarf_unit_type unit_type;
618
619   /* Offset to the first byte of this compilation unit header in the
620      .debug_info section, for resolving relative reference dies.  */
621   sect_offset sect_off;
622
623   /* Offset to first die in this cu from the start of the cu.
624      This will be the first byte following the compilation unit header.  */
625   cu_offset first_die_cu_offset;
626
627   /* 64-bit signature of this type unit - it is valid only for
628      UNIT_TYPE DW_UT_type.  */
629   ULONGEST signature;
630
631   /* For types, offset in the type's DIE of the type defined by this TU.  */
632   cu_offset type_cu_offset_in_tu;
633 };
634
635 /* Type used for delaying computation of method physnames.
636    See comments for compute_delayed_physnames.  */
637 struct delayed_method_info
638 {
639   /* The type to which the method is attached, i.e., its parent class.  */
640   struct type *type;
641
642   /* The index of the method in the type's function fieldlists.  */
643   int fnfield_index;
644
645   /* The index of the method in the fieldlist.  */
646   int index;
647
648   /* The name of the DIE.  */
649   const char *name;
650
651   /*  The DIE associated with this method.  */
652   struct die_info *die;
653 };
654
655 /* Internal state when decoding a particular compilation unit.  */
656 struct dwarf2_cu
657 {
658   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
659   ~dwarf2_cu ();
660
661   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
662
663   /* The header of the compilation unit.  */
664   struct comp_unit_head header {};
665
666   /* Base address of this compilation unit.  */
667   CORE_ADDR base_address = 0;
668
669   /* Non-zero if base_address has been set.  */
670   int base_known = 0;
671
672   /* The language we are debugging.  */
673   enum language language = language_unknown;
674   const struct language_defn *language_defn = nullptr;
675
676   const char *producer = nullptr;
677
678   /* The generic symbol table building routines have separate lists for
679      file scope symbols and all all other scopes (local scopes).  So
680      we need to select the right one to pass to add_symbol_to_list().
681      We do it by keeping a pointer to the correct list in list_in_scope.
682
683      FIXME: The original dwarf code just treated the file scope as the
684      first local scope, and all other local scopes as nested local
685      scopes, and worked fine.  Check to see if we really need to
686      distinguish these in buildsym.c.  */
687   struct pending **list_in_scope = nullptr;
688
689   /* Hash table holding all the loaded partial DIEs
690      with partial_die->offset.SECT_OFF as hash.  */
691   htab_t partial_dies = nullptr;
692
693   /* Storage for things with the same lifetime as this read-in compilation
694      unit, including partial DIEs.  */
695   auto_obstack comp_unit_obstack;
696
697   /* When multiple dwarf2_cu structures are living in memory, this field
698      chains them all together, so that they can be released efficiently.
699      We will probably also want a generation counter so that most-recently-used
700      compilation units are cached...  */
701   struct dwarf2_per_cu_data *read_in_chain = nullptr;
702
703   /* Backlink to our per_cu entry.  */
704   struct dwarf2_per_cu_data *per_cu;
705
706   /* How many compilation units ago was this CU last referenced?  */
707   int last_used = 0;
708
709   /* A hash table of DIE cu_offset for following references with
710      die_info->offset.sect_off as hash.  */
711   htab_t die_hash = nullptr;
712
713   /* Full DIEs if read in.  */
714   struct die_info *dies = nullptr;
715
716   /* A set of pointers to dwarf2_per_cu_data objects for compilation
717      units referenced by this one.  Only set during full symbol processing;
718      partial symbol tables do not have dependencies.  */
719   htab_t dependencies = nullptr;
720
721   /* Header data from the line table, during full symbol processing.  */
722   struct line_header *line_header = nullptr;
723   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
724      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
725      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
726      to the line header as long as this DIE is being processed.  See
727      process_die_scope.  */
728   die_info *line_header_die_owner = nullptr;
729
730   /* A list of methods which need to have physnames computed
731      after all type information has been read.  */
732   std::vector<delayed_method_info> method_list;
733
734   /* To be copied to symtab->call_site_htab.  */
735   htab_t call_site_htab = nullptr;
736
737   /* Non-NULL if this CU came from a DWO file.
738      There is an invariant here that is important to remember:
739      Except for attributes copied from the top level DIE in the "main"
740      (or "stub") file in preparation for reading the DWO file
741      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
742      Either there isn't a DWO file (in which case this is NULL and the point
743      is moot), or there is and either we're not going to read it (in which
744      case this is NULL) or there is and we are reading it (in which case this
745      is non-NULL).  */
746   struct dwo_unit *dwo_unit = nullptr;
747
748   /* The DW_AT_addr_base attribute if present, zero otherwise
749      (zero is a valid value though).
750      Note this value comes from the Fission stub CU/TU's DIE.  */
751   ULONGEST addr_base = 0;
752
753   /* The DW_AT_ranges_base attribute if present, zero otherwise
754      (zero is a valid value though).
755      Note this value comes from the Fission stub CU/TU's DIE.
756      Also note that the value is zero in the non-DWO case so this value can
757      be used without needing to know whether DWO files are in use or not.
758      N.B. This does not apply to DW_AT_ranges appearing in
759      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
760      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
761      DW_AT_ranges_base *would* have to be applied, and we'd have to care
762      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
763   ULONGEST ranges_base = 0;
764
765   /* Mark used when releasing cached dies.  */
766   unsigned int mark : 1;
767
768   /* This CU references .debug_loc.  See the symtab->locations_valid field.
769      This test is imperfect as there may exist optimized debug code not using
770      any location list and still facing inlining issues if handled as
771      unoptimized code.  For a future better test see GCC PR other/32998.  */
772   unsigned int has_loclist : 1;
773
774   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
775      if all the producer_is_* fields are valid.  This information is cached
776      because profiling CU expansion showed excessive time spent in
777      producer_is_gxx_lt_4_6.  */
778   unsigned int checked_producer : 1;
779   unsigned int producer_is_gxx_lt_4_6 : 1;
780   unsigned int producer_is_gcc_lt_4_3 : 1;
781   unsigned int producer_is_icc_lt_14 : 1;
782
783   /* When set, the file that we're processing is known to have
784      debugging info for C++ namespaces.  GCC 3.3.x did not produce
785      this information, but later versions do.  */
786
787   unsigned int processing_has_namespace_info : 1;
788
789   struct partial_die_info *find_partial_die (sect_offset sect_off);
790 };
791
792 /* Persistent data held for a compilation unit, even when not
793    processing it.  We put a pointer to this structure in the
794    read_symtab_private field of the psymtab.  */
795
796 struct dwarf2_per_cu_data
797 {
798   /* The start offset and length of this compilation unit.
799      NOTE: Unlike comp_unit_head.length, this length includes
800      initial_length_size.
801      If the DIE refers to a DWO file, this is always of the original die,
802      not the DWO file.  */
803   sect_offset sect_off;
804   unsigned int length;
805
806   /* DWARF standard version this data has been read from (such as 4 or 5).  */
807   short dwarf_version;
808
809   /* Flag indicating this compilation unit will be read in before
810      any of the current compilation units are processed.  */
811   unsigned int queued : 1;
812
813   /* This flag will be set when reading partial DIEs if we need to load
814      absolutely all DIEs for this compilation unit, instead of just the ones
815      we think are interesting.  It gets set if we look for a DIE in the
816      hash table and don't find it.  */
817   unsigned int load_all_dies : 1;
818
819   /* Non-zero if this CU is from .debug_types.
820      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
821      this is non-zero.  */
822   unsigned int is_debug_types : 1;
823
824   /* Non-zero if this CU is from the .dwz file.  */
825   unsigned int is_dwz : 1;
826
827   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
828      This flag is only valid if is_debug_types is true.
829      We can't read a CU directly from a DWO file: There are required
830      attributes in the stub.  */
831   unsigned int reading_dwo_directly : 1;
832
833   /* Non-zero if the TU has been read.
834      This is used to assist the "Stay in DWO Optimization" for Fission:
835      When reading a DWO, it's faster to read TUs from the DWO instead of
836      fetching them from random other DWOs (due to comdat folding).
837      If the TU has already been read, the optimization is unnecessary
838      (and unwise - we don't want to change where gdb thinks the TU lives
839      "midflight").
840      This flag is only valid if is_debug_types is true.  */
841   unsigned int tu_read : 1;
842
843   /* The section this CU/TU lives in.
844      If the DIE refers to a DWO file, this is always the original die,
845      not the DWO file.  */
846   struct dwarf2_section_info *section;
847
848   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
849      of the CU cache it gets reset to NULL again.  This is left as NULL for
850      dummy CUs (a CU header, but nothing else).  */
851   struct dwarf2_cu *cu;
852
853   /* The corresponding dwarf2_per_objfile.  */
854   struct dwarf2_per_objfile *dwarf2_per_objfile;
855
856   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
857      is active.  Otherwise, the 'psymtab' field is active.  */
858   union
859   {
860     /* The partial symbol table associated with this compilation unit,
861        or NULL for unread partial units.  */
862     struct partial_symtab *psymtab;
863
864     /* Data needed by the "quick" functions.  */
865     struct dwarf2_per_cu_quick_data *quick;
866   } v;
867
868   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
869      while reading psymtabs, used to compute the psymtab dependencies,
870      and then cleared.  Then it is filled in again while reading full
871      symbols, and only deleted when the objfile is destroyed.
872
873      This is also used to work around a difference between the way gold
874      generates .gdb_index version <=7 and the way gdb does.  Arguably this
875      is a gold bug.  For symbols coming from TUs, gold records in the index
876      the CU that includes the TU instead of the TU itself.  This breaks
877      dw2_lookup_symbol: It assumes that if the index says symbol X lives
878      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
879      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
880      we need to look in TU Z to find X.  Fortunately, this is akin to
881      DW_TAG_imported_unit, so we just use the same mechanism: For
882      .gdb_index version <=7 this also records the TUs that the CU referred
883      to.  Concurrently with this change gdb was modified to emit version 8
884      indices so we only pay a price for gold generated indices.
885      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
886   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
887 };
888
889 /* Entry in the signatured_types hash table.  */
890
891 struct signatured_type
892 {
893   /* The "per_cu" object of this type.
894      This struct is used iff per_cu.is_debug_types.
895      N.B.: This is the first member so that it's easy to convert pointers
896      between them.  */
897   struct dwarf2_per_cu_data per_cu;
898
899   /* The type's signature.  */
900   ULONGEST signature;
901
902   /* Offset in the TU of the type's DIE, as read from the TU header.
903      If this TU is a DWO stub and the definition lives in a DWO file
904      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
905   cu_offset type_offset_in_tu;
906
907   /* Offset in the section of the type's DIE.
908      If the definition lives in a DWO file, this is the offset in the
909      .debug_types.dwo section.
910      The value is zero until the actual value is known.
911      Zero is otherwise not a valid section offset.  */
912   sect_offset type_offset_in_section;
913
914   /* Type units are grouped by their DW_AT_stmt_list entry so that they
915      can share them.  This points to the containing symtab.  */
916   struct type_unit_group *type_unit_group;
917
918   /* The type.
919      The first time we encounter this type we fully read it in and install it
920      in the symbol tables.  Subsequent times we only need the type.  */
921   struct type *type;
922
923   /* Containing DWO unit.
924      This field is valid iff per_cu.reading_dwo_directly.  */
925   struct dwo_unit *dwo_unit;
926 };
927
928 typedef struct signatured_type *sig_type_ptr;
929 DEF_VEC_P (sig_type_ptr);
930
931 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
932    This includes type_unit_group and quick_file_names.  */
933
934 struct stmt_list_hash
935 {
936   /* The DWO unit this table is from or NULL if there is none.  */
937   struct dwo_unit *dwo_unit;
938
939   /* Offset in .debug_line or .debug_line.dwo.  */
940   sect_offset line_sect_off;
941 };
942
943 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
944    an object of this type.  */
945
946 struct type_unit_group
947 {
948   /* dwarf2read.c's main "handle" on a TU symtab.
949      To simplify things we create an artificial CU that "includes" all the
950      type units using this stmt_list so that the rest of the code still has
951      a "per_cu" handle on the symtab.
952      This PER_CU is recognized by having no section.  */
953 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
954   struct dwarf2_per_cu_data per_cu;
955
956   /* The TUs that share this DW_AT_stmt_list entry.
957      This is added to while parsing type units to build partial symtabs,
958      and is deleted afterwards and not used again.  */
959   VEC (sig_type_ptr) *tus;
960
961   /* The compunit symtab.
962      Type units in a group needn't all be defined in the same source file,
963      so we create an essentially anonymous symtab as the compunit symtab.  */
964   struct compunit_symtab *compunit_symtab;
965
966   /* The data used to construct the hash key.  */
967   struct stmt_list_hash hash;
968
969   /* The number of symtabs from the line header.
970      The value here must match line_header.num_file_names.  */
971   unsigned int num_symtabs;
972
973   /* The symbol tables for this TU (obtained from the files listed in
974      DW_AT_stmt_list).
975      WARNING: The order of entries here must match the order of entries
976      in the line header.  After the first TU using this type_unit_group, the
977      line header for the subsequent TUs is recreated from this.  This is done
978      because we need to use the same symtabs for each TU using the same
979      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
980      there's no guarantee the line header doesn't have duplicate entries.  */
981   struct symtab **symtabs;
982 };
983
984 /* These sections are what may appear in a (real or virtual) DWO file.  */
985
986 struct dwo_sections
987 {
988   struct dwarf2_section_info abbrev;
989   struct dwarf2_section_info line;
990   struct dwarf2_section_info loc;
991   struct dwarf2_section_info loclists;
992   struct dwarf2_section_info macinfo;
993   struct dwarf2_section_info macro;
994   struct dwarf2_section_info str;
995   struct dwarf2_section_info str_offsets;
996   /* In the case of a virtual DWO file, these two are unused.  */
997   struct dwarf2_section_info info;
998   VEC (dwarf2_section_info_def) *types;
999 };
1000
1001 /* CUs/TUs in DWP/DWO files.  */
1002
1003 struct dwo_unit
1004 {
1005   /* Backlink to the containing struct dwo_file.  */
1006   struct dwo_file *dwo_file;
1007
1008   /* The "id" that distinguishes this CU/TU.
1009      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1010      Since signatures came first, we stick with it for consistency.  */
1011   ULONGEST signature;
1012
1013   /* The section this CU/TU lives in, in the DWO file.  */
1014   struct dwarf2_section_info *section;
1015
1016   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1017   sect_offset sect_off;
1018   unsigned int length;
1019
1020   /* For types, offset in the type's DIE of the type defined by this TU.  */
1021   cu_offset type_offset_in_tu;
1022 };
1023
1024 /* include/dwarf2.h defines the DWP section codes.
1025    It defines a max value but it doesn't define a min value, which we
1026    use for error checking, so provide one.  */
1027
1028 enum dwp_v2_section_ids
1029 {
1030   DW_SECT_MIN = 1
1031 };
1032
1033 /* Data for one DWO file.
1034
1035    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1036    appears in a DWP file).  DWP files don't really have DWO files per se -
1037    comdat folding of types "loses" the DWO file they came from, and from
1038    a high level view DWP files appear to contain a mass of random types.
1039    However, to maintain consistency with the non-DWP case we pretend DWP
1040    files contain virtual DWO files, and we assign each TU with one virtual
1041    DWO file (generally based on the line and abbrev section offsets -
1042    a heuristic that seems to work in practice).  */
1043
1044 struct dwo_file
1045 {
1046   /* The DW_AT_GNU_dwo_name attribute.
1047      For virtual DWO files the name is constructed from the section offsets
1048      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1049      from related CU+TUs.  */
1050   const char *dwo_name;
1051
1052   /* The DW_AT_comp_dir attribute.  */
1053   const char *comp_dir;
1054
1055   /* The bfd, when the file is open.  Otherwise this is NULL.
1056      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1057   bfd *dbfd;
1058
1059   /* The sections that make up this DWO file.
1060      Remember that for virtual DWO files in DWP V2, these are virtual
1061      sections (for lack of a better name).  */
1062   struct dwo_sections sections;
1063
1064   /* The CUs in the file.
1065      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1066      an extension to handle LLVM's Link Time Optimization output (where
1067      multiple source files may be compiled into a single object/dwo pair). */
1068   htab_t cus;
1069
1070   /* Table of TUs in the file.
1071      Each element is a struct dwo_unit.  */
1072   htab_t tus;
1073 };
1074
1075 /* These sections are what may appear in a DWP file.  */
1076
1077 struct dwp_sections
1078 {
1079   /* These are used by both DWP version 1 and 2.  */
1080   struct dwarf2_section_info str;
1081   struct dwarf2_section_info cu_index;
1082   struct dwarf2_section_info tu_index;
1083
1084   /* These are only used by DWP version 2 files.
1085      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1086      sections are referenced by section number, and are not recorded here.
1087      In DWP version 2 there is at most one copy of all these sections, each
1088      section being (effectively) comprised of the concatenation of all of the
1089      individual sections that exist in the version 1 format.
1090      To keep the code simple we treat each of these concatenated pieces as a
1091      section itself (a virtual section?).  */
1092   struct dwarf2_section_info abbrev;
1093   struct dwarf2_section_info info;
1094   struct dwarf2_section_info line;
1095   struct dwarf2_section_info loc;
1096   struct dwarf2_section_info macinfo;
1097   struct dwarf2_section_info macro;
1098   struct dwarf2_section_info str_offsets;
1099   struct dwarf2_section_info types;
1100 };
1101
1102 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1103    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1104
1105 struct virtual_v1_dwo_sections
1106 {
1107   struct dwarf2_section_info abbrev;
1108   struct dwarf2_section_info line;
1109   struct dwarf2_section_info loc;
1110   struct dwarf2_section_info macinfo;
1111   struct dwarf2_section_info macro;
1112   struct dwarf2_section_info str_offsets;
1113   /* Each DWP hash table entry records one CU or one TU.
1114      That is recorded here, and copied to dwo_unit.section.  */
1115   struct dwarf2_section_info info_or_types;
1116 };
1117
1118 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1119    In version 2, the sections of the DWO files are concatenated together
1120    and stored in one section of that name.  Thus each ELF section contains
1121    several "virtual" sections.  */
1122
1123 struct virtual_v2_dwo_sections
1124 {
1125   bfd_size_type abbrev_offset;
1126   bfd_size_type abbrev_size;
1127
1128   bfd_size_type line_offset;
1129   bfd_size_type line_size;
1130
1131   bfd_size_type loc_offset;
1132   bfd_size_type loc_size;
1133
1134   bfd_size_type macinfo_offset;
1135   bfd_size_type macinfo_size;
1136
1137   bfd_size_type macro_offset;
1138   bfd_size_type macro_size;
1139
1140   bfd_size_type str_offsets_offset;
1141   bfd_size_type str_offsets_size;
1142
1143   /* Each DWP hash table entry records one CU or one TU.
1144      That is recorded here, and copied to dwo_unit.section.  */
1145   bfd_size_type info_or_types_offset;
1146   bfd_size_type info_or_types_size;
1147 };
1148
1149 /* Contents of DWP hash tables.  */
1150
1151 struct dwp_hash_table
1152 {
1153   uint32_t version, nr_columns;
1154   uint32_t nr_units, nr_slots;
1155   const gdb_byte *hash_table, *unit_table;
1156   union
1157   {
1158     struct
1159     {
1160       const gdb_byte *indices;
1161     } v1;
1162     struct
1163     {
1164       /* This is indexed by column number and gives the id of the section
1165          in that column.  */
1166 #define MAX_NR_V2_DWO_SECTIONS \
1167   (1 /* .debug_info or .debug_types */ \
1168    + 1 /* .debug_abbrev */ \
1169    + 1 /* .debug_line */ \
1170    + 1 /* .debug_loc */ \
1171    + 1 /* .debug_str_offsets */ \
1172    + 1 /* .debug_macro or .debug_macinfo */)
1173       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1174       const gdb_byte *offsets;
1175       const gdb_byte *sizes;
1176     } v2;
1177   } section_pool;
1178 };
1179
1180 /* Data for one DWP file.  */
1181
1182 struct dwp_file
1183 {
1184   /* Name of the file.  */
1185   const char *name;
1186
1187   /* File format version.  */
1188   int version;
1189
1190   /* The bfd.  */
1191   bfd *dbfd;
1192
1193   /* Section info for this file.  */
1194   struct dwp_sections sections;
1195
1196   /* Table of CUs in the file.  */
1197   const struct dwp_hash_table *cus;
1198
1199   /* Table of TUs in the file.  */
1200   const struct dwp_hash_table *tus;
1201
1202   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1203   htab_t loaded_cus;
1204   htab_t loaded_tus;
1205
1206   /* Table to map ELF section numbers to their sections.
1207      This is only needed for the DWP V1 file format.  */
1208   unsigned int num_sections;
1209   asection **elf_sections;
1210 };
1211
1212 /* This represents a '.dwz' file.  */
1213
1214 struct dwz_file
1215 {
1216   /* A dwz file can only contain a few sections.  */
1217   struct dwarf2_section_info abbrev;
1218   struct dwarf2_section_info info;
1219   struct dwarf2_section_info str;
1220   struct dwarf2_section_info line;
1221   struct dwarf2_section_info macro;
1222   struct dwarf2_section_info gdb_index;
1223   struct dwarf2_section_info debug_names;
1224
1225   /* The dwz's BFD.  */
1226   bfd *dwz_bfd;
1227 };
1228
1229 /* Struct used to pass misc. parameters to read_die_and_children, et
1230    al.  which are used for both .debug_info and .debug_types dies.
1231    All parameters here are unchanging for the life of the call.  This
1232    struct exists to abstract away the constant parameters of die reading.  */
1233
1234 struct die_reader_specs
1235 {
1236   /* The bfd of die_section.  */
1237   bfd* abfd;
1238
1239   /* The CU of the DIE we are parsing.  */
1240   struct dwarf2_cu *cu;
1241
1242   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1243   struct dwo_file *dwo_file;
1244
1245   /* The section the die comes from.
1246      This is either .debug_info or .debug_types, or the .dwo variants.  */
1247   struct dwarf2_section_info *die_section;
1248
1249   /* die_section->buffer.  */
1250   const gdb_byte *buffer;
1251
1252   /* The end of the buffer.  */
1253   const gdb_byte *buffer_end;
1254
1255   /* The value of the DW_AT_comp_dir attribute.  */
1256   const char *comp_dir;
1257
1258   /* The abbreviation table to use when reading the DIEs.  */
1259   struct abbrev_table *abbrev_table;
1260 };
1261
1262 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1263 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1264                                       const gdb_byte *info_ptr,
1265                                       struct die_info *comp_unit_die,
1266                                       int has_children,
1267                                       void *data);
1268
1269 /* A 1-based directory index.  This is a strong typedef to prevent
1270    accidentally using a directory index as a 0-based index into an
1271    array/vector.  */
1272 enum class dir_index : unsigned int {};
1273
1274 /* Likewise, a 1-based file name index.  */
1275 enum class file_name_index : unsigned int {};
1276
1277 struct file_entry
1278 {
1279   file_entry () = default;
1280
1281   file_entry (const char *name_, dir_index d_index_,
1282               unsigned int mod_time_, unsigned int length_)
1283     : name (name_),
1284       d_index (d_index_),
1285       mod_time (mod_time_),
1286       length (length_)
1287   {}
1288
1289   /* Return the include directory at D_INDEX stored in LH.  Returns
1290      NULL if D_INDEX is out of bounds.  */
1291   const char *include_dir (const line_header *lh) const;
1292
1293   /* The file name.  Note this is an observing pointer.  The memory is
1294      owned by debug_line_buffer.  */
1295   const char *name {};
1296
1297   /* The directory index (1-based).  */
1298   dir_index d_index {};
1299
1300   unsigned int mod_time {};
1301
1302   unsigned int length {};
1303
1304   /* True if referenced by the Line Number Program.  */
1305   bool included_p {};
1306
1307   /* The associated symbol table, if any.  */
1308   struct symtab *symtab {};
1309 };
1310
1311 /* The line number information for a compilation unit (found in the
1312    .debug_line section) begins with a "statement program header",
1313    which contains the following information.  */
1314 struct line_header
1315 {
1316   line_header ()
1317     : offset_in_dwz {}
1318   {}
1319
1320   /* Add an entry to the include directory table.  */
1321   void add_include_dir (const char *include_dir);
1322
1323   /* Add an entry to the file name table.  */
1324   void add_file_name (const char *name, dir_index d_index,
1325                       unsigned int mod_time, unsigned int length);
1326
1327   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1328      is out of bounds.  */
1329   const char *include_dir_at (dir_index index) const
1330   {
1331     /* Convert directory index number (1-based) to vector index
1332        (0-based).  */
1333     size_t vec_index = to_underlying (index) - 1;
1334
1335     if (vec_index >= include_dirs.size ())
1336       return NULL;
1337     return include_dirs[vec_index];
1338   }
1339
1340   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1341      is out of bounds.  */
1342   file_entry *file_name_at (file_name_index index)
1343   {
1344     /* Convert file name index number (1-based) to vector index
1345        (0-based).  */
1346     size_t vec_index = to_underlying (index) - 1;
1347
1348     if (vec_index >= file_names.size ())
1349       return NULL;
1350     return &file_names[vec_index];
1351   }
1352
1353   /* Const version of the above.  */
1354   const file_entry *file_name_at (unsigned int index) const
1355   {
1356     if (index >= file_names.size ())
1357       return NULL;
1358     return &file_names[index];
1359   }
1360
1361   /* Offset of line number information in .debug_line section.  */
1362   sect_offset sect_off {};
1363
1364   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1365   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1366
1367   unsigned int total_length {};
1368   unsigned short version {};
1369   unsigned int header_length {};
1370   unsigned char minimum_instruction_length {};
1371   unsigned char maximum_ops_per_instruction {};
1372   unsigned char default_is_stmt {};
1373   int line_base {};
1374   unsigned char line_range {};
1375   unsigned char opcode_base {};
1376
1377   /* standard_opcode_lengths[i] is the number of operands for the
1378      standard opcode whose value is i.  This means that
1379      standard_opcode_lengths[0] is unused, and the last meaningful
1380      element is standard_opcode_lengths[opcode_base - 1].  */
1381   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1382
1383   /* The include_directories table.  Note these are observing
1384      pointers.  The memory is owned by debug_line_buffer.  */
1385   std::vector<const char *> include_dirs;
1386
1387   /* The file_names table.  */
1388   std::vector<file_entry> file_names;
1389
1390   /* The start and end of the statement program following this
1391      header.  These point into dwarf2_per_objfile->line_buffer.  */
1392   const gdb_byte *statement_program_start {}, *statement_program_end {};
1393 };
1394
1395 typedef std::unique_ptr<line_header> line_header_up;
1396
1397 const char *
1398 file_entry::include_dir (const line_header *lh) const
1399 {
1400   return lh->include_dir_at (d_index);
1401 }
1402
1403 /* When we construct a partial symbol table entry we only
1404    need this much information.  */
1405 struct partial_die_info
1406   {
1407     /* Offset of this DIE.  */
1408     sect_offset sect_off;
1409
1410     /* DWARF-2 tag for this DIE.  */
1411     ENUM_BITFIELD(dwarf_tag) tag : 16;
1412
1413     /* Assorted flags describing the data found in this DIE.  */
1414     unsigned int has_children : 1;
1415     unsigned int is_external : 1;
1416     unsigned int is_declaration : 1;
1417     unsigned int has_type : 1;
1418     unsigned int has_specification : 1;
1419     unsigned int has_pc_info : 1;
1420     unsigned int may_be_inlined : 1;
1421
1422     /* This DIE has been marked DW_AT_main_subprogram.  */
1423     unsigned int main_subprogram : 1;
1424
1425     /* Flag set if the SCOPE field of this structure has been
1426        computed.  */
1427     unsigned int scope_set : 1;
1428
1429     /* Flag set if the DIE has a byte_size attribute.  */
1430     unsigned int has_byte_size : 1;
1431
1432     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1433     unsigned int has_const_value : 1;
1434
1435     /* Flag set if any of the DIE's children are template arguments.  */
1436     unsigned int has_template_arguments : 1;
1437
1438     /* Flag set if fixup_partial_die has been called on this die.  */
1439     unsigned int fixup_called : 1;
1440
1441     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1442     unsigned int is_dwz : 1;
1443
1444     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1445     unsigned int spec_is_dwz : 1;
1446
1447     /* The name of this DIE.  Normally the value of DW_AT_name, but
1448        sometimes a default name for unnamed DIEs.  */
1449     const char *name;
1450
1451     /* The linkage name, if present.  */
1452     const char *linkage_name;
1453
1454     /* The scope to prepend to our children.  This is generally
1455        allocated on the comp_unit_obstack, so will disappear
1456        when this compilation unit leaves the cache.  */
1457     const char *scope;
1458
1459     /* Some data associated with the partial DIE.  The tag determines
1460        which field is live.  */
1461     union
1462     {
1463       /* The location description associated with this DIE, if any.  */
1464       struct dwarf_block *locdesc;
1465       /* The offset of an import, for DW_TAG_imported_unit.  */
1466       sect_offset sect_off;
1467     } d;
1468
1469     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1470     CORE_ADDR lowpc;
1471     CORE_ADDR highpc;
1472
1473     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1474        DW_AT_sibling, if any.  */
1475     /* NOTE: This member isn't strictly necessary, read_partial_die could
1476        return DW_AT_sibling values to its caller load_partial_dies.  */
1477     const gdb_byte *sibling;
1478
1479     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1480        DW_AT_specification (or DW_AT_abstract_origin or
1481        DW_AT_extension).  */
1482     sect_offset spec_offset;
1483
1484     /* Pointers to this DIE's parent, first child, and next sibling,
1485        if any.  */
1486     struct partial_die_info *die_parent, *die_child, *die_sibling;
1487   };
1488
1489 /* This data structure holds the information of an abbrev.  */
1490 struct abbrev_info
1491   {
1492     unsigned int number;        /* number identifying abbrev */
1493     enum dwarf_tag tag;         /* dwarf tag */
1494     unsigned short has_children;                /* boolean */
1495     unsigned short num_attrs;   /* number of attributes */
1496     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1497     struct abbrev_info *next;   /* next in chain */
1498   };
1499
1500 struct attr_abbrev
1501   {
1502     ENUM_BITFIELD(dwarf_attribute) name : 16;
1503     ENUM_BITFIELD(dwarf_form) form : 16;
1504
1505     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1506     LONGEST implicit_const;
1507   };
1508
1509 /* Size of abbrev_table.abbrev_hash_table.  */
1510 #define ABBREV_HASH_SIZE 121
1511
1512 /* Top level data structure to contain an abbreviation table.  */
1513
1514 struct abbrev_table
1515 {
1516   explicit abbrev_table (sect_offset off)
1517     : sect_off (off)
1518   {
1519     m_abbrevs =
1520       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1521     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1522   }
1523
1524   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1525
1526   /* Allocate space for a struct abbrev_info object in
1527      ABBREV_TABLE.  */
1528   struct abbrev_info *alloc_abbrev ();
1529
1530   /* Add an abbreviation to the table.  */
1531   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1532
1533   /* Look up an abbrev in the table.
1534      Returns NULL if the abbrev is not found.  */
1535
1536   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1537
1538
1539   /* Where the abbrev table came from.
1540      This is used as a sanity check when the table is used.  */
1541   const sect_offset sect_off;
1542
1543   /* Storage for the abbrev table.  */
1544   auto_obstack abbrev_obstack;
1545
1546 private:
1547
1548   /* Hash table of abbrevs.
1549      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1550      It could be statically allocated, but the previous code didn't so we
1551      don't either.  */
1552   struct abbrev_info **m_abbrevs;
1553 };
1554
1555 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1556
1557 /* Attributes have a name and a value.  */
1558 struct attribute
1559   {
1560     ENUM_BITFIELD(dwarf_attribute) name : 16;
1561     ENUM_BITFIELD(dwarf_form) form : 15;
1562
1563     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1564        field should be in u.str (existing only for DW_STRING) but it is kept
1565        here for better struct attribute alignment.  */
1566     unsigned int string_is_canonical : 1;
1567
1568     union
1569       {
1570         const char *str;
1571         struct dwarf_block *blk;
1572         ULONGEST unsnd;
1573         LONGEST snd;
1574         CORE_ADDR addr;
1575         ULONGEST signature;
1576       }
1577     u;
1578   };
1579
1580 /* This data structure holds a complete die structure.  */
1581 struct die_info
1582   {
1583     /* DWARF-2 tag for this DIE.  */
1584     ENUM_BITFIELD(dwarf_tag) tag : 16;
1585
1586     /* Number of attributes */
1587     unsigned char num_attrs;
1588
1589     /* True if we're presently building the full type name for the
1590        type derived from this DIE.  */
1591     unsigned char building_fullname : 1;
1592
1593     /* True if this die is in process.  PR 16581.  */
1594     unsigned char in_process : 1;
1595
1596     /* Abbrev number */
1597     unsigned int abbrev;
1598
1599     /* Offset in .debug_info or .debug_types section.  */
1600     sect_offset sect_off;
1601
1602     /* The dies in a compilation unit form an n-ary tree.  PARENT
1603        points to this die's parent; CHILD points to the first child of
1604        this node; and all the children of a given node are chained
1605        together via their SIBLING fields.  */
1606     struct die_info *child;     /* Its first child, if any.  */
1607     struct die_info *sibling;   /* Its next sibling, if any.  */
1608     struct die_info *parent;    /* Its parent, if any.  */
1609
1610     /* An array of attributes, with NUM_ATTRS elements.  There may be
1611        zero, but it's not common and zero-sized arrays are not
1612        sufficiently portable C.  */
1613     struct attribute attrs[1];
1614   };
1615
1616 /* Get at parts of an attribute structure.  */
1617
1618 #define DW_STRING(attr)    ((attr)->u.str)
1619 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1620 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1621 #define DW_BLOCK(attr)     ((attr)->u.blk)
1622 #define DW_SND(attr)       ((attr)->u.snd)
1623 #define DW_ADDR(attr)      ((attr)->u.addr)
1624 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1625
1626 /* Blocks are a bunch of untyped bytes.  */
1627 struct dwarf_block
1628   {
1629     size_t size;
1630
1631     /* Valid only if SIZE is not zero.  */
1632     const gdb_byte *data;
1633   };
1634
1635 #ifndef ATTR_ALLOC_CHUNK
1636 #define ATTR_ALLOC_CHUNK 4
1637 #endif
1638
1639 /* Allocate fields for structs, unions and enums in this size.  */
1640 #ifndef DW_FIELD_ALLOC_CHUNK
1641 #define DW_FIELD_ALLOC_CHUNK 4
1642 #endif
1643
1644 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1645    but this would require a corresponding change in unpack_field_as_long
1646    and friends.  */
1647 static int bits_per_byte = 8;
1648
1649 struct nextfield
1650 {
1651   struct nextfield *next;
1652   int accessibility;
1653   int virtuality;
1654   struct field field;
1655 };
1656
1657 struct nextfnfield
1658 {
1659   struct nextfnfield *next;
1660   struct fn_field fnfield;
1661 };
1662
1663 struct fnfieldlist
1664 {
1665   const char *name;
1666   int length;
1667   struct nextfnfield *head;
1668 };
1669
1670 struct decl_field_list
1671 {
1672   struct decl_field field;
1673   struct decl_field_list *next;
1674 };
1675
1676 /* The routines that read and process dies for a C struct or C++ class
1677    pass lists of data member fields and lists of member function fields
1678    in an instance of a field_info structure, as defined below.  */
1679 struct field_info
1680   {
1681     /* List of data member and baseclasses fields.  */
1682     struct nextfield *fields, *baseclasses;
1683
1684     /* Number of fields (including baseclasses).  */
1685     int nfields;
1686
1687     /* Number of baseclasses.  */
1688     int nbaseclasses;
1689
1690     /* Set if the accesibility of one of the fields is not public.  */
1691     int non_public_fields;
1692
1693     /* Member function fieldlist array, contains name of possibly overloaded
1694        member function, number of overloaded member functions and a pointer
1695        to the head of the member function field chain.  */
1696     struct fnfieldlist *fnfieldlists;
1697
1698     /* Number of entries in the fnfieldlists array.  */
1699     int nfnfields;
1700
1701     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1702        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1703     struct decl_field_list *typedef_field_list;
1704     unsigned typedef_field_list_count;
1705
1706     /* Nested types defined by this class and the number of elements in this
1707        list.  */
1708     struct decl_field_list *nested_types_list;
1709     unsigned nested_types_list_count;
1710   };
1711
1712 /* One item on the queue of compilation units to read in full symbols
1713    for.  */
1714 struct dwarf2_queue_item
1715 {
1716   struct dwarf2_per_cu_data *per_cu;
1717   enum language pretend_language;
1718   struct dwarf2_queue_item *next;
1719 };
1720
1721 /* The current queue.  */
1722 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1723
1724 /* Loaded secondary compilation units are kept in memory until they
1725    have not been referenced for the processing of this many
1726    compilation units.  Set this to zero to disable caching.  Cache
1727    sizes of up to at least twenty will improve startup time for
1728    typical inter-CU-reference binaries, at an obvious memory cost.  */
1729 static int dwarf_max_cache_age = 5;
1730 static void
1731 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1732                           struct cmd_list_element *c, const char *value)
1733 {
1734   fprintf_filtered (file, _("The upper bound on the age of cached "
1735                             "DWARF compilation units is %s.\n"),
1736                     value);
1737 }
1738 \f
1739 /* local function prototypes */
1740
1741 static const char *get_section_name (const struct dwarf2_section_info *);
1742
1743 static const char *get_section_file_name (const struct dwarf2_section_info *);
1744
1745 static void dwarf2_find_base_address (struct die_info *die,
1746                                       struct dwarf2_cu *cu);
1747
1748 static struct partial_symtab *create_partial_symtab
1749   (struct dwarf2_per_cu_data *per_cu, const char *name);
1750
1751 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1752                                         const gdb_byte *info_ptr,
1753                                         struct die_info *type_unit_die,
1754                                         int has_children, void *data);
1755
1756 static void dwarf2_build_psymtabs_hard
1757   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1758
1759 static void scan_partial_symbols (struct partial_die_info *,
1760                                   CORE_ADDR *, CORE_ADDR *,
1761                                   int, struct dwarf2_cu *);
1762
1763 static void add_partial_symbol (struct partial_die_info *,
1764                                 struct dwarf2_cu *);
1765
1766 static void add_partial_namespace (struct partial_die_info *pdi,
1767                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1768                                    int set_addrmap, struct dwarf2_cu *cu);
1769
1770 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1771                                 CORE_ADDR *highpc, int set_addrmap,
1772                                 struct dwarf2_cu *cu);
1773
1774 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1775                                      struct dwarf2_cu *cu);
1776
1777 static void add_partial_subprogram (struct partial_die_info *pdi,
1778                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1779                                     int need_pc, struct dwarf2_cu *cu);
1780
1781 static void dwarf2_read_symtab (struct partial_symtab *,
1782                                 struct objfile *);
1783
1784 static void psymtab_to_symtab_1 (struct partial_symtab *);
1785
1786 static abbrev_table_up abbrev_table_read_table
1787   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1788    sect_offset);
1789
1790 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1791
1792 static struct partial_die_info *load_partial_dies
1793   (const struct die_reader_specs *, const gdb_byte *, int);
1794
1795 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1796                                          struct partial_die_info *,
1797                                          const struct abbrev_info &,
1798                                          unsigned int,
1799                                          const gdb_byte *);
1800
1801 static struct partial_die_info *find_partial_die (sect_offset, int,
1802                                                   struct dwarf2_cu *);
1803
1804 static void fixup_partial_die (struct partial_die_info *,
1805                                struct dwarf2_cu *);
1806
1807 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1808                                        struct attribute *, struct attr_abbrev *,
1809                                        const gdb_byte *);
1810
1811 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1812
1813 static int read_1_signed_byte (bfd *, const gdb_byte *);
1814
1815 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1816
1817 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1818
1819 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1820
1821 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1822                                unsigned int *);
1823
1824 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1825
1826 static LONGEST read_checked_initial_length_and_offset
1827   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1828    unsigned int *, unsigned int *);
1829
1830 static LONGEST read_offset (bfd *, const gdb_byte *,
1831                             const struct comp_unit_head *,
1832                             unsigned int *);
1833
1834 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1835
1836 static sect_offset read_abbrev_offset
1837   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1838    struct dwarf2_section_info *, sect_offset);
1839
1840 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1841
1842 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1843
1844 static const char *read_indirect_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_line_string
1849   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1850    const struct comp_unit_head *, unsigned int *);
1851
1852 static const char *read_indirect_string_at_offset
1853   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1854    LONGEST str_offset);
1855
1856 static const char *read_indirect_string_from_dwz
1857   (struct objfile *objfile, struct dwz_file *, LONGEST);
1858
1859 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1860
1861 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1862                                               const gdb_byte *,
1863                                               unsigned int *);
1864
1865 static const char *read_str_index (const struct die_reader_specs *reader,
1866                                    ULONGEST str_index);
1867
1868 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1869
1870 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1871                                       struct dwarf2_cu *);
1872
1873 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1874                                                 unsigned int);
1875
1876 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1877                                        struct dwarf2_cu *cu);
1878
1879 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1880                                struct dwarf2_cu *cu);
1881
1882 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1883
1884 static struct die_info *die_specification (struct die_info *die,
1885                                            struct dwarf2_cu **);
1886
1887 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1888                                                 struct dwarf2_cu *cu);
1889
1890 static void dwarf_decode_lines (struct line_header *, const char *,
1891                                 struct dwarf2_cu *, struct partial_symtab *,
1892                                 CORE_ADDR, int decode_mapping);
1893
1894 static void dwarf2_start_subfile (const char *, const char *);
1895
1896 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1897                                                     const char *, const char *,
1898                                                     CORE_ADDR);
1899
1900 static struct symbol *new_symbol (struct die_info *, struct type *,
1901                                   struct dwarf2_cu *, struct symbol * = NULL);
1902
1903 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1904                                 struct dwarf2_cu *);
1905
1906 static void dwarf2_const_value_attr (const struct attribute *attr,
1907                                      struct type *type,
1908                                      const char *name,
1909                                      struct obstack *obstack,
1910                                      struct dwarf2_cu *cu, LONGEST *value,
1911                                      const gdb_byte **bytes,
1912                                      struct dwarf2_locexpr_baton **baton);
1913
1914 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1915
1916 static int need_gnat_info (struct dwarf2_cu *);
1917
1918 static struct type *die_descriptive_type (struct die_info *,
1919                                           struct dwarf2_cu *);
1920
1921 static void set_descriptive_type (struct type *, struct die_info *,
1922                                   struct dwarf2_cu *);
1923
1924 static struct type *die_containing_type (struct die_info *,
1925                                          struct dwarf2_cu *);
1926
1927 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1928                                      struct dwarf2_cu *);
1929
1930 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1931
1932 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1933
1934 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1935
1936 static char *typename_concat (struct obstack *obs, const char *prefix,
1937                               const char *suffix, int physname,
1938                               struct dwarf2_cu *cu);
1939
1940 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1941
1942 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1943
1944 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1945
1946 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1947
1948 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1949
1950 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1951
1952 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1953                                struct dwarf2_cu *, struct partial_symtab *);
1954
1955 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1956    values.  Keep the items ordered with increasing constraints compliance.  */
1957 enum pc_bounds_kind
1958 {
1959   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1960   PC_BOUNDS_NOT_PRESENT,
1961
1962   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1963      were present but they do not form a valid range of PC addresses.  */
1964   PC_BOUNDS_INVALID,
1965
1966   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1967   PC_BOUNDS_RANGES,
1968
1969   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1970   PC_BOUNDS_HIGH_LOW,
1971 };
1972
1973 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1974                                                  CORE_ADDR *, CORE_ADDR *,
1975                                                  struct dwarf2_cu *,
1976                                                  struct partial_symtab *);
1977
1978 static void get_scope_pc_bounds (struct die_info *,
1979                                  CORE_ADDR *, CORE_ADDR *,
1980                                  struct dwarf2_cu *);
1981
1982 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1983                                         CORE_ADDR, struct dwarf2_cu *);
1984
1985 static void dwarf2_add_field (struct field_info *, struct die_info *,
1986                               struct dwarf2_cu *);
1987
1988 static void dwarf2_attach_fields_to_type (struct field_info *,
1989                                           struct type *, struct dwarf2_cu *);
1990
1991 static void dwarf2_add_member_fn (struct field_info *,
1992                                   struct die_info *, struct type *,
1993                                   struct dwarf2_cu *);
1994
1995 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1996                                              struct type *,
1997                                              struct dwarf2_cu *);
1998
1999 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
2000
2001 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2002
2003 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2004
2005 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2006
2007 static struct using_direct **using_directives (enum language);
2008
2009 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2010
2011 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2012
2013 static struct type *read_module_type (struct die_info *die,
2014                                       struct dwarf2_cu *cu);
2015
2016 static const char *namespace_name (struct die_info *die,
2017                                    int *is_anonymous, struct dwarf2_cu *);
2018
2019 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2020
2021 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2022
2023 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2024                                                        struct dwarf2_cu *);
2025
2026 static struct die_info *read_die_and_siblings_1
2027   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2028    struct die_info *);
2029
2030 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2031                                                const gdb_byte *info_ptr,
2032                                                const gdb_byte **new_info_ptr,
2033                                                struct die_info *parent);
2034
2035 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2036                                         struct die_info **, const gdb_byte *,
2037                                         int *, int);
2038
2039 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2040                                       struct die_info **, const gdb_byte *,
2041                                       int *);
2042
2043 static void process_die (struct die_info *, struct dwarf2_cu *);
2044
2045 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2046                                              struct obstack *);
2047
2048 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2049
2050 static const char *dwarf2_full_name (const char *name,
2051                                      struct die_info *die,
2052                                      struct dwarf2_cu *cu);
2053
2054 static const char *dwarf2_physname (const char *name, struct die_info *die,
2055                                     struct dwarf2_cu *cu);
2056
2057 static struct die_info *dwarf2_extension (struct die_info *die,
2058                                           struct dwarf2_cu **);
2059
2060 static const char *dwarf_tag_name (unsigned int);
2061
2062 static const char *dwarf_attr_name (unsigned int);
2063
2064 static const char *dwarf_form_name (unsigned int);
2065
2066 static const char *dwarf_bool_name (unsigned int);
2067
2068 static const char *dwarf_type_encoding_name (unsigned int);
2069
2070 static struct die_info *sibling_die (struct die_info *);
2071
2072 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2073
2074 static void dump_die_for_error (struct die_info *);
2075
2076 static void dump_die_1 (struct ui_file *, int level, int max_level,
2077                         struct die_info *);
2078
2079 /*static*/ void dump_die (struct die_info *, int max_level);
2080
2081 static void store_in_ref_table (struct die_info *,
2082                                 struct dwarf2_cu *);
2083
2084 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2085
2086 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2087
2088 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2089                                                const struct attribute *,
2090                                                struct dwarf2_cu **);
2091
2092 static struct die_info *follow_die_ref (struct die_info *,
2093                                         const struct attribute *,
2094                                         struct dwarf2_cu **);
2095
2096 static struct die_info *follow_die_sig (struct die_info *,
2097                                         const struct attribute *,
2098                                         struct dwarf2_cu **);
2099
2100 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2101                                          struct dwarf2_cu *);
2102
2103 static struct type *get_DW_AT_signature_type (struct die_info *,
2104                                               const struct attribute *,
2105                                               struct dwarf2_cu *);
2106
2107 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2108
2109 static void read_signatured_type (struct signatured_type *);
2110
2111 static int attr_to_dynamic_prop (const struct attribute *attr,
2112                                  struct die_info *die, struct dwarf2_cu *cu,
2113                                  struct dynamic_prop *prop);
2114
2115 /* memory allocation interface */
2116
2117 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2118
2119 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2120
2121 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2122
2123 static int attr_form_is_block (const struct attribute *);
2124
2125 static int attr_form_is_section_offset (const struct attribute *);
2126
2127 static int attr_form_is_constant (const struct attribute *);
2128
2129 static int attr_form_is_ref (const struct attribute *);
2130
2131 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2132                                    struct dwarf2_loclist_baton *baton,
2133                                    const struct attribute *attr);
2134
2135 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2136                                          struct symbol *sym,
2137                                          struct dwarf2_cu *cu,
2138                                          int is_block);
2139
2140 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2141                                      const gdb_byte *info_ptr,
2142                                      struct abbrev_info *abbrev);
2143
2144 static hashval_t partial_die_hash (const void *item);
2145
2146 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2147
2148 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2149   (sect_offset sect_off, unsigned int offset_in_dwz,
2150    struct dwarf2_per_objfile *dwarf2_per_objfile);
2151
2152 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2153                                    struct die_info *comp_unit_die,
2154                                    enum language pretend_language);
2155
2156 static void free_cached_comp_units (void *);
2157
2158 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2159
2160 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2161
2162 static struct type *set_die_type (struct die_info *, struct type *,
2163                                   struct dwarf2_cu *);
2164
2165 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2166
2167 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2168
2169 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2170                                  enum language);
2171
2172 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2173                                     enum language);
2174
2175 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2176                                     enum language);
2177
2178 static void dwarf2_add_dependence (struct dwarf2_cu *,
2179                                    struct dwarf2_per_cu_data *);
2180
2181 static void dwarf2_mark (struct dwarf2_cu *);
2182
2183 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2184
2185 static struct type *get_die_type_at_offset (sect_offset,
2186                                             struct dwarf2_per_cu_data *);
2187
2188 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2189
2190 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2191                              enum language pretend_language);
2192
2193 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2194
2195 /* Class, the destructor of which frees all allocated queue entries.  This
2196    will only have work to do if an error was thrown while processing the
2197    dwarf.  If no error was thrown then the queue entries should have all
2198    been processed, and freed, as we went along.  */
2199
2200 class dwarf2_queue_guard
2201 {
2202 public:
2203   dwarf2_queue_guard () = default;
2204
2205   /* Free any entries remaining on the queue.  There should only be
2206      entries left if we hit an error while processing the dwarf.  */
2207   ~dwarf2_queue_guard ()
2208   {
2209     struct dwarf2_queue_item *item, *last;
2210
2211     item = dwarf2_queue;
2212     while (item)
2213       {
2214         /* Anything still marked queued is likely to be in an
2215            inconsistent state, so discard it.  */
2216         if (item->per_cu->queued)
2217           {
2218             if (item->per_cu->cu != NULL)
2219               free_one_cached_comp_unit (item->per_cu);
2220             item->per_cu->queued = 0;
2221           }
2222
2223         last = item;
2224         item = item->next;
2225         xfree (last);
2226       }
2227
2228     dwarf2_queue = dwarf2_queue_tail = NULL;
2229   }
2230 };
2231
2232 /* The return type of find_file_and_directory.  Note, the enclosed
2233    string pointers are only valid while this object is valid.  */
2234
2235 struct file_and_directory
2236 {
2237   /* The filename.  This is never NULL.  */
2238   const char *name;
2239
2240   /* The compilation directory.  NULL if not known.  If we needed to
2241      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2242      points directly to the DW_AT_comp_dir string attribute owned by
2243      the obstack that owns the DIE.  */
2244   const char *comp_dir;
2245
2246   /* If we needed to build a new string for comp_dir, this is what
2247      owns the storage.  */
2248   std::string comp_dir_storage;
2249 };
2250
2251 static file_and_directory find_file_and_directory (struct die_info *die,
2252                                                    struct dwarf2_cu *cu);
2253
2254 static char *file_full_name (int file, struct line_header *lh,
2255                              const char *comp_dir);
2256
2257 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2258 enum class rcuh_kind { COMPILE, TYPE };
2259
2260 static const gdb_byte *read_and_check_comp_unit_head
2261   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2262    struct comp_unit_head *header,
2263    struct dwarf2_section_info *section,
2264    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2265    rcuh_kind section_kind);
2266
2267 static void init_cutu_and_read_dies
2268   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2269    int use_existing_cu, int keep,
2270    die_reader_func_ftype *die_reader_func, void *data);
2271
2272 static void init_cutu_and_read_dies_simple
2273   (struct dwarf2_per_cu_data *this_cu,
2274    die_reader_func_ftype *die_reader_func, void *data);
2275
2276 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2277
2278 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2279
2280 static struct dwo_unit *lookup_dwo_unit_in_dwp
2281   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2282    struct dwp_file *dwp_file, const char *comp_dir,
2283    ULONGEST signature, int is_debug_types);
2284
2285 static struct dwp_file *get_dwp_file
2286   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2287
2288 static struct dwo_unit *lookup_dwo_comp_unit
2289   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2290
2291 static struct dwo_unit *lookup_dwo_type_unit
2292   (struct signatured_type *, const char *, const char *);
2293
2294 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2295
2296 static void free_dwo_file_cleanup (void *);
2297
2298 struct free_dwo_file_cleanup_data
2299 {
2300   struct dwo_file *dwo_file;
2301   struct dwarf2_per_objfile *dwarf2_per_objfile;
2302 };
2303
2304 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2305
2306 static void check_producer (struct dwarf2_cu *cu);
2307
2308 static void free_line_header_voidp (void *arg);
2309 \f
2310 /* Various complaints about symbol reading that don't abort the process.  */
2311
2312 static void
2313 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2314 {
2315   complaint (&symfile_complaints,
2316              _("statement list doesn't fit in .debug_line section"));
2317 }
2318
2319 static void
2320 dwarf2_debug_line_missing_file_complaint (void)
2321 {
2322   complaint (&symfile_complaints,
2323              _(".debug_line section has line data without a file"));
2324 }
2325
2326 static void
2327 dwarf2_debug_line_missing_end_sequence_complaint (void)
2328 {
2329   complaint (&symfile_complaints,
2330              _(".debug_line section has line "
2331                "program sequence without an end"));
2332 }
2333
2334 static void
2335 dwarf2_complex_location_expr_complaint (void)
2336 {
2337   complaint (&symfile_complaints, _("location expression too complex"));
2338 }
2339
2340 static void
2341 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2342                                               int arg3)
2343 {
2344   complaint (&symfile_complaints,
2345              _("const value length mismatch for '%s', got %d, expected %d"),
2346              arg1, arg2, arg3);
2347 }
2348
2349 static void
2350 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2351 {
2352   complaint (&symfile_complaints,
2353              _("debug info runs off end of %s section"
2354                " [in module %s]"),
2355              get_section_name (section),
2356              get_section_file_name (section));
2357 }
2358
2359 static void
2360 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2361 {
2362   complaint (&symfile_complaints,
2363              _("macro debug info contains a "
2364                "malformed macro definition:\n`%s'"),
2365              arg1);
2366 }
2367
2368 static void
2369 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2370 {
2371   complaint (&symfile_complaints,
2372              _("invalid attribute class or form for '%s' in '%s'"),
2373              arg1, arg2);
2374 }
2375
2376 /* Hash function for line_header_hash.  */
2377
2378 static hashval_t
2379 line_header_hash (const struct line_header *ofs)
2380 {
2381   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2382 }
2383
2384 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2385
2386 static hashval_t
2387 line_header_hash_voidp (const void *item)
2388 {
2389   const struct line_header *ofs = (const struct line_header *) item;
2390
2391   return line_header_hash (ofs);
2392 }
2393
2394 /* Equality function for line_header_hash.  */
2395
2396 static int
2397 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2398 {
2399   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2400   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2401
2402   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2403           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2404 }
2405
2406 \f
2407
2408 /* Read the given attribute value as an address, taking the attribute's
2409    form into account.  */
2410
2411 static CORE_ADDR
2412 attr_value_as_address (struct attribute *attr)
2413 {
2414   CORE_ADDR addr;
2415
2416   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2417     {
2418       /* Aside from a few clearly defined exceptions, attributes that
2419          contain an address must always be in DW_FORM_addr form.
2420          Unfortunately, some compilers happen to be violating this
2421          requirement by encoding addresses using other forms, such
2422          as DW_FORM_data4 for example.  For those broken compilers,
2423          we try to do our best, without any guarantee of success,
2424          to interpret the address correctly.  It would also be nice
2425          to generate a complaint, but that would require us to maintain
2426          a list of legitimate cases where a non-address form is allowed,
2427          as well as update callers to pass in at least the CU's DWARF
2428          version.  This is more overhead than what we're willing to
2429          expand for a pretty rare case.  */
2430       addr = DW_UNSND (attr);
2431     }
2432   else
2433     addr = DW_ADDR (attr);
2434
2435   return addr;
2436 }
2437
2438 /* The suffix for an index file.  */
2439 #define INDEX4_SUFFIX ".gdb-index"
2440 #define INDEX5_SUFFIX ".debug_names"
2441 #define DEBUG_STR_SUFFIX ".debug_str"
2442
2443 /* See declaration.  */
2444
2445 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2446                                         const dwarf2_debug_sections *names)
2447   : objfile (objfile_)
2448 {
2449   if (names == NULL)
2450     names = &dwarf2_elf_names;
2451
2452   bfd *obfd = objfile->obfd;
2453
2454   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2455     locate_sections (obfd, sec, *names);
2456 }
2457
2458 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2459
2460 dwarf2_per_objfile::~dwarf2_per_objfile ()
2461 {
2462   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2463   free_cached_comp_units ();
2464
2465   if (quick_file_names_table)
2466     htab_delete (quick_file_names_table);
2467
2468   if (line_header_hash)
2469     htab_delete (line_header_hash);
2470
2471   for (int ix = 0; ix < n_comp_units; ++ix)
2472    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2473
2474   for (int ix = 0; ix < n_type_units; ++ix)
2475     VEC_free (dwarf2_per_cu_ptr,
2476               all_type_units[ix]->per_cu.imported_symtabs);
2477   xfree (all_type_units);
2478
2479   VEC_free (dwarf2_section_info_def, types);
2480
2481   if (dwo_files != NULL)
2482     free_dwo_files (dwo_files, objfile);
2483   if (dwp_file != NULL)
2484     gdb_bfd_unref (dwp_file->dbfd);
2485
2486   if (dwz_file != NULL && dwz_file->dwz_bfd)
2487     gdb_bfd_unref (dwz_file->dwz_bfd);
2488
2489   if (index_table != NULL)
2490     index_table->~mapped_index ();
2491
2492   /* Everything else should be on the objfile obstack.  */
2493 }
2494
2495 /* See declaration.  */
2496
2497 void
2498 dwarf2_per_objfile::free_cached_comp_units ()
2499 {
2500   dwarf2_per_cu_data *per_cu = read_in_chain;
2501   dwarf2_per_cu_data **last_chain = &read_in_chain;
2502   while (per_cu != NULL)
2503     {
2504       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2505
2506       delete per_cu->cu;
2507       *last_chain = next_cu;
2508       per_cu = next_cu;
2509     }
2510 }
2511
2512 /* Try to locate the sections we need for DWARF 2 debugging
2513    information and return true if we have enough to do something.
2514    NAMES points to the dwarf2 section names, or is NULL if the standard
2515    ELF names are used.  */
2516
2517 int
2518 dwarf2_has_info (struct objfile *objfile,
2519                  const struct dwarf2_debug_sections *names)
2520 {
2521   if (objfile->flags & OBJF_READNEVER)
2522     return 0;
2523
2524   struct dwarf2_per_objfile *dwarf2_per_objfile
2525     = get_dwarf2_per_objfile (objfile);
2526
2527   if (dwarf2_per_objfile == NULL)
2528     {
2529       /* Initialize per-objfile state.  */
2530       dwarf2_per_objfile
2531         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2532                                                                      names);
2533       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2534     }
2535   return (!dwarf2_per_objfile->info.is_virtual
2536           && dwarf2_per_objfile->info.s.section != NULL
2537           && !dwarf2_per_objfile->abbrev.is_virtual
2538           && dwarf2_per_objfile->abbrev.s.section != NULL);
2539 }
2540
2541 /* Return the containing section of virtual section SECTION.  */
2542
2543 static struct dwarf2_section_info *
2544 get_containing_section (const struct dwarf2_section_info *section)
2545 {
2546   gdb_assert (section->is_virtual);
2547   return section->s.containing_section;
2548 }
2549
2550 /* Return the bfd owner of SECTION.  */
2551
2552 static struct bfd *
2553 get_section_bfd_owner (const struct dwarf2_section_info *section)
2554 {
2555   if (section->is_virtual)
2556     {
2557       section = get_containing_section (section);
2558       gdb_assert (!section->is_virtual);
2559     }
2560   return section->s.section->owner;
2561 }
2562
2563 /* Return the bfd section of SECTION.
2564    Returns NULL if the section is not present.  */
2565
2566 static asection *
2567 get_section_bfd_section (const struct dwarf2_section_info *section)
2568 {
2569   if (section->is_virtual)
2570     {
2571       section = get_containing_section (section);
2572       gdb_assert (!section->is_virtual);
2573     }
2574   return section->s.section;
2575 }
2576
2577 /* Return the name of SECTION.  */
2578
2579 static const char *
2580 get_section_name (const struct dwarf2_section_info *section)
2581 {
2582   asection *sectp = get_section_bfd_section (section);
2583
2584   gdb_assert (sectp != NULL);
2585   return bfd_section_name (get_section_bfd_owner (section), sectp);
2586 }
2587
2588 /* Return the name of the file SECTION is in.  */
2589
2590 static const char *
2591 get_section_file_name (const struct dwarf2_section_info *section)
2592 {
2593   bfd *abfd = get_section_bfd_owner (section);
2594
2595   return bfd_get_filename (abfd);
2596 }
2597
2598 /* Return the id of SECTION.
2599    Returns 0 if SECTION doesn't exist.  */
2600
2601 static int
2602 get_section_id (const struct dwarf2_section_info *section)
2603 {
2604   asection *sectp = get_section_bfd_section (section);
2605
2606   if (sectp == NULL)
2607     return 0;
2608   return sectp->id;
2609 }
2610
2611 /* Return the flags of SECTION.
2612    SECTION (or containing section if this is a virtual section) must exist.  */
2613
2614 static int
2615 get_section_flags (const struct dwarf2_section_info *section)
2616 {
2617   asection *sectp = get_section_bfd_section (section);
2618
2619   gdb_assert (sectp != NULL);
2620   return bfd_get_section_flags (sectp->owner, sectp);
2621 }
2622
2623 /* When loading sections, we look either for uncompressed section or for
2624    compressed section names.  */
2625
2626 static int
2627 section_is_p (const char *section_name,
2628               const struct dwarf2_section_names *names)
2629 {
2630   if (names->normal != NULL
2631       && strcmp (section_name, names->normal) == 0)
2632     return 1;
2633   if (names->compressed != NULL
2634       && strcmp (section_name, names->compressed) == 0)
2635     return 1;
2636   return 0;
2637 }
2638
2639 /* See declaration.  */
2640
2641 void
2642 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2643                                      const dwarf2_debug_sections &names)
2644 {
2645   flagword aflag = bfd_get_section_flags (abfd, sectp);
2646
2647   if ((aflag & SEC_HAS_CONTENTS) == 0)
2648     {
2649     }
2650   else if (section_is_p (sectp->name, &names.info))
2651     {
2652       this->info.s.section = sectp;
2653       this->info.size = bfd_get_section_size (sectp);
2654     }
2655   else if (section_is_p (sectp->name, &names.abbrev))
2656     {
2657       this->abbrev.s.section = sectp;
2658       this->abbrev.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &names.line))
2661     {
2662       this->line.s.section = sectp;
2663       this->line.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &names.loc))
2666     {
2667       this->loc.s.section = sectp;
2668       this->loc.size = bfd_get_section_size (sectp);
2669     }
2670   else if (section_is_p (sectp->name, &names.loclists))
2671     {
2672       this->loclists.s.section = sectp;
2673       this->loclists.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &names.macinfo))
2676     {
2677       this->macinfo.s.section = sectp;
2678       this->macinfo.size = bfd_get_section_size (sectp);
2679     }
2680   else if (section_is_p (sectp->name, &names.macro))
2681     {
2682       this->macro.s.section = sectp;
2683       this->macro.size = bfd_get_section_size (sectp);
2684     }
2685   else if (section_is_p (sectp->name, &names.str))
2686     {
2687       this->str.s.section = sectp;
2688       this->str.size = bfd_get_section_size (sectp);
2689     }
2690   else if (section_is_p (sectp->name, &names.line_str))
2691     {
2692       this->line_str.s.section = sectp;
2693       this->line_str.size = bfd_get_section_size (sectp);
2694     }
2695   else if (section_is_p (sectp->name, &names.addr))
2696     {
2697       this->addr.s.section = sectp;
2698       this->addr.size = bfd_get_section_size (sectp);
2699     }
2700   else if (section_is_p (sectp->name, &names.frame))
2701     {
2702       this->frame.s.section = sectp;
2703       this->frame.size = bfd_get_section_size (sectp);
2704     }
2705   else if (section_is_p (sectp->name, &names.eh_frame))
2706     {
2707       this->eh_frame.s.section = sectp;
2708       this->eh_frame.size = bfd_get_section_size (sectp);
2709     }
2710   else if (section_is_p (sectp->name, &names.ranges))
2711     {
2712       this->ranges.s.section = sectp;
2713       this->ranges.size = bfd_get_section_size (sectp);
2714     }
2715   else if (section_is_p (sectp->name, &names.rnglists))
2716     {
2717       this->rnglists.s.section = sectp;
2718       this->rnglists.size = bfd_get_section_size (sectp);
2719     }
2720   else if (section_is_p (sectp->name, &names.types))
2721     {
2722       struct dwarf2_section_info type_section;
2723
2724       memset (&type_section, 0, sizeof (type_section));
2725       type_section.s.section = sectp;
2726       type_section.size = bfd_get_section_size (sectp);
2727
2728       VEC_safe_push (dwarf2_section_info_def, this->types,
2729                      &type_section);
2730     }
2731   else if (section_is_p (sectp->name, &names.gdb_index))
2732     {
2733       this->gdb_index.s.section = sectp;
2734       this->gdb_index.size = bfd_get_section_size (sectp);
2735     }
2736   else if (section_is_p (sectp->name, &names.debug_names))
2737     {
2738       this->debug_names.s.section = sectp;
2739       this->debug_names.size = bfd_get_section_size (sectp);
2740     }
2741   else if (section_is_p (sectp->name, &names.debug_aranges))
2742     {
2743       this->debug_aranges.s.section = sectp;
2744       this->debug_aranges.size = bfd_get_section_size (sectp);
2745     }
2746
2747   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2748       && bfd_section_vma (abfd, sectp) == 0)
2749     this->has_section_at_zero = true;
2750 }
2751
2752 /* A helper function that decides whether a section is empty,
2753    or not present.  */
2754
2755 static int
2756 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2757 {
2758   if (section->is_virtual)
2759     return section->size == 0;
2760   return section->s.section == NULL || section->size == 0;
2761 }
2762
2763 /* Read the contents of the section INFO.
2764    OBJFILE is the main object file, but not necessarily the file where
2765    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2766    of the DWO file.
2767    If the section is compressed, uncompress it before returning.  */
2768
2769 static void
2770 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2771 {
2772   asection *sectp;
2773   bfd *abfd;
2774   gdb_byte *buf, *retbuf;
2775
2776   if (info->readin)
2777     return;
2778   info->buffer = NULL;
2779   info->readin = 1;
2780
2781   if (dwarf2_section_empty_p (info))
2782     return;
2783
2784   sectp = get_section_bfd_section (info);
2785
2786   /* If this is a virtual section we need to read in the real one first.  */
2787   if (info->is_virtual)
2788     {
2789       struct dwarf2_section_info *containing_section =
2790         get_containing_section (info);
2791
2792       gdb_assert (sectp != NULL);
2793       if ((sectp->flags & SEC_RELOC) != 0)
2794         {
2795           error (_("Dwarf Error: DWP format V2 with relocations is not"
2796                    " supported in section %s [in module %s]"),
2797                  get_section_name (info), get_section_file_name (info));
2798         }
2799       dwarf2_read_section (objfile, containing_section);
2800       /* Other code should have already caught virtual sections that don't
2801          fit.  */
2802       gdb_assert (info->virtual_offset + info->size
2803                   <= containing_section->size);
2804       /* If the real section is empty or there was a problem reading the
2805          section we shouldn't get here.  */
2806       gdb_assert (containing_section->buffer != NULL);
2807       info->buffer = containing_section->buffer + info->virtual_offset;
2808       return;
2809     }
2810
2811   /* If the section has relocations, we must read it ourselves.
2812      Otherwise we attach it to the BFD.  */
2813   if ((sectp->flags & SEC_RELOC) == 0)
2814     {
2815       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2816       return;
2817     }
2818
2819   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2820   info->buffer = buf;
2821
2822   /* When debugging .o files, we may need to apply relocations; see
2823      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2824      We never compress sections in .o files, so we only need to
2825      try this when the section is not compressed.  */
2826   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2827   if (retbuf != NULL)
2828     {
2829       info->buffer = retbuf;
2830       return;
2831     }
2832
2833   abfd = get_section_bfd_owner (info);
2834   gdb_assert (abfd != NULL);
2835
2836   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2837       || bfd_bread (buf, info->size, abfd) != info->size)
2838     {
2839       error (_("Dwarf Error: Can't read DWARF data"
2840                " in section %s [in module %s]"),
2841              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2842     }
2843 }
2844
2845 /* A helper function that returns the size of a section in a safe way.
2846    If you are positive that the section has been read before using the
2847    size, then it is safe to refer to the dwarf2_section_info object's
2848    "size" field directly.  In other cases, you must call this
2849    function, because for compressed sections the size field is not set
2850    correctly until the section has been read.  */
2851
2852 static bfd_size_type
2853 dwarf2_section_size (struct objfile *objfile,
2854                      struct dwarf2_section_info *info)
2855 {
2856   if (!info->readin)
2857     dwarf2_read_section (objfile, info);
2858   return info->size;
2859 }
2860
2861 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2862    SECTION_NAME.  */
2863
2864 void
2865 dwarf2_get_section_info (struct objfile *objfile,
2866                          enum dwarf2_section_enum sect,
2867                          asection **sectp, const gdb_byte **bufp,
2868                          bfd_size_type *sizep)
2869 {
2870   struct dwarf2_per_objfile *data
2871     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2872                                                   dwarf2_objfile_data_key);
2873   struct dwarf2_section_info *info;
2874
2875   /* We may see an objfile without any DWARF, in which case we just
2876      return nothing.  */
2877   if (data == NULL)
2878     {
2879       *sectp = NULL;
2880       *bufp = NULL;
2881       *sizep = 0;
2882       return;
2883     }
2884   switch (sect)
2885     {
2886     case DWARF2_DEBUG_FRAME:
2887       info = &data->frame;
2888       break;
2889     case DWARF2_EH_FRAME:
2890       info = &data->eh_frame;
2891       break;
2892     default:
2893       gdb_assert_not_reached ("unexpected section");
2894     }
2895
2896   dwarf2_read_section (objfile, info);
2897
2898   *sectp = get_section_bfd_section (info);
2899   *bufp = info->buffer;
2900   *sizep = info->size;
2901 }
2902
2903 /* A helper function to find the sections for a .dwz file.  */
2904
2905 static void
2906 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2907 {
2908   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2909
2910   /* Note that we only support the standard ELF names, because .dwz
2911      is ELF-only (at the time of writing).  */
2912   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2913     {
2914       dwz_file->abbrev.s.section = sectp;
2915       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2916     }
2917   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2918     {
2919       dwz_file->info.s.section = sectp;
2920       dwz_file->info.size = bfd_get_section_size (sectp);
2921     }
2922   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2923     {
2924       dwz_file->str.s.section = sectp;
2925       dwz_file->str.size = bfd_get_section_size (sectp);
2926     }
2927   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2928     {
2929       dwz_file->line.s.section = sectp;
2930       dwz_file->line.size = bfd_get_section_size (sectp);
2931     }
2932   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2933     {
2934       dwz_file->macro.s.section = sectp;
2935       dwz_file->macro.size = bfd_get_section_size (sectp);
2936     }
2937   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2938     {
2939       dwz_file->gdb_index.s.section = sectp;
2940       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2941     }
2942   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2943     {
2944       dwz_file->debug_names.s.section = sectp;
2945       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2946     }
2947 }
2948
2949 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2950    there is no .gnu_debugaltlink section in the file.  Error if there
2951    is such a section but the file cannot be found.  */
2952
2953 static struct dwz_file *
2954 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2955 {
2956   const char *filename;
2957   struct dwz_file *result;
2958   bfd_size_type buildid_len_arg;
2959   size_t buildid_len;
2960   bfd_byte *buildid;
2961
2962   if (dwarf2_per_objfile->dwz_file != NULL)
2963     return dwarf2_per_objfile->dwz_file;
2964
2965   bfd_set_error (bfd_error_no_error);
2966   gdb::unique_xmalloc_ptr<char> data
2967     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2968                                   &buildid_len_arg, &buildid));
2969   if (data == NULL)
2970     {
2971       if (bfd_get_error () == bfd_error_no_error)
2972         return NULL;
2973       error (_("could not read '.gnu_debugaltlink' section: %s"),
2974              bfd_errmsg (bfd_get_error ()));
2975     }
2976
2977   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2978
2979   buildid_len = (size_t) buildid_len_arg;
2980
2981   filename = data.get ();
2982
2983   std::string abs_storage;
2984   if (!IS_ABSOLUTE_PATH (filename))
2985     {
2986       gdb::unique_xmalloc_ptr<char> abs
2987         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2988
2989       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2990       filename = abs_storage.c_str ();
2991     }
2992
2993   /* First try the file name given in the section.  If that doesn't
2994      work, try to use the build-id instead.  */
2995   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2996   if (dwz_bfd != NULL)
2997     {
2998       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2999         dwz_bfd.release ();
3000     }
3001
3002   if (dwz_bfd == NULL)
3003     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
3004
3005   if (dwz_bfd == NULL)
3006     error (_("could not find '.gnu_debugaltlink' file for %s"),
3007            objfile_name (dwarf2_per_objfile->objfile));
3008
3009   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
3010                            struct dwz_file);
3011   result->dwz_bfd = dwz_bfd.release ();
3012
3013   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
3014
3015   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
3016   dwarf2_per_objfile->dwz_file = result;
3017   return result;
3018 }
3019 \f
3020 /* DWARF quick_symbols_functions support.  */
3021
3022 /* TUs can share .debug_line entries, and there can be a lot more TUs than
3023    unique line tables, so we maintain a separate table of all .debug_line
3024    derived entries to support the sharing.
3025    All the quick functions need is the list of file names.  We discard the
3026    line_header when we're done and don't need to record it here.  */
3027 struct quick_file_names
3028 {
3029   /* The data used to construct the hash key.  */
3030   struct stmt_list_hash hash;
3031
3032   /* The number of entries in file_names, real_names.  */
3033   unsigned int num_file_names;
3034
3035   /* The file names from the line table, after being run through
3036      file_full_name.  */
3037   const char **file_names;
3038
3039   /* The file names from the line table after being run through
3040      gdb_realpath.  These are computed lazily.  */
3041   const char **real_names;
3042 };
3043
3044 /* When using the index (and thus not using psymtabs), each CU has an
3045    object of this type.  This is used to hold information needed by
3046    the various "quick" methods.  */
3047 struct dwarf2_per_cu_quick_data
3048 {
3049   /* The file table.  This can be NULL if there was no file table
3050      or it's currently not read in.
3051      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3052   struct quick_file_names *file_names;
3053
3054   /* The corresponding symbol table.  This is NULL if symbols for this
3055      CU have not yet been read.  */
3056   struct compunit_symtab *compunit_symtab;
3057
3058   /* A temporary mark bit used when iterating over all CUs in
3059      expand_symtabs_matching.  */
3060   unsigned int mark : 1;
3061
3062   /* True if we've tried to read the file table and found there isn't one.
3063      There will be no point in trying to read it again next time.  */
3064   unsigned int no_file_data : 1;
3065 };
3066
3067 /* Utility hash function for a stmt_list_hash.  */
3068
3069 static hashval_t
3070 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3071 {
3072   hashval_t v = 0;
3073
3074   if (stmt_list_hash->dwo_unit != NULL)
3075     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3076   v += to_underlying (stmt_list_hash->line_sect_off);
3077   return v;
3078 }
3079
3080 /* Utility equality function for a stmt_list_hash.  */
3081
3082 static int
3083 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3084                     const struct stmt_list_hash *rhs)
3085 {
3086   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3087     return 0;
3088   if (lhs->dwo_unit != NULL
3089       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3090     return 0;
3091
3092   return lhs->line_sect_off == rhs->line_sect_off;
3093 }
3094
3095 /* Hash function for a quick_file_names.  */
3096
3097 static hashval_t
3098 hash_file_name_entry (const void *e)
3099 {
3100   const struct quick_file_names *file_data
3101     = (const struct quick_file_names *) e;
3102
3103   return hash_stmt_list_entry (&file_data->hash);
3104 }
3105
3106 /* Equality function for a quick_file_names.  */
3107
3108 static int
3109 eq_file_name_entry (const void *a, const void *b)
3110 {
3111   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3112   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3113
3114   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3115 }
3116
3117 /* Delete function for a quick_file_names.  */
3118
3119 static void
3120 delete_file_name_entry (void *e)
3121 {
3122   struct quick_file_names *file_data = (struct quick_file_names *) e;
3123   int i;
3124
3125   for (i = 0; i < file_data->num_file_names; ++i)
3126     {
3127       xfree ((void*) file_data->file_names[i]);
3128       if (file_data->real_names)
3129         xfree ((void*) file_data->real_names[i]);
3130     }
3131
3132   /* The space for the struct itself lives on objfile_obstack,
3133      so we don't free it here.  */
3134 }
3135
3136 /* Create a quick_file_names hash table.  */
3137
3138 static htab_t
3139 create_quick_file_names_table (unsigned int nr_initial_entries)
3140 {
3141   return htab_create_alloc (nr_initial_entries,
3142                             hash_file_name_entry, eq_file_name_entry,
3143                             delete_file_name_entry, xcalloc, xfree);
3144 }
3145
3146 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3147    have to be created afterwards.  You should call age_cached_comp_units after
3148    processing PER_CU->CU.  dw2_setup must have been already called.  */
3149
3150 static void
3151 load_cu (struct dwarf2_per_cu_data *per_cu)
3152 {
3153   if (per_cu->is_debug_types)
3154     load_full_type_unit (per_cu);
3155   else
3156     load_full_comp_unit (per_cu, language_minimal);
3157
3158   if (per_cu->cu == NULL)
3159     return;  /* Dummy CU.  */
3160
3161   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3162 }
3163
3164 /* Read in the symbols for PER_CU.  */
3165
3166 static void
3167 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3168 {
3169   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3170
3171   /* Skip type_unit_groups, reading the type units they contain
3172      is handled elsewhere.  */
3173   if (IS_TYPE_UNIT_GROUP (per_cu))
3174     return;
3175
3176   /* The destructor of dwarf2_queue_guard frees any entries left on
3177      the queue.  After this point we're guaranteed to leave this function
3178      with the dwarf queue empty.  */
3179   dwarf2_queue_guard q_guard;
3180
3181   if (dwarf2_per_objfile->using_index
3182       ? per_cu->v.quick->compunit_symtab == NULL
3183       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3184     {
3185       queue_comp_unit (per_cu, language_minimal);
3186       load_cu (per_cu);
3187
3188       /* If we just loaded a CU from a DWO, and we're working with an index
3189          that may badly handle TUs, load all the TUs in that DWO as well.
3190          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3191       if (!per_cu->is_debug_types
3192           && per_cu->cu != NULL
3193           && per_cu->cu->dwo_unit != NULL
3194           && dwarf2_per_objfile->index_table != NULL
3195           && dwarf2_per_objfile->index_table->version <= 7
3196           /* DWP files aren't supported yet.  */
3197           && get_dwp_file (dwarf2_per_objfile) == NULL)
3198         queue_and_load_all_dwo_tus (per_cu);
3199     }
3200
3201   process_queue (dwarf2_per_objfile);
3202
3203   /* Age the cache, releasing compilation units that have not
3204      been used recently.  */
3205   age_cached_comp_units (dwarf2_per_objfile);
3206 }
3207
3208 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3209    the objfile from which this CU came.  Returns the resulting symbol
3210    table.  */
3211
3212 static struct compunit_symtab *
3213 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3214 {
3215   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3216
3217   gdb_assert (dwarf2_per_objfile->using_index);
3218   if (!per_cu->v.quick->compunit_symtab)
3219     {
3220       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3221                                               dwarf2_per_objfile);
3222       scoped_restore decrementer = increment_reading_symtab ();
3223       dw2_do_instantiate_symtab (per_cu);
3224       process_cu_includes (dwarf2_per_objfile);
3225       do_cleanups (back_to);
3226     }
3227
3228   return per_cu->v.quick->compunit_symtab;
3229 }
3230
3231 /* Return the CU/TU given its index.
3232
3233    This is intended for loops like:
3234
3235    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3236                     + dwarf2_per_objfile->n_type_units); ++i)
3237      {
3238        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3239
3240        ...;
3241      }
3242 */
3243
3244 static struct dwarf2_per_cu_data *
3245 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3246               int index)
3247 {
3248   if (index >= dwarf2_per_objfile->n_comp_units)
3249     {
3250       index -= dwarf2_per_objfile->n_comp_units;
3251       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3252       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3253     }
3254
3255   return dwarf2_per_objfile->all_comp_units[index];
3256 }
3257
3258 /* Return the CU given its index.
3259    This differs from dw2_get_cutu in that it's for when you know INDEX
3260    refers to a CU.  */
3261
3262 static struct dwarf2_per_cu_data *
3263 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3264 {
3265   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3266
3267   return dwarf2_per_objfile->all_comp_units[index];
3268 }
3269
3270 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3271    objfile_obstack, and constructed with the specified field
3272    values.  */
3273
3274 static dwarf2_per_cu_data *
3275 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3276                           struct dwarf2_section_info *section,
3277                           int is_dwz,
3278                           sect_offset sect_off, ULONGEST length)
3279 {
3280   struct objfile *objfile = dwarf2_per_objfile->objfile;
3281   dwarf2_per_cu_data *the_cu
3282     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3283                      struct dwarf2_per_cu_data);
3284   the_cu->sect_off = sect_off;
3285   the_cu->length = length;
3286   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3287   the_cu->section = section;
3288   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3289                                    struct dwarf2_per_cu_quick_data);
3290   the_cu->is_dwz = is_dwz;
3291   return the_cu;
3292 }
3293
3294 /* A helper for create_cus_from_index that handles a given list of
3295    CUs.  */
3296
3297 static void
3298 create_cus_from_index_list (struct objfile *objfile,
3299                             const gdb_byte *cu_list, offset_type n_elements,
3300                             struct dwarf2_section_info *section,
3301                             int is_dwz,
3302                             int base_offset)
3303 {
3304   offset_type i;
3305   struct dwarf2_per_objfile *dwarf2_per_objfile
3306     = get_dwarf2_per_objfile (objfile);
3307
3308   for (i = 0; i < n_elements; i += 2)
3309     {
3310       gdb_static_assert (sizeof (ULONGEST) >= 8);
3311
3312       sect_offset sect_off
3313         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3314       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3315       cu_list += 2 * 8;
3316
3317       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3318         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3319                                      sect_off, length);
3320     }
3321 }
3322
3323 /* Read the CU list from the mapped index, and use it to create all
3324    the CU objects for this objfile.  */
3325
3326 static void
3327 create_cus_from_index (struct objfile *objfile,
3328                        const gdb_byte *cu_list, offset_type cu_list_elements,
3329                        const gdb_byte *dwz_list, offset_type dwz_elements)
3330 {
3331   struct dwz_file *dwz;
3332   struct dwarf2_per_objfile *dwarf2_per_objfile
3333     = get_dwarf2_per_objfile (objfile);
3334
3335   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3336   dwarf2_per_objfile->all_comp_units =
3337     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3338                dwarf2_per_objfile->n_comp_units);
3339
3340   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3341                               &dwarf2_per_objfile->info, 0, 0);
3342
3343   if (dwz_elements == 0)
3344     return;
3345
3346   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3347   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3348                               cu_list_elements / 2);
3349 }
3350
3351 /* Create the signatured type hash table from the index.  */
3352
3353 static void
3354 create_signatured_type_table_from_index (struct objfile *objfile,
3355                                          struct dwarf2_section_info *section,
3356                                          const gdb_byte *bytes,
3357                                          offset_type elements)
3358 {
3359   offset_type i;
3360   htab_t sig_types_hash;
3361   struct dwarf2_per_objfile *dwarf2_per_objfile
3362     = get_dwarf2_per_objfile (objfile);
3363
3364   dwarf2_per_objfile->n_type_units
3365     = dwarf2_per_objfile->n_allocated_type_units
3366     = elements / 3;
3367   dwarf2_per_objfile->all_type_units =
3368     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3369
3370   sig_types_hash = allocate_signatured_type_table (objfile);
3371
3372   for (i = 0; i < elements; i += 3)
3373     {
3374       struct signatured_type *sig_type;
3375       ULONGEST signature;
3376       void **slot;
3377       cu_offset type_offset_in_tu;
3378
3379       gdb_static_assert (sizeof (ULONGEST) >= 8);
3380       sect_offset sect_off
3381         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3382       type_offset_in_tu
3383         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3384                                                 BFD_ENDIAN_LITTLE);
3385       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3386       bytes += 3 * 8;
3387
3388       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3389                                  struct signatured_type);
3390       sig_type->signature = signature;
3391       sig_type->type_offset_in_tu = type_offset_in_tu;
3392       sig_type->per_cu.is_debug_types = 1;
3393       sig_type->per_cu.section = section;
3394       sig_type->per_cu.sect_off = sect_off;
3395       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3396       sig_type->per_cu.v.quick
3397         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3398                           struct dwarf2_per_cu_quick_data);
3399
3400       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3401       *slot = sig_type;
3402
3403       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3404     }
3405
3406   dwarf2_per_objfile->signatured_types = sig_types_hash;
3407 }
3408
3409 /* Create the signatured type hash table from .debug_names.  */
3410
3411 static void
3412 create_signatured_type_table_from_debug_names
3413   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3414    const mapped_debug_names &map,
3415    struct dwarf2_section_info *section,
3416    struct dwarf2_section_info *abbrev_section)
3417 {
3418   struct objfile *objfile = dwarf2_per_objfile->objfile;
3419
3420   dwarf2_read_section (objfile, section);
3421   dwarf2_read_section (objfile, abbrev_section);
3422
3423   dwarf2_per_objfile->n_type_units
3424     = dwarf2_per_objfile->n_allocated_type_units
3425     = map.tu_count;
3426   dwarf2_per_objfile->all_type_units
3427     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3428
3429   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3430
3431   for (uint32_t i = 0; i < map.tu_count; ++i)
3432     {
3433       struct signatured_type *sig_type;
3434       ULONGEST signature;
3435       void **slot;
3436       cu_offset type_offset_in_tu;
3437
3438       sect_offset sect_off
3439         = (sect_offset) (extract_unsigned_integer
3440                          (map.tu_table_reordered + i * map.offset_size,
3441                           map.offset_size,
3442                           map.dwarf5_byte_order));
3443
3444       comp_unit_head cu_header;
3445       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3446                                      abbrev_section,
3447                                      section->buffer + to_underlying (sect_off),
3448                                      rcuh_kind::TYPE);
3449
3450       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3451                                  struct signatured_type);
3452       sig_type->signature = cu_header.signature;
3453       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3454       sig_type->per_cu.is_debug_types = 1;
3455       sig_type->per_cu.section = section;
3456       sig_type->per_cu.sect_off = sect_off;
3457       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3458       sig_type->per_cu.v.quick
3459         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3460                           struct dwarf2_per_cu_quick_data);
3461
3462       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3463       *slot = sig_type;
3464
3465       dwarf2_per_objfile->all_type_units[i] = sig_type;
3466     }
3467
3468   dwarf2_per_objfile->signatured_types = sig_types_hash;
3469 }
3470
3471 /* Read the address map data from the mapped index, and use it to
3472    populate the objfile's psymtabs_addrmap.  */
3473
3474 static void
3475 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3476                            struct mapped_index *index)
3477 {
3478   struct objfile *objfile = dwarf2_per_objfile->objfile;
3479   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3480   const gdb_byte *iter, *end;
3481   struct addrmap *mutable_map;
3482   CORE_ADDR baseaddr;
3483
3484   auto_obstack temp_obstack;
3485
3486   mutable_map = addrmap_create_mutable (&temp_obstack);
3487
3488   iter = index->address_table.data ();
3489   end = iter + index->address_table.size ();
3490
3491   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3492
3493   while (iter < end)
3494     {
3495       ULONGEST hi, lo, cu_index;
3496       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3497       iter += 8;
3498       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3499       iter += 8;
3500       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3501       iter += 4;
3502
3503       if (lo > hi)
3504         {
3505           complaint (&symfile_complaints,
3506                      _(".gdb_index address table has invalid range (%s - %s)"),
3507                      hex_string (lo), hex_string (hi));
3508           continue;
3509         }
3510
3511       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3512         {
3513           complaint (&symfile_complaints,
3514                      _(".gdb_index address table has invalid CU number %u"),
3515                      (unsigned) cu_index);
3516           continue;
3517         }
3518
3519       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3520       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3521       addrmap_set_empty (mutable_map, lo, hi - 1,
3522                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3523     }
3524
3525   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3526                                                     &objfile->objfile_obstack);
3527 }
3528
3529 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3530    populate the objfile's psymtabs_addrmap.  */
3531
3532 static void
3533 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3534                              struct dwarf2_section_info *section)
3535 {
3536   struct objfile *objfile = dwarf2_per_objfile->objfile;
3537   bfd *abfd = objfile->obfd;
3538   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3539   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3540                                        SECT_OFF_TEXT (objfile));
3541
3542   auto_obstack temp_obstack;
3543   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3544
3545   std::unordered_map<sect_offset,
3546                      dwarf2_per_cu_data *,
3547                      gdb::hash_enum<sect_offset>>
3548     debug_info_offset_to_per_cu;
3549   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3550     {
3551       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3552       const auto insertpair
3553         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3554       if (!insertpair.second)
3555         {
3556           warning (_("Section .debug_aranges in %s has duplicate "
3557                      "debug_info_offset %s, ignoring .debug_aranges."),
3558                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3559           return;
3560         }
3561     }
3562
3563   dwarf2_read_section (objfile, section);
3564
3565   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3566
3567   const gdb_byte *addr = section->buffer;
3568
3569   while (addr < section->buffer + section->size)
3570     {
3571       const gdb_byte *const entry_addr = addr;
3572       unsigned int bytes_read;
3573
3574       const LONGEST entry_length = read_initial_length (abfd, addr,
3575                                                         &bytes_read);
3576       addr += bytes_read;
3577
3578       const gdb_byte *const entry_end = addr + entry_length;
3579       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3580       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3581       if (addr + entry_length > section->buffer + section->size)
3582         {
3583           warning (_("Section .debug_aranges in %s entry at offset %zu "
3584                      "length %s exceeds section length %s, "
3585                      "ignoring .debug_aranges."),
3586                    objfile_name (objfile), entry_addr - section->buffer,
3587                    plongest (bytes_read + entry_length),
3588                    pulongest (section->size));
3589           return;
3590         }
3591
3592       /* The version number.  */
3593       const uint16_t version = read_2_bytes (abfd, addr);
3594       addr += 2;
3595       if (version != 2)
3596         {
3597           warning (_("Section .debug_aranges in %s entry at offset %zu "
3598                      "has unsupported version %d, ignoring .debug_aranges."),
3599                    objfile_name (objfile), entry_addr - section->buffer,
3600                    version);
3601           return;
3602         }
3603
3604       const uint64_t debug_info_offset
3605         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3606       addr += offset_size;
3607       const auto per_cu_it
3608         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3609       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3610         {
3611           warning (_("Section .debug_aranges in %s entry at offset %zu "
3612                      "debug_info_offset %s does not exists, "
3613                      "ignoring .debug_aranges."),
3614                    objfile_name (objfile), entry_addr - section->buffer,
3615                    pulongest (debug_info_offset));
3616           return;
3617         }
3618       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3619
3620       const uint8_t address_size = *addr++;
3621       if (address_size < 1 || address_size > 8)
3622         {
3623           warning (_("Section .debug_aranges in %s entry at offset %zu "
3624                      "address_size %u is invalid, ignoring .debug_aranges."),
3625                    objfile_name (objfile), entry_addr - section->buffer,
3626                    address_size);
3627           return;
3628         }
3629
3630       const uint8_t segment_selector_size = *addr++;
3631       if (segment_selector_size != 0)
3632         {
3633           warning (_("Section .debug_aranges in %s entry at offset %zu "
3634                      "segment_selector_size %u is not supported, "
3635                      "ignoring .debug_aranges."),
3636                    objfile_name (objfile), entry_addr - section->buffer,
3637                    segment_selector_size);
3638           return;
3639         }
3640
3641       /* Must pad to an alignment boundary that is twice the address
3642          size.  It is undocumented by the DWARF standard but GCC does
3643          use it.  */
3644       for (size_t padding = ((-(addr - section->buffer))
3645                              & (2 * address_size - 1));
3646            padding > 0; padding--)
3647         if (*addr++ != 0)
3648           {
3649             warning (_("Section .debug_aranges in %s entry at offset %zu "
3650                        "padding is not zero, ignoring .debug_aranges."),
3651                      objfile_name (objfile), entry_addr - section->buffer);
3652             return;
3653           }
3654
3655       for (;;)
3656         {
3657           if (addr + 2 * address_size > entry_end)
3658             {
3659               warning (_("Section .debug_aranges in %s entry at offset %zu "
3660                          "address list is not properly terminated, "
3661                          "ignoring .debug_aranges."),
3662                        objfile_name (objfile), entry_addr - section->buffer);
3663               return;
3664             }
3665           ULONGEST start = extract_unsigned_integer (addr, address_size,
3666                                                      dwarf5_byte_order);
3667           addr += address_size;
3668           ULONGEST length = extract_unsigned_integer (addr, address_size,
3669                                                       dwarf5_byte_order);
3670           addr += address_size;
3671           if (start == 0 && length == 0)
3672             break;
3673           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3674             {
3675               /* Symbol was eliminated due to a COMDAT group.  */
3676               continue;
3677             }
3678           ULONGEST end = start + length;
3679           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3680           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3681           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3682         }
3683     }
3684
3685   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3686                                                     &objfile->objfile_obstack);
3687 }
3688
3689 /* The hash function for strings in the mapped index.  This is the same as
3690    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3691    implementation.  This is necessary because the hash function is tied to the
3692    format of the mapped index file.  The hash values do not have to match with
3693    SYMBOL_HASH_NEXT.
3694    
3695    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3696
3697 static hashval_t
3698 mapped_index_string_hash (int index_version, const void *p)
3699 {
3700   const unsigned char *str = (const unsigned char *) p;
3701   hashval_t r = 0;
3702   unsigned char c;
3703
3704   while ((c = *str++) != 0)
3705     {
3706       if (index_version >= 5)
3707         c = tolower (c);
3708       r = r * 67 + c - 113;
3709     }
3710
3711   return r;
3712 }
3713
3714 /* Find a slot in the mapped index INDEX for the object named NAME.
3715    If NAME is found, set *VEC_OUT to point to the CU vector in the
3716    constant pool and return true.  If NAME cannot be found, return
3717    false.  */
3718
3719 static bool
3720 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3721                           offset_type **vec_out)
3722 {
3723   offset_type hash;
3724   offset_type slot, step;
3725   int (*cmp) (const char *, const char *);
3726
3727   gdb::unique_xmalloc_ptr<char> without_params;
3728   if (current_language->la_language == language_cplus
3729       || current_language->la_language == language_fortran
3730       || current_language->la_language == language_d)
3731     {
3732       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3733          not contain any.  */
3734
3735       if (strchr (name, '(') != NULL)
3736         {
3737           without_params = cp_remove_params (name);
3738
3739           if (without_params != NULL)
3740             name = without_params.get ();
3741         }
3742     }
3743
3744   /* Index version 4 did not support case insensitive searches.  But the
3745      indices for case insensitive languages are built in lowercase, therefore
3746      simulate our NAME being searched is also lowercased.  */
3747   hash = mapped_index_string_hash ((index->version == 4
3748                                     && case_sensitivity == case_sensitive_off
3749                                     ? 5 : index->version),
3750                                    name);
3751
3752   slot = hash & (index->symbol_table.size () - 1);
3753   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3754   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3755
3756   for (;;)
3757     {
3758       const char *str;
3759
3760       const auto &bucket = index->symbol_table[slot];
3761       if (bucket.name == 0 && bucket.vec == 0)
3762         return false;
3763
3764       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3765       if (!cmp (name, str))
3766         {
3767           *vec_out = (offset_type *) (index->constant_pool
3768                                       + MAYBE_SWAP (bucket.vec));
3769           return true;
3770         }
3771
3772       slot = (slot + step) & (index->symbol_table.size () - 1);
3773     }
3774 }
3775
3776 /* A helper function that reads the .gdb_index from SECTION and fills
3777    in MAP.  FILENAME is the name of the file containing the section;
3778    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3779    ok to use deprecated sections.
3780
3781    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3782    out parameters that are filled in with information about the CU and
3783    TU lists in the section.
3784
3785    Returns 1 if all went well, 0 otherwise.  */
3786
3787 static int
3788 read_index_from_section (struct objfile *objfile,
3789                          const char *filename,
3790                          int deprecated_ok,
3791                          struct dwarf2_section_info *section,
3792                          struct mapped_index *map,
3793                          const gdb_byte **cu_list,
3794                          offset_type *cu_list_elements,
3795                          const gdb_byte **types_list,
3796                          offset_type *types_list_elements)
3797 {
3798   const gdb_byte *addr;
3799   offset_type version;
3800   offset_type *metadata;
3801   int i;
3802
3803   if (dwarf2_section_empty_p (section))
3804     return 0;
3805
3806   /* Older elfutils strip versions could keep the section in the main
3807      executable while splitting it for the separate debug info file.  */
3808   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3809     return 0;
3810
3811   dwarf2_read_section (objfile, section);
3812
3813   addr = section->buffer;
3814   /* Version check.  */
3815   version = MAYBE_SWAP (*(offset_type *) addr);
3816   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3817      causes the index to behave very poorly for certain requests.  Version 3
3818      contained incomplete addrmap.  So, it seems better to just ignore such
3819      indices.  */
3820   if (version < 4)
3821     {
3822       static int warning_printed = 0;
3823       if (!warning_printed)
3824         {
3825           warning (_("Skipping obsolete .gdb_index section in %s."),
3826                    filename);
3827           warning_printed = 1;
3828         }
3829       return 0;
3830     }
3831   /* Index version 4 uses a different hash function than index version
3832      5 and later.
3833
3834      Versions earlier than 6 did not emit psymbols for inlined
3835      functions.  Using these files will cause GDB not to be able to
3836      set breakpoints on inlined functions by name, so we ignore these
3837      indices unless the user has done
3838      "set use-deprecated-index-sections on".  */
3839   if (version < 6 && !deprecated_ok)
3840     {
3841       static int warning_printed = 0;
3842       if (!warning_printed)
3843         {
3844           warning (_("\
3845 Skipping deprecated .gdb_index section in %s.\n\
3846 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3847 to use the section anyway."),
3848                    filename);
3849           warning_printed = 1;
3850         }
3851       return 0;
3852     }
3853   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3854      of the TU (for symbols coming from TUs),
3855      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3856      Plus gold-generated indices can have duplicate entries for global symbols,
3857      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3858      These are just performance bugs, and we can't distinguish gdb-generated
3859      indices from gold-generated ones, so issue no warning here.  */
3860
3861   /* Indexes with higher version than the one supported by GDB may be no
3862      longer backward compatible.  */
3863   if (version > 8)
3864     return 0;
3865
3866   map->version = version;
3867   map->total_size = section->size;
3868
3869   metadata = (offset_type *) (addr + sizeof (offset_type));
3870
3871   i = 0;
3872   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3873   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3874                        / 8);
3875   ++i;
3876
3877   *types_list = addr + MAYBE_SWAP (metadata[i]);
3878   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3879                            - MAYBE_SWAP (metadata[i]))
3880                           / 8);
3881   ++i;
3882
3883   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3884   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3885   map->address_table
3886     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3887   ++i;
3888
3889   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3890   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3891   map->symbol_table
3892     = gdb::array_view<mapped_index::symbol_table_slot>
3893        ((mapped_index::symbol_table_slot *) symbol_table,
3894         (mapped_index::symbol_table_slot *) symbol_table_end);
3895
3896   ++i;
3897   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3898
3899   return 1;
3900 }
3901
3902 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3903    elements of all the CUs and return 1.  Otherwise, return 0.  */
3904
3905 static int
3906 dwarf2_read_index (struct objfile *objfile)
3907 {
3908   struct mapped_index local_map, *map;
3909   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3910   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3911   struct dwz_file *dwz;
3912   struct dwarf2_per_objfile *dwarf2_per_objfile
3913     = get_dwarf2_per_objfile (objfile);
3914
3915   if (!read_index_from_section (objfile, objfile_name (objfile),
3916                                 use_deprecated_index_sections,
3917                                 &dwarf2_per_objfile->gdb_index, &local_map,
3918                                 &cu_list, &cu_list_elements,
3919                                 &types_list, &types_list_elements))
3920     return 0;
3921
3922   /* Don't use the index if it's empty.  */
3923   if (local_map.symbol_table.empty ())
3924     return 0;
3925
3926   /* If there is a .dwz file, read it so we can get its CU list as
3927      well.  */
3928   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3929   if (dwz != NULL)
3930     {
3931       struct mapped_index dwz_map;
3932       const gdb_byte *dwz_types_ignore;
3933       offset_type dwz_types_elements_ignore;
3934
3935       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3936                                     1,
3937                                     &dwz->gdb_index, &dwz_map,
3938                                     &dwz_list, &dwz_list_elements,
3939                                     &dwz_types_ignore,
3940                                     &dwz_types_elements_ignore))
3941         {
3942           warning (_("could not read '.gdb_index' section from %s; skipping"),
3943                    bfd_get_filename (dwz->dwz_bfd));
3944           return 0;
3945         }
3946     }
3947
3948   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3949                          dwz_list_elements);
3950
3951   if (types_list_elements)
3952     {
3953       struct dwarf2_section_info *section;
3954
3955       /* We can only handle a single .debug_types when we have an
3956          index.  */
3957       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3958         return 0;
3959
3960       section = VEC_index (dwarf2_section_info_def,
3961                            dwarf2_per_objfile->types, 0);
3962
3963       create_signatured_type_table_from_index (objfile, section, types_list,
3964                                                types_list_elements);
3965     }
3966
3967   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3968
3969   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3970   map = new (map) mapped_index ();
3971   *map = local_map;
3972
3973   dwarf2_per_objfile->index_table = map;
3974   dwarf2_per_objfile->using_index = 1;
3975   dwarf2_per_objfile->quick_file_names_table =
3976     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3977
3978   return 1;
3979 }
3980
3981 /* die_reader_func for dw2_get_file_names.  */
3982
3983 static void
3984 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3985                            const gdb_byte *info_ptr,
3986                            struct die_info *comp_unit_die,
3987                            int has_children,
3988                            void *data)
3989 {
3990   struct dwarf2_cu *cu = reader->cu;
3991   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3992   struct dwarf2_per_objfile *dwarf2_per_objfile
3993     = cu->per_cu->dwarf2_per_objfile;
3994   struct objfile *objfile = dwarf2_per_objfile->objfile;
3995   struct dwarf2_per_cu_data *lh_cu;
3996   struct attribute *attr;
3997   int i;
3998   void **slot;
3999   struct quick_file_names *qfn;
4000
4001   gdb_assert (! this_cu->is_debug_types);
4002
4003   /* Our callers never want to match partial units -- instead they
4004      will match the enclosing full CU.  */
4005   if (comp_unit_die->tag == DW_TAG_partial_unit)
4006     {
4007       this_cu->v.quick->no_file_data = 1;
4008       return;
4009     }
4010
4011   lh_cu = this_cu;
4012   slot = NULL;
4013
4014   line_header_up lh;
4015   sect_offset line_offset {};
4016
4017   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4018   if (attr)
4019     {
4020       struct quick_file_names find_entry;
4021
4022       line_offset = (sect_offset) DW_UNSND (attr);
4023
4024       /* We may have already read in this line header (TU line header sharing).
4025          If we have we're done.  */
4026       find_entry.hash.dwo_unit = cu->dwo_unit;
4027       find_entry.hash.line_sect_off = line_offset;
4028       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
4029                              &find_entry, INSERT);
4030       if (*slot != NULL)
4031         {
4032           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
4033           return;
4034         }
4035
4036       lh = dwarf_decode_line_header (line_offset, cu);
4037     }
4038   if (lh == NULL)
4039     {
4040       lh_cu->v.quick->no_file_data = 1;
4041       return;
4042     }
4043
4044   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4045   qfn->hash.dwo_unit = cu->dwo_unit;
4046   qfn->hash.line_sect_off = line_offset;
4047   gdb_assert (slot != NULL);
4048   *slot = qfn;
4049
4050   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4051
4052   qfn->num_file_names = lh->file_names.size ();
4053   qfn->file_names =
4054     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4055   for (i = 0; i < lh->file_names.size (); ++i)
4056     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4057   qfn->real_names = NULL;
4058
4059   lh_cu->v.quick->file_names = qfn;
4060 }
4061
4062 /* A helper for the "quick" functions which attempts to read the line
4063    table for THIS_CU.  */
4064
4065 static struct quick_file_names *
4066 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4067 {
4068   /* This should never be called for TUs.  */
4069   gdb_assert (! this_cu->is_debug_types);
4070   /* Nor type unit groups.  */
4071   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4072
4073   if (this_cu->v.quick->file_names != NULL)
4074     return this_cu->v.quick->file_names;
4075   /* If we know there is no line data, no point in looking again.  */
4076   if (this_cu->v.quick->no_file_data)
4077     return NULL;
4078
4079   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4080
4081   if (this_cu->v.quick->no_file_data)
4082     return NULL;
4083   return this_cu->v.quick->file_names;
4084 }
4085
4086 /* A helper for the "quick" functions which computes and caches the
4087    real path for a given file name from the line table.  */
4088
4089 static const char *
4090 dw2_get_real_path (struct objfile *objfile,
4091                    struct quick_file_names *qfn, int index)
4092 {
4093   if (qfn->real_names == NULL)
4094     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4095                                       qfn->num_file_names, const char *);
4096
4097   if (qfn->real_names[index] == NULL)
4098     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4099
4100   return qfn->real_names[index];
4101 }
4102
4103 static struct symtab *
4104 dw2_find_last_source_symtab (struct objfile *objfile)
4105 {
4106   struct dwarf2_per_objfile *dwarf2_per_objfile
4107     = get_dwarf2_per_objfile (objfile);
4108   int index = dwarf2_per_objfile->n_comp_units - 1;
4109   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4110   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4111
4112   if (cust == NULL)
4113     return NULL;
4114
4115   return compunit_primary_filetab (cust);
4116 }
4117
4118 /* Traversal function for dw2_forget_cached_source_info.  */
4119
4120 static int
4121 dw2_free_cached_file_names (void **slot, void *info)
4122 {
4123   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4124
4125   if (file_data->real_names)
4126     {
4127       int i;
4128
4129       for (i = 0; i < file_data->num_file_names; ++i)
4130         {
4131           xfree ((void*) file_data->real_names[i]);
4132           file_data->real_names[i] = NULL;
4133         }
4134     }
4135
4136   return 1;
4137 }
4138
4139 static void
4140 dw2_forget_cached_source_info (struct objfile *objfile)
4141 {
4142   struct dwarf2_per_objfile *dwarf2_per_objfile
4143     = get_dwarf2_per_objfile (objfile);
4144
4145   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4146                           dw2_free_cached_file_names, NULL);
4147 }
4148
4149 /* Helper function for dw2_map_symtabs_matching_filename that expands
4150    the symtabs and calls the iterator.  */
4151
4152 static int
4153 dw2_map_expand_apply (struct objfile *objfile,
4154                       struct dwarf2_per_cu_data *per_cu,
4155                       const char *name, const char *real_path,
4156                       gdb::function_view<bool (symtab *)> callback)
4157 {
4158   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4159
4160   /* Don't visit already-expanded CUs.  */
4161   if (per_cu->v.quick->compunit_symtab)
4162     return 0;
4163
4164   /* This may expand more than one symtab, and we want to iterate over
4165      all of them.  */
4166   dw2_instantiate_symtab (per_cu);
4167
4168   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4169                                     last_made, callback);
4170 }
4171
4172 /* Implementation of the map_symtabs_matching_filename method.  */
4173
4174 static bool
4175 dw2_map_symtabs_matching_filename
4176   (struct objfile *objfile, const char *name, const char *real_path,
4177    gdb::function_view<bool (symtab *)> callback)
4178 {
4179   int i;
4180   const char *name_basename = lbasename (name);
4181   struct dwarf2_per_objfile *dwarf2_per_objfile
4182     = get_dwarf2_per_objfile (objfile);
4183
4184   /* The rule is CUs specify all the files, including those used by
4185      any TU, so there's no need to scan TUs here.  */
4186
4187   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4188     {
4189       int j;
4190       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4191       struct quick_file_names *file_data;
4192
4193       /* We only need to look at symtabs not already expanded.  */
4194       if (per_cu->v.quick->compunit_symtab)
4195         continue;
4196
4197       file_data = dw2_get_file_names (per_cu);
4198       if (file_data == NULL)
4199         continue;
4200
4201       for (j = 0; j < file_data->num_file_names; ++j)
4202         {
4203           const char *this_name = file_data->file_names[j];
4204           const char *this_real_name;
4205
4206           if (compare_filenames_for_search (this_name, name))
4207             {
4208               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4209                                         callback))
4210                 return true;
4211               continue;
4212             }
4213
4214           /* Before we invoke realpath, which can get expensive when many
4215              files are involved, do a quick comparison of the basenames.  */
4216           if (! basenames_may_differ
4217               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4218             continue;
4219
4220           this_real_name = dw2_get_real_path (objfile, file_data, j);
4221           if (compare_filenames_for_search (this_real_name, name))
4222             {
4223               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4224                                         callback))
4225                 return true;
4226               continue;
4227             }
4228
4229           if (real_path != NULL)
4230             {
4231               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4232               gdb_assert (IS_ABSOLUTE_PATH (name));
4233               if (this_real_name != NULL
4234                   && FILENAME_CMP (real_path, this_real_name) == 0)
4235                 {
4236                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4237                                             callback))
4238                     return true;
4239                   continue;
4240                 }
4241             }
4242         }
4243     }
4244
4245   return false;
4246 }
4247
4248 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4249
4250 struct dw2_symtab_iterator
4251 {
4252   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4253   struct dwarf2_per_objfile *dwarf2_per_objfile;
4254   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4255   int want_specific_block;
4256   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4257      Unused if !WANT_SPECIFIC_BLOCK.  */
4258   int block_index;
4259   /* The kind of symbol we're looking for.  */
4260   domain_enum domain;
4261   /* The list of CUs from the index entry of the symbol,
4262      or NULL if not found.  */
4263   offset_type *vec;
4264   /* The next element in VEC to look at.  */
4265   int next;
4266   /* The number of elements in VEC, or zero if there is no match.  */
4267   int length;
4268   /* Have we seen a global version of the symbol?
4269      If so we can ignore all further global instances.
4270      This is to work around gold/15646, inefficient gold-generated
4271      indices.  */
4272   int global_seen;
4273 };
4274
4275 /* Initialize the index symtab iterator ITER.
4276    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4277    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4278
4279 static void
4280 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4281                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4282                       int want_specific_block,
4283                       int block_index,
4284                       domain_enum domain,
4285                       const char *name)
4286 {
4287   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4288   iter->want_specific_block = want_specific_block;
4289   iter->block_index = block_index;
4290   iter->domain = domain;
4291   iter->next = 0;
4292   iter->global_seen = 0;
4293
4294   mapped_index *index = dwarf2_per_objfile->index_table;
4295
4296   /* index is NULL if OBJF_READNOW.  */
4297   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4298     iter->length = MAYBE_SWAP (*iter->vec);
4299   else
4300     {
4301       iter->vec = NULL;
4302       iter->length = 0;
4303     }
4304 }
4305
4306 /* Return the next matching CU or NULL if there are no more.  */
4307
4308 static struct dwarf2_per_cu_data *
4309 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4310 {
4311   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4312
4313   for ( ; iter->next < iter->length; ++iter->next)
4314     {
4315       offset_type cu_index_and_attrs =
4316         MAYBE_SWAP (iter->vec[iter->next + 1]);
4317       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4318       struct dwarf2_per_cu_data *per_cu;
4319       int want_static = iter->block_index != GLOBAL_BLOCK;
4320       /* This value is only valid for index versions >= 7.  */
4321       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4322       gdb_index_symbol_kind symbol_kind =
4323         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4324       /* Only check the symbol attributes if they're present.
4325          Indices prior to version 7 don't record them,
4326          and indices >= 7 may elide them for certain symbols
4327          (gold does this).  */
4328       int attrs_valid =
4329         (dwarf2_per_objfile->index_table->version >= 7
4330          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4331
4332       /* Don't crash on bad data.  */
4333       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4334                        + dwarf2_per_objfile->n_type_units))
4335         {
4336           complaint (&symfile_complaints,
4337                      _(".gdb_index entry has bad CU index"
4338                        " [in module %s]"),
4339                      objfile_name (dwarf2_per_objfile->objfile));
4340           continue;
4341         }
4342
4343       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4344
4345       /* Skip if already read in.  */
4346       if (per_cu->v.quick->compunit_symtab)
4347         continue;
4348
4349       /* Check static vs global.  */
4350       if (attrs_valid)
4351         {
4352           if (iter->want_specific_block
4353               && want_static != is_static)
4354             continue;
4355           /* Work around gold/15646.  */
4356           if (!is_static && iter->global_seen)
4357             continue;
4358           if (!is_static)
4359             iter->global_seen = 1;
4360         }
4361
4362       /* Only check the symbol's kind if it has one.  */
4363       if (attrs_valid)
4364         {
4365           switch (iter->domain)
4366             {
4367             case VAR_DOMAIN:
4368               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4369                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4370                   /* Some types are also in VAR_DOMAIN.  */
4371                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4372                 continue;
4373               break;
4374             case STRUCT_DOMAIN:
4375               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4376                 continue;
4377               break;
4378             case LABEL_DOMAIN:
4379               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4380                 continue;
4381               break;
4382             default:
4383               break;
4384             }
4385         }
4386
4387       ++iter->next;
4388       return per_cu;
4389     }
4390
4391   return NULL;
4392 }
4393
4394 static struct compunit_symtab *
4395 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4396                    const char *name, domain_enum domain)
4397 {
4398   struct compunit_symtab *stab_best = NULL;
4399   struct dwarf2_per_objfile *dwarf2_per_objfile
4400     = get_dwarf2_per_objfile (objfile);
4401
4402   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4403
4404   struct dw2_symtab_iterator iter;
4405   struct dwarf2_per_cu_data *per_cu;
4406
4407   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4408
4409   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4410     {
4411       struct symbol *sym, *with_opaque = NULL;
4412       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4413       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4414       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4415
4416       sym = block_find_symbol (block, name, domain,
4417                                block_find_non_opaque_type_preferred,
4418                                &with_opaque);
4419
4420       /* Some caution must be observed with overloaded functions
4421          and methods, since the index will not contain any overload
4422          information (but NAME might contain it).  */
4423
4424       if (sym != NULL
4425           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4426         return stab;
4427       if (with_opaque != NULL
4428           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4429         stab_best = stab;
4430
4431       /* Keep looking through other CUs.  */
4432     }
4433
4434   return stab_best;
4435 }
4436
4437 static void
4438 dw2_print_stats (struct objfile *objfile)
4439 {
4440   struct dwarf2_per_objfile *dwarf2_per_objfile
4441     = get_dwarf2_per_objfile (objfile);
4442   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4443   int count = 0;
4444
4445   for (int i = 0; i < total; ++i)
4446     {
4447       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4448
4449       if (!per_cu->v.quick->compunit_symtab)
4450         ++count;
4451     }
4452   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4453   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4454 }
4455
4456 /* This dumps minimal information about the index.
4457    It is called via "mt print objfiles".
4458    One use is to verify .gdb_index has been loaded by the
4459    gdb.dwarf2/gdb-index.exp testcase.  */
4460
4461 static void
4462 dw2_dump (struct objfile *objfile)
4463 {
4464   struct dwarf2_per_objfile *dwarf2_per_objfile
4465     = get_dwarf2_per_objfile (objfile);
4466
4467   gdb_assert (dwarf2_per_objfile->using_index);
4468   printf_filtered (".gdb_index:");
4469   if (dwarf2_per_objfile->index_table != NULL)
4470     {
4471       printf_filtered (" version %d\n",
4472                        dwarf2_per_objfile->index_table->version);
4473     }
4474   else
4475     printf_filtered (" faked for \"readnow\"\n");
4476   printf_filtered ("\n");
4477 }
4478
4479 static void
4480 dw2_relocate (struct objfile *objfile,
4481               const struct section_offsets *new_offsets,
4482               const struct section_offsets *delta)
4483 {
4484   /* There's nothing to relocate here.  */
4485 }
4486
4487 static void
4488 dw2_expand_symtabs_for_function (struct objfile *objfile,
4489                                  const char *func_name)
4490 {
4491   struct dwarf2_per_objfile *dwarf2_per_objfile
4492     = get_dwarf2_per_objfile (objfile);
4493
4494   struct dw2_symtab_iterator iter;
4495   struct dwarf2_per_cu_data *per_cu;
4496
4497   /* Note: It doesn't matter what we pass for block_index here.  */
4498   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4499                         func_name);
4500
4501   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4502     dw2_instantiate_symtab (per_cu);
4503
4504 }
4505
4506 static void
4507 dw2_expand_all_symtabs (struct objfile *objfile)
4508 {
4509   struct dwarf2_per_objfile *dwarf2_per_objfile
4510     = get_dwarf2_per_objfile (objfile);
4511   int total_units = (dwarf2_per_objfile->n_comp_units
4512                      + dwarf2_per_objfile->n_type_units);
4513
4514   for (int i = 0; i < total_units; ++i)
4515     {
4516       struct dwarf2_per_cu_data *per_cu
4517         = dw2_get_cutu (dwarf2_per_objfile, i);
4518
4519       dw2_instantiate_symtab (per_cu);
4520     }
4521 }
4522
4523 static void
4524 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4525                                   const char *fullname)
4526 {
4527   struct dwarf2_per_objfile *dwarf2_per_objfile
4528     = get_dwarf2_per_objfile (objfile);
4529
4530   /* We don't need to consider type units here.
4531      This is only called for examining code, e.g. expand_line_sal.
4532      There can be an order of magnitude (or more) more type units
4533      than comp units, and we avoid them if we can.  */
4534
4535   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4536     {
4537       int j;
4538       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4539       struct quick_file_names *file_data;
4540
4541       /* We only need to look at symtabs not already expanded.  */
4542       if (per_cu->v.quick->compunit_symtab)
4543         continue;
4544
4545       file_data = dw2_get_file_names (per_cu);
4546       if (file_data == NULL)
4547         continue;
4548
4549       for (j = 0; j < file_data->num_file_names; ++j)
4550         {
4551           const char *this_fullname = file_data->file_names[j];
4552
4553           if (filename_cmp (this_fullname, fullname) == 0)
4554             {
4555               dw2_instantiate_symtab (per_cu);
4556               break;
4557             }
4558         }
4559     }
4560 }
4561
4562 static void
4563 dw2_map_matching_symbols (struct objfile *objfile,
4564                           const char * name, domain_enum domain,
4565                           int global,
4566                           int (*callback) (struct block *,
4567                                            struct symbol *, void *),
4568                           void *data, symbol_name_match_type match,
4569                           symbol_compare_ftype *ordered_compare)
4570 {
4571   /* Currently unimplemented; used for Ada.  The function can be called if the
4572      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4573      does not look for non-Ada symbols this function should just return.  */
4574 }
4575
4576 /* Symbol name matcher for .gdb_index names.
4577
4578    Symbol names in .gdb_index have a few particularities:
4579
4580    - There's no indication of which is the language of each symbol.
4581
4582      Since each language has its own symbol name matching algorithm,
4583      and we don't know which language is the right one, we must match
4584      each symbol against all languages.  This would be a potential
4585      performance problem if it were not mitigated by the
4586      mapped_index::name_components lookup table, which significantly
4587      reduces the number of times we need to call into this matcher,
4588      making it a non-issue.
4589
4590    - Symbol names in the index have no overload (parameter)
4591      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4592      appear as "foo" in the index, for example.
4593
4594      This means that the lookup names passed to the symbol name
4595      matcher functions must have no parameter information either
4596      because (e.g.) symbol search name "foo" does not match
4597      lookup-name "foo(int)" [while swapping search name for lookup
4598      name would match].
4599 */
4600 class gdb_index_symbol_name_matcher
4601 {
4602 public:
4603   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4604   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4605
4606   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4607      Returns true if any matcher matches.  */
4608   bool matches (const char *symbol_name);
4609
4610 private:
4611   /* A reference to the lookup name we're matching against.  */
4612   const lookup_name_info &m_lookup_name;
4613
4614   /* A vector holding all the different symbol name matchers, for all
4615      languages.  */
4616   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4617 };
4618
4619 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4620   (const lookup_name_info &lookup_name)
4621     : m_lookup_name (lookup_name)
4622 {
4623   /* Prepare the vector of comparison functions upfront, to avoid
4624      doing the same work for each symbol.  Care is taken to avoid
4625      matching with the same matcher more than once if/when multiple
4626      languages use the same matcher function.  */
4627   auto &matchers = m_symbol_name_matcher_funcs;
4628   matchers.reserve (nr_languages);
4629
4630   matchers.push_back (default_symbol_name_matcher);
4631
4632   for (int i = 0; i < nr_languages; i++)
4633     {
4634       const language_defn *lang = language_def ((enum language) i);
4635       symbol_name_matcher_ftype *name_matcher
4636         = get_symbol_name_matcher (lang, m_lookup_name);
4637
4638       /* Don't insert the same comparison routine more than once.
4639          Note that we do this linear walk instead of a seemingly
4640          cheaper sorted insert, or use a std::set or something like
4641          that, because relative order of function addresses is not
4642          stable.  This is not a problem in practice because the number
4643          of supported languages is low, and the cost here is tiny
4644          compared to the number of searches we'll do afterwards using
4645          this object.  */
4646       if (name_matcher != default_symbol_name_matcher
4647           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4648               == matchers.end ()))
4649         matchers.push_back (name_matcher);
4650     }
4651 }
4652
4653 bool
4654 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4655 {
4656   for (auto matches_name : m_symbol_name_matcher_funcs)
4657     if (matches_name (symbol_name, m_lookup_name, NULL))
4658       return true;
4659
4660   return false;
4661 }
4662
4663 /* Starting from a search name, return the string that finds the upper
4664    bound of all strings that start with SEARCH_NAME in a sorted name
4665    list.  Returns the empty string to indicate that the upper bound is
4666    the end of the list.  */
4667
4668 static std::string
4669 make_sort_after_prefix_name (const char *search_name)
4670 {
4671   /* When looking to complete "func", we find the upper bound of all
4672      symbols that start with "func" by looking for where we'd insert
4673      the closest string that would follow "func" in lexicographical
4674      order.  Usually, that's "func"-with-last-character-incremented,
4675      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4676      will be UTF-8 multi-byte sequences, but we can't be certain.
4677      Especially mind the 0xff character, which is a valid character in
4678      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4679      rule out compilers allowing it in identifiers.  Note that
4680      conveniently, strcmp/strcasecmp are specified to compare
4681      characters interpreted as unsigned char.  So what we do is treat
4682      the whole string as a base 256 number composed of a sequence of
4683      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4684      to 0, and carries 1 to the following more-significant position.
4685      If the very first character in SEARCH_NAME ends up incremented
4686      and carries/overflows, then the upper bound is the end of the
4687      list.  The string after the empty string is also the empty
4688      string.
4689
4690      Some examples of this operation:
4691
4692        SEARCH_NAME  => "+1" RESULT
4693
4694        "abc"              => "abd"
4695        "ab\xff"           => "ac"
4696        "\xff" "a" "\xff"  => "\xff" "b"
4697        "\xff"             => ""
4698        "\xff\xff"         => ""
4699        ""                 => ""
4700
4701      Then, with these symbols for example:
4702
4703       func
4704       func1
4705       fund
4706
4707      completing "func" looks for symbols between "func" and
4708      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4709      which finds "func" and "func1", but not "fund".
4710
4711      And with:
4712
4713       funcÿ     (Latin1 'ÿ' [0xff])
4714       funcÿ1
4715       fund
4716
4717      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4718      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4719
4720      And with:
4721
4722       ÿÿ        (Latin1 'ÿ' [0xff])
4723       ÿÿ1
4724
4725      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4726      the end of the list.
4727   */
4728   std::string after = search_name;
4729   while (!after.empty () && (unsigned char) after.back () == 0xff)
4730     after.pop_back ();
4731   if (!after.empty ())
4732     after.back () = (unsigned char) after.back () + 1;
4733   return after;
4734 }
4735
4736 /* See declaration.  */
4737
4738 std::pair<std::vector<name_component>::const_iterator,
4739           std::vector<name_component>::const_iterator>
4740 mapped_index_base::find_name_components_bounds
4741   (const lookup_name_info &lookup_name_without_params) const
4742 {
4743   auto *name_cmp
4744     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4745
4746   const char *cplus
4747     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4748
4749   /* Comparison function object for lower_bound that matches against a
4750      given symbol name.  */
4751   auto lookup_compare_lower = [&] (const name_component &elem,
4752                                    const char *name)
4753     {
4754       const char *elem_qualified = this->symbol_name_at (elem.idx);
4755       const char *elem_name = elem_qualified + elem.name_offset;
4756       return name_cmp (elem_name, name) < 0;
4757     };
4758
4759   /* Comparison function object for upper_bound that matches against a
4760      given symbol name.  */
4761   auto lookup_compare_upper = [&] (const char *name,
4762                                    const name_component &elem)
4763     {
4764       const char *elem_qualified = this->symbol_name_at (elem.idx);
4765       const char *elem_name = elem_qualified + elem.name_offset;
4766       return name_cmp (name, elem_name) < 0;
4767     };
4768
4769   auto begin = this->name_components.begin ();
4770   auto end = this->name_components.end ();
4771
4772   /* Find the lower bound.  */
4773   auto lower = [&] ()
4774     {
4775       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4776         return begin;
4777       else
4778         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4779     } ();
4780
4781   /* Find the upper bound.  */
4782   auto upper = [&] ()
4783     {
4784       if (lookup_name_without_params.completion_mode ())
4785         {
4786           /* In completion mode, we want UPPER to point past all
4787              symbols names that have the same prefix.  I.e., with
4788              these symbols, and completing "func":
4789
4790               function        << lower bound
4791               function1
4792               other_function  << upper bound
4793
4794              We find the upper bound by looking for the insertion
4795              point of "func"-with-last-character-incremented,
4796              i.e. "fund".  */
4797           std::string after = make_sort_after_prefix_name (cplus);
4798           if (after.empty ())
4799             return end;
4800           return std::lower_bound (lower, end, after.c_str (),
4801                                    lookup_compare_lower);
4802         }
4803       else
4804         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4805     } ();
4806
4807   return {lower, upper};
4808 }
4809
4810 /* See declaration.  */
4811
4812 void
4813 mapped_index_base::build_name_components ()
4814 {
4815   if (!this->name_components.empty ())
4816     return;
4817
4818   this->name_components_casing = case_sensitivity;
4819   auto *name_cmp
4820     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4821
4822   /* The code below only knows how to break apart components of C++
4823      symbol names (and other languages that use '::' as
4824      namespace/module separator).  If we add support for wild matching
4825      to some language that uses some other operator (E.g., Ada, Go and
4826      D use '.'), then we'll need to try splitting the symbol name
4827      according to that language too.  Note that Ada does support wild
4828      matching, but doesn't currently support .gdb_index.  */
4829   auto count = this->symbol_name_count ();
4830   for (offset_type idx = 0; idx < count; idx++)
4831     {
4832       if (this->symbol_name_slot_invalid (idx))
4833         continue;
4834
4835       const char *name = this->symbol_name_at (idx);
4836
4837       /* Add each name component to the name component table.  */
4838       unsigned int previous_len = 0;
4839       for (unsigned int current_len = cp_find_first_component (name);
4840            name[current_len] != '\0';
4841            current_len += cp_find_first_component (name + current_len))
4842         {
4843           gdb_assert (name[current_len] == ':');
4844           this->name_components.push_back ({previous_len, idx});
4845           /* Skip the '::'.  */
4846           current_len += 2;
4847           previous_len = current_len;
4848         }
4849       this->name_components.push_back ({previous_len, idx});
4850     }
4851
4852   /* Sort name_components elements by name.  */
4853   auto name_comp_compare = [&] (const name_component &left,
4854                                 const name_component &right)
4855     {
4856       const char *left_qualified = this->symbol_name_at (left.idx);
4857       const char *right_qualified = this->symbol_name_at (right.idx);
4858
4859       const char *left_name = left_qualified + left.name_offset;
4860       const char *right_name = right_qualified + right.name_offset;
4861
4862       return name_cmp (left_name, right_name) < 0;
4863     };
4864
4865   std::sort (this->name_components.begin (),
4866              this->name_components.end (),
4867              name_comp_compare);
4868 }
4869
4870 /* Helper for dw2_expand_symtabs_matching that works with a
4871    mapped_index_base instead of the containing objfile.  This is split
4872    to a separate function in order to be able to unit test the
4873    name_components matching using a mock mapped_index_base.  For each
4874    symbol name that matches, calls MATCH_CALLBACK, passing it the
4875    symbol's index in the mapped_index_base symbol table.  */
4876
4877 static void
4878 dw2_expand_symtabs_matching_symbol
4879   (mapped_index_base &index,
4880    const lookup_name_info &lookup_name_in,
4881    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4882    enum search_domain kind,
4883    gdb::function_view<void (offset_type)> match_callback)
4884 {
4885   lookup_name_info lookup_name_without_params
4886     = lookup_name_in.make_ignore_params ();
4887   gdb_index_symbol_name_matcher lookup_name_matcher
4888     (lookup_name_without_params);
4889
4890   /* Build the symbol name component sorted vector, if we haven't
4891      yet.  */
4892   index.build_name_components ();
4893
4894   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4895
4896   /* Now for each symbol name in range, check to see if we have a name
4897      match, and if so, call the MATCH_CALLBACK callback.  */
4898
4899   /* The same symbol may appear more than once in the range though.
4900      E.g., if we're looking for symbols that complete "w", and we have
4901      a symbol named "w1::w2", we'll find the two name components for
4902      that same symbol in the range.  To be sure we only call the
4903      callback once per symbol, we first collect the symbol name
4904      indexes that matched in a temporary vector and ignore
4905      duplicates.  */
4906   std::vector<offset_type> matches;
4907   matches.reserve (std::distance (bounds.first, bounds.second));
4908
4909   for (; bounds.first != bounds.second; ++bounds.first)
4910     {
4911       const char *qualified = index.symbol_name_at (bounds.first->idx);
4912
4913       if (!lookup_name_matcher.matches (qualified)
4914           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4915         continue;
4916
4917       matches.push_back (bounds.first->idx);
4918     }
4919
4920   std::sort (matches.begin (), matches.end ());
4921
4922   /* Finally call the callback, once per match.  */
4923   ULONGEST prev = -1;
4924   for (offset_type idx : matches)
4925     {
4926       if (prev != idx)
4927         {
4928           match_callback (idx);
4929           prev = idx;
4930         }
4931     }
4932
4933   /* Above we use a type wider than idx's for 'prev', since 0 and
4934      (offset_type)-1 are both possible values.  */
4935   static_assert (sizeof (prev) > sizeof (offset_type), "");
4936 }
4937
4938 #if GDB_SELF_TEST
4939
4940 namespace selftests { namespace dw2_expand_symtabs_matching {
4941
4942 /* A mock .gdb_index/.debug_names-like name index table, enough to
4943    exercise dw2_expand_symtabs_matching_symbol, which works with the
4944    mapped_index_base interface.  Builds an index from the symbol list
4945    passed as parameter to the constructor.  */
4946 class mock_mapped_index : public mapped_index_base
4947 {
4948 public:
4949   mock_mapped_index (gdb::array_view<const char *> symbols)
4950     : m_symbol_table (symbols)
4951   {}
4952
4953   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4954
4955   /* Return the number of names in the symbol table.  */
4956   virtual size_t symbol_name_count () const
4957   {
4958     return m_symbol_table.size ();
4959   }
4960
4961   /* Get the name of the symbol at IDX in the symbol table.  */
4962   virtual const char *symbol_name_at (offset_type idx) const
4963   {
4964     return m_symbol_table[idx];
4965   }
4966
4967 private:
4968   gdb::array_view<const char *> m_symbol_table;
4969 };
4970
4971 /* Convenience function that converts a NULL pointer to a "<null>"
4972    string, to pass to print routines.  */
4973
4974 static const char *
4975 string_or_null (const char *str)
4976 {
4977   return str != NULL ? str : "<null>";
4978 }
4979
4980 /* Check if a lookup_name_info built from
4981    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4982    index.  EXPECTED_LIST is the list of expected matches, in expected
4983    matching order.  If no match expected, then an empty list is
4984    specified.  Returns true on success.  On failure prints a warning
4985    indicating the file:line that failed, and returns false.  */
4986
4987 static bool
4988 check_match (const char *file, int line,
4989              mock_mapped_index &mock_index,
4990              const char *name, symbol_name_match_type match_type,
4991              bool completion_mode,
4992              std::initializer_list<const char *> expected_list)
4993 {
4994   lookup_name_info lookup_name (name, match_type, completion_mode);
4995
4996   bool matched = true;
4997
4998   auto mismatch = [&] (const char *expected_str,
4999                        const char *got)
5000   {
5001     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
5002                "expected=\"%s\", got=\"%s\"\n"),
5003              file, line,
5004              (match_type == symbol_name_match_type::FULL
5005               ? "FULL" : "WILD"),
5006              name, string_or_null (expected_str), string_or_null (got));
5007     matched = false;
5008   };
5009
5010   auto expected_it = expected_list.begin ();
5011   auto expected_end = expected_list.end ();
5012
5013   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
5014                                       NULL, ALL_DOMAIN,
5015                                       [&] (offset_type idx)
5016   {
5017     const char *matched_name = mock_index.symbol_name_at (idx);
5018     const char *expected_str
5019       = expected_it == expected_end ? NULL : *expected_it++;
5020
5021     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
5022       mismatch (expected_str, matched_name);
5023   });
5024
5025   const char *expected_str
5026   = expected_it == expected_end ? NULL : *expected_it++;
5027   if (expected_str != NULL)
5028     mismatch (expected_str, NULL);
5029
5030   return matched;
5031 }
5032
5033 /* The symbols added to the mock mapped_index for testing (in
5034    canonical form).  */
5035 static const char *test_symbols[] = {
5036   "function",
5037   "std::bar",
5038   "std::zfunction",
5039   "std::zfunction2",
5040   "w1::w2",
5041   "ns::foo<char*>",
5042   "ns::foo<int>",
5043   "ns::foo<long>",
5044   "ns2::tmpl<int>::foo2",
5045   "(anonymous namespace)::A::B::C",
5046
5047   /* These are used to check that the increment-last-char in the
5048      matching algorithm for completion doesn't match "t1_fund" when
5049      completing "t1_func".  */
5050   "t1_func",
5051   "t1_func1",
5052   "t1_fund",
5053   "t1_fund1",
5054
5055   /* A UTF-8 name with multi-byte sequences to make sure that
5056      cp-name-parser understands this as a single identifier ("função"
5057      is "function" in PT).  */
5058   u8"u8função",
5059
5060   /* \377 (0xff) is Latin1 'ÿ'.  */
5061   "yfunc\377",
5062
5063   /* \377 (0xff) is Latin1 'ÿ'.  */
5064   "\377",
5065   "\377\377123",
5066
5067   /* A name with all sorts of complications.  Starts with "z" to make
5068      it easier for the completion tests below.  */
5069 #define Z_SYM_NAME \
5070   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5071     "::tuple<(anonymous namespace)::ui*, " \
5072     "std::default_delete<(anonymous namespace)::ui>, void>"
5073
5074   Z_SYM_NAME
5075 };
5076
5077 /* Returns true if the mapped_index_base::find_name_component_bounds
5078    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5079    in completion mode.  */
5080
5081 static bool
5082 check_find_bounds_finds (mapped_index_base &index,
5083                          const char *search_name,
5084                          gdb::array_view<const char *> expected_syms)
5085 {
5086   lookup_name_info lookup_name (search_name,
5087                                 symbol_name_match_type::FULL, true);
5088
5089   auto bounds = index.find_name_components_bounds (lookup_name);
5090
5091   size_t distance = std::distance (bounds.first, bounds.second);
5092   if (distance != expected_syms.size ())
5093     return false;
5094
5095   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5096     {
5097       auto nc_elem = bounds.first + exp_elem;
5098       const char *qualified = index.symbol_name_at (nc_elem->idx);
5099       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5100         return false;
5101     }
5102
5103   return true;
5104 }
5105
5106 /* Test the lower-level mapped_index::find_name_component_bounds
5107    method.  */
5108
5109 static void
5110 test_mapped_index_find_name_component_bounds ()
5111 {
5112   mock_mapped_index mock_index (test_symbols);
5113
5114   mock_index.build_name_components ();
5115
5116   /* Test the lower-level mapped_index::find_name_component_bounds
5117      method in completion mode.  */
5118   {
5119     static const char *expected_syms[] = {
5120       "t1_func",
5121       "t1_func1",
5122     };
5123
5124     SELF_CHECK (check_find_bounds_finds (mock_index,
5125                                          "t1_func", expected_syms));
5126   }
5127
5128   /* Check that the increment-last-char in the name matching algorithm
5129      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5130   {
5131     static const char *expected_syms1[] = {
5132       "\377",
5133       "\377\377123",
5134     };
5135     SELF_CHECK (check_find_bounds_finds (mock_index,
5136                                          "\377", expected_syms1));
5137
5138     static const char *expected_syms2[] = {
5139       "\377\377123",
5140     };
5141     SELF_CHECK (check_find_bounds_finds (mock_index,
5142                                          "\377\377", expected_syms2));
5143   }
5144 }
5145
5146 /* Test dw2_expand_symtabs_matching_symbol.  */
5147
5148 static void
5149 test_dw2_expand_symtabs_matching_symbol ()
5150 {
5151   mock_mapped_index mock_index (test_symbols);
5152
5153   /* We let all tests run until the end even if some fails, for debug
5154      convenience.  */
5155   bool any_mismatch = false;
5156
5157   /* Create the expected symbols list (an initializer_list).  Needed
5158      because lists have commas, and we need to pass them to CHECK,
5159      which is a macro.  */
5160 #define EXPECT(...) { __VA_ARGS__ }
5161
5162   /* Wrapper for check_match that passes down the current
5163      __FILE__/__LINE__.  */
5164 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5165   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5166                                 mock_index,                             \
5167                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5168                                 EXPECTED_LIST)
5169
5170   /* Identity checks.  */
5171   for (const char *sym : test_symbols)
5172     {
5173       /* Should be able to match all existing symbols.  */
5174       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5175                    EXPECT (sym));
5176
5177       /* Should be able to match all existing symbols with
5178          parameters.  */
5179       std::string with_params = std::string (sym) + "(int)";
5180       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5181                    EXPECT (sym));
5182
5183       /* Should be able to match all existing symbols with
5184          parameters and qualifiers.  */
5185       with_params = std::string (sym) + " ( int ) const";
5186       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5187                    EXPECT (sym));
5188
5189       /* This should really find sym, but cp-name-parser.y doesn't
5190          know about lvalue/rvalue qualifiers yet.  */
5191       with_params = std::string (sym) + " ( int ) &&";
5192       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5193                    {});
5194     }
5195
5196   /* Check that the name matching algorithm for completion doesn't get
5197      confused with Latin1 'ÿ' / 0xff.  */
5198   {
5199     static const char str[] = "\377";
5200     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5201                  EXPECT ("\377", "\377\377123"));
5202   }
5203
5204   /* Check that the increment-last-char in the matching algorithm for
5205      completion doesn't match "t1_fund" when completing "t1_func".  */
5206   {
5207     static const char str[] = "t1_func";
5208     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5209                  EXPECT ("t1_func", "t1_func1"));
5210   }
5211
5212   /* Check that completion mode works at each prefix of the expected
5213      symbol name.  */
5214   {
5215     static const char str[] = "function(int)";
5216     size_t len = strlen (str);
5217     std::string lookup;
5218
5219     for (size_t i = 1; i < len; i++)
5220       {
5221         lookup.assign (str, i);
5222         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5223                      EXPECT ("function"));
5224       }
5225   }
5226
5227   /* While "w" is a prefix of both components, the match function
5228      should still only be called once.  */
5229   {
5230     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5231                  EXPECT ("w1::w2"));
5232     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5233                  EXPECT ("w1::w2"));
5234   }
5235
5236   /* Same, with a "complicated" symbol.  */
5237   {
5238     static const char str[] = Z_SYM_NAME;
5239     size_t len = strlen (str);
5240     std::string lookup;
5241
5242     for (size_t i = 1; i < len; i++)
5243       {
5244         lookup.assign (str, i);
5245         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5246                      EXPECT (Z_SYM_NAME));
5247       }
5248   }
5249
5250   /* In FULL mode, an incomplete symbol doesn't match.  */
5251   {
5252     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5253                  {});
5254   }
5255
5256   /* A complete symbol with parameters matches any overload, since the
5257      index has no overload info.  */
5258   {
5259     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5260                  EXPECT ("std::zfunction", "std::zfunction2"));
5261     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5262                  EXPECT ("std::zfunction", "std::zfunction2"));
5263     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5264                  EXPECT ("std::zfunction", "std::zfunction2"));
5265   }
5266
5267   /* Check that whitespace is ignored appropriately.  A symbol with a
5268      template argument list. */
5269   {
5270     static const char expected[] = "ns::foo<int>";
5271     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5272                  EXPECT (expected));
5273     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5274                  EXPECT (expected));
5275   }
5276
5277   /* Check that whitespace is ignored appropriately.  A symbol with a
5278      template argument list that includes a pointer.  */
5279   {
5280     static const char expected[] = "ns::foo<char*>";
5281     /* Try both completion and non-completion modes.  */
5282     static const bool completion_mode[2] = {false, true};
5283     for (size_t i = 0; i < 2; i++)
5284       {
5285         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5286                      completion_mode[i], EXPECT (expected));
5287         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5288                      completion_mode[i], EXPECT (expected));
5289
5290         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5291                      completion_mode[i], EXPECT (expected));
5292         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5293                      completion_mode[i], EXPECT (expected));
5294       }
5295   }
5296
5297   {
5298     /* Check method qualifiers are ignored.  */
5299     static const char expected[] = "ns::foo<char*>";
5300     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5301                  symbol_name_match_type::FULL, true, EXPECT (expected));
5302     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5303                  symbol_name_match_type::FULL, true, EXPECT (expected));
5304     CHECK_MATCH ("foo < char * >  ( int ) const",
5305                  symbol_name_match_type::WILD, true, EXPECT (expected));
5306     CHECK_MATCH ("foo < char * >  ( int ) &&",
5307                  symbol_name_match_type::WILD, true, EXPECT (expected));
5308   }
5309
5310   /* Test lookup names that don't match anything.  */
5311   {
5312     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5313                  {});
5314
5315     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5316                  {});
5317   }
5318
5319   /* Some wild matching tests, exercising "(anonymous namespace)",
5320      which should not be confused with a parameter list.  */
5321   {
5322     static const char *syms[] = {
5323       "A::B::C",
5324       "B::C",
5325       "C",
5326       "A :: B :: C ( int )",
5327       "B :: C ( int )",
5328       "C ( int )",
5329     };
5330
5331     for (const char *s : syms)
5332       {
5333         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5334                      EXPECT ("(anonymous namespace)::A::B::C"));
5335       }
5336   }
5337
5338   {
5339     static const char expected[] = "ns2::tmpl<int>::foo2";
5340     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5341                  EXPECT (expected));
5342     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5343                  EXPECT (expected));
5344   }
5345
5346   SELF_CHECK (!any_mismatch);
5347
5348 #undef EXPECT
5349 #undef CHECK_MATCH
5350 }
5351
5352 static void
5353 run_test ()
5354 {
5355   test_mapped_index_find_name_component_bounds ();
5356   test_dw2_expand_symtabs_matching_symbol ();
5357 }
5358
5359 }} // namespace selftests::dw2_expand_symtabs_matching
5360
5361 #endif /* GDB_SELF_TEST */
5362
5363 /* If FILE_MATCHER is NULL or if PER_CU has
5364    dwarf2_per_cu_quick_data::MARK set (see
5365    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5366    EXPANSION_NOTIFY on it.  */
5367
5368 static void
5369 dw2_expand_symtabs_matching_one
5370   (struct dwarf2_per_cu_data *per_cu,
5371    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5372    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5373 {
5374   if (file_matcher == NULL || per_cu->v.quick->mark)
5375     {
5376       bool symtab_was_null
5377         = (per_cu->v.quick->compunit_symtab == NULL);
5378
5379       dw2_instantiate_symtab (per_cu);
5380
5381       if (expansion_notify != NULL
5382           && symtab_was_null
5383           && per_cu->v.quick->compunit_symtab != NULL)
5384         expansion_notify (per_cu->v.quick->compunit_symtab);
5385     }
5386 }
5387
5388 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5389    matched, to expand corresponding CUs that were marked.  IDX is the
5390    index of the symbol name that matched.  */
5391
5392 static void
5393 dw2_expand_marked_cus
5394   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5395    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5396    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5397    search_domain kind)
5398 {
5399   offset_type *vec, vec_len, vec_idx;
5400   bool global_seen = false;
5401   mapped_index &index = *dwarf2_per_objfile->index_table;
5402
5403   vec = (offset_type *) (index.constant_pool
5404                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5405   vec_len = MAYBE_SWAP (vec[0]);
5406   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5407     {
5408       struct dwarf2_per_cu_data *per_cu;
5409       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5410       /* This value is only valid for index versions >= 7.  */
5411       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5412       gdb_index_symbol_kind symbol_kind =
5413         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5414       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5415       /* Only check the symbol attributes if they're present.
5416          Indices prior to version 7 don't record them,
5417          and indices >= 7 may elide them for certain symbols
5418          (gold does this).  */
5419       int attrs_valid =
5420         (index.version >= 7
5421          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5422
5423       /* Work around gold/15646.  */
5424       if (attrs_valid)
5425         {
5426           if (!is_static && global_seen)
5427             continue;
5428           if (!is_static)
5429             global_seen = true;
5430         }
5431
5432       /* Only check the symbol's kind if it has one.  */
5433       if (attrs_valid)
5434         {
5435           switch (kind)
5436             {
5437             case VARIABLES_DOMAIN:
5438               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5439                 continue;
5440               break;
5441             case FUNCTIONS_DOMAIN:
5442               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5443                 continue;
5444               break;
5445             case TYPES_DOMAIN:
5446               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5447                 continue;
5448               break;
5449             default:
5450               break;
5451             }
5452         }
5453
5454       /* Don't crash on bad data.  */
5455       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5456                        + dwarf2_per_objfile->n_type_units))
5457         {
5458           complaint (&symfile_complaints,
5459                      _(".gdb_index entry has bad CU index"
5460                        " [in module %s]"),
5461                        objfile_name (dwarf2_per_objfile->objfile));
5462           continue;
5463         }
5464
5465       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5466       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5467                                        expansion_notify);
5468     }
5469 }
5470
5471 /* If FILE_MATCHER is non-NULL, set all the
5472    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5473    that match FILE_MATCHER.  */
5474
5475 static void
5476 dw_expand_symtabs_matching_file_matcher
5477   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5478    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5479 {
5480   if (file_matcher == NULL)
5481     return;
5482
5483   objfile *const objfile = dwarf2_per_objfile->objfile;
5484
5485   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5486                                             htab_eq_pointer,
5487                                             NULL, xcalloc, xfree));
5488   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5489                                                 htab_eq_pointer,
5490                                                 NULL, xcalloc, xfree));
5491
5492   /* The rule is CUs specify all the files, including those used by
5493      any TU, so there's no need to scan TUs here.  */
5494
5495   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5496     {
5497       int j;
5498       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5499       struct quick_file_names *file_data;
5500       void **slot;
5501
5502       QUIT;
5503
5504       per_cu->v.quick->mark = 0;
5505
5506       /* We only need to look at symtabs not already expanded.  */
5507       if (per_cu->v.quick->compunit_symtab)
5508         continue;
5509
5510       file_data = dw2_get_file_names (per_cu);
5511       if (file_data == NULL)
5512         continue;
5513
5514       if (htab_find (visited_not_found.get (), file_data) != NULL)
5515         continue;
5516       else if (htab_find (visited_found.get (), file_data) != NULL)
5517         {
5518           per_cu->v.quick->mark = 1;
5519           continue;
5520         }
5521
5522       for (j = 0; j < file_data->num_file_names; ++j)
5523         {
5524           const char *this_real_name;
5525
5526           if (file_matcher (file_data->file_names[j], false))
5527             {
5528               per_cu->v.quick->mark = 1;
5529               break;
5530             }
5531
5532           /* Before we invoke realpath, which can get expensive when many
5533              files are involved, do a quick comparison of the basenames.  */
5534           if (!basenames_may_differ
5535               && !file_matcher (lbasename (file_data->file_names[j]),
5536                                 true))
5537             continue;
5538
5539           this_real_name = dw2_get_real_path (objfile, file_data, j);
5540           if (file_matcher (this_real_name, false))
5541             {
5542               per_cu->v.quick->mark = 1;
5543               break;
5544             }
5545         }
5546
5547       slot = htab_find_slot (per_cu->v.quick->mark
5548                              ? visited_found.get ()
5549                              : visited_not_found.get (),
5550                              file_data, INSERT);
5551       *slot = file_data;
5552     }
5553 }
5554
5555 static void
5556 dw2_expand_symtabs_matching
5557   (struct objfile *objfile,
5558    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5559    const lookup_name_info &lookup_name,
5560    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5561    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5562    enum search_domain kind)
5563 {
5564   struct dwarf2_per_objfile *dwarf2_per_objfile
5565     = get_dwarf2_per_objfile (objfile);
5566
5567   /* index_table is NULL if OBJF_READNOW.  */
5568   if (!dwarf2_per_objfile->index_table)
5569     return;
5570
5571   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5572
5573   mapped_index &index = *dwarf2_per_objfile->index_table;
5574
5575   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5576                                       symbol_matcher,
5577                                       kind, [&] (offset_type idx)
5578     {
5579       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5580                              expansion_notify, kind);
5581     });
5582 }
5583
5584 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5585    symtab.  */
5586
5587 static struct compunit_symtab *
5588 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5589                                           CORE_ADDR pc)
5590 {
5591   int i;
5592
5593   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5594       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5595     return cust;
5596
5597   if (cust->includes == NULL)
5598     return NULL;
5599
5600   for (i = 0; cust->includes[i]; ++i)
5601     {
5602       struct compunit_symtab *s = cust->includes[i];
5603
5604       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5605       if (s != NULL)
5606         return s;
5607     }
5608
5609   return NULL;
5610 }
5611
5612 static struct compunit_symtab *
5613 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5614                                   struct bound_minimal_symbol msymbol,
5615                                   CORE_ADDR pc,
5616                                   struct obj_section *section,
5617                                   int warn_if_readin)
5618 {
5619   struct dwarf2_per_cu_data *data;
5620   struct compunit_symtab *result;
5621
5622   if (!objfile->psymtabs_addrmap)
5623     return NULL;
5624
5625   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5626                                                      pc);
5627   if (!data)
5628     return NULL;
5629
5630   if (warn_if_readin && data->v.quick->compunit_symtab)
5631     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5632              paddress (get_objfile_arch (objfile), pc));
5633
5634   result
5635     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5636                                                 pc);
5637   gdb_assert (result != NULL);
5638   return result;
5639 }
5640
5641 static void
5642 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5643                           void *data, int need_fullname)
5644 {
5645   struct dwarf2_per_objfile *dwarf2_per_objfile
5646     = get_dwarf2_per_objfile (objfile);
5647
5648   if (!dwarf2_per_objfile->filenames_cache)
5649     {
5650       dwarf2_per_objfile->filenames_cache.emplace ();
5651
5652       htab_up visited (htab_create_alloc (10,
5653                                           htab_hash_pointer, htab_eq_pointer,
5654                                           NULL, xcalloc, xfree));
5655
5656       /* The rule is CUs specify all the files, including those used
5657          by any TU, so there's no need to scan TUs here.  We can
5658          ignore file names coming from already-expanded CUs.  */
5659
5660       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5661         {
5662           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5663
5664           if (per_cu->v.quick->compunit_symtab)
5665             {
5666               void **slot = htab_find_slot (visited.get (),
5667                                             per_cu->v.quick->file_names,
5668                                             INSERT);
5669
5670               *slot = per_cu->v.quick->file_names;
5671             }
5672         }
5673
5674       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5675         {
5676           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5677           struct quick_file_names *file_data;
5678           void **slot;
5679
5680           /* We only need to look at symtabs not already expanded.  */
5681           if (per_cu->v.quick->compunit_symtab)
5682             continue;
5683
5684           file_data = dw2_get_file_names (per_cu);
5685           if (file_data == NULL)
5686             continue;
5687
5688           slot = htab_find_slot (visited.get (), file_data, INSERT);
5689           if (*slot)
5690             {
5691               /* Already visited.  */
5692               continue;
5693             }
5694           *slot = file_data;
5695
5696           for (int j = 0; j < file_data->num_file_names; ++j)
5697             {
5698               const char *filename = file_data->file_names[j];
5699               dwarf2_per_objfile->filenames_cache->seen (filename);
5700             }
5701         }
5702     }
5703
5704   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5705     {
5706       gdb::unique_xmalloc_ptr<char> this_real_name;
5707
5708       if (need_fullname)
5709         this_real_name = gdb_realpath (filename);
5710       (*fun) (filename, this_real_name.get (), data);
5711     });
5712 }
5713
5714 static int
5715 dw2_has_symbols (struct objfile *objfile)
5716 {
5717   return 1;
5718 }
5719
5720 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5721 {
5722   dw2_has_symbols,
5723   dw2_find_last_source_symtab,
5724   dw2_forget_cached_source_info,
5725   dw2_map_symtabs_matching_filename,
5726   dw2_lookup_symbol,
5727   dw2_print_stats,
5728   dw2_dump,
5729   dw2_relocate,
5730   dw2_expand_symtabs_for_function,
5731   dw2_expand_all_symtabs,
5732   dw2_expand_symtabs_with_fullname,
5733   dw2_map_matching_symbols,
5734   dw2_expand_symtabs_matching,
5735   dw2_find_pc_sect_compunit_symtab,
5736   NULL,
5737   dw2_map_symbol_filenames
5738 };
5739
5740 /* DWARF-5 debug_names reader.  */
5741
5742 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5743 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5744
5745 /* A helper function that reads the .debug_names section in SECTION
5746    and fills in MAP.  FILENAME is the name of the file containing the
5747    section; it is used for error reporting.
5748
5749    Returns true if all went well, false otherwise.  */
5750
5751 static bool
5752 read_debug_names_from_section (struct objfile *objfile,
5753                                const char *filename,
5754                                struct dwarf2_section_info *section,
5755                                mapped_debug_names &map)
5756 {
5757   if (dwarf2_section_empty_p (section))
5758     return false;
5759
5760   /* Older elfutils strip versions could keep the section in the main
5761      executable while splitting it for the separate debug info file.  */
5762   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5763     return false;
5764
5765   dwarf2_read_section (objfile, section);
5766
5767   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5768
5769   const gdb_byte *addr = section->buffer;
5770
5771   bfd *const abfd = get_section_bfd_owner (section);
5772
5773   unsigned int bytes_read;
5774   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5775   addr += bytes_read;
5776
5777   map.dwarf5_is_dwarf64 = bytes_read != 4;
5778   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5779   if (bytes_read + length != section->size)
5780     {
5781       /* There may be multiple per-CU indices.  */
5782       warning (_("Section .debug_names in %s length %s does not match "
5783                  "section length %s, ignoring .debug_names."),
5784                filename, plongest (bytes_read + length),
5785                pulongest (section->size));
5786       return false;
5787     }
5788
5789   /* The version number.  */
5790   uint16_t version = read_2_bytes (abfd, addr);
5791   addr += 2;
5792   if (version != 5)
5793     {
5794       warning (_("Section .debug_names in %s has unsupported version %d, "
5795                  "ignoring .debug_names."),
5796                filename, version);
5797       return false;
5798     }
5799
5800   /* Padding.  */
5801   uint16_t padding = read_2_bytes (abfd, addr);
5802   addr += 2;
5803   if (padding != 0)
5804     {
5805       warning (_("Section .debug_names in %s has unsupported padding %d, "
5806                  "ignoring .debug_names."),
5807                filename, padding);
5808       return false;
5809     }
5810
5811   /* comp_unit_count - The number of CUs in the CU list.  */
5812   map.cu_count = read_4_bytes (abfd, addr);
5813   addr += 4;
5814
5815   /* local_type_unit_count - The number of TUs in the local TU
5816      list.  */
5817   map.tu_count = read_4_bytes (abfd, addr);
5818   addr += 4;
5819
5820   /* foreign_type_unit_count - The number of TUs in the foreign TU
5821      list.  */
5822   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5823   addr += 4;
5824   if (foreign_tu_count != 0)
5825     {
5826       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5827                  "ignoring .debug_names."),
5828                filename, static_cast<unsigned long> (foreign_tu_count));
5829       return false;
5830     }
5831
5832   /* bucket_count - The number of hash buckets in the hash lookup
5833      table.  */
5834   map.bucket_count = read_4_bytes (abfd, addr);
5835   addr += 4;
5836
5837   /* name_count - The number of unique names in the index.  */
5838   map.name_count = read_4_bytes (abfd, addr);
5839   addr += 4;
5840
5841   /* abbrev_table_size - The size in bytes of the abbreviations
5842      table.  */
5843   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5844   addr += 4;
5845
5846   /* augmentation_string_size - The size in bytes of the augmentation
5847      string.  This value is rounded up to a multiple of 4.  */
5848   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5849   addr += 4;
5850   map.augmentation_is_gdb = ((augmentation_string_size
5851                               == sizeof (dwarf5_augmentation))
5852                              && memcmp (addr, dwarf5_augmentation,
5853                                         sizeof (dwarf5_augmentation)) == 0);
5854   augmentation_string_size += (-augmentation_string_size) & 3;
5855   addr += augmentation_string_size;
5856
5857   /* List of CUs */
5858   map.cu_table_reordered = addr;
5859   addr += map.cu_count * map.offset_size;
5860
5861   /* List of Local TUs */
5862   map.tu_table_reordered = addr;
5863   addr += map.tu_count * map.offset_size;
5864
5865   /* Hash Lookup Table */
5866   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5867   addr += map.bucket_count * 4;
5868   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5869   addr += map.name_count * 4;
5870
5871   /* Name Table */
5872   map.name_table_string_offs_reordered = addr;
5873   addr += map.name_count * map.offset_size;
5874   map.name_table_entry_offs_reordered = addr;
5875   addr += map.name_count * map.offset_size;
5876
5877   const gdb_byte *abbrev_table_start = addr;
5878   for (;;)
5879     {
5880       unsigned int bytes_read;
5881       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5882       addr += bytes_read;
5883       if (index_num == 0)
5884         break;
5885
5886       const auto insertpair
5887         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5888       if (!insertpair.second)
5889         {
5890           warning (_("Section .debug_names in %s has duplicate index %s, "
5891                      "ignoring .debug_names."),
5892                    filename, pulongest (index_num));
5893           return false;
5894         }
5895       mapped_debug_names::index_val &indexval = insertpair.first->second;
5896       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5897       addr += bytes_read;
5898
5899       for (;;)
5900         {
5901           mapped_debug_names::index_val::attr attr;
5902           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5903           addr += bytes_read;
5904           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5905           addr += bytes_read;
5906           if (attr.form == DW_FORM_implicit_const)
5907             {
5908               attr.implicit_const = read_signed_leb128 (abfd, addr,
5909                                                         &bytes_read);
5910               addr += bytes_read;
5911             }
5912           if (attr.dw_idx == 0 && attr.form == 0)
5913             break;
5914           indexval.attr_vec.push_back (std::move (attr));
5915         }
5916     }
5917   if (addr != abbrev_table_start + abbrev_table_size)
5918     {
5919       warning (_("Section .debug_names in %s has abbreviation_table "
5920                  "of size %zu vs. written as %u, ignoring .debug_names."),
5921                filename, addr - abbrev_table_start, abbrev_table_size);
5922       return false;
5923     }
5924   map.entry_pool = addr;
5925
5926   return true;
5927 }
5928
5929 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5930    list.  */
5931
5932 static void
5933 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5934                                   const mapped_debug_names &map,
5935                                   dwarf2_section_info &section,
5936                                   bool is_dwz, int base_offset)
5937 {
5938   sect_offset sect_off_prev;
5939   for (uint32_t i = 0; i <= map.cu_count; ++i)
5940     {
5941       sect_offset sect_off_next;
5942       if (i < map.cu_count)
5943         {
5944           sect_off_next
5945             = (sect_offset) (extract_unsigned_integer
5946                              (map.cu_table_reordered + i * map.offset_size,
5947                               map.offset_size,
5948                               map.dwarf5_byte_order));
5949         }
5950       else
5951         sect_off_next = (sect_offset) section.size;
5952       if (i >= 1)
5953         {
5954           const ULONGEST length = sect_off_next - sect_off_prev;
5955           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5956             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5957                                          sect_off_prev, length);
5958         }
5959       sect_off_prev = sect_off_next;
5960     }
5961 }
5962
5963 /* Read the CU list from the mapped index, and use it to create all
5964    the CU objects for this dwarf2_per_objfile.  */
5965
5966 static void
5967 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5968                              const mapped_debug_names &map,
5969                              const mapped_debug_names &dwz_map)
5970 {
5971   struct objfile *objfile = dwarf2_per_objfile->objfile;
5972
5973   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5974   dwarf2_per_objfile->all_comp_units
5975     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5976                  dwarf2_per_objfile->n_comp_units);
5977
5978   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5979                                     dwarf2_per_objfile->info,
5980                                     false /* is_dwz */,
5981                                     0 /* base_offset */);
5982
5983   if (dwz_map.cu_count == 0)
5984     return;
5985
5986   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5987   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5988                                     true /* is_dwz */,
5989                                     map.cu_count /* base_offset */);
5990 }
5991
5992 /* Read .debug_names.  If everything went ok, initialize the "quick"
5993    elements of all the CUs and return true.  Otherwise, return false.  */
5994
5995 static bool
5996 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5997 {
5998   mapped_debug_names local_map (dwarf2_per_objfile);
5999   mapped_debug_names dwz_map (dwarf2_per_objfile);
6000   struct objfile *objfile = dwarf2_per_objfile->objfile;
6001
6002   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
6003                                       &dwarf2_per_objfile->debug_names,
6004                                       local_map))
6005     return false;
6006
6007   /* Don't use the index if it's empty.  */
6008   if (local_map.name_count == 0)
6009     return false;
6010
6011   /* If there is a .dwz file, read it so we can get its CU list as
6012      well.  */
6013   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6014   if (dwz != NULL)
6015     {
6016       if (!read_debug_names_from_section (objfile,
6017                                           bfd_get_filename (dwz->dwz_bfd),
6018                                           &dwz->debug_names, dwz_map))
6019         {
6020           warning (_("could not read '.debug_names' section from %s; skipping"),
6021                    bfd_get_filename (dwz->dwz_bfd));
6022           return false;
6023         }
6024     }
6025
6026   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
6027
6028   if (local_map.tu_count != 0)
6029     {
6030       /* We can only handle a single .debug_types when we have an
6031          index.  */
6032       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
6033         return false;
6034
6035       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6036                                                 dwarf2_per_objfile->types, 0);
6037
6038       create_signatured_type_table_from_debug_names
6039         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6040     }
6041
6042   create_addrmap_from_aranges (dwarf2_per_objfile,
6043                                &dwarf2_per_objfile->debug_aranges);
6044
6045   dwarf2_per_objfile->debug_names_table.reset
6046     (new mapped_debug_names (dwarf2_per_objfile));
6047   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6048   dwarf2_per_objfile->using_index = 1;
6049   dwarf2_per_objfile->quick_file_names_table =
6050     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6051
6052   return true;
6053 }
6054
6055 /* Symbol name hashing function as specified by DWARF-5.  */
6056
6057 static uint32_t
6058 dwarf5_djb_hash (const char *str_)
6059 {
6060   const unsigned char *str = (const unsigned char *) str_;
6061
6062   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6063      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6064
6065   uint32_t hash = 5381;
6066   while (int c = *str++)
6067     hash = hash * 33 + tolower (c);
6068   return hash;
6069 }
6070
6071 /* Type used to manage iterating over all CUs looking for a symbol for
6072    .debug_names.  */
6073
6074 class dw2_debug_names_iterator
6075 {
6076 public:
6077   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6078      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6079   dw2_debug_names_iterator (const mapped_debug_names &map,
6080                             bool want_specific_block,
6081                             block_enum block_index, domain_enum domain,
6082                             const char *name)
6083     : m_map (map), m_want_specific_block (want_specific_block),
6084       m_block_index (block_index), m_domain (domain),
6085       m_addr (find_vec_in_debug_names (map, name))
6086   {}
6087
6088   dw2_debug_names_iterator (const mapped_debug_names &map,
6089                             search_domain search, uint32_t namei)
6090     : m_map (map),
6091       m_search (search),
6092       m_addr (find_vec_in_debug_names (map, namei))
6093   {}
6094
6095   /* Return the next matching CU or NULL if there are no more.  */
6096   dwarf2_per_cu_data *next ();
6097
6098 private:
6099   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6100                                                   const char *name);
6101   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6102                                                   uint32_t namei);
6103
6104   /* The internalized form of .debug_names.  */
6105   const mapped_debug_names &m_map;
6106
6107   /* If true, only look for symbols that match BLOCK_INDEX.  */
6108   const bool m_want_specific_block = false;
6109
6110   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6111      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6112      value.  */
6113   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6114
6115   /* The kind of symbol we're looking for.  */
6116   const domain_enum m_domain = UNDEF_DOMAIN;
6117   const search_domain m_search = ALL_DOMAIN;
6118
6119   /* The list of CUs from the index entry of the symbol, or NULL if
6120      not found.  */
6121   const gdb_byte *m_addr;
6122 };
6123
6124 const char *
6125 mapped_debug_names::namei_to_name (uint32_t namei) const
6126 {
6127   const ULONGEST namei_string_offs
6128     = extract_unsigned_integer ((name_table_string_offs_reordered
6129                                  + namei * offset_size),
6130                                 offset_size,
6131                                 dwarf5_byte_order);
6132   return read_indirect_string_at_offset
6133     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6134 }
6135
6136 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6137    found, return pointer to its pool data.  If NAME cannot be found,
6138    return NULL.  */
6139
6140 const gdb_byte *
6141 dw2_debug_names_iterator::find_vec_in_debug_names
6142   (const mapped_debug_names &map, const char *name)
6143 {
6144   int (*cmp) (const char *, const char *);
6145
6146   if (current_language->la_language == language_cplus
6147       || current_language->la_language == language_fortran
6148       || current_language->la_language == language_d)
6149     {
6150       /* NAME is already canonical.  Drop any qualifiers as
6151          .debug_names does not contain any.  */
6152
6153       if (strchr (name, '(') != NULL)
6154         {
6155           gdb::unique_xmalloc_ptr<char> without_params
6156             = cp_remove_params (name);
6157
6158           if (without_params != NULL)
6159             {
6160               name = without_params.get();
6161             }
6162         }
6163     }
6164
6165   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6166
6167   const uint32_t full_hash = dwarf5_djb_hash (name);
6168   uint32_t namei
6169     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6170                                 (map.bucket_table_reordered
6171                                  + (full_hash % map.bucket_count)), 4,
6172                                 map.dwarf5_byte_order);
6173   if (namei == 0)
6174     return NULL;
6175   --namei;
6176   if (namei >= map.name_count)
6177     {
6178       complaint (&symfile_complaints,
6179                  _("Wrong .debug_names with name index %u but name_count=%u "
6180                    "[in module %s]"),
6181                  namei, map.name_count,
6182                  objfile_name (map.dwarf2_per_objfile->objfile));
6183       return NULL;
6184     }
6185
6186   for (;;)
6187     {
6188       const uint32_t namei_full_hash
6189         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6190                                     (map.hash_table_reordered + namei), 4,
6191                                     map.dwarf5_byte_order);
6192       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6193         return NULL;
6194
6195       if (full_hash == namei_full_hash)
6196         {
6197           const char *const namei_string = map.namei_to_name (namei);
6198
6199 #if 0 /* An expensive sanity check.  */
6200           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6201             {
6202               complaint (&symfile_complaints,
6203                          _("Wrong .debug_names hash for string at index %u "
6204                            "[in module %s]"),
6205                          namei, objfile_name (dwarf2_per_objfile->objfile));
6206               return NULL;
6207             }
6208 #endif
6209
6210           if (cmp (namei_string, name) == 0)
6211             {
6212               const ULONGEST namei_entry_offs
6213                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6214                                              + namei * map.offset_size),
6215                                             map.offset_size, map.dwarf5_byte_order);
6216               return map.entry_pool + namei_entry_offs;
6217             }
6218         }
6219
6220       ++namei;
6221       if (namei >= map.name_count)
6222         return NULL;
6223     }
6224 }
6225
6226 const gdb_byte *
6227 dw2_debug_names_iterator::find_vec_in_debug_names
6228   (const mapped_debug_names &map, uint32_t namei)
6229 {
6230   if (namei >= map.name_count)
6231     {
6232       complaint (&symfile_complaints,
6233                  _("Wrong .debug_names with name index %u but name_count=%u "
6234                    "[in module %s]"),
6235                  namei, map.name_count,
6236                  objfile_name (map.dwarf2_per_objfile->objfile));
6237       return NULL;
6238     }
6239
6240   const ULONGEST namei_entry_offs
6241     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6242                                  + namei * map.offset_size),
6243                                 map.offset_size, map.dwarf5_byte_order);
6244   return map.entry_pool + namei_entry_offs;
6245 }
6246
6247 /* See dw2_debug_names_iterator.  */
6248
6249 dwarf2_per_cu_data *
6250 dw2_debug_names_iterator::next ()
6251 {
6252   if (m_addr == NULL)
6253     return NULL;
6254
6255   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6256   struct objfile *objfile = dwarf2_per_objfile->objfile;
6257   bfd *const abfd = objfile->obfd;
6258
6259  again:
6260
6261   unsigned int bytes_read;
6262   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6263   m_addr += bytes_read;
6264   if (abbrev == 0)
6265     return NULL;
6266
6267   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6268   if (indexval_it == m_map.abbrev_map.cend ())
6269     {
6270       complaint (&symfile_complaints,
6271                  _("Wrong .debug_names undefined abbrev code %s "
6272                    "[in module %s]"),
6273                  pulongest (abbrev), objfile_name (objfile));
6274       return NULL;
6275     }
6276   const mapped_debug_names::index_val &indexval = indexval_it->second;
6277   bool have_is_static = false;
6278   bool is_static;
6279   dwarf2_per_cu_data *per_cu = NULL;
6280   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6281     {
6282       ULONGEST ull;
6283       switch (attr.form)
6284         {
6285         case DW_FORM_implicit_const:
6286           ull = attr.implicit_const;
6287           break;
6288         case DW_FORM_flag_present:
6289           ull = 1;
6290           break;
6291         case DW_FORM_udata:
6292           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6293           m_addr += bytes_read;
6294           break;
6295         default:
6296           complaint (&symfile_complaints,
6297                      _("Unsupported .debug_names form %s [in module %s]"),
6298                      dwarf_form_name (attr.form),
6299                      objfile_name (objfile));
6300           return NULL;
6301         }
6302       switch (attr.dw_idx)
6303         {
6304         case DW_IDX_compile_unit:
6305           /* Don't crash on bad data.  */
6306           if (ull >= dwarf2_per_objfile->n_comp_units)
6307             {
6308               complaint (&symfile_complaints,
6309                          _(".debug_names entry has bad CU index %s"
6310                            " [in module %s]"),
6311                          pulongest (ull),
6312                          objfile_name (dwarf2_per_objfile->objfile));
6313               continue;
6314             }
6315           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6316           break;
6317         case DW_IDX_type_unit:
6318           /* Don't crash on bad data.  */
6319           if (ull >= dwarf2_per_objfile->n_type_units)
6320             {
6321               complaint (&symfile_complaints,
6322                          _(".debug_names entry has bad TU index %s"
6323                            " [in module %s]"),
6324                          pulongest (ull),
6325                          objfile_name (dwarf2_per_objfile->objfile));
6326               continue;
6327             }
6328           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6329                                  dwarf2_per_objfile->n_comp_units + ull);
6330           break;
6331         case DW_IDX_GNU_internal:
6332           if (!m_map.augmentation_is_gdb)
6333             break;
6334           have_is_static = true;
6335           is_static = true;
6336           break;
6337         case DW_IDX_GNU_external:
6338           if (!m_map.augmentation_is_gdb)
6339             break;
6340           have_is_static = true;
6341           is_static = false;
6342           break;
6343         }
6344     }
6345
6346   /* Skip if already read in.  */
6347   if (per_cu->v.quick->compunit_symtab)
6348     goto again;
6349
6350   /* Check static vs global.  */
6351   if (have_is_static)
6352     {
6353       const bool want_static = m_block_index != GLOBAL_BLOCK;
6354       if (m_want_specific_block && want_static != is_static)
6355         goto again;
6356     }
6357
6358   /* Match dw2_symtab_iter_next, symbol_kind
6359      and debug_names::psymbol_tag.  */
6360   switch (m_domain)
6361     {
6362     case VAR_DOMAIN:
6363       switch (indexval.dwarf_tag)
6364         {
6365         case DW_TAG_variable:
6366         case DW_TAG_subprogram:
6367         /* Some types are also in VAR_DOMAIN.  */
6368         case DW_TAG_typedef:
6369         case DW_TAG_structure_type:
6370           break;
6371         default:
6372           goto again;
6373         }
6374       break;
6375     case STRUCT_DOMAIN:
6376       switch (indexval.dwarf_tag)
6377         {
6378         case DW_TAG_typedef:
6379         case DW_TAG_structure_type:
6380           break;
6381         default:
6382           goto again;
6383         }
6384       break;
6385     case LABEL_DOMAIN:
6386       switch (indexval.dwarf_tag)
6387         {
6388         case 0:
6389         case DW_TAG_variable:
6390           break;
6391         default:
6392           goto again;
6393         }
6394       break;
6395     default:
6396       break;
6397     }
6398
6399   /* Match dw2_expand_symtabs_matching, symbol_kind and
6400      debug_names::psymbol_tag.  */
6401   switch (m_search)
6402     {
6403     case VARIABLES_DOMAIN:
6404       switch (indexval.dwarf_tag)
6405         {
6406         case DW_TAG_variable:
6407           break;
6408         default:
6409           goto again;
6410         }
6411       break;
6412     case FUNCTIONS_DOMAIN:
6413       switch (indexval.dwarf_tag)
6414         {
6415         case DW_TAG_subprogram:
6416           break;
6417         default:
6418           goto again;
6419         }
6420       break;
6421     case TYPES_DOMAIN:
6422       switch (indexval.dwarf_tag)
6423         {
6424         case DW_TAG_typedef:
6425         case DW_TAG_structure_type:
6426           break;
6427         default:
6428           goto again;
6429         }
6430       break;
6431     default:
6432       break;
6433     }
6434
6435   return per_cu;
6436 }
6437
6438 static struct compunit_symtab *
6439 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6440                                const char *name, domain_enum domain)
6441 {
6442   const block_enum block_index = static_cast<block_enum> (block_index_int);
6443   struct dwarf2_per_objfile *dwarf2_per_objfile
6444     = get_dwarf2_per_objfile (objfile);
6445
6446   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6447   if (!mapp)
6448     {
6449       /* index is NULL if OBJF_READNOW.  */
6450       return NULL;
6451     }
6452   const auto &map = *mapp;
6453
6454   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6455                                  block_index, domain, name);
6456
6457   struct compunit_symtab *stab_best = NULL;
6458   struct dwarf2_per_cu_data *per_cu;
6459   while ((per_cu = iter.next ()) != NULL)
6460     {
6461       struct symbol *sym, *with_opaque = NULL;
6462       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6463       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6464       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6465
6466       sym = block_find_symbol (block, name, domain,
6467                                block_find_non_opaque_type_preferred,
6468                                &with_opaque);
6469
6470       /* Some caution must be observed with overloaded functions and
6471          methods, since the index will not contain any overload
6472          information (but NAME might contain it).  */
6473
6474       if (sym != NULL
6475           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6476         return stab;
6477       if (with_opaque != NULL
6478           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6479         stab_best = stab;
6480
6481       /* Keep looking through other CUs.  */
6482     }
6483
6484   return stab_best;
6485 }
6486
6487 /* This dumps minimal information about .debug_names.  It is called
6488    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6489    uses this to verify that .debug_names has been loaded.  */
6490
6491 static void
6492 dw2_debug_names_dump (struct objfile *objfile)
6493 {
6494   struct dwarf2_per_objfile *dwarf2_per_objfile
6495     = get_dwarf2_per_objfile (objfile);
6496
6497   gdb_assert (dwarf2_per_objfile->using_index);
6498   printf_filtered (".debug_names:");
6499   if (dwarf2_per_objfile->debug_names_table)
6500     printf_filtered (" exists\n");
6501   else
6502     printf_filtered (" faked for \"readnow\"\n");
6503   printf_filtered ("\n");
6504 }
6505
6506 static void
6507 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6508                                              const char *func_name)
6509 {
6510   struct dwarf2_per_objfile *dwarf2_per_objfile
6511     = get_dwarf2_per_objfile (objfile);
6512
6513   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6514   if (dwarf2_per_objfile->debug_names_table)
6515     {
6516       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6517
6518       /* Note: It doesn't matter what we pass for block_index here.  */
6519       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6520                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6521
6522       struct dwarf2_per_cu_data *per_cu;
6523       while ((per_cu = iter.next ()) != NULL)
6524         dw2_instantiate_symtab (per_cu);
6525     }
6526 }
6527
6528 static void
6529 dw2_debug_names_expand_symtabs_matching
6530   (struct objfile *objfile,
6531    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6532    const lookup_name_info &lookup_name,
6533    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6534    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6535    enum search_domain kind)
6536 {
6537   struct dwarf2_per_objfile *dwarf2_per_objfile
6538     = get_dwarf2_per_objfile (objfile);
6539
6540   /* debug_names_table is NULL if OBJF_READNOW.  */
6541   if (!dwarf2_per_objfile->debug_names_table)
6542     return;
6543
6544   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6545
6546   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6547
6548   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6549                                       symbol_matcher,
6550                                       kind, [&] (offset_type namei)
6551     {
6552       /* The name was matched, now expand corresponding CUs that were
6553          marked.  */
6554       dw2_debug_names_iterator iter (map, kind, namei);
6555
6556       struct dwarf2_per_cu_data *per_cu;
6557       while ((per_cu = iter.next ()) != NULL)
6558         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6559                                          expansion_notify);
6560     });
6561 }
6562
6563 const struct quick_symbol_functions dwarf2_debug_names_functions =
6564 {
6565   dw2_has_symbols,
6566   dw2_find_last_source_symtab,
6567   dw2_forget_cached_source_info,
6568   dw2_map_symtabs_matching_filename,
6569   dw2_debug_names_lookup_symbol,
6570   dw2_print_stats,
6571   dw2_debug_names_dump,
6572   dw2_relocate,
6573   dw2_debug_names_expand_symtabs_for_function,
6574   dw2_expand_all_symtabs,
6575   dw2_expand_symtabs_with_fullname,
6576   dw2_map_matching_symbols,
6577   dw2_debug_names_expand_symtabs_matching,
6578   dw2_find_pc_sect_compunit_symtab,
6579   NULL,
6580   dw2_map_symbol_filenames
6581 };
6582
6583 /* See symfile.h.  */
6584
6585 bool
6586 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6587 {
6588   struct dwarf2_per_objfile *dwarf2_per_objfile
6589     = get_dwarf2_per_objfile (objfile);
6590
6591   /* If we're about to read full symbols, don't bother with the
6592      indices.  In this case we also don't care if some other debug
6593      format is making psymtabs, because they are all about to be
6594      expanded anyway.  */
6595   if ((objfile->flags & OBJF_READNOW))
6596     {
6597       int i;
6598
6599       dwarf2_per_objfile->using_index = 1;
6600       create_all_comp_units (dwarf2_per_objfile);
6601       create_all_type_units (dwarf2_per_objfile);
6602       dwarf2_per_objfile->quick_file_names_table =
6603         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6604
6605       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6606                        + dwarf2_per_objfile->n_type_units); ++i)
6607         {
6608           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6609
6610           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6611                                             struct dwarf2_per_cu_quick_data);
6612         }
6613
6614       /* Return 1 so that gdb sees the "quick" functions.  However,
6615          these functions will be no-ops because we will have expanded
6616          all symtabs.  */
6617       *index_kind = dw_index_kind::GDB_INDEX;
6618       return true;
6619     }
6620
6621   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6622     {
6623       *index_kind = dw_index_kind::DEBUG_NAMES;
6624       return true;
6625     }
6626
6627   if (dwarf2_read_index (objfile))
6628     {
6629       *index_kind = dw_index_kind::GDB_INDEX;
6630       return true;
6631     }
6632
6633   return false;
6634 }
6635
6636 \f
6637
6638 /* Build a partial symbol table.  */
6639
6640 void
6641 dwarf2_build_psymtabs (struct objfile *objfile)
6642 {
6643   struct dwarf2_per_objfile *dwarf2_per_objfile
6644     = get_dwarf2_per_objfile (objfile);
6645
6646   if (objfile->global_psymbols.capacity () == 0
6647       && objfile->static_psymbols.capacity () == 0)
6648     init_psymbol_list (objfile, 1024);
6649
6650   TRY
6651     {
6652       /* This isn't really ideal: all the data we allocate on the
6653          objfile's obstack is still uselessly kept around.  However,
6654          freeing it seems unsafe.  */
6655       psymtab_discarder psymtabs (objfile);
6656       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6657       psymtabs.keep ();
6658     }
6659   CATCH (except, RETURN_MASK_ERROR)
6660     {
6661       exception_print (gdb_stderr, except);
6662     }
6663   END_CATCH
6664 }
6665
6666 /* Return the total length of the CU described by HEADER.  */
6667
6668 static unsigned int
6669 get_cu_length (const struct comp_unit_head *header)
6670 {
6671   return header->initial_length_size + header->length;
6672 }
6673
6674 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6675
6676 static inline bool
6677 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6678 {
6679   sect_offset bottom = cu_header->sect_off;
6680   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6681
6682   return sect_off >= bottom && sect_off < top;
6683 }
6684
6685 /* Find the base address of the compilation unit for range lists and
6686    location lists.  It will normally be specified by DW_AT_low_pc.
6687    In DWARF-3 draft 4, the base address could be overridden by
6688    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6689    compilation units with discontinuous ranges.  */
6690
6691 static void
6692 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6693 {
6694   struct attribute *attr;
6695
6696   cu->base_known = 0;
6697   cu->base_address = 0;
6698
6699   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6700   if (attr)
6701     {
6702       cu->base_address = attr_value_as_address (attr);
6703       cu->base_known = 1;
6704     }
6705   else
6706     {
6707       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6708       if (attr)
6709         {
6710           cu->base_address = attr_value_as_address (attr);
6711           cu->base_known = 1;
6712         }
6713     }
6714 }
6715
6716 /* Read in the comp unit header information from the debug_info at info_ptr.
6717    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6718    NOTE: This leaves members offset, first_die_offset to be filled in
6719    by the caller.  */
6720
6721 static const gdb_byte *
6722 read_comp_unit_head (struct comp_unit_head *cu_header,
6723                      const gdb_byte *info_ptr,
6724                      struct dwarf2_section_info *section,
6725                      rcuh_kind section_kind)
6726 {
6727   int signed_addr;
6728   unsigned int bytes_read;
6729   const char *filename = get_section_file_name (section);
6730   bfd *abfd = get_section_bfd_owner (section);
6731
6732   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6733   cu_header->initial_length_size = bytes_read;
6734   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6735   info_ptr += bytes_read;
6736   cu_header->version = read_2_bytes (abfd, info_ptr);
6737   info_ptr += 2;
6738   if (cu_header->version < 5)
6739     switch (section_kind)
6740       {
6741       case rcuh_kind::COMPILE:
6742         cu_header->unit_type = DW_UT_compile;
6743         break;
6744       case rcuh_kind::TYPE:
6745         cu_header->unit_type = DW_UT_type;
6746         break;
6747       default:
6748         internal_error (__FILE__, __LINE__,
6749                         _("read_comp_unit_head: invalid section_kind"));
6750       }
6751   else
6752     {
6753       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6754                                                  (read_1_byte (abfd, info_ptr));
6755       info_ptr += 1;
6756       switch (cu_header->unit_type)
6757         {
6758         case DW_UT_compile:
6759           if (section_kind != rcuh_kind::COMPILE)
6760             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6761                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6762                    filename);
6763           break;
6764         case DW_UT_type:
6765           section_kind = rcuh_kind::TYPE;
6766           break;
6767         default:
6768           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6769                  "(is %d, should be %d or %d) [in module %s]"),
6770                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6771         }
6772
6773       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6774       info_ptr += 1;
6775     }
6776   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6777                                                           cu_header,
6778                                                           &bytes_read);
6779   info_ptr += bytes_read;
6780   if (cu_header->version < 5)
6781     {
6782       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6783       info_ptr += 1;
6784     }
6785   signed_addr = bfd_get_sign_extend_vma (abfd);
6786   if (signed_addr < 0)
6787     internal_error (__FILE__, __LINE__,
6788                     _("read_comp_unit_head: dwarf from non elf file"));
6789   cu_header->signed_addr_p = signed_addr;
6790
6791   if (section_kind == rcuh_kind::TYPE)
6792     {
6793       LONGEST type_offset;
6794
6795       cu_header->signature = read_8_bytes (abfd, info_ptr);
6796       info_ptr += 8;
6797
6798       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6799       info_ptr += bytes_read;
6800       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6801       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6802         error (_("Dwarf Error: Too big type_offset in compilation unit "
6803                "header (is %s) [in module %s]"), plongest (type_offset),
6804                filename);
6805     }
6806
6807   return info_ptr;
6808 }
6809
6810 /* Helper function that returns the proper abbrev section for
6811    THIS_CU.  */
6812
6813 static struct dwarf2_section_info *
6814 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6815 {
6816   struct dwarf2_section_info *abbrev;
6817   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6818
6819   if (this_cu->is_dwz)
6820     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6821   else
6822     abbrev = &dwarf2_per_objfile->abbrev;
6823
6824   return abbrev;
6825 }
6826
6827 /* Subroutine of read_and_check_comp_unit_head and
6828    read_and_check_type_unit_head to simplify them.
6829    Perform various error checking on the header.  */
6830
6831 static void
6832 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6833                             struct comp_unit_head *header,
6834                             struct dwarf2_section_info *section,
6835                             struct dwarf2_section_info *abbrev_section)
6836 {
6837   const char *filename = get_section_file_name (section);
6838
6839   if (header->version < 2 || header->version > 5)
6840     error (_("Dwarf Error: wrong version in compilation unit header "
6841            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6842            filename);
6843
6844   if (to_underlying (header->abbrev_sect_off)
6845       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6846     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6847            "(offset %s + 6) [in module %s]"),
6848            sect_offset_str (header->abbrev_sect_off),
6849            sect_offset_str (header->sect_off),
6850            filename);
6851
6852   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6853      avoid potential 32-bit overflow.  */
6854   if (((ULONGEST) header->sect_off + get_cu_length (header))
6855       > section->size)
6856     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6857            "(offset %s + 0) [in module %s]"),
6858            header->length, sect_offset_str (header->sect_off),
6859            filename);
6860 }
6861
6862 /* Read in a CU/TU header and perform some basic error checking.
6863    The contents of the header are stored in HEADER.
6864    The result is a pointer to the start of the first DIE.  */
6865
6866 static const gdb_byte *
6867 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6868                                struct comp_unit_head *header,
6869                                struct dwarf2_section_info *section,
6870                                struct dwarf2_section_info *abbrev_section,
6871                                const gdb_byte *info_ptr,
6872                                rcuh_kind section_kind)
6873 {
6874   const gdb_byte *beg_of_comp_unit = info_ptr;
6875
6876   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6877
6878   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6879
6880   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6881
6882   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6883                               abbrev_section);
6884
6885   return info_ptr;
6886 }
6887
6888 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6889
6890 static sect_offset
6891 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6892                     struct dwarf2_section_info *section,
6893                     sect_offset sect_off)
6894 {
6895   bfd *abfd = get_section_bfd_owner (section);
6896   const gdb_byte *info_ptr;
6897   unsigned int initial_length_size, offset_size;
6898   uint16_t version;
6899
6900   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6901   info_ptr = section->buffer + to_underlying (sect_off);
6902   read_initial_length (abfd, info_ptr, &initial_length_size);
6903   offset_size = initial_length_size == 4 ? 4 : 8;
6904   info_ptr += initial_length_size;
6905
6906   version = read_2_bytes (abfd, info_ptr);
6907   info_ptr += 2;
6908   if (version >= 5)
6909     {
6910       /* Skip unit type and address size.  */
6911       info_ptr += 2;
6912     }
6913
6914   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6915 }
6916
6917 /* Allocate a new partial symtab for file named NAME and mark this new
6918    partial symtab as being an include of PST.  */
6919
6920 static void
6921 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6922                                struct objfile *objfile)
6923 {
6924   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6925
6926   if (!IS_ABSOLUTE_PATH (subpst->filename))
6927     {
6928       /* It shares objfile->objfile_obstack.  */
6929       subpst->dirname = pst->dirname;
6930     }
6931
6932   subpst->textlow = 0;
6933   subpst->texthigh = 0;
6934
6935   subpst->dependencies
6936     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6937   subpst->dependencies[0] = pst;
6938   subpst->number_of_dependencies = 1;
6939
6940   subpst->globals_offset = 0;
6941   subpst->n_global_syms = 0;
6942   subpst->statics_offset = 0;
6943   subpst->n_static_syms = 0;
6944   subpst->compunit_symtab = NULL;
6945   subpst->read_symtab = pst->read_symtab;
6946   subpst->readin = 0;
6947
6948   /* No private part is necessary for include psymtabs.  This property
6949      can be used to differentiate between such include psymtabs and
6950      the regular ones.  */
6951   subpst->read_symtab_private = NULL;
6952 }
6953
6954 /* Read the Line Number Program data and extract the list of files
6955    included by the source file represented by PST.  Build an include
6956    partial symtab for each of these included files.  */
6957
6958 static void
6959 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6960                                struct die_info *die,
6961                                struct partial_symtab *pst)
6962 {
6963   line_header_up lh;
6964   struct attribute *attr;
6965
6966   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6967   if (attr)
6968     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6969   if (lh == NULL)
6970     return;  /* No linetable, so no includes.  */
6971
6972   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6973   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6974 }
6975
6976 static hashval_t
6977 hash_signatured_type (const void *item)
6978 {
6979   const struct signatured_type *sig_type
6980     = (const struct signatured_type *) item;
6981
6982   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6983   return sig_type->signature;
6984 }
6985
6986 static int
6987 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6988 {
6989   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6990   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6991
6992   return lhs->signature == rhs->signature;
6993 }
6994
6995 /* Allocate a hash table for signatured types.  */
6996
6997 static htab_t
6998 allocate_signatured_type_table (struct objfile *objfile)
6999 {
7000   return htab_create_alloc_ex (41,
7001                                hash_signatured_type,
7002                                eq_signatured_type,
7003                                NULL,
7004                                &objfile->objfile_obstack,
7005                                hashtab_obstack_allocate,
7006                                dummy_obstack_deallocate);
7007 }
7008
7009 /* A helper function to add a signatured type CU to a table.  */
7010
7011 static int
7012 add_signatured_type_cu_to_table (void **slot, void *datum)
7013 {
7014   struct signatured_type *sigt = (struct signatured_type *) *slot;
7015   struct signatured_type ***datap = (struct signatured_type ***) datum;
7016
7017   **datap = sigt;
7018   ++*datap;
7019
7020   return 1;
7021 }
7022
7023 /* A helper for create_debug_types_hash_table.  Read types from SECTION
7024    and fill them into TYPES_HTAB.  It will process only type units,
7025    therefore DW_UT_type.  */
7026
7027 static void
7028 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7029                               struct dwo_file *dwo_file,
7030                               dwarf2_section_info *section, htab_t &types_htab,
7031                               rcuh_kind section_kind)
7032 {
7033   struct objfile *objfile = dwarf2_per_objfile->objfile;
7034   struct dwarf2_section_info *abbrev_section;
7035   bfd *abfd;
7036   const gdb_byte *info_ptr, *end_ptr;
7037
7038   abbrev_section = (dwo_file != NULL
7039                     ? &dwo_file->sections.abbrev
7040                     : &dwarf2_per_objfile->abbrev);
7041
7042   if (dwarf_read_debug)
7043     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7044                         get_section_name (section),
7045                         get_section_file_name (abbrev_section));
7046
7047   dwarf2_read_section (objfile, section);
7048   info_ptr = section->buffer;
7049
7050   if (info_ptr == NULL)
7051     return;
7052
7053   /* We can't set abfd until now because the section may be empty or
7054      not present, in which case the bfd is unknown.  */
7055   abfd = get_section_bfd_owner (section);
7056
7057   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7058      because we don't need to read any dies: the signature is in the
7059      header.  */
7060
7061   end_ptr = info_ptr + section->size;
7062   while (info_ptr < end_ptr)
7063     {
7064       struct signatured_type *sig_type;
7065       struct dwo_unit *dwo_tu;
7066       void **slot;
7067       const gdb_byte *ptr = info_ptr;
7068       struct comp_unit_head header;
7069       unsigned int length;
7070
7071       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7072
7073       /* Initialize it due to a false compiler warning.  */
7074       header.signature = -1;
7075       header.type_cu_offset_in_tu = (cu_offset) -1;
7076
7077       /* We need to read the type's signature in order to build the hash
7078          table, but we don't need anything else just yet.  */
7079
7080       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7081                                            abbrev_section, ptr, section_kind);
7082
7083       length = get_cu_length (&header);
7084
7085       /* Skip dummy type units.  */
7086       if (ptr >= info_ptr + length
7087           || peek_abbrev_code (abfd, ptr) == 0
7088           || header.unit_type != DW_UT_type)
7089         {
7090           info_ptr += length;
7091           continue;
7092         }
7093
7094       if (types_htab == NULL)
7095         {
7096           if (dwo_file)
7097             types_htab = allocate_dwo_unit_table (objfile);
7098           else
7099             types_htab = allocate_signatured_type_table (objfile);
7100         }
7101
7102       if (dwo_file)
7103         {
7104           sig_type = NULL;
7105           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7106                                    struct dwo_unit);
7107           dwo_tu->dwo_file = dwo_file;
7108           dwo_tu->signature = header.signature;
7109           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7110           dwo_tu->section = section;
7111           dwo_tu->sect_off = sect_off;
7112           dwo_tu->length = length;
7113         }
7114       else
7115         {
7116           /* N.B.: type_offset is not usable if this type uses a DWO file.
7117              The real type_offset is in the DWO file.  */
7118           dwo_tu = NULL;
7119           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7120                                      struct signatured_type);
7121           sig_type->signature = header.signature;
7122           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7123           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7124           sig_type->per_cu.is_debug_types = 1;
7125           sig_type->per_cu.section = section;
7126           sig_type->per_cu.sect_off = sect_off;
7127           sig_type->per_cu.length = length;
7128         }
7129
7130       slot = htab_find_slot (types_htab,
7131                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7132                              INSERT);
7133       gdb_assert (slot != NULL);
7134       if (*slot != NULL)
7135         {
7136           sect_offset dup_sect_off;
7137
7138           if (dwo_file)
7139             {
7140               const struct dwo_unit *dup_tu
7141                 = (const struct dwo_unit *) *slot;
7142
7143               dup_sect_off = dup_tu->sect_off;
7144             }
7145           else
7146             {
7147               const struct signatured_type *dup_tu
7148                 = (const struct signatured_type *) *slot;
7149
7150               dup_sect_off = dup_tu->per_cu.sect_off;
7151             }
7152
7153           complaint (&symfile_complaints,
7154                      _("debug type entry at offset %s is duplicate to"
7155                        " the entry at offset %s, signature %s"),
7156                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
7157                      hex_string (header.signature));
7158         }
7159       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7160
7161       if (dwarf_read_debug > 1)
7162         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
7163                             sect_offset_str (sect_off),
7164                             hex_string (header.signature));
7165
7166       info_ptr += length;
7167     }
7168 }
7169
7170 /* Create the hash table of all entries in the .debug_types
7171    (or .debug_types.dwo) section(s).
7172    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7173    otherwise it is NULL.
7174
7175    The result is a pointer to the hash table or NULL if there are no types.
7176
7177    Note: This function processes DWO files only, not DWP files.  */
7178
7179 static void
7180 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7181                                struct dwo_file *dwo_file,
7182                                VEC (dwarf2_section_info_def) *types,
7183                                htab_t &types_htab)
7184 {
7185   int ix;
7186   struct dwarf2_section_info *section;
7187
7188   if (VEC_empty (dwarf2_section_info_def, types))
7189     return;
7190
7191   for (ix = 0;
7192        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7193        ++ix)
7194     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7195                                   types_htab, rcuh_kind::TYPE);
7196 }
7197
7198 /* Create the hash table of all entries in the .debug_types section,
7199    and initialize all_type_units.
7200    The result is zero if there is an error (e.g. missing .debug_types section),
7201    otherwise non-zero.  */
7202
7203 static int
7204 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7205 {
7206   htab_t types_htab = NULL;
7207   struct signatured_type **iter;
7208
7209   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7210                                 &dwarf2_per_objfile->info, types_htab,
7211                                 rcuh_kind::COMPILE);
7212   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7213                                  dwarf2_per_objfile->types, types_htab);
7214   if (types_htab == NULL)
7215     {
7216       dwarf2_per_objfile->signatured_types = NULL;
7217       return 0;
7218     }
7219
7220   dwarf2_per_objfile->signatured_types = types_htab;
7221
7222   dwarf2_per_objfile->n_type_units
7223     = dwarf2_per_objfile->n_allocated_type_units
7224     = htab_elements (types_htab);
7225   dwarf2_per_objfile->all_type_units =
7226     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7227   iter = &dwarf2_per_objfile->all_type_units[0];
7228   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7229   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7230               == dwarf2_per_objfile->n_type_units);
7231
7232   return 1;
7233 }
7234
7235 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7236    If SLOT is non-NULL, it is the entry to use in the hash table.
7237    Otherwise we find one.  */
7238
7239 static struct signatured_type *
7240 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7241                void **slot)
7242 {
7243   struct objfile *objfile = dwarf2_per_objfile->objfile;
7244   int n_type_units = dwarf2_per_objfile->n_type_units;
7245   struct signatured_type *sig_type;
7246
7247   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7248   ++n_type_units;
7249   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7250     {
7251       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7252         dwarf2_per_objfile->n_allocated_type_units = 1;
7253       dwarf2_per_objfile->n_allocated_type_units *= 2;
7254       dwarf2_per_objfile->all_type_units
7255         = XRESIZEVEC (struct signatured_type *,
7256                       dwarf2_per_objfile->all_type_units,
7257                       dwarf2_per_objfile->n_allocated_type_units);
7258       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7259     }
7260   dwarf2_per_objfile->n_type_units = n_type_units;
7261
7262   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7263                              struct signatured_type);
7264   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7265   sig_type->signature = sig;
7266   sig_type->per_cu.is_debug_types = 1;
7267   if (dwarf2_per_objfile->using_index)
7268     {
7269       sig_type->per_cu.v.quick =
7270         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7271                         struct dwarf2_per_cu_quick_data);
7272     }
7273
7274   if (slot == NULL)
7275     {
7276       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7277                              sig_type, INSERT);
7278     }
7279   gdb_assert (*slot == NULL);
7280   *slot = sig_type;
7281   /* The rest of sig_type must be filled in by the caller.  */
7282   return sig_type;
7283 }
7284
7285 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7286    Fill in SIG_ENTRY with DWO_ENTRY.  */
7287
7288 static void
7289 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7290                                   struct signatured_type *sig_entry,
7291                                   struct dwo_unit *dwo_entry)
7292 {
7293   /* Make sure we're not clobbering something we don't expect to.  */
7294   gdb_assert (! sig_entry->per_cu.queued);
7295   gdb_assert (sig_entry->per_cu.cu == NULL);
7296   if (dwarf2_per_objfile->using_index)
7297     {
7298       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7299       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7300     }
7301   else
7302       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7303   gdb_assert (sig_entry->signature == dwo_entry->signature);
7304   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7305   gdb_assert (sig_entry->type_unit_group == NULL);
7306   gdb_assert (sig_entry->dwo_unit == NULL);
7307
7308   sig_entry->per_cu.section = dwo_entry->section;
7309   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7310   sig_entry->per_cu.length = dwo_entry->length;
7311   sig_entry->per_cu.reading_dwo_directly = 1;
7312   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7313   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7314   sig_entry->dwo_unit = dwo_entry;
7315 }
7316
7317 /* Subroutine of lookup_signatured_type.
7318    If we haven't read the TU yet, create the signatured_type data structure
7319    for a TU to be read in directly from a DWO file, bypassing the stub.
7320    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7321    using .gdb_index, then when reading a CU we want to stay in the DWO file
7322    containing that CU.  Otherwise we could end up reading several other DWO
7323    files (due to comdat folding) to process the transitive closure of all the
7324    mentioned TUs, and that can be slow.  The current DWO file will have every
7325    type signature that it needs.
7326    We only do this for .gdb_index because in the psymtab case we already have
7327    to read all the DWOs to build the type unit groups.  */
7328
7329 static struct signatured_type *
7330 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7331 {
7332   struct dwarf2_per_objfile *dwarf2_per_objfile
7333     = cu->per_cu->dwarf2_per_objfile;
7334   struct objfile *objfile = dwarf2_per_objfile->objfile;
7335   struct dwo_file *dwo_file;
7336   struct dwo_unit find_dwo_entry, *dwo_entry;
7337   struct signatured_type find_sig_entry, *sig_entry;
7338   void **slot;
7339
7340   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7341
7342   /* If TU skeletons have been removed then we may not have read in any
7343      TUs yet.  */
7344   if (dwarf2_per_objfile->signatured_types == NULL)
7345     {
7346       dwarf2_per_objfile->signatured_types
7347         = allocate_signatured_type_table (objfile);
7348     }
7349
7350   /* We only ever need to read in one copy of a signatured type.
7351      Use the global signatured_types array to do our own comdat-folding
7352      of types.  If this is the first time we're reading this TU, and
7353      the TU has an entry in .gdb_index, replace the recorded data from
7354      .gdb_index with this TU.  */
7355
7356   find_sig_entry.signature = sig;
7357   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7358                          &find_sig_entry, INSERT);
7359   sig_entry = (struct signatured_type *) *slot;
7360
7361   /* We can get here with the TU already read, *or* in the process of being
7362      read.  Don't reassign the global entry to point to this DWO if that's
7363      the case.  Also note that if the TU is already being read, it may not
7364      have come from a DWO, the program may be a mix of Fission-compiled
7365      code and non-Fission-compiled code.  */
7366
7367   /* Have we already tried to read this TU?
7368      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7369      needn't exist in the global table yet).  */
7370   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7371     return sig_entry;
7372
7373   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7374      dwo_unit of the TU itself.  */
7375   dwo_file = cu->dwo_unit->dwo_file;
7376
7377   /* Ok, this is the first time we're reading this TU.  */
7378   if (dwo_file->tus == NULL)
7379     return NULL;
7380   find_dwo_entry.signature = sig;
7381   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7382   if (dwo_entry == NULL)
7383     return NULL;
7384
7385   /* If the global table doesn't have an entry for this TU, add one.  */
7386   if (sig_entry == NULL)
7387     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7388
7389   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7390   sig_entry->per_cu.tu_read = 1;
7391   return sig_entry;
7392 }
7393
7394 /* Subroutine of lookup_signatured_type.
7395    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7396    then try the DWP file.  If the TU stub (skeleton) has been removed then
7397    it won't be in .gdb_index.  */
7398
7399 static struct signatured_type *
7400 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7401 {
7402   struct dwarf2_per_objfile *dwarf2_per_objfile
7403     = cu->per_cu->dwarf2_per_objfile;
7404   struct objfile *objfile = dwarf2_per_objfile->objfile;
7405   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7406   struct dwo_unit *dwo_entry;
7407   struct signatured_type find_sig_entry, *sig_entry;
7408   void **slot;
7409
7410   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7411   gdb_assert (dwp_file != NULL);
7412
7413   /* If TU skeletons have been removed then we may not have read in any
7414      TUs yet.  */
7415   if (dwarf2_per_objfile->signatured_types == NULL)
7416     {
7417       dwarf2_per_objfile->signatured_types
7418         = allocate_signatured_type_table (objfile);
7419     }
7420
7421   find_sig_entry.signature = sig;
7422   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7423                          &find_sig_entry, INSERT);
7424   sig_entry = (struct signatured_type *) *slot;
7425
7426   /* Have we already tried to read this TU?
7427      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7428      needn't exist in the global table yet).  */
7429   if (sig_entry != NULL)
7430     return sig_entry;
7431
7432   if (dwp_file->tus == NULL)
7433     return NULL;
7434   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7435                                       sig, 1 /* is_debug_types */);
7436   if (dwo_entry == NULL)
7437     return NULL;
7438
7439   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7440   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7441
7442   return sig_entry;
7443 }
7444
7445 /* Lookup a signature based type for DW_FORM_ref_sig8.
7446    Returns NULL if signature SIG is not present in the table.
7447    It is up to the caller to complain about this.  */
7448
7449 static struct signatured_type *
7450 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7451 {
7452   struct dwarf2_per_objfile *dwarf2_per_objfile
7453     = cu->per_cu->dwarf2_per_objfile;
7454
7455   if (cu->dwo_unit
7456       && dwarf2_per_objfile->using_index)
7457     {
7458       /* We're in a DWO/DWP file, and we're using .gdb_index.
7459          These cases require special processing.  */
7460       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7461         return lookup_dwo_signatured_type (cu, sig);
7462       else
7463         return lookup_dwp_signatured_type (cu, sig);
7464     }
7465   else
7466     {
7467       struct signatured_type find_entry, *entry;
7468
7469       if (dwarf2_per_objfile->signatured_types == NULL)
7470         return NULL;
7471       find_entry.signature = sig;
7472       entry = ((struct signatured_type *)
7473                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7474       return entry;
7475     }
7476 }
7477 \f
7478 /* Low level DIE reading support.  */
7479
7480 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7481
7482 static void
7483 init_cu_die_reader (struct die_reader_specs *reader,
7484                     struct dwarf2_cu *cu,
7485                     struct dwarf2_section_info *section,
7486                     struct dwo_file *dwo_file,
7487                     struct abbrev_table *abbrev_table)
7488 {
7489   gdb_assert (section->readin && section->buffer != NULL);
7490   reader->abfd = get_section_bfd_owner (section);
7491   reader->cu = cu;
7492   reader->dwo_file = dwo_file;
7493   reader->die_section = section;
7494   reader->buffer = section->buffer;
7495   reader->buffer_end = section->buffer + section->size;
7496   reader->comp_dir = NULL;
7497   reader->abbrev_table = abbrev_table;
7498 }
7499
7500 /* Subroutine of init_cutu_and_read_dies to simplify it.
7501    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7502    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7503    already.
7504
7505    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7506    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7507    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7508    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7509    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7510    STUB_COMP_DIR may be non-NULL.
7511    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7512    are filled in with the info of the DIE from the DWO file.
7513    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7514    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7515    kept around for at least as long as *RESULT_READER.
7516
7517    The result is non-zero if a valid (non-dummy) DIE was found.  */
7518
7519 static int
7520 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7521                         struct dwo_unit *dwo_unit,
7522                         struct die_info *stub_comp_unit_die,
7523                         const char *stub_comp_dir,
7524                         struct die_reader_specs *result_reader,
7525                         const gdb_byte **result_info_ptr,
7526                         struct die_info **result_comp_unit_die,
7527                         int *result_has_children,
7528                         abbrev_table_up *result_dwo_abbrev_table)
7529 {
7530   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7531   struct objfile *objfile = dwarf2_per_objfile->objfile;
7532   struct dwarf2_cu *cu = this_cu->cu;
7533   bfd *abfd;
7534   const gdb_byte *begin_info_ptr, *info_ptr;
7535   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7536   int i,num_extra_attrs;
7537   struct dwarf2_section_info *dwo_abbrev_section;
7538   struct attribute *attr;
7539   struct die_info *comp_unit_die;
7540
7541   /* At most one of these may be provided.  */
7542   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7543
7544   /* These attributes aren't processed until later:
7545      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7546      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7547      referenced later.  However, these attributes are found in the stub
7548      which we won't have later.  In order to not impose this complication
7549      on the rest of the code, we read them here and copy them to the
7550      DWO CU/TU die.  */
7551
7552   stmt_list = NULL;
7553   low_pc = NULL;
7554   high_pc = NULL;
7555   ranges = NULL;
7556   comp_dir = NULL;
7557
7558   if (stub_comp_unit_die != NULL)
7559     {
7560       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7561          DWO file.  */
7562       if (! this_cu->is_debug_types)
7563         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7564       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7565       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7566       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7567       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7568
7569       /* There should be a DW_AT_addr_base attribute here (if needed).
7570          We need the value before we can process DW_FORM_GNU_addr_index.  */
7571       cu->addr_base = 0;
7572       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7573       if (attr)
7574         cu->addr_base = DW_UNSND (attr);
7575
7576       /* There should be a DW_AT_ranges_base attribute here (if needed).
7577          We need the value before we can process DW_AT_ranges.  */
7578       cu->ranges_base = 0;
7579       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7580       if (attr)
7581         cu->ranges_base = DW_UNSND (attr);
7582     }
7583   else if (stub_comp_dir != NULL)
7584     {
7585       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7586       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7587       comp_dir->name = DW_AT_comp_dir;
7588       comp_dir->form = DW_FORM_string;
7589       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7590       DW_STRING (comp_dir) = stub_comp_dir;
7591     }
7592
7593   /* Set up for reading the DWO CU/TU.  */
7594   cu->dwo_unit = dwo_unit;
7595   dwarf2_section_info *section = dwo_unit->section;
7596   dwarf2_read_section (objfile, section);
7597   abfd = get_section_bfd_owner (section);
7598   begin_info_ptr = info_ptr = (section->buffer
7599                                + to_underlying (dwo_unit->sect_off));
7600   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7601
7602   if (this_cu->is_debug_types)
7603     {
7604       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7605
7606       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7607                                                 &cu->header, section,
7608                                                 dwo_abbrev_section,
7609                                                 info_ptr, rcuh_kind::TYPE);
7610       /* This is not an assert because it can be caused by bad debug info.  */
7611       if (sig_type->signature != cu->header.signature)
7612         {
7613           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7614                    " TU at offset %s [in module %s]"),
7615                  hex_string (sig_type->signature),
7616                  hex_string (cu->header.signature),
7617                  sect_offset_str (dwo_unit->sect_off),
7618                  bfd_get_filename (abfd));
7619         }
7620       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7621       /* For DWOs coming from DWP files, we don't know the CU length
7622          nor the type's offset in the TU until now.  */
7623       dwo_unit->length = get_cu_length (&cu->header);
7624       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7625
7626       /* Establish the type offset that can be used to lookup the type.
7627          For DWO files, we don't know it until now.  */
7628       sig_type->type_offset_in_section
7629         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7630     }
7631   else
7632     {
7633       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7634                                                 &cu->header, section,
7635                                                 dwo_abbrev_section,
7636                                                 info_ptr, rcuh_kind::COMPILE);
7637       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7638       /* For DWOs coming from DWP files, we don't know the CU length
7639          until now.  */
7640       dwo_unit->length = get_cu_length (&cu->header);
7641     }
7642
7643   *result_dwo_abbrev_table
7644     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7645                                cu->header.abbrev_sect_off);
7646   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7647                       result_dwo_abbrev_table->get ());
7648
7649   /* Read in the die, but leave space to copy over the attributes
7650      from the stub.  This has the benefit of simplifying the rest of
7651      the code - all the work to maintain the illusion of a single
7652      DW_TAG_{compile,type}_unit DIE is done here.  */
7653   num_extra_attrs = ((stmt_list != NULL)
7654                      + (low_pc != NULL)
7655                      + (high_pc != NULL)
7656                      + (ranges != NULL)
7657                      + (comp_dir != NULL));
7658   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7659                               result_has_children, num_extra_attrs);
7660
7661   /* Copy over the attributes from the stub to the DIE we just read in.  */
7662   comp_unit_die = *result_comp_unit_die;
7663   i = comp_unit_die->num_attrs;
7664   if (stmt_list != NULL)
7665     comp_unit_die->attrs[i++] = *stmt_list;
7666   if (low_pc != NULL)
7667     comp_unit_die->attrs[i++] = *low_pc;
7668   if (high_pc != NULL)
7669     comp_unit_die->attrs[i++] = *high_pc;
7670   if (ranges != NULL)
7671     comp_unit_die->attrs[i++] = *ranges;
7672   if (comp_dir != NULL)
7673     comp_unit_die->attrs[i++] = *comp_dir;
7674   comp_unit_die->num_attrs += num_extra_attrs;
7675
7676   if (dwarf_die_debug)
7677     {
7678       fprintf_unfiltered (gdb_stdlog,
7679                           "Read die from %s@0x%x of %s:\n",
7680                           get_section_name (section),
7681                           (unsigned) (begin_info_ptr - section->buffer),
7682                           bfd_get_filename (abfd));
7683       dump_die (comp_unit_die, dwarf_die_debug);
7684     }
7685
7686   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7687      TUs by skipping the stub and going directly to the entry in the DWO file.
7688      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7689      to get it via circuitous means.  Blech.  */
7690   if (comp_dir != NULL)
7691     result_reader->comp_dir = DW_STRING (comp_dir);
7692
7693   /* Skip dummy compilation units.  */
7694   if (info_ptr >= begin_info_ptr + dwo_unit->length
7695       || peek_abbrev_code (abfd, info_ptr) == 0)
7696     return 0;
7697
7698   *result_info_ptr = info_ptr;
7699   return 1;
7700 }
7701
7702 /* Subroutine of init_cutu_and_read_dies to simplify it.
7703    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7704    Returns NULL if the specified DWO unit cannot be found.  */
7705
7706 static struct dwo_unit *
7707 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7708                  struct die_info *comp_unit_die)
7709 {
7710   struct dwarf2_cu *cu = this_cu->cu;
7711   ULONGEST signature;
7712   struct dwo_unit *dwo_unit;
7713   const char *comp_dir, *dwo_name;
7714
7715   gdb_assert (cu != NULL);
7716
7717   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7718   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7719   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7720
7721   if (this_cu->is_debug_types)
7722     {
7723       struct signatured_type *sig_type;
7724
7725       /* Since this_cu is the first member of struct signatured_type,
7726          we can go from a pointer to one to a pointer to the other.  */
7727       sig_type = (struct signatured_type *) this_cu;
7728       signature = sig_type->signature;
7729       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7730     }
7731   else
7732     {
7733       struct attribute *attr;
7734
7735       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7736       if (! attr)
7737         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7738                  " [in module %s]"),
7739                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7740       signature = DW_UNSND (attr);
7741       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7742                                        signature);
7743     }
7744
7745   return dwo_unit;
7746 }
7747
7748 /* Subroutine of init_cutu_and_read_dies to simplify it.
7749    See it for a description of the parameters.
7750    Read a TU directly from a DWO file, bypassing the stub.  */
7751
7752 static void
7753 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7754                            int use_existing_cu, int keep,
7755                            die_reader_func_ftype *die_reader_func,
7756                            void *data)
7757 {
7758   std::unique_ptr<dwarf2_cu> new_cu;
7759   struct signatured_type *sig_type;
7760   struct die_reader_specs reader;
7761   const gdb_byte *info_ptr;
7762   struct die_info *comp_unit_die;
7763   int has_children;
7764   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7765
7766   /* Verify we can do the following downcast, and that we have the
7767      data we need.  */
7768   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7769   sig_type = (struct signatured_type *) this_cu;
7770   gdb_assert (sig_type->dwo_unit != NULL);
7771
7772   if (use_existing_cu && this_cu->cu != NULL)
7773     {
7774       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7775       /* There's no need to do the rereading_dwo_cu handling that
7776          init_cutu_and_read_dies does since we don't read the stub.  */
7777     }
7778   else
7779     {
7780       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7781       gdb_assert (this_cu->cu == NULL);
7782       new_cu.reset (new dwarf2_cu (this_cu));
7783     }
7784
7785   /* A future optimization, if needed, would be to use an existing
7786      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7787      could share abbrev tables.  */
7788
7789   /* The abbreviation table used by READER, this must live at least as long as
7790      READER.  */
7791   abbrev_table_up dwo_abbrev_table;
7792
7793   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7794                               NULL /* stub_comp_unit_die */,
7795                               sig_type->dwo_unit->dwo_file->comp_dir,
7796                               &reader, &info_ptr,
7797                               &comp_unit_die, &has_children,
7798                               &dwo_abbrev_table) == 0)
7799     {
7800       /* Dummy die.  */
7801       return;
7802     }
7803
7804   /* All the "real" work is done here.  */
7805   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7806
7807   /* This duplicates the code in init_cutu_and_read_dies,
7808      but the alternative is making the latter more complex.
7809      This function is only for the special case of using DWO files directly:
7810      no point in overly complicating the general case just to handle this.  */
7811   if (new_cu != NULL && keep)
7812     {
7813       /* Link this CU into read_in_chain.  */
7814       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7815       dwarf2_per_objfile->read_in_chain = this_cu;
7816       /* The chain owns it now.  */
7817       new_cu.release ();
7818     }
7819 }
7820
7821 /* Initialize a CU (or TU) and read its DIEs.
7822    If the CU defers to a DWO file, read the DWO file as well.
7823
7824    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7825    Otherwise the table specified in the comp unit header is read in and used.
7826    This is an optimization for when we already have the abbrev table.
7827
7828    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7829    Otherwise, a new CU is allocated with xmalloc.
7830
7831    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7832    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7833
7834    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7835    linker) then DIE_READER_FUNC will not get called.  */
7836
7837 static void
7838 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7839                          struct abbrev_table *abbrev_table,
7840                          int use_existing_cu, int keep,
7841                          die_reader_func_ftype *die_reader_func,
7842                          void *data)
7843 {
7844   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7845   struct objfile *objfile = dwarf2_per_objfile->objfile;
7846   struct dwarf2_section_info *section = this_cu->section;
7847   bfd *abfd = get_section_bfd_owner (section);
7848   struct dwarf2_cu *cu;
7849   const gdb_byte *begin_info_ptr, *info_ptr;
7850   struct die_reader_specs reader;
7851   struct die_info *comp_unit_die;
7852   int has_children;
7853   struct attribute *attr;
7854   struct signatured_type *sig_type = NULL;
7855   struct dwarf2_section_info *abbrev_section;
7856   /* Non-zero if CU currently points to a DWO file and we need to
7857      reread it.  When this happens we need to reread the skeleton die
7858      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7859   int rereading_dwo_cu = 0;
7860
7861   if (dwarf_die_debug)
7862     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7863                         this_cu->is_debug_types ? "type" : "comp",
7864                         sect_offset_str (this_cu->sect_off));
7865
7866   if (use_existing_cu)
7867     gdb_assert (keep);
7868
7869   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7870      file (instead of going through the stub), short-circuit all of this.  */
7871   if (this_cu->reading_dwo_directly)
7872     {
7873       /* Narrow down the scope of possibilities to have to understand.  */
7874       gdb_assert (this_cu->is_debug_types);
7875       gdb_assert (abbrev_table == NULL);
7876       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7877                                  die_reader_func, data);
7878       return;
7879     }
7880
7881   /* This is cheap if the section is already read in.  */
7882   dwarf2_read_section (objfile, section);
7883
7884   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7885
7886   abbrev_section = get_abbrev_section_for_cu (this_cu);
7887
7888   std::unique_ptr<dwarf2_cu> new_cu;
7889   if (use_existing_cu && this_cu->cu != NULL)
7890     {
7891       cu = this_cu->cu;
7892       /* If this CU is from a DWO file we need to start over, we need to
7893          refetch the attributes from the skeleton CU.
7894          This could be optimized by retrieving those attributes from when we
7895          were here the first time: the previous comp_unit_die was stored in
7896          comp_unit_obstack.  But there's no data yet that we need this
7897          optimization.  */
7898       if (cu->dwo_unit != NULL)
7899         rereading_dwo_cu = 1;
7900     }
7901   else
7902     {
7903       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7904       gdb_assert (this_cu->cu == NULL);
7905       new_cu.reset (new dwarf2_cu (this_cu));
7906       cu = new_cu.get ();
7907     }
7908
7909   /* Get the header.  */
7910   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7911     {
7912       /* We already have the header, there's no need to read it in again.  */
7913       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7914     }
7915   else
7916     {
7917       if (this_cu->is_debug_types)
7918         {
7919           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7920                                                     &cu->header, section,
7921                                                     abbrev_section, info_ptr,
7922                                                     rcuh_kind::TYPE);
7923
7924           /* Since per_cu is the first member of struct signatured_type,
7925              we can go from a pointer to one to a pointer to the other.  */
7926           sig_type = (struct signatured_type *) this_cu;
7927           gdb_assert (sig_type->signature == cu->header.signature);
7928           gdb_assert (sig_type->type_offset_in_tu
7929                       == cu->header.type_cu_offset_in_tu);
7930           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7931
7932           /* LENGTH has not been set yet for type units if we're
7933              using .gdb_index.  */
7934           this_cu->length = get_cu_length (&cu->header);
7935
7936           /* Establish the type offset that can be used to lookup the type.  */
7937           sig_type->type_offset_in_section =
7938             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7939
7940           this_cu->dwarf_version = cu->header.version;
7941         }
7942       else
7943         {
7944           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7945                                                     &cu->header, section,
7946                                                     abbrev_section,
7947                                                     info_ptr,
7948                                                     rcuh_kind::COMPILE);
7949
7950           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7951           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7952           this_cu->dwarf_version = cu->header.version;
7953         }
7954     }
7955
7956   /* Skip dummy compilation units.  */
7957   if (info_ptr >= begin_info_ptr + this_cu->length
7958       || peek_abbrev_code (abfd, info_ptr) == 0)
7959     return;
7960
7961   /* If we don't have them yet, read the abbrevs for this compilation unit.
7962      And if we need to read them now, make sure they're freed when we're
7963      done (own the table through ABBREV_TABLE_HOLDER).  */
7964   abbrev_table_up abbrev_table_holder;
7965   if (abbrev_table != NULL)
7966     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7967   else
7968     {
7969       abbrev_table_holder
7970         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7971                                    cu->header.abbrev_sect_off);
7972       abbrev_table = abbrev_table_holder.get ();
7973     }
7974
7975   /* Read the top level CU/TU die.  */
7976   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7977   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7978
7979   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7980      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7981      table from the DWO file and pass the ownership over to us.  It will be
7982      referenced from READER, so we must make sure to free it after we're done
7983      with READER.
7984
7985      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7986      DWO CU, that this test will fail (the attribute will not be present).  */
7987   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7988   abbrev_table_up dwo_abbrev_table;
7989   if (attr)
7990     {
7991       struct dwo_unit *dwo_unit;
7992       struct die_info *dwo_comp_unit_die;
7993
7994       if (has_children)
7995         {
7996           complaint (&symfile_complaints,
7997                      _("compilation unit with DW_AT_GNU_dwo_name"
7998                        " has children (offset %s) [in module %s]"),
7999                      sect_offset_str (this_cu->sect_off),
8000                      bfd_get_filename (abfd));
8001         }
8002       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
8003       if (dwo_unit != NULL)
8004         {
8005           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
8006                                       comp_unit_die, NULL,
8007                                       &reader, &info_ptr,
8008                                       &dwo_comp_unit_die, &has_children,
8009                                       &dwo_abbrev_table) == 0)
8010             {
8011               /* Dummy die.  */
8012               return;
8013             }
8014           comp_unit_die = dwo_comp_unit_die;
8015         }
8016       else
8017         {
8018           /* Yikes, we couldn't find the rest of the DIE, we only have
8019              the stub.  A complaint has already been logged.  There's
8020              not much more we can do except pass on the stub DIE to
8021              die_reader_func.  We don't want to throw an error on bad
8022              debug info.  */
8023         }
8024     }
8025
8026   /* All of the above is setup for this call.  Yikes.  */
8027   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8028
8029   /* Done, clean up.  */
8030   if (new_cu != NULL && keep)
8031     {
8032       /* Link this CU into read_in_chain.  */
8033       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8034       dwarf2_per_objfile->read_in_chain = this_cu;
8035       /* The chain owns it now.  */
8036       new_cu.release ();
8037     }
8038 }
8039
8040 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8041    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8042    to have already done the lookup to find the DWO file).
8043
8044    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8045    THIS_CU->is_debug_types, but nothing else.
8046
8047    We fill in THIS_CU->length.
8048
8049    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8050    linker) then DIE_READER_FUNC will not get called.
8051
8052    THIS_CU->cu is always freed when done.
8053    This is done in order to not leave THIS_CU->cu in a state where we have
8054    to care whether it refers to the "main" CU or the DWO CU.  */
8055
8056 static void
8057 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8058                                    struct dwo_file *dwo_file,
8059                                    die_reader_func_ftype *die_reader_func,
8060                                    void *data)
8061 {
8062   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8063   struct objfile *objfile = dwarf2_per_objfile->objfile;
8064   struct dwarf2_section_info *section = this_cu->section;
8065   bfd *abfd = get_section_bfd_owner (section);
8066   struct dwarf2_section_info *abbrev_section;
8067   const gdb_byte *begin_info_ptr, *info_ptr;
8068   struct die_reader_specs reader;
8069   struct die_info *comp_unit_die;
8070   int has_children;
8071
8072   if (dwarf_die_debug)
8073     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
8074                         this_cu->is_debug_types ? "type" : "comp",
8075                         sect_offset_str (this_cu->sect_off));
8076
8077   gdb_assert (this_cu->cu == NULL);
8078
8079   abbrev_section = (dwo_file != NULL
8080                     ? &dwo_file->sections.abbrev
8081                     : get_abbrev_section_for_cu (this_cu));
8082
8083   /* This is cheap if the section is already read in.  */
8084   dwarf2_read_section (objfile, section);
8085
8086   struct dwarf2_cu cu (this_cu);
8087
8088   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8089   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8090                                             &cu.header, section,
8091                                             abbrev_section, info_ptr,
8092                                             (this_cu->is_debug_types
8093                                              ? rcuh_kind::TYPE
8094                                              : rcuh_kind::COMPILE));
8095
8096   this_cu->length = get_cu_length (&cu.header);
8097
8098   /* Skip dummy compilation units.  */
8099   if (info_ptr >= begin_info_ptr + this_cu->length
8100       || peek_abbrev_code (abfd, info_ptr) == 0)
8101     return;
8102
8103   abbrev_table_up abbrev_table
8104     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8105                                cu.header.abbrev_sect_off);
8106
8107   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8108   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8109
8110   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8111 }
8112
8113 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8114    does not lookup the specified DWO file.
8115    This cannot be used to read DWO files.
8116
8117    THIS_CU->cu is always freed when done.
8118    This is done in order to not leave THIS_CU->cu in a state where we have
8119    to care whether it refers to the "main" CU or the DWO CU.
8120    We can revisit this if the data shows there's a performance issue.  */
8121
8122 static void
8123 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8124                                 die_reader_func_ftype *die_reader_func,
8125                                 void *data)
8126 {
8127   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8128 }
8129 \f
8130 /* Type Unit Groups.
8131
8132    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8133    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8134    so that all types coming from the same compilation (.o file) are grouped
8135    together.  A future step could be to put the types in the same symtab as
8136    the CU the types ultimately came from.  */
8137
8138 static hashval_t
8139 hash_type_unit_group (const void *item)
8140 {
8141   const struct type_unit_group *tu_group
8142     = (const struct type_unit_group *) item;
8143
8144   return hash_stmt_list_entry (&tu_group->hash);
8145 }
8146
8147 static int
8148 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8149 {
8150   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8151   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8152
8153   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8154 }
8155
8156 /* Allocate a hash table for type unit groups.  */
8157
8158 static htab_t
8159 allocate_type_unit_groups_table (struct objfile *objfile)
8160 {
8161   return htab_create_alloc_ex (3,
8162                                hash_type_unit_group,
8163                                eq_type_unit_group,
8164                                NULL,
8165                                &objfile->objfile_obstack,
8166                                hashtab_obstack_allocate,
8167                                dummy_obstack_deallocate);
8168 }
8169
8170 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8171    partial symtabs.  We combine several TUs per psymtab to not let the size
8172    of any one psymtab grow too big.  */
8173 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8174 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8175
8176 /* Helper routine for get_type_unit_group.
8177    Create the type_unit_group object used to hold one or more TUs.  */
8178
8179 static struct type_unit_group *
8180 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8181 {
8182   struct dwarf2_per_objfile *dwarf2_per_objfile
8183     = cu->per_cu->dwarf2_per_objfile;
8184   struct objfile *objfile = dwarf2_per_objfile->objfile;
8185   struct dwarf2_per_cu_data *per_cu;
8186   struct type_unit_group *tu_group;
8187
8188   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8189                              struct type_unit_group);
8190   per_cu = &tu_group->per_cu;
8191   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8192
8193   if (dwarf2_per_objfile->using_index)
8194     {
8195       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8196                                         struct dwarf2_per_cu_quick_data);
8197     }
8198   else
8199     {
8200       unsigned int line_offset = to_underlying (line_offset_struct);
8201       struct partial_symtab *pst;
8202       char *name;
8203
8204       /* Give the symtab a useful name for debug purposes.  */
8205       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8206         name = xstrprintf ("<type_units_%d>",
8207                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8208       else
8209         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8210
8211       pst = create_partial_symtab (per_cu, name);
8212       pst->anonymous = 1;
8213
8214       xfree (name);
8215     }
8216
8217   tu_group->hash.dwo_unit = cu->dwo_unit;
8218   tu_group->hash.line_sect_off = line_offset_struct;
8219
8220   return tu_group;
8221 }
8222
8223 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8224    STMT_LIST is a DW_AT_stmt_list attribute.  */
8225
8226 static struct type_unit_group *
8227 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8228 {
8229   struct dwarf2_per_objfile *dwarf2_per_objfile
8230     = cu->per_cu->dwarf2_per_objfile;
8231   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8232   struct type_unit_group *tu_group;
8233   void **slot;
8234   unsigned int line_offset;
8235   struct type_unit_group type_unit_group_for_lookup;
8236
8237   if (dwarf2_per_objfile->type_unit_groups == NULL)
8238     {
8239       dwarf2_per_objfile->type_unit_groups =
8240         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8241     }
8242
8243   /* Do we need to create a new group, or can we use an existing one?  */
8244
8245   if (stmt_list)
8246     {
8247       line_offset = DW_UNSND (stmt_list);
8248       ++tu_stats->nr_symtab_sharers;
8249     }
8250   else
8251     {
8252       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8253          We can do various things here like create one group per TU or
8254          spread them over multiple groups to split up the expansion work.
8255          To avoid worst case scenarios (too many groups or too large groups)
8256          we, umm, group them in bunches.  */
8257       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8258                      | (tu_stats->nr_stmt_less_type_units
8259                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8260       ++tu_stats->nr_stmt_less_type_units;
8261     }
8262
8263   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8264   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8265   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8266                          &type_unit_group_for_lookup, INSERT);
8267   if (*slot != NULL)
8268     {
8269       tu_group = (struct type_unit_group *) *slot;
8270       gdb_assert (tu_group != NULL);
8271     }
8272   else
8273     {
8274       sect_offset line_offset_struct = (sect_offset) line_offset;
8275       tu_group = create_type_unit_group (cu, line_offset_struct);
8276       *slot = tu_group;
8277       ++tu_stats->nr_symtabs;
8278     }
8279
8280   return tu_group;
8281 }
8282 \f
8283 /* Partial symbol tables.  */
8284
8285 /* Create a psymtab named NAME and assign it to PER_CU.
8286
8287    The caller must fill in the following details:
8288    dirname, textlow, texthigh.  */
8289
8290 static struct partial_symtab *
8291 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8292 {
8293   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8294   struct partial_symtab *pst;
8295
8296   pst = start_psymtab_common (objfile, name, 0,
8297                               objfile->global_psymbols,
8298                               objfile->static_psymbols);
8299
8300   pst->psymtabs_addrmap_supported = 1;
8301
8302   /* This is the glue that links PST into GDB's symbol API.  */
8303   pst->read_symtab_private = per_cu;
8304   pst->read_symtab = dwarf2_read_symtab;
8305   per_cu->v.psymtab = pst;
8306
8307   return pst;
8308 }
8309
8310 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8311    type.  */
8312
8313 struct process_psymtab_comp_unit_data
8314 {
8315   /* True if we are reading a DW_TAG_partial_unit.  */
8316
8317   int want_partial_unit;
8318
8319   /* The "pretend" language that is used if the CU doesn't declare a
8320      language.  */
8321
8322   enum language pretend_language;
8323 };
8324
8325 /* die_reader_func for process_psymtab_comp_unit.  */
8326
8327 static void
8328 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8329                                   const gdb_byte *info_ptr,
8330                                   struct die_info *comp_unit_die,
8331                                   int has_children,
8332                                   void *data)
8333 {
8334   struct dwarf2_cu *cu = reader->cu;
8335   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8336   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8337   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8338   CORE_ADDR baseaddr;
8339   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8340   struct partial_symtab *pst;
8341   enum pc_bounds_kind cu_bounds_kind;
8342   const char *filename;
8343   struct process_psymtab_comp_unit_data *info
8344     = (struct process_psymtab_comp_unit_data *) data;
8345
8346   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8347     return;
8348
8349   gdb_assert (! per_cu->is_debug_types);
8350
8351   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8352
8353   cu->list_in_scope = &file_symbols;
8354
8355   /* Allocate a new partial symbol table structure.  */
8356   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8357   if (filename == NULL)
8358     filename = "";
8359
8360   pst = create_partial_symtab (per_cu, filename);
8361
8362   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8363   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8364
8365   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8366
8367   dwarf2_find_base_address (comp_unit_die, cu);
8368
8369   /* Possibly set the default values of LOWPC and HIGHPC from
8370      `DW_AT_ranges'.  */
8371   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8372                                          &best_highpc, cu, pst);
8373   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8374     /* Store the contiguous range if it is not empty; it can be empty for
8375        CUs with no code.  */
8376     addrmap_set_empty (objfile->psymtabs_addrmap,
8377                        gdbarch_adjust_dwarf2_addr (gdbarch,
8378                                                    best_lowpc + baseaddr),
8379                        gdbarch_adjust_dwarf2_addr (gdbarch,
8380                                                    best_highpc + baseaddr) - 1,
8381                        pst);
8382
8383   /* Check if comp unit has_children.
8384      If so, read the rest of the partial symbols from this comp unit.
8385      If not, there's no more debug_info for this comp unit.  */
8386   if (has_children)
8387     {
8388       struct partial_die_info *first_die;
8389       CORE_ADDR lowpc, highpc;
8390
8391       lowpc = ((CORE_ADDR) -1);
8392       highpc = ((CORE_ADDR) 0);
8393
8394       first_die = load_partial_dies (reader, info_ptr, 1);
8395
8396       scan_partial_symbols (first_die, &lowpc, &highpc,
8397                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8398
8399       /* If we didn't find a lowpc, set it to highpc to avoid
8400          complaints from `maint check'.  */
8401       if (lowpc == ((CORE_ADDR) -1))
8402         lowpc = highpc;
8403
8404       /* If the compilation unit didn't have an explicit address range,
8405          then use the information extracted from its child dies.  */
8406       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8407         {
8408           best_lowpc = lowpc;
8409           best_highpc = highpc;
8410         }
8411     }
8412   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8413   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8414
8415   end_psymtab_common (objfile, pst);
8416
8417   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8418     {
8419       int i;
8420       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8421       struct dwarf2_per_cu_data *iter;
8422
8423       /* Fill in 'dependencies' here; we fill in 'users' in a
8424          post-pass.  */
8425       pst->number_of_dependencies = len;
8426       pst->dependencies =
8427         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8428       for (i = 0;
8429            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8430                         i, iter);
8431            ++i)
8432         pst->dependencies[i] = iter->v.psymtab;
8433
8434       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8435     }
8436
8437   /* Get the list of files included in the current compilation unit,
8438      and build a psymtab for each of them.  */
8439   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8440
8441   if (dwarf_read_debug)
8442     {
8443       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8444
8445       fprintf_unfiltered (gdb_stdlog,
8446                           "Psymtab for %s unit @%s: %s - %s"
8447                           ", %d global, %d static syms\n",
8448                           per_cu->is_debug_types ? "type" : "comp",
8449                           sect_offset_str (per_cu->sect_off),
8450                           paddress (gdbarch, pst->textlow),
8451                           paddress (gdbarch, pst->texthigh),
8452                           pst->n_global_syms, pst->n_static_syms);
8453     }
8454 }
8455
8456 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8457    Process compilation unit THIS_CU for a psymtab.  */
8458
8459 static void
8460 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8461                            int want_partial_unit,
8462                            enum language pretend_language)
8463 {
8464   /* If this compilation unit was already read in, free the
8465      cached copy in order to read it in again.  This is
8466      necessary because we skipped some symbols when we first
8467      read in the compilation unit (see load_partial_dies).
8468      This problem could be avoided, but the benefit is unclear.  */
8469   if (this_cu->cu != NULL)
8470     free_one_cached_comp_unit (this_cu);
8471
8472   if (this_cu->is_debug_types)
8473     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8474                              NULL);
8475   else
8476     {
8477       process_psymtab_comp_unit_data info;
8478       info.want_partial_unit = want_partial_unit;
8479       info.pretend_language = pretend_language;
8480       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8481                                process_psymtab_comp_unit_reader, &info);
8482     }
8483
8484   /* Age out any secondary CUs.  */
8485   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8486 }
8487
8488 /* Reader function for build_type_psymtabs.  */
8489
8490 static void
8491 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8492                             const gdb_byte *info_ptr,
8493                             struct die_info *type_unit_die,
8494                             int has_children,
8495                             void *data)
8496 {
8497   struct dwarf2_per_objfile *dwarf2_per_objfile
8498     = reader->cu->per_cu->dwarf2_per_objfile;
8499   struct objfile *objfile = dwarf2_per_objfile->objfile;
8500   struct dwarf2_cu *cu = reader->cu;
8501   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8502   struct signatured_type *sig_type;
8503   struct type_unit_group *tu_group;
8504   struct attribute *attr;
8505   struct partial_die_info *first_die;
8506   CORE_ADDR lowpc, highpc;
8507   struct partial_symtab *pst;
8508
8509   gdb_assert (data == NULL);
8510   gdb_assert (per_cu->is_debug_types);
8511   sig_type = (struct signatured_type *) per_cu;
8512
8513   if (! has_children)
8514     return;
8515
8516   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8517   tu_group = get_type_unit_group (cu, attr);
8518
8519   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8520
8521   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8522   cu->list_in_scope = &file_symbols;
8523   pst = create_partial_symtab (per_cu, "");
8524   pst->anonymous = 1;
8525
8526   first_die = load_partial_dies (reader, info_ptr, 1);
8527
8528   lowpc = (CORE_ADDR) -1;
8529   highpc = (CORE_ADDR) 0;
8530   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8531
8532   end_psymtab_common (objfile, pst);
8533 }
8534
8535 /* Struct used to sort TUs by their abbreviation table offset.  */
8536
8537 struct tu_abbrev_offset
8538 {
8539   struct signatured_type *sig_type;
8540   sect_offset abbrev_offset;
8541 };
8542
8543 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8544
8545 static int
8546 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8547 {
8548   const struct tu_abbrev_offset * const *a
8549     = (const struct tu_abbrev_offset * const*) ap;
8550   const struct tu_abbrev_offset * const *b
8551     = (const struct tu_abbrev_offset * const*) bp;
8552   sect_offset aoff = (*a)->abbrev_offset;
8553   sect_offset boff = (*b)->abbrev_offset;
8554
8555   return (aoff > boff) - (aoff < boff);
8556 }
8557
8558 /* Efficiently read all the type units.
8559    This does the bulk of the work for build_type_psymtabs.
8560
8561    The efficiency is because we sort TUs by the abbrev table they use and
8562    only read each abbrev table once.  In one program there are 200K TUs
8563    sharing 8K abbrev tables.
8564
8565    The main purpose of this function is to support building the
8566    dwarf2_per_objfile->type_unit_groups table.
8567    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8568    can collapse the search space by grouping them by stmt_list.
8569    The savings can be significant, in the same program from above the 200K TUs
8570    share 8K stmt_list tables.
8571
8572    FUNC is expected to call get_type_unit_group, which will create the
8573    struct type_unit_group if necessary and add it to
8574    dwarf2_per_objfile->type_unit_groups.  */
8575
8576 static void
8577 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8578 {
8579   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8580   struct cleanup *cleanups;
8581   abbrev_table_up abbrev_table;
8582   sect_offset abbrev_offset;
8583   struct tu_abbrev_offset *sorted_by_abbrev;
8584   int i;
8585
8586   /* It's up to the caller to not call us multiple times.  */
8587   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8588
8589   if (dwarf2_per_objfile->n_type_units == 0)
8590     return;
8591
8592   /* TUs typically share abbrev tables, and there can be way more TUs than
8593      abbrev tables.  Sort by abbrev table to reduce the number of times we
8594      read each abbrev table in.
8595      Alternatives are to punt or to maintain a cache of abbrev tables.
8596      This is simpler and efficient enough for now.
8597
8598      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8599      symtab to use).  Typically TUs with the same abbrev offset have the same
8600      stmt_list value too so in practice this should work well.
8601
8602      The basic algorithm here is:
8603
8604       sort TUs by abbrev table
8605       for each TU with same abbrev table:
8606         read abbrev table if first user
8607         read TU top level DIE
8608           [IWBN if DWO skeletons had DW_AT_stmt_list]
8609         call FUNC  */
8610
8611   if (dwarf_read_debug)
8612     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8613
8614   /* Sort in a separate table to maintain the order of all_type_units
8615      for .gdb_index: TU indices directly index all_type_units.  */
8616   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8617                               dwarf2_per_objfile->n_type_units);
8618   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8619     {
8620       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8621
8622       sorted_by_abbrev[i].sig_type = sig_type;
8623       sorted_by_abbrev[i].abbrev_offset =
8624         read_abbrev_offset (dwarf2_per_objfile,
8625                             sig_type->per_cu.section,
8626                             sig_type->per_cu.sect_off);
8627     }
8628   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8629   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8630          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8631
8632   abbrev_offset = (sect_offset) ~(unsigned) 0;
8633
8634   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8635     {
8636       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8637
8638       /* Switch to the next abbrev table if necessary.  */
8639       if (abbrev_table == NULL
8640           || tu->abbrev_offset != abbrev_offset)
8641         {
8642           abbrev_offset = tu->abbrev_offset;
8643           abbrev_table =
8644             abbrev_table_read_table (dwarf2_per_objfile,
8645                                      &dwarf2_per_objfile->abbrev,
8646                                      abbrev_offset);
8647           ++tu_stats->nr_uniq_abbrev_tables;
8648         }
8649
8650       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8651                                0, 0, build_type_psymtabs_reader, NULL);
8652     }
8653
8654   do_cleanups (cleanups);
8655 }
8656
8657 /* Print collected type unit statistics.  */
8658
8659 static void
8660 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8661 {
8662   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8663
8664   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8665   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8666                       dwarf2_per_objfile->n_type_units);
8667   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8668                       tu_stats->nr_uniq_abbrev_tables);
8669   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8670                       tu_stats->nr_symtabs);
8671   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8672                       tu_stats->nr_symtab_sharers);
8673   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8674                       tu_stats->nr_stmt_less_type_units);
8675   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8676                       tu_stats->nr_all_type_units_reallocs);
8677 }
8678
8679 /* Traversal function for build_type_psymtabs.  */
8680
8681 static int
8682 build_type_psymtab_dependencies (void **slot, void *info)
8683 {
8684   struct dwarf2_per_objfile *dwarf2_per_objfile
8685     = (struct dwarf2_per_objfile *) info;
8686   struct objfile *objfile = dwarf2_per_objfile->objfile;
8687   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8688   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8689   struct partial_symtab *pst = per_cu->v.psymtab;
8690   int len = VEC_length (sig_type_ptr, tu_group->tus);
8691   struct signatured_type *iter;
8692   int i;
8693
8694   gdb_assert (len > 0);
8695   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8696
8697   pst->number_of_dependencies = len;
8698   pst->dependencies =
8699     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8700   for (i = 0;
8701        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8702        ++i)
8703     {
8704       gdb_assert (iter->per_cu.is_debug_types);
8705       pst->dependencies[i] = iter->per_cu.v.psymtab;
8706       iter->type_unit_group = tu_group;
8707     }
8708
8709   VEC_free (sig_type_ptr, tu_group->tus);
8710
8711   return 1;
8712 }
8713
8714 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8715    Build partial symbol tables for the .debug_types comp-units.  */
8716
8717 static void
8718 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8719 {
8720   if (! create_all_type_units (dwarf2_per_objfile))
8721     return;
8722
8723   build_type_psymtabs_1 (dwarf2_per_objfile);
8724 }
8725
8726 /* Traversal function for process_skeletonless_type_unit.
8727    Read a TU in a DWO file and build partial symbols for it.  */
8728
8729 static int
8730 process_skeletonless_type_unit (void **slot, void *info)
8731 {
8732   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8733   struct dwarf2_per_objfile *dwarf2_per_objfile
8734     = (struct dwarf2_per_objfile *) info;
8735   struct signatured_type find_entry, *entry;
8736
8737   /* If this TU doesn't exist in the global table, add it and read it in.  */
8738
8739   if (dwarf2_per_objfile->signatured_types == NULL)
8740     {
8741       dwarf2_per_objfile->signatured_types
8742         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8743     }
8744
8745   find_entry.signature = dwo_unit->signature;
8746   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8747                          INSERT);
8748   /* If we've already seen this type there's nothing to do.  What's happening
8749      is we're doing our own version of comdat-folding here.  */
8750   if (*slot != NULL)
8751     return 1;
8752
8753   /* This does the job that create_all_type_units would have done for
8754      this TU.  */
8755   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8756   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8757   *slot = entry;
8758
8759   /* This does the job that build_type_psymtabs_1 would have done.  */
8760   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8761                            build_type_psymtabs_reader, NULL);
8762
8763   return 1;
8764 }
8765
8766 /* Traversal function for process_skeletonless_type_units.  */
8767
8768 static int
8769 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8770 {
8771   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8772
8773   if (dwo_file->tus != NULL)
8774     {
8775       htab_traverse_noresize (dwo_file->tus,
8776                               process_skeletonless_type_unit, info);
8777     }
8778
8779   return 1;
8780 }
8781
8782 /* Scan all TUs of DWO files, verifying we've processed them.
8783    This is needed in case a TU was emitted without its skeleton.
8784    Note: This can't be done until we know what all the DWO files are.  */
8785
8786 static void
8787 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8788 {
8789   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8790   if (get_dwp_file (dwarf2_per_objfile) == NULL
8791       && dwarf2_per_objfile->dwo_files != NULL)
8792     {
8793       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8794                               process_dwo_file_for_skeletonless_type_units,
8795                               dwarf2_per_objfile);
8796     }
8797 }
8798
8799 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8800
8801 static void
8802 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8803 {
8804   int i;
8805
8806   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8807     {
8808       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8809       struct partial_symtab *pst = per_cu->v.psymtab;
8810       int j;
8811
8812       if (pst == NULL)
8813         continue;
8814
8815       for (j = 0; j < pst->number_of_dependencies; ++j)
8816         {
8817           /* Set the 'user' field only if it is not already set.  */
8818           if (pst->dependencies[j]->user == NULL)
8819             pst->dependencies[j]->user = pst;
8820         }
8821     }
8822 }
8823
8824 /* Build the partial symbol table by doing a quick pass through the
8825    .debug_info and .debug_abbrev sections.  */
8826
8827 static void
8828 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8829 {
8830   struct cleanup *back_to;
8831   int i;
8832   struct objfile *objfile = dwarf2_per_objfile->objfile;
8833
8834   if (dwarf_read_debug)
8835     {
8836       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8837                           objfile_name (objfile));
8838     }
8839
8840   dwarf2_per_objfile->reading_partial_symbols = 1;
8841
8842   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8843
8844   /* Any cached compilation units will be linked by the per-objfile
8845      read_in_chain.  Make sure to free them when we're done.  */
8846   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8847
8848   build_type_psymtabs (dwarf2_per_objfile);
8849
8850   create_all_comp_units (dwarf2_per_objfile);
8851
8852   /* Create a temporary address map on a temporary obstack.  We later
8853      copy this to the final obstack.  */
8854   auto_obstack temp_obstack;
8855
8856   scoped_restore save_psymtabs_addrmap
8857     = make_scoped_restore (&objfile->psymtabs_addrmap,
8858                            addrmap_create_mutable (&temp_obstack));
8859
8860   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8861     {
8862       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8863
8864       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8865     }
8866
8867   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8868   process_skeletonless_type_units (dwarf2_per_objfile);
8869
8870   /* Now that all TUs have been processed we can fill in the dependencies.  */
8871   if (dwarf2_per_objfile->type_unit_groups != NULL)
8872     {
8873       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8874                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8875     }
8876
8877   if (dwarf_read_debug)
8878     print_tu_stats (dwarf2_per_objfile);
8879
8880   set_partial_user (dwarf2_per_objfile);
8881
8882   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8883                                                     &objfile->objfile_obstack);
8884   /* At this point we want to keep the address map.  */
8885   save_psymtabs_addrmap.release ();
8886
8887   do_cleanups (back_to);
8888
8889   if (dwarf_read_debug)
8890     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8891                         objfile_name (objfile));
8892 }
8893
8894 /* die_reader_func for load_partial_comp_unit.  */
8895
8896 static void
8897 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8898                                const gdb_byte *info_ptr,
8899                                struct die_info *comp_unit_die,
8900                                int has_children,
8901                                void *data)
8902 {
8903   struct dwarf2_cu *cu = reader->cu;
8904
8905   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8906
8907   /* Check if comp unit has_children.
8908      If so, read the rest of the partial symbols from this comp unit.
8909      If not, there's no more debug_info for this comp unit.  */
8910   if (has_children)
8911     load_partial_dies (reader, info_ptr, 0);
8912 }
8913
8914 /* Load the partial DIEs for a secondary CU into memory.
8915    This is also used when rereading a primary CU with load_all_dies.  */
8916
8917 static void
8918 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8919 {
8920   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8921                            load_partial_comp_unit_reader, NULL);
8922 }
8923
8924 static void
8925 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8926                               struct dwarf2_section_info *section,
8927                               struct dwarf2_section_info *abbrev_section,
8928                               unsigned int is_dwz,
8929                               int *n_allocated,
8930                               int *n_comp_units,
8931                               struct dwarf2_per_cu_data ***all_comp_units)
8932 {
8933   const gdb_byte *info_ptr;
8934   struct objfile *objfile = dwarf2_per_objfile->objfile;
8935
8936   if (dwarf_read_debug)
8937     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8938                         get_section_name (section),
8939                         get_section_file_name (section));
8940
8941   dwarf2_read_section (objfile, section);
8942
8943   info_ptr = section->buffer;
8944
8945   while (info_ptr < section->buffer + section->size)
8946     {
8947       struct dwarf2_per_cu_data *this_cu;
8948
8949       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8950
8951       comp_unit_head cu_header;
8952       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8953                                      abbrev_section, info_ptr,
8954                                      rcuh_kind::COMPILE);
8955
8956       /* Save the compilation unit for later lookup.  */
8957       if (cu_header.unit_type != DW_UT_type)
8958         {
8959           this_cu = XOBNEW (&objfile->objfile_obstack,
8960                             struct dwarf2_per_cu_data);
8961           memset (this_cu, 0, sizeof (*this_cu));
8962         }
8963       else
8964         {
8965           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8966                                   struct signatured_type);
8967           memset (sig_type, 0, sizeof (*sig_type));
8968           sig_type->signature = cu_header.signature;
8969           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8970           this_cu = &sig_type->per_cu;
8971         }
8972       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8973       this_cu->sect_off = sect_off;
8974       this_cu->length = cu_header.length + cu_header.initial_length_size;
8975       this_cu->is_dwz = is_dwz;
8976       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8977       this_cu->section = section;
8978
8979       if (*n_comp_units == *n_allocated)
8980         {
8981           *n_allocated *= 2;
8982           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8983                                         *all_comp_units, *n_allocated);
8984         }
8985       (*all_comp_units)[*n_comp_units] = this_cu;
8986       ++*n_comp_units;
8987
8988       info_ptr = info_ptr + this_cu->length;
8989     }
8990 }
8991
8992 /* Create a list of all compilation units in OBJFILE.
8993    This is only done for -readnow and building partial symtabs.  */
8994
8995 static void
8996 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8997 {
8998   int n_allocated;
8999   int n_comp_units;
9000   struct dwarf2_per_cu_data **all_comp_units;
9001   struct dwz_file *dwz;
9002   struct objfile *objfile = dwarf2_per_objfile->objfile;
9003
9004   n_comp_units = 0;
9005   n_allocated = 10;
9006   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9007
9008   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9009                                 &dwarf2_per_objfile->abbrev, 0,
9010                                 &n_allocated, &n_comp_units, &all_comp_units);
9011
9012   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9013   if (dwz != NULL)
9014     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9015                                   1, &n_allocated, &n_comp_units,
9016                                   &all_comp_units);
9017
9018   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9019                                                   struct dwarf2_per_cu_data *,
9020                                                   n_comp_units);
9021   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9022           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9023   xfree (all_comp_units);
9024   dwarf2_per_objfile->n_comp_units = n_comp_units;
9025 }
9026
9027 /* Process all loaded DIEs for compilation unit CU, starting at
9028    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9029    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9030    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9031    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9032
9033 static void
9034 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9035                       CORE_ADDR *highpc, int set_addrmap,
9036                       struct dwarf2_cu *cu)
9037 {
9038   struct partial_die_info *pdi;
9039
9040   /* Now, march along the PDI's, descending into ones which have
9041      interesting children but skipping the children of the other ones,
9042      until we reach the end of the compilation unit.  */
9043
9044   pdi = first_die;
9045
9046   while (pdi != NULL)
9047     {
9048       fixup_partial_die (pdi, cu);
9049
9050       /* Anonymous namespaces or modules have no name but have interesting
9051          children, so we need to look at them.  Ditto for anonymous
9052          enums.  */
9053
9054       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9055           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9056           || pdi->tag == DW_TAG_imported_unit
9057           || pdi->tag == DW_TAG_inlined_subroutine)
9058         {
9059           switch (pdi->tag)
9060             {
9061             case DW_TAG_subprogram:
9062             case DW_TAG_inlined_subroutine:
9063               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9064               break;
9065             case DW_TAG_constant:
9066             case DW_TAG_variable:
9067             case DW_TAG_typedef:
9068             case DW_TAG_union_type:
9069               if (!pdi->is_declaration)
9070                 {
9071                   add_partial_symbol (pdi, cu);
9072                 }
9073               break;
9074             case DW_TAG_class_type:
9075             case DW_TAG_interface_type:
9076             case DW_TAG_structure_type:
9077               if (!pdi->is_declaration)
9078                 {
9079                   add_partial_symbol (pdi, cu);
9080                 }
9081               if (cu->language == language_rust && pdi->has_children)
9082                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9083                                       set_addrmap, cu);
9084               break;
9085             case DW_TAG_enumeration_type:
9086               if (!pdi->is_declaration)
9087                 add_partial_enumeration (pdi, cu);
9088               break;
9089             case DW_TAG_base_type:
9090             case DW_TAG_subrange_type:
9091               /* File scope base type definitions are added to the partial
9092                  symbol table.  */
9093               add_partial_symbol (pdi, cu);
9094               break;
9095             case DW_TAG_namespace:
9096               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9097               break;
9098             case DW_TAG_module:
9099               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9100               break;
9101             case DW_TAG_imported_unit:
9102               {
9103                 struct dwarf2_per_cu_data *per_cu;
9104
9105                 /* For now we don't handle imported units in type units.  */
9106                 if (cu->per_cu->is_debug_types)
9107                   {
9108                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9109                              " supported in type units [in module %s]"),
9110                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9111                   }
9112
9113                 per_cu = dwarf2_find_containing_comp_unit
9114                            (pdi->d.sect_off, pdi->is_dwz,
9115                             cu->per_cu->dwarf2_per_objfile);
9116
9117                 /* Go read the partial unit, if needed.  */
9118                 if (per_cu->v.psymtab == NULL)
9119                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9120
9121                 VEC_safe_push (dwarf2_per_cu_ptr,
9122                                cu->per_cu->imported_symtabs, per_cu);
9123               }
9124               break;
9125             case DW_TAG_imported_declaration:
9126               add_partial_symbol (pdi, cu);
9127               break;
9128             default:
9129               break;
9130             }
9131         }
9132
9133       /* If the die has a sibling, skip to the sibling.  */
9134
9135       pdi = pdi->die_sibling;
9136     }
9137 }
9138
9139 /* Functions used to compute the fully scoped name of a partial DIE.
9140
9141    Normally, this is simple.  For C++, the parent DIE's fully scoped
9142    name is concatenated with "::" and the partial DIE's name.
9143    Enumerators are an exception; they use the scope of their parent
9144    enumeration type, i.e. the name of the enumeration type is not
9145    prepended to the enumerator.
9146
9147    There are two complexities.  One is DW_AT_specification; in this
9148    case "parent" means the parent of the target of the specification,
9149    instead of the direct parent of the DIE.  The other is compilers
9150    which do not emit DW_TAG_namespace; in this case we try to guess
9151    the fully qualified name of structure types from their members'
9152    linkage names.  This must be done using the DIE's children rather
9153    than the children of any DW_AT_specification target.  We only need
9154    to do this for structures at the top level, i.e. if the target of
9155    any DW_AT_specification (if any; otherwise the DIE itself) does not
9156    have a parent.  */
9157
9158 /* Compute the scope prefix associated with PDI's parent, in
9159    compilation unit CU.  The result will be allocated on CU's
9160    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9161    field.  NULL is returned if no prefix is necessary.  */
9162 static const char *
9163 partial_die_parent_scope (struct partial_die_info *pdi,
9164                           struct dwarf2_cu *cu)
9165 {
9166   const char *grandparent_scope;
9167   struct partial_die_info *parent, *real_pdi;
9168
9169   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9170      then this means the parent of the specification DIE.  */
9171
9172   real_pdi = pdi;
9173   while (real_pdi->has_specification)
9174     real_pdi = find_partial_die (real_pdi->spec_offset,
9175                                  real_pdi->spec_is_dwz, cu);
9176
9177   parent = real_pdi->die_parent;
9178   if (parent == NULL)
9179     return NULL;
9180
9181   if (parent->scope_set)
9182     return parent->scope;
9183
9184   fixup_partial_die (parent, cu);
9185
9186   grandparent_scope = partial_die_parent_scope (parent, cu);
9187
9188   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9189      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9190      Work around this problem here.  */
9191   if (cu->language == language_cplus
9192       && parent->tag == DW_TAG_namespace
9193       && strcmp (parent->name, "::") == 0
9194       && grandparent_scope == NULL)
9195     {
9196       parent->scope = NULL;
9197       parent->scope_set = 1;
9198       return NULL;
9199     }
9200
9201   if (pdi->tag == DW_TAG_enumerator)
9202     /* Enumerators should not get the name of the enumeration as a prefix.  */
9203     parent->scope = grandparent_scope;
9204   else if (parent->tag == DW_TAG_namespace
9205       || parent->tag == DW_TAG_module
9206       || parent->tag == DW_TAG_structure_type
9207       || parent->tag == DW_TAG_class_type
9208       || parent->tag == DW_TAG_interface_type
9209       || parent->tag == DW_TAG_union_type
9210       || parent->tag == DW_TAG_enumeration_type)
9211     {
9212       if (grandparent_scope == NULL)
9213         parent->scope = parent->name;
9214       else
9215         parent->scope = typename_concat (&cu->comp_unit_obstack,
9216                                          grandparent_scope,
9217                                          parent->name, 0, cu);
9218     }
9219   else
9220     {
9221       /* FIXME drow/2004-04-01: What should we be doing with
9222          function-local names?  For partial symbols, we should probably be
9223          ignoring them.  */
9224       complaint (&symfile_complaints,
9225                  _("unhandled containing DIE tag %d for DIE at %s"),
9226                  parent->tag, sect_offset_str (pdi->sect_off));
9227       parent->scope = grandparent_scope;
9228     }
9229
9230   parent->scope_set = 1;
9231   return parent->scope;
9232 }
9233
9234 /* Return the fully scoped name associated with PDI, from compilation unit
9235    CU.  The result will be allocated with malloc.  */
9236
9237 static char *
9238 partial_die_full_name (struct partial_die_info *pdi,
9239                        struct dwarf2_cu *cu)
9240 {
9241   const char *parent_scope;
9242
9243   /* If this is a template instantiation, we can not work out the
9244      template arguments from partial DIEs.  So, unfortunately, we have
9245      to go through the full DIEs.  At least any work we do building
9246      types here will be reused if full symbols are loaded later.  */
9247   if (pdi->has_template_arguments)
9248     {
9249       fixup_partial_die (pdi, cu);
9250
9251       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9252         {
9253           struct die_info *die;
9254           struct attribute attr;
9255           struct dwarf2_cu *ref_cu = cu;
9256
9257           /* DW_FORM_ref_addr is using section offset.  */
9258           attr.name = (enum dwarf_attribute) 0;
9259           attr.form = DW_FORM_ref_addr;
9260           attr.u.unsnd = to_underlying (pdi->sect_off);
9261           die = follow_die_ref (NULL, &attr, &ref_cu);
9262
9263           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9264         }
9265     }
9266
9267   parent_scope = partial_die_parent_scope (pdi, cu);
9268   if (parent_scope == NULL)
9269     return NULL;
9270   else
9271     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9272 }
9273
9274 static void
9275 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9276 {
9277   struct dwarf2_per_objfile *dwarf2_per_objfile
9278     = cu->per_cu->dwarf2_per_objfile;
9279   struct objfile *objfile = dwarf2_per_objfile->objfile;
9280   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9281   CORE_ADDR addr = 0;
9282   const char *actual_name = NULL;
9283   CORE_ADDR baseaddr;
9284   char *built_actual_name;
9285
9286   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9287
9288   built_actual_name = partial_die_full_name (pdi, cu);
9289   if (built_actual_name != NULL)
9290     actual_name = built_actual_name;
9291
9292   if (actual_name == NULL)
9293     actual_name = pdi->name;
9294
9295   switch (pdi->tag)
9296     {
9297     case DW_TAG_inlined_subroutine:
9298     case DW_TAG_subprogram:
9299       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9300       if (pdi->is_external || cu->language == language_ada)
9301         {
9302           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9303              of the global scope.  But in Ada, we want to be able to access
9304              nested procedures globally.  So all Ada subprograms are stored
9305              in the global scope.  */
9306           add_psymbol_to_list (actual_name, strlen (actual_name),
9307                                built_actual_name != NULL,
9308                                VAR_DOMAIN, LOC_BLOCK,
9309                                &objfile->global_psymbols,
9310                                addr, cu->language, objfile);
9311         }
9312       else
9313         {
9314           add_psymbol_to_list (actual_name, strlen (actual_name),
9315                                built_actual_name != NULL,
9316                                VAR_DOMAIN, LOC_BLOCK,
9317                                &objfile->static_psymbols,
9318                                addr, cu->language, objfile);
9319         }
9320
9321       if (pdi->main_subprogram && actual_name != NULL)
9322         set_objfile_main_name (objfile, actual_name, cu->language);
9323       break;
9324     case DW_TAG_constant:
9325       {
9326         std::vector<partial_symbol *> *list;
9327
9328         if (pdi->is_external)
9329           list = &objfile->global_psymbols;
9330         else
9331           list = &objfile->static_psymbols;
9332         add_psymbol_to_list (actual_name, strlen (actual_name),
9333                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9334                              list, 0, cu->language, objfile);
9335       }
9336       break;
9337     case DW_TAG_variable:
9338       if (pdi->d.locdesc)
9339         addr = decode_locdesc (pdi->d.locdesc, cu);
9340
9341       if (pdi->d.locdesc
9342           && addr == 0
9343           && !dwarf2_per_objfile->has_section_at_zero)
9344         {
9345           /* A global or static variable may also have been stripped
9346              out by the linker if unused, in which case its address
9347              will be nullified; do not add such variables into partial
9348              symbol table then.  */
9349         }
9350       else if (pdi->is_external)
9351         {
9352           /* Global Variable.
9353              Don't enter into the minimal symbol tables as there is
9354              a minimal symbol table entry from the ELF symbols already.
9355              Enter into partial symbol table if it has a location
9356              descriptor or a type.
9357              If the location descriptor is missing, new_symbol will create
9358              a LOC_UNRESOLVED symbol, the address of the variable will then
9359              be determined from the minimal symbol table whenever the variable
9360              is referenced.
9361              The address for the partial symbol table entry is not
9362              used by GDB, but it comes in handy for debugging partial symbol
9363              table building.  */
9364
9365           if (pdi->d.locdesc || pdi->has_type)
9366             add_psymbol_to_list (actual_name, strlen (actual_name),
9367                                  built_actual_name != NULL,
9368                                  VAR_DOMAIN, LOC_STATIC,
9369                                  &objfile->global_psymbols,
9370                                  addr + baseaddr,
9371                                  cu->language, objfile);
9372         }
9373       else
9374         {
9375           int has_loc = pdi->d.locdesc != NULL;
9376
9377           /* Static Variable.  Skip symbols whose value we cannot know (those
9378              without location descriptors or constant values).  */
9379           if (!has_loc && !pdi->has_const_value)
9380             {
9381               xfree (built_actual_name);
9382               return;
9383             }
9384
9385           add_psymbol_to_list (actual_name, strlen (actual_name),
9386                                built_actual_name != NULL,
9387                                VAR_DOMAIN, LOC_STATIC,
9388                                &objfile->static_psymbols,
9389                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9390                                cu->language, objfile);
9391         }
9392       break;
9393     case DW_TAG_typedef:
9394     case DW_TAG_base_type:
9395     case DW_TAG_subrange_type:
9396       add_psymbol_to_list (actual_name, strlen (actual_name),
9397                            built_actual_name != NULL,
9398                            VAR_DOMAIN, LOC_TYPEDEF,
9399                            &objfile->static_psymbols,
9400                            0, cu->language, objfile);
9401       break;
9402     case DW_TAG_imported_declaration:
9403     case DW_TAG_namespace:
9404       add_psymbol_to_list (actual_name, strlen (actual_name),
9405                            built_actual_name != NULL,
9406                            VAR_DOMAIN, LOC_TYPEDEF,
9407                            &objfile->global_psymbols,
9408                            0, cu->language, objfile);
9409       break;
9410     case DW_TAG_module:
9411       add_psymbol_to_list (actual_name, strlen (actual_name),
9412                            built_actual_name != NULL,
9413                            MODULE_DOMAIN, LOC_TYPEDEF,
9414                            &objfile->global_psymbols,
9415                            0, cu->language, objfile);
9416       break;
9417     case DW_TAG_class_type:
9418     case DW_TAG_interface_type:
9419     case DW_TAG_structure_type:
9420     case DW_TAG_union_type:
9421     case DW_TAG_enumeration_type:
9422       /* Skip external references.  The DWARF standard says in the section
9423          about "Structure, Union, and Class Type Entries": "An incomplete
9424          structure, union or class type is represented by a structure,
9425          union or class entry that does not have a byte size attribute
9426          and that has a DW_AT_declaration attribute."  */
9427       if (!pdi->has_byte_size && pdi->is_declaration)
9428         {
9429           xfree (built_actual_name);
9430           return;
9431         }
9432
9433       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9434          static vs. global.  */
9435       add_psymbol_to_list (actual_name, strlen (actual_name),
9436                            built_actual_name != NULL,
9437                            STRUCT_DOMAIN, LOC_TYPEDEF,
9438                            cu->language == language_cplus
9439                            ? &objfile->global_psymbols
9440                            : &objfile->static_psymbols,
9441                            0, cu->language, objfile);
9442
9443       break;
9444     case DW_TAG_enumerator:
9445       add_psymbol_to_list (actual_name, strlen (actual_name),
9446                            built_actual_name != NULL,
9447                            VAR_DOMAIN, LOC_CONST,
9448                            cu->language == language_cplus
9449                            ? &objfile->global_psymbols
9450                            : &objfile->static_psymbols,
9451                            0, cu->language, objfile);
9452       break;
9453     default:
9454       break;
9455     }
9456
9457   xfree (built_actual_name);
9458 }
9459
9460 /* Read a partial die corresponding to a namespace; also, add a symbol
9461    corresponding to that namespace to the symbol table.  NAMESPACE is
9462    the name of the enclosing namespace.  */
9463
9464 static void
9465 add_partial_namespace (struct partial_die_info *pdi,
9466                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9467                        int set_addrmap, struct dwarf2_cu *cu)
9468 {
9469   /* Add a symbol for the namespace.  */
9470
9471   add_partial_symbol (pdi, cu);
9472
9473   /* Now scan partial symbols in that namespace.  */
9474
9475   if (pdi->has_children)
9476     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9477 }
9478
9479 /* Read a partial die corresponding to a Fortran module.  */
9480
9481 static void
9482 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9483                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9484 {
9485   /* Add a symbol for the namespace.  */
9486
9487   add_partial_symbol (pdi, cu);
9488
9489   /* Now scan partial symbols in that module.  */
9490
9491   if (pdi->has_children)
9492     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9493 }
9494
9495 /* Read a partial die corresponding to a subprogram or an inlined
9496    subprogram and create a partial symbol for that subprogram.
9497    When the CU language allows it, this routine also defines a partial
9498    symbol for each nested subprogram that this subprogram contains.
9499    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9500    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9501
9502    PDI may also be a lexical block, in which case we simply search
9503    recursively for subprograms defined inside that lexical block.
9504    Again, this is only performed when the CU language allows this
9505    type of definitions.  */
9506
9507 static void
9508 add_partial_subprogram (struct partial_die_info *pdi,
9509                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9510                         int set_addrmap, struct dwarf2_cu *cu)
9511 {
9512   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9513     {
9514       if (pdi->has_pc_info)
9515         {
9516           if (pdi->lowpc < *lowpc)
9517             *lowpc = pdi->lowpc;
9518           if (pdi->highpc > *highpc)
9519             *highpc = pdi->highpc;
9520           if (set_addrmap)
9521             {
9522               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9523               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9524               CORE_ADDR baseaddr;
9525               CORE_ADDR highpc;
9526               CORE_ADDR lowpc;
9527
9528               baseaddr = ANOFFSET (objfile->section_offsets,
9529                                    SECT_OFF_TEXT (objfile));
9530               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9531                                                   pdi->lowpc + baseaddr);
9532               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9533                                                    pdi->highpc + baseaddr);
9534               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9535                                  cu->per_cu->v.psymtab);
9536             }
9537         }
9538
9539       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9540         {
9541           if (!pdi->is_declaration)
9542             /* Ignore subprogram DIEs that do not have a name, they are
9543                illegal.  Do not emit a complaint at this point, we will
9544                do so when we convert this psymtab into a symtab.  */
9545             if (pdi->name)
9546               add_partial_symbol (pdi, cu);
9547         }
9548     }
9549
9550   if (! pdi->has_children)
9551     return;
9552
9553   if (cu->language == language_ada)
9554     {
9555       pdi = pdi->die_child;
9556       while (pdi != NULL)
9557         {
9558           fixup_partial_die (pdi, cu);
9559           if (pdi->tag == DW_TAG_subprogram
9560               || pdi->tag == DW_TAG_inlined_subroutine
9561               || pdi->tag == DW_TAG_lexical_block)
9562             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9563           pdi = pdi->die_sibling;
9564         }
9565     }
9566 }
9567
9568 /* Read a partial die corresponding to an enumeration type.  */
9569
9570 static void
9571 add_partial_enumeration (struct partial_die_info *enum_pdi,
9572                          struct dwarf2_cu *cu)
9573 {
9574   struct partial_die_info *pdi;
9575
9576   if (enum_pdi->name != NULL)
9577     add_partial_symbol (enum_pdi, cu);
9578
9579   pdi = enum_pdi->die_child;
9580   while (pdi)
9581     {
9582       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9583         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9584       else
9585         add_partial_symbol (pdi, cu);
9586       pdi = pdi->die_sibling;
9587     }
9588 }
9589
9590 /* Return the initial uleb128 in the die at INFO_PTR.  */
9591
9592 static unsigned int
9593 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9594 {
9595   unsigned int bytes_read;
9596
9597   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9598 }
9599
9600 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9601    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9602
9603    Return the corresponding abbrev, or NULL if the number is zero (indicating
9604    an empty DIE).  In either case *BYTES_READ will be set to the length of
9605    the initial number.  */
9606
9607 static struct abbrev_info *
9608 peek_die_abbrev (const die_reader_specs &reader,
9609                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9610 {
9611   dwarf2_cu *cu = reader.cu;
9612   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9613   unsigned int abbrev_number
9614     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9615
9616   if (abbrev_number == 0)
9617     return NULL;
9618
9619   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9620   if (!abbrev)
9621     {
9622       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9623                " at offset %s [in module %s]"),
9624              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9625              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9626     }
9627
9628   return abbrev;
9629 }
9630
9631 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9632    Returns a pointer to the end of a series of DIEs, terminated by an empty
9633    DIE.  Any children of the skipped DIEs will also be skipped.  */
9634
9635 static const gdb_byte *
9636 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9637 {
9638   while (1)
9639     {
9640       unsigned int bytes_read;
9641       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9642
9643       if (abbrev == NULL)
9644         return info_ptr + bytes_read;
9645       else
9646         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9647     }
9648 }
9649
9650 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9651    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9652    abbrev corresponding to that skipped uleb128 should be passed in
9653    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9654    children.  */
9655
9656 static const gdb_byte *
9657 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9658               struct abbrev_info *abbrev)
9659 {
9660   unsigned int bytes_read;
9661   struct attribute attr;
9662   bfd *abfd = reader->abfd;
9663   struct dwarf2_cu *cu = reader->cu;
9664   const gdb_byte *buffer = reader->buffer;
9665   const gdb_byte *buffer_end = reader->buffer_end;
9666   unsigned int form, i;
9667
9668   for (i = 0; i < abbrev->num_attrs; i++)
9669     {
9670       /* The only abbrev we care about is DW_AT_sibling.  */
9671       if (abbrev->attrs[i].name == DW_AT_sibling)
9672         {
9673           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9674           if (attr.form == DW_FORM_ref_addr)
9675             complaint (&symfile_complaints,
9676                        _("ignoring absolute DW_AT_sibling"));
9677           else
9678             {
9679               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9680               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9681
9682               if (sibling_ptr < info_ptr)
9683                 complaint (&symfile_complaints,
9684                            _("DW_AT_sibling points backwards"));
9685               else if (sibling_ptr > reader->buffer_end)
9686                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9687               else
9688                 return sibling_ptr;
9689             }
9690         }
9691
9692       /* If it isn't DW_AT_sibling, skip this attribute.  */
9693       form = abbrev->attrs[i].form;
9694     skip_attribute:
9695       switch (form)
9696         {
9697         case DW_FORM_ref_addr:
9698           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9699              and later it is offset sized.  */
9700           if (cu->header.version == 2)
9701             info_ptr += cu->header.addr_size;
9702           else
9703             info_ptr += cu->header.offset_size;
9704           break;
9705         case DW_FORM_GNU_ref_alt:
9706           info_ptr += cu->header.offset_size;
9707           break;
9708         case DW_FORM_addr:
9709           info_ptr += cu->header.addr_size;
9710           break;
9711         case DW_FORM_data1:
9712         case DW_FORM_ref1:
9713         case DW_FORM_flag:
9714           info_ptr += 1;
9715           break;
9716         case DW_FORM_flag_present:
9717         case DW_FORM_implicit_const:
9718           break;
9719         case DW_FORM_data2:
9720         case DW_FORM_ref2:
9721           info_ptr += 2;
9722           break;
9723         case DW_FORM_data4:
9724         case DW_FORM_ref4:
9725           info_ptr += 4;
9726           break;
9727         case DW_FORM_data8:
9728         case DW_FORM_ref8:
9729         case DW_FORM_ref_sig8:
9730           info_ptr += 8;
9731           break;
9732         case DW_FORM_data16:
9733           info_ptr += 16;
9734           break;
9735         case DW_FORM_string:
9736           read_direct_string (abfd, info_ptr, &bytes_read);
9737           info_ptr += bytes_read;
9738           break;
9739         case DW_FORM_sec_offset:
9740         case DW_FORM_strp:
9741         case DW_FORM_GNU_strp_alt:
9742           info_ptr += cu->header.offset_size;
9743           break;
9744         case DW_FORM_exprloc:
9745         case DW_FORM_block:
9746           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9747           info_ptr += bytes_read;
9748           break;
9749         case DW_FORM_block1:
9750           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9751           break;
9752         case DW_FORM_block2:
9753           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9754           break;
9755         case DW_FORM_block4:
9756           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9757           break;
9758         case DW_FORM_sdata:
9759         case DW_FORM_udata:
9760         case DW_FORM_ref_udata:
9761         case DW_FORM_GNU_addr_index:
9762         case DW_FORM_GNU_str_index:
9763           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9764           break;
9765         case DW_FORM_indirect:
9766           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9767           info_ptr += bytes_read;
9768           /* We need to continue parsing from here, so just go back to
9769              the top.  */
9770           goto skip_attribute;
9771
9772         default:
9773           error (_("Dwarf Error: Cannot handle %s "
9774                    "in DWARF reader [in module %s]"),
9775                  dwarf_form_name (form),
9776                  bfd_get_filename (abfd));
9777         }
9778     }
9779
9780   if (abbrev->has_children)
9781     return skip_children (reader, info_ptr);
9782   else
9783     return info_ptr;
9784 }
9785
9786 /* Locate ORIG_PDI's sibling.
9787    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9788
9789 static const gdb_byte *
9790 locate_pdi_sibling (const struct die_reader_specs *reader,
9791                     struct partial_die_info *orig_pdi,
9792                     const gdb_byte *info_ptr)
9793 {
9794   /* Do we know the sibling already?  */
9795
9796   if (orig_pdi->sibling)
9797     return orig_pdi->sibling;
9798
9799   /* Are there any children to deal with?  */
9800
9801   if (!orig_pdi->has_children)
9802     return info_ptr;
9803
9804   /* Skip the children the long way.  */
9805
9806   return skip_children (reader, info_ptr);
9807 }
9808
9809 /* Expand this partial symbol table into a full symbol table.  SELF is
9810    not NULL.  */
9811
9812 static void
9813 dwarf2_read_symtab (struct partial_symtab *self,
9814                     struct objfile *objfile)
9815 {
9816   struct dwarf2_per_objfile *dwarf2_per_objfile
9817     = get_dwarf2_per_objfile (objfile);
9818
9819   if (self->readin)
9820     {
9821       warning (_("bug: psymtab for %s is already read in."),
9822                self->filename);
9823     }
9824   else
9825     {
9826       if (info_verbose)
9827         {
9828           printf_filtered (_("Reading in symbols for %s..."),
9829                            self->filename);
9830           gdb_flush (gdb_stdout);
9831         }
9832
9833       /* If this psymtab is constructed from a debug-only objfile, the
9834          has_section_at_zero flag will not necessarily be correct.  We
9835          can get the correct value for this flag by looking at the data
9836          associated with the (presumably stripped) associated objfile.  */
9837       if (objfile->separate_debug_objfile_backlink)
9838         {
9839           struct dwarf2_per_objfile *dpo_backlink
9840             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9841
9842           dwarf2_per_objfile->has_section_at_zero
9843             = dpo_backlink->has_section_at_zero;
9844         }
9845
9846       dwarf2_per_objfile->reading_partial_symbols = 0;
9847
9848       psymtab_to_symtab_1 (self);
9849
9850       /* Finish up the debug error message.  */
9851       if (info_verbose)
9852         printf_filtered (_("done.\n"));
9853     }
9854
9855   process_cu_includes (dwarf2_per_objfile);
9856 }
9857 \f
9858 /* Reading in full CUs.  */
9859
9860 /* Add PER_CU to the queue.  */
9861
9862 static void
9863 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9864                  enum language pretend_language)
9865 {
9866   struct dwarf2_queue_item *item;
9867
9868   per_cu->queued = 1;
9869   item = XNEW (struct dwarf2_queue_item);
9870   item->per_cu = per_cu;
9871   item->pretend_language = pretend_language;
9872   item->next = NULL;
9873
9874   if (dwarf2_queue == NULL)
9875     dwarf2_queue = item;
9876   else
9877     dwarf2_queue_tail->next = item;
9878
9879   dwarf2_queue_tail = item;
9880 }
9881
9882 /* If PER_CU is not yet queued, add it to the queue.
9883    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9884    dependency.
9885    The result is non-zero if PER_CU was queued, otherwise the result is zero
9886    meaning either PER_CU is already queued or it is already loaded.
9887
9888    N.B. There is an invariant here that if a CU is queued then it is loaded.
9889    The caller is required to load PER_CU if we return non-zero.  */
9890
9891 static int
9892 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9893                        struct dwarf2_per_cu_data *per_cu,
9894                        enum language pretend_language)
9895 {
9896   /* We may arrive here during partial symbol reading, if we need full
9897      DIEs to process an unusual case (e.g. template arguments).  Do
9898      not queue PER_CU, just tell our caller to load its DIEs.  */
9899   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9900     {
9901       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9902         return 1;
9903       return 0;
9904     }
9905
9906   /* Mark the dependence relation so that we don't flush PER_CU
9907      too early.  */
9908   if (dependent_cu != NULL)
9909     dwarf2_add_dependence (dependent_cu, per_cu);
9910
9911   /* If it's already on the queue, we have nothing to do.  */
9912   if (per_cu->queued)
9913     return 0;
9914
9915   /* If the compilation unit is already loaded, just mark it as
9916      used.  */
9917   if (per_cu->cu != NULL)
9918     {
9919       per_cu->cu->last_used = 0;
9920       return 0;
9921     }
9922
9923   /* Add it to the queue.  */
9924   queue_comp_unit (per_cu, pretend_language);
9925
9926   return 1;
9927 }
9928
9929 /* Process the queue.  */
9930
9931 static void
9932 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9933 {
9934   struct dwarf2_queue_item *item, *next_item;
9935
9936   if (dwarf_read_debug)
9937     {
9938       fprintf_unfiltered (gdb_stdlog,
9939                           "Expanding one or more symtabs of objfile %s ...\n",
9940                           objfile_name (dwarf2_per_objfile->objfile));
9941     }
9942
9943   /* The queue starts out with one item, but following a DIE reference
9944      may load a new CU, adding it to the end of the queue.  */
9945   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9946     {
9947       if ((dwarf2_per_objfile->using_index
9948            ? !item->per_cu->v.quick->compunit_symtab
9949            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9950           /* Skip dummy CUs.  */
9951           && item->per_cu->cu != NULL)
9952         {
9953           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9954           unsigned int debug_print_threshold;
9955           char buf[100];
9956
9957           if (per_cu->is_debug_types)
9958             {
9959               struct signatured_type *sig_type =
9960                 (struct signatured_type *) per_cu;
9961
9962               sprintf (buf, "TU %s at offset %s",
9963                        hex_string (sig_type->signature),
9964                        sect_offset_str (per_cu->sect_off));
9965               /* There can be 100s of TUs.
9966                  Only print them in verbose mode.  */
9967               debug_print_threshold = 2;
9968             }
9969           else
9970             {
9971               sprintf (buf, "CU at offset %s",
9972                        sect_offset_str (per_cu->sect_off));
9973               debug_print_threshold = 1;
9974             }
9975
9976           if (dwarf_read_debug >= debug_print_threshold)
9977             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9978
9979           if (per_cu->is_debug_types)
9980             process_full_type_unit (per_cu, item->pretend_language);
9981           else
9982             process_full_comp_unit (per_cu, item->pretend_language);
9983
9984           if (dwarf_read_debug >= debug_print_threshold)
9985             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9986         }
9987
9988       item->per_cu->queued = 0;
9989       next_item = item->next;
9990       xfree (item);
9991     }
9992
9993   dwarf2_queue_tail = NULL;
9994
9995   if (dwarf_read_debug)
9996     {
9997       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9998                           objfile_name (dwarf2_per_objfile->objfile));
9999     }
10000 }
10001
10002 /* Read in full symbols for PST, and anything it depends on.  */
10003
10004 static void
10005 psymtab_to_symtab_1 (struct partial_symtab *pst)
10006 {
10007   struct dwarf2_per_cu_data *per_cu;
10008   int i;
10009
10010   if (pst->readin)
10011     return;
10012
10013   for (i = 0; i < pst->number_of_dependencies; i++)
10014     if (!pst->dependencies[i]->readin
10015         && pst->dependencies[i]->user == NULL)
10016       {
10017         /* Inform about additional files that need to be read in.  */
10018         if (info_verbose)
10019           {
10020             /* FIXME: i18n: Need to make this a single string.  */
10021             fputs_filtered (" ", gdb_stdout);
10022             wrap_here ("");
10023             fputs_filtered ("and ", gdb_stdout);
10024             wrap_here ("");
10025             printf_filtered ("%s...", pst->dependencies[i]->filename);
10026             wrap_here ("");     /* Flush output.  */
10027             gdb_flush (gdb_stdout);
10028           }
10029         psymtab_to_symtab_1 (pst->dependencies[i]);
10030       }
10031
10032   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10033
10034   if (per_cu == NULL)
10035     {
10036       /* It's an include file, no symbols to read for it.
10037          Everything is in the parent symtab.  */
10038       pst->readin = 1;
10039       return;
10040     }
10041
10042   dw2_do_instantiate_symtab (per_cu);
10043 }
10044
10045 /* Trivial hash function for die_info: the hash value of a DIE
10046    is its offset in .debug_info for this objfile.  */
10047
10048 static hashval_t
10049 die_hash (const void *item)
10050 {
10051   const struct die_info *die = (const struct die_info *) item;
10052
10053   return to_underlying (die->sect_off);
10054 }
10055
10056 /* Trivial comparison function for die_info structures: two DIEs
10057    are equal if they have the same offset.  */
10058
10059 static int
10060 die_eq (const void *item_lhs, const void *item_rhs)
10061 {
10062   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10063   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10064
10065   return die_lhs->sect_off == die_rhs->sect_off;
10066 }
10067
10068 /* die_reader_func for load_full_comp_unit.
10069    This is identical to read_signatured_type_reader,
10070    but is kept separate for now.  */
10071
10072 static void
10073 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10074                             const gdb_byte *info_ptr,
10075                             struct die_info *comp_unit_die,
10076                             int has_children,
10077                             void *data)
10078 {
10079   struct dwarf2_cu *cu = reader->cu;
10080   enum language *language_ptr = (enum language *) data;
10081
10082   gdb_assert (cu->die_hash == NULL);
10083   cu->die_hash =
10084     htab_create_alloc_ex (cu->header.length / 12,
10085                           die_hash,
10086                           die_eq,
10087                           NULL,
10088                           &cu->comp_unit_obstack,
10089                           hashtab_obstack_allocate,
10090                           dummy_obstack_deallocate);
10091
10092   if (has_children)
10093     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10094                                                   &info_ptr, comp_unit_die);
10095   cu->dies = comp_unit_die;
10096   /* comp_unit_die is not stored in die_hash, no need.  */
10097
10098   /* We try not to read any attributes in this function, because not
10099      all CUs needed for references have been loaded yet, and symbol
10100      table processing isn't initialized.  But we have to set the CU language,
10101      or we won't be able to build types correctly.
10102      Similarly, if we do not read the producer, we can not apply
10103      producer-specific interpretation.  */
10104   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10105 }
10106
10107 /* Load the DIEs associated with PER_CU into memory.  */
10108
10109 static void
10110 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10111                      enum language pretend_language)
10112 {
10113   gdb_assert (! this_cu->is_debug_types);
10114
10115   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10116                            load_full_comp_unit_reader, &pretend_language);
10117 }
10118
10119 /* Add a DIE to the delayed physname list.  */
10120
10121 static void
10122 add_to_method_list (struct type *type, int fnfield_index, int index,
10123                     const char *name, struct die_info *die,
10124                     struct dwarf2_cu *cu)
10125 {
10126   struct delayed_method_info mi;
10127   mi.type = type;
10128   mi.fnfield_index = fnfield_index;
10129   mi.index = index;
10130   mi.name = name;
10131   mi.die = die;
10132   cu->method_list.push_back (mi);
10133 }
10134
10135 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10136    "const" / "volatile".  If so, decrements LEN by the length of the
10137    modifier and return true.  Otherwise return false.  */
10138
10139 template<size_t N>
10140 static bool
10141 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10142 {
10143   size_t mod_len = sizeof (mod) - 1;
10144   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10145     {
10146       len -= mod_len;
10147       return true;
10148     }
10149   return false;
10150 }
10151
10152 /* Compute the physnames of any methods on the CU's method list.
10153
10154    The computation of method physnames is delayed in order to avoid the
10155    (bad) condition that one of the method's formal parameters is of an as yet
10156    incomplete type.  */
10157
10158 static void
10159 compute_delayed_physnames (struct dwarf2_cu *cu)
10160 {
10161   /* Only C++ delays computing physnames.  */
10162   if (cu->method_list.empty ())
10163     return;
10164   gdb_assert (cu->language == language_cplus);
10165
10166   for (struct delayed_method_info &mi : cu->method_list)
10167     {
10168       const char *physname;
10169       struct fn_fieldlist *fn_flp
10170         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10171       physname = dwarf2_physname (mi.name, mi.die, cu);
10172       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10173         = physname ? physname : "";
10174
10175       /* Since there's no tag to indicate whether a method is a
10176          const/volatile overload, extract that information out of the
10177          demangled name.  */
10178       if (physname != NULL)
10179         {
10180           size_t len = strlen (physname);
10181
10182           while (1)
10183             {
10184               if (physname[len] == ')') /* shortcut */
10185                 break;
10186               else if (check_modifier (physname, len, " const"))
10187                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10188               else if (check_modifier (physname, len, " volatile"))
10189                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10190               else
10191                 break;
10192             }
10193         }
10194     }
10195
10196   /* The list is no longer needed.  */
10197   cu->method_list.clear ();
10198 }
10199
10200 /* Go objects should be embedded in a DW_TAG_module DIE,
10201    and it's not clear if/how imported objects will appear.
10202    To keep Go support simple until that's worked out,
10203    go back through what we've read and create something usable.
10204    We could do this while processing each DIE, and feels kinda cleaner,
10205    but that way is more invasive.
10206    This is to, for example, allow the user to type "p var" or "b main"
10207    without having to specify the package name, and allow lookups
10208    of module.object to work in contexts that use the expression
10209    parser.  */
10210
10211 static void
10212 fixup_go_packaging (struct dwarf2_cu *cu)
10213 {
10214   char *package_name = NULL;
10215   struct pending *list;
10216   int i;
10217
10218   for (list = global_symbols; list != NULL; list = list->next)
10219     {
10220       for (i = 0; i < list->nsyms; ++i)
10221         {
10222           struct symbol *sym = list->symbol[i];
10223
10224           if (SYMBOL_LANGUAGE (sym) == language_go
10225               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10226             {
10227               char *this_package_name = go_symbol_package_name (sym);
10228
10229               if (this_package_name == NULL)
10230                 continue;
10231               if (package_name == NULL)
10232                 package_name = this_package_name;
10233               else
10234                 {
10235                   struct objfile *objfile
10236                     = cu->per_cu->dwarf2_per_objfile->objfile;
10237                   if (strcmp (package_name, this_package_name) != 0)
10238                     complaint (&symfile_complaints,
10239                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10240                                (symbol_symtab (sym) != NULL
10241                                 ? symtab_to_filename_for_display
10242                                     (symbol_symtab (sym))
10243                                 : objfile_name (objfile)),
10244                                this_package_name, package_name);
10245                   xfree (this_package_name);
10246                 }
10247             }
10248         }
10249     }
10250
10251   if (package_name != NULL)
10252     {
10253       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10254       const char *saved_package_name
10255         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10256                                         package_name,
10257                                         strlen (package_name));
10258       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10259                                      saved_package_name);
10260       struct symbol *sym;
10261
10262       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10263
10264       sym = allocate_symbol (objfile);
10265       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10266       SYMBOL_SET_NAMES (sym, saved_package_name,
10267                         strlen (saved_package_name), 0, objfile);
10268       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10269          e.g., "main" finds the "main" module and not C's main().  */
10270       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10271       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10272       SYMBOL_TYPE (sym) = type;
10273
10274       add_symbol_to_list (sym, &global_symbols);
10275
10276       xfree (package_name);
10277     }
10278 }
10279
10280 /* Return the symtab for PER_CU.  This works properly regardless of
10281    whether we're using the index or psymtabs.  */
10282
10283 static struct compunit_symtab *
10284 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10285 {
10286   return (per_cu->dwarf2_per_objfile->using_index
10287           ? per_cu->v.quick->compunit_symtab
10288           : per_cu->v.psymtab->compunit_symtab);
10289 }
10290
10291 /* A helper function for computing the list of all symbol tables
10292    included by PER_CU.  */
10293
10294 static void
10295 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10296                                 htab_t all_children, htab_t all_type_symtabs,
10297                                 struct dwarf2_per_cu_data *per_cu,
10298                                 struct compunit_symtab *immediate_parent)
10299 {
10300   void **slot;
10301   int ix;
10302   struct compunit_symtab *cust;
10303   struct dwarf2_per_cu_data *iter;
10304
10305   slot = htab_find_slot (all_children, per_cu, INSERT);
10306   if (*slot != NULL)
10307     {
10308       /* This inclusion and its children have been processed.  */
10309       return;
10310     }
10311
10312   *slot = per_cu;
10313   /* Only add a CU if it has a symbol table.  */
10314   cust = get_compunit_symtab (per_cu);
10315   if (cust != NULL)
10316     {
10317       /* If this is a type unit only add its symbol table if we haven't
10318          seen it yet (type unit per_cu's can share symtabs).  */
10319       if (per_cu->is_debug_types)
10320         {
10321           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10322           if (*slot == NULL)
10323             {
10324               *slot = cust;
10325               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10326               if (cust->user == NULL)
10327                 cust->user = immediate_parent;
10328             }
10329         }
10330       else
10331         {
10332           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10333           if (cust->user == NULL)
10334             cust->user = immediate_parent;
10335         }
10336     }
10337
10338   for (ix = 0;
10339        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10340        ++ix)
10341     {
10342       recursively_compute_inclusions (result, all_children,
10343                                       all_type_symtabs, iter, cust);
10344     }
10345 }
10346
10347 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10348    PER_CU.  */
10349
10350 static void
10351 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10352 {
10353   gdb_assert (! per_cu->is_debug_types);
10354
10355   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10356     {
10357       int ix, len;
10358       struct dwarf2_per_cu_data *per_cu_iter;
10359       struct compunit_symtab *compunit_symtab_iter;
10360       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10361       htab_t all_children, all_type_symtabs;
10362       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10363
10364       /* If we don't have a symtab, we can just skip this case.  */
10365       if (cust == NULL)
10366         return;
10367
10368       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10369                                         NULL, xcalloc, xfree);
10370       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10371                                             NULL, xcalloc, xfree);
10372
10373       for (ix = 0;
10374            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10375                         ix, per_cu_iter);
10376            ++ix)
10377         {
10378           recursively_compute_inclusions (&result_symtabs, all_children,
10379                                           all_type_symtabs, per_cu_iter,
10380                                           cust);
10381         }
10382
10383       /* Now we have a transitive closure of all the included symtabs.  */
10384       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10385       cust->includes
10386         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10387                      struct compunit_symtab *, len + 1);
10388       for (ix = 0;
10389            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10390                         compunit_symtab_iter);
10391            ++ix)
10392         cust->includes[ix] = compunit_symtab_iter;
10393       cust->includes[len] = NULL;
10394
10395       VEC_free (compunit_symtab_ptr, result_symtabs);
10396       htab_delete (all_children);
10397       htab_delete (all_type_symtabs);
10398     }
10399 }
10400
10401 /* Compute the 'includes' field for the symtabs of all the CUs we just
10402    read.  */
10403
10404 static void
10405 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10406 {
10407   int ix;
10408   struct dwarf2_per_cu_data *iter;
10409
10410   for (ix = 0;
10411        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10412                     ix, iter);
10413        ++ix)
10414     {
10415       if (! iter->is_debug_types)
10416         compute_compunit_symtab_includes (iter);
10417     }
10418
10419   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10420 }
10421
10422 /* Generate full symbol information for PER_CU, whose DIEs have
10423    already been loaded into memory.  */
10424
10425 static void
10426 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10427                         enum language pretend_language)
10428 {
10429   struct dwarf2_cu *cu = per_cu->cu;
10430   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10431   struct objfile *objfile = dwarf2_per_objfile->objfile;
10432   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10433   CORE_ADDR lowpc, highpc;
10434   struct compunit_symtab *cust;
10435   CORE_ADDR baseaddr;
10436   struct block *static_block;
10437   CORE_ADDR addr;
10438
10439   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10440
10441   buildsym_init ();
10442   scoped_free_pendings free_pending;
10443
10444   /* Clear the list here in case something was left over.  */
10445   cu->method_list.clear ();
10446
10447   cu->list_in_scope = &file_symbols;
10448
10449   cu->language = pretend_language;
10450   cu->language_defn = language_def (cu->language);
10451
10452   /* Do line number decoding in read_file_scope () */
10453   process_die (cu->dies, cu);
10454
10455   /* For now fudge the Go package.  */
10456   if (cu->language == language_go)
10457     fixup_go_packaging (cu);
10458
10459   /* Now that we have processed all the DIEs in the CU, all the types 
10460      should be complete, and it should now be safe to compute all of the
10461      physnames.  */
10462   compute_delayed_physnames (cu);
10463
10464   /* Some compilers don't define a DW_AT_high_pc attribute for the
10465      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10466      it, by scanning the DIE's below the compilation unit.  */
10467   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10468
10469   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10470   static_block = end_symtab_get_static_block (addr, 0, 1);
10471
10472   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10473      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10474      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10475      addrmap to help ensure it has an accurate map of pc values belonging to
10476      this comp unit.  */
10477   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10478
10479   cust = end_symtab_from_static_block (static_block,
10480                                        SECT_OFF_TEXT (objfile), 0);
10481
10482   if (cust != NULL)
10483     {
10484       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10485
10486       /* Set symtab language to language from DW_AT_language.  If the
10487          compilation is from a C file generated by language preprocessors, do
10488          not set the language if it was already deduced by start_subfile.  */
10489       if (!(cu->language == language_c
10490             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10491         COMPUNIT_FILETABS (cust)->language = cu->language;
10492
10493       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10494          produce DW_AT_location with location lists but it can be possibly
10495          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10496          there were bugs in prologue debug info, fixed later in GCC-4.5
10497          by "unwind info for epilogues" patch (which is not directly related).
10498
10499          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10500          needed, it would be wrong due to missing DW_AT_producer there.
10501
10502          Still one can confuse GDB by using non-standard GCC compilation
10503          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10504          */ 
10505       if (cu->has_loclist && gcc_4_minor >= 5)
10506         cust->locations_valid = 1;
10507
10508       if (gcc_4_minor >= 5)
10509         cust->epilogue_unwind_valid = 1;
10510
10511       cust->call_site_htab = cu->call_site_htab;
10512     }
10513
10514   if (dwarf2_per_objfile->using_index)
10515     per_cu->v.quick->compunit_symtab = cust;
10516   else
10517     {
10518       struct partial_symtab *pst = per_cu->v.psymtab;
10519       pst->compunit_symtab = cust;
10520       pst->readin = 1;
10521     }
10522
10523   /* Push it for inclusion processing later.  */
10524   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10525 }
10526
10527 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10528    already been loaded into memory.  */
10529
10530 static void
10531 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10532                         enum language pretend_language)
10533 {
10534   struct dwarf2_cu *cu = per_cu->cu;
10535   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10536   struct objfile *objfile = dwarf2_per_objfile->objfile;
10537   struct compunit_symtab *cust;
10538   struct signatured_type *sig_type;
10539
10540   gdb_assert (per_cu->is_debug_types);
10541   sig_type = (struct signatured_type *) per_cu;
10542
10543   buildsym_init ();
10544   scoped_free_pendings free_pending;
10545
10546   /* Clear the list here in case something was left over.  */
10547   cu->method_list.clear ();
10548
10549   cu->list_in_scope = &file_symbols;
10550
10551   cu->language = pretend_language;
10552   cu->language_defn = language_def (cu->language);
10553
10554   /* The symbol tables are set up in read_type_unit_scope.  */
10555   process_die (cu->dies, cu);
10556
10557   /* For now fudge the Go package.  */
10558   if (cu->language == language_go)
10559     fixup_go_packaging (cu);
10560
10561   /* Now that we have processed all the DIEs in the CU, all the types 
10562      should be complete, and it should now be safe to compute all of the
10563      physnames.  */
10564   compute_delayed_physnames (cu);
10565
10566   /* TUs share symbol tables.
10567      If this is the first TU to use this symtab, complete the construction
10568      of it with end_expandable_symtab.  Otherwise, complete the addition of
10569      this TU's symbols to the existing symtab.  */
10570   if (sig_type->type_unit_group->compunit_symtab == NULL)
10571     {
10572       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10573       sig_type->type_unit_group->compunit_symtab = cust;
10574
10575       if (cust != NULL)
10576         {
10577           /* Set symtab language to language from DW_AT_language.  If the
10578              compilation is from a C file generated by language preprocessors,
10579              do not set the language if it was already deduced by
10580              start_subfile.  */
10581           if (!(cu->language == language_c
10582                 && COMPUNIT_FILETABS (cust)->language != language_c))
10583             COMPUNIT_FILETABS (cust)->language = cu->language;
10584         }
10585     }
10586   else
10587     {
10588       augment_type_symtab ();
10589       cust = sig_type->type_unit_group->compunit_symtab;
10590     }
10591
10592   if (dwarf2_per_objfile->using_index)
10593     per_cu->v.quick->compunit_symtab = cust;
10594   else
10595     {
10596       struct partial_symtab *pst = per_cu->v.psymtab;
10597       pst->compunit_symtab = cust;
10598       pst->readin = 1;
10599     }
10600 }
10601
10602 /* Process an imported unit DIE.  */
10603
10604 static void
10605 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10606 {
10607   struct attribute *attr;
10608
10609   /* For now we don't handle imported units in type units.  */
10610   if (cu->per_cu->is_debug_types)
10611     {
10612       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10613                " supported in type units [in module %s]"),
10614              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10615     }
10616
10617   attr = dwarf2_attr (die, DW_AT_import, cu);
10618   if (attr != NULL)
10619     {
10620       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10621       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10622       dwarf2_per_cu_data *per_cu
10623         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10624                                             cu->per_cu->dwarf2_per_objfile);
10625
10626       /* If necessary, add it to the queue and load its DIEs.  */
10627       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10628         load_full_comp_unit (per_cu, cu->language);
10629
10630       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10631                      per_cu);
10632     }
10633 }
10634
10635 /* RAII object that represents a process_die scope: i.e.,
10636    starts/finishes processing a DIE.  */
10637 class process_die_scope
10638 {
10639 public:
10640   process_die_scope (die_info *die, dwarf2_cu *cu)
10641     : m_die (die), m_cu (cu)
10642   {
10643     /* We should only be processing DIEs not already in process.  */
10644     gdb_assert (!m_die->in_process);
10645     m_die->in_process = true;
10646   }
10647
10648   ~process_die_scope ()
10649   {
10650     m_die->in_process = false;
10651
10652     /* If we're done processing the DIE for the CU that owns the line
10653        header, we don't need the line header anymore.  */
10654     if (m_cu->line_header_die_owner == m_die)
10655       {
10656         delete m_cu->line_header;
10657         m_cu->line_header = NULL;
10658         m_cu->line_header_die_owner = NULL;
10659       }
10660   }
10661
10662 private:
10663   die_info *m_die;
10664   dwarf2_cu *m_cu;
10665 };
10666
10667 /* Process a die and its children.  */
10668
10669 static void
10670 process_die (struct die_info *die, struct dwarf2_cu *cu)
10671 {
10672   process_die_scope scope (die, cu);
10673
10674   switch (die->tag)
10675     {
10676     case DW_TAG_padding:
10677       break;
10678     case DW_TAG_compile_unit:
10679     case DW_TAG_partial_unit:
10680       read_file_scope (die, cu);
10681       break;
10682     case DW_TAG_type_unit:
10683       read_type_unit_scope (die, cu);
10684       break;
10685     case DW_TAG_subprogram:
10686     case DW_TAG_inlined_subroutine:
10687       read_func_scope (die, cu);
10688       break;
10689     case DW_TAG_lexical_block:
10690     case DW_TAG_try_block:
10691     case DW_TAG_catch_block:
10692       read_lexical_block_scope (die, cu);
10693       break;
10694     case DW_TAG_call_site:
10695     case DW_TAG_GNU_call_site:
10696       read_call_site_scope (die, cu);
10697       break;
10698     case DW_TAG_class_type:
10699     case DW_TAG_interface_type:
10700     case DW_TAG_structure_type:
10701     case DW_TAG_union_type:
10702       process_structure_scope (die, cu);
10703       break;
10704     case DW_TAG_enumeration_type:
10705       process_enumeration_scope (die, cu);
10706       break;
10707
10708     /* These dies have a type, but processing them does not create
10709        a symbol or recurse to process the children.  Therefore we can
10710        read them on-demand through read_type_die.  */
10711     case DW_TAG_subroutine_type:
10712     case DW_TAG_set_type:
10713     case DW_TAG_array_type:
10714     case DW_TAG_pointer_type:
10715     case DW_TAG_ptr_to_member_type:
10716     case DW_TAG_reference_type:
10717     case DW_TAG_rvalue_reference_type:
10718     case DW_TAG_string_type:
10719       break;
10720
10721     case DW_TAG_base_type:
10722     case DW_TAG_subrange_type:
10723     case DW_TAG_typedef:
10724       /* Add a typedef symbol for the type definition, if it has a
10725          DW_AT_name.  */
10726       new_symbol (die, read_type_die (die, cu), cu);
10727       break;
10728     case DW_TAG_common_block:
10729       read_common_block (die, cu);
10730       break;
10731     case DW_TAG_common_inclusion:
10732       break;
10733     case DW_TAG_namespace:
10734       cu->processing_has_namespace_info = 1;
10735       read_namespace (die, cu);
10736       break;
10737     case DW_TAG_module:
10738       cu->processing_has_namespace_info = 1;
10739       read_module (die, cu);
10740       break;
10741     case DW_TAG_imported_declaration:
10742       cu->processing_has_namespace_info = 1;
10743       if (read_namespace_alias (die, cu))
10744         break;
10745       /* The declaration is not a global namespace alias: fall through.  */
10746     case DW_TAG_imported_module:
10747       cu->processing_has_namespace_info = 1;
10748       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10749                                  || cu->language != language_fortran))
10750         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10751                    dwarf_tag_name (die->tag));
10752       read_import_statement (die, cu);
10753       break;
10754
10755     case DW_TAG_imported_unit:
10756       process_imported_unit_die (die, cu);
10757       break;
10758
10759     case DW_TAG_variable:
10760       read_variable (die, cu);
10761       break;
10762
10763     default:
10764       new_symbol (die, NULL, cu);
10765       break;
10766     }
10767 }
10768 \f
10769 /* DWARF name computation.  */
10770
10771 /* A helper function for dwarf2_compute_name which determines whether DIE
10772    needs to have the name of the scope prepended to the name listed in the
10773    die.  */
10774
10775 static int
10776 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10777 {
10778   struct attribute *attr;
10779
10780   switch (die->tag)
10781     {
10782     case DW_TAG_namespace:
10783     case DW_TAG_typedef:
10784     case DW_TAG_class_type:
10785     case DW_TAG_interface_type:
10786     case DW_TAG_structure_type:
10787     case DW_TAG_union_type:
10788     case DW_TAG_enumeration_type:
10789     case DW_TAG_enumerator:
10790     case DW_TAG_subprogram:
10791     case DW_TAG_inlined_subroutine:
10792     case DW_TAG_member:
10793     case DW_TAG_imported_declaration:
10794       return 1;
10795
10796     case DW_TAG_variable:
10797     case DW_TAG_constant:
10798       /* We only need to prefix "globally" visible variables.  These include
10799          any variable marked with DW_AT_external or any variable that
10800          lives in a namespace.  [Variables in anonymous namespaces
10801          require prefixing, but they are not DW_AT_external.]  */
10802
10803       if (dwarf2_attr (die, DW_AT_specification, cu))
10804         {
10805           struct dwarf2_cu *spec_cu = cu;
10806
10807           return die_needs_namespace (die_specification (die, &spec_cu),
10808                                       spec_cu);
10809         }
10810
10811       attr = dwarf2_attr (die, DW_AT_external, cu);
10812       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10813           && die->parent->tag != DW_TAG_module)
10814         return 0;
10815       /* A variable in a lexical block of some kind does not need a
10816          namespace, even though in C++ such variables may be external
10817          and have a mangled name.  */
10818       if (die->parent->tag ==  DW_TAG_lexical_block
10819           || die->parent->tag ==  DW_TAG_try_block
10820           || die->parent->tag ==  DW_TAG_catch_block
10821           || die->parent->tag == DW_TAG_subprogram)
10822         return 0;
10823       return 1;
10824
10825     default:
10826       return 0;
10827     }
10828 }
10829
10830 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10831    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10832    defined for the given DIE.  */
10833
10834 static struct attribute *
10835 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10836 {
10837   struct attribute *attr;
10838
10839   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10840   if (attr == NULL)
10841     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10842
10843   return attr;
10844 }
10845
10846 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10847    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10848    defined for the given DIE.  */
10849
10850 static const char *
10851 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10852 {
10853   const char *linkage_name;
10854
10855   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10856   if (linkage_name == NULL)
10857     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10858
10859   return linkage_name;
10860 }
10861
10862 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10863    compute the physname for the object, which include a method's:
10864    - formal parameters (C++),
10865    - receiver type (Go),
10866
10867    The term "physname" is a bit confusing.
10868    For C++, for example, it is the demangled name.
10869    For Go, for example, it's the mangled name.
10870
10871    For Ada, return the DIE's linkage name rather than the fully qualified
10872    name.  PHYSNAME is ignored..
10873
10874    The result is allocated on the objfile_obstack and canonicalized.  */
10875
10876 static const char *
10877 dwarf2_compute_name (const char *name,
10878                      struct die_info *die, struct dwarf2_cu *cu,
10879                      int physname)
10880 {
10881   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10882
10883   if (name == NULL)
10884     name = dwarf2_name (die, cu);
10885
10886   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10887      but otherwise compute it by typename_concat inside GDB.
10888      FIXME: Actually this is not really true, or at least not always true.
10889      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10890      Fortran names because there is no mangling standard.  So new_symbol
10891      will set the demangled name to the result of dwarf2_full_name, and it is
10892      the demangled name that GDB uses if it exists.  */
10893   if (cu->language == language_ada
10894       || (cu->language == language_fortran && physname))
10895     {
10896       /* For Ada unit, we prefer the linkage name over the name, as
10897          the former contains the exported name, which the user expects
10898          to be able to reference.  Ideally, we want the user to be able
10899          to reference this entity using either natural or linkage name,
10900          but we haven't started looking at this enhancement yet.  */
10901       const char *linkage_name = dw2_linkage_name (die, cu);
10902
10903       if (linkage_name != NULL)
10904         return linkage_name;
10905     }
10906
10907   /* These are the only languages we know how to qualify names in.  */
10908   if (name != NULL
10909       && (cu->language == language_cplus
10910           || cu->language == language_fortran || cu->language == language_d
10911           || cu->language == language_rust))
10912     {
10913       if (die_needs_namespace (die, cu))
10914         {
10915           const char *prefix;
10916           const char *canonical_name = NULL;
10917
10918           string_file buf;
10919
10920           prefix = determine_prefix (die, cu);
10921           if (*prefix != '\0')
10922             {
10923               char *prefixed_name = typename_concat (NULL, prefix, name,
10924                                                      physname, cu);
10925
10926               buf.puts (prefixed_name);
10927               xfree (prefixed_name);
10928             }
10929           else
10930             buf.puts (name);
10931
10932           /* Template parameters may be specified in the DIE's DW_AT_name, or
10933              as children with DW_TAG_template_type_param or
10934              DW_TAG_value_type_param.  If the latter, add them to the name
10935              here.  If the name already has template parameters, then
10936              skip this step; some versions of GCC emit both, and
10937              it is more efficient to use the pre-computed name.
10938
10939              Something to keep in mind about this process: it is very
10940              unlikely, or in some cases downright impossible, to produce
10941              something that will match the mangled name of a function.
10942              If the definition of the function has the same debug info,
10943              we should be able to match up with it anyway.  But fallbacks
10944              using the minimal symbol, for instance to find a method
10945              implemented in a stripped copy of libstdc++, will not work.
10946              If we do not have debug info for the definition, we will have to
10947              match them up some other way.
10948
10949              When we do name matching there is a related problem with function
10950              templates; two instantiated function templates are allowed to
10951              differ only by their return types, which we do not add here.  */
10952
10953           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10954             {
10955               struct attribute *attr;
10956               struct die_info *child;
10957               int first = 1;
10958
10959               die->building_fullname = 1;
10960
10961               for (child = die->child; child != NULL; child = child->sibling)
10962                 {
10963                   struct type *type;
10964                   LONGEST value;
10965                   const gdb_byte *bytes;
10966                   struct dwarf2_locexpr_baton *baton;
10967                   struct value *v;
10968
10969                   if (child->tag != DW_TAG_template_type_param
10970                       && child->tag != DW_TAG_template_value_param)
10971                     continue;
10972
10973                   if (first)
10974                     {
10975                       buf.puts ("<");
10976                       first = 0;
10977                     }
10978                   else
10979                     buf.puts (", ");
10980
10981                   attr = dwarf2_attr (child, DW_AT_type, cu);
10982                   if (attr == NULL)
10983                     {
10984                       complaint (&symfile_complaints,
10985                                  _("template parameter missing DW_AT_type"));
10986                       buf.puts ("UNKNOWN_TYPE");
10987                       continue;
10988                     }
10989                   type = die_type (child, cu);
10990
10991                   if (child->tag == DW_TAG_template_type_param)
10992                     {
10993                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10994                       continue;
10995                     }
10996
10997                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10998                   if (attr == NULL)
10999                     {
11000                       complaint (&symfile_complaints,
11001                                  _("template parameter missing "
11002                                    "DW_AT_const_value"));
11003                       buf.puts ("UNKNOWN_VALUE");
11004                       continue;
11005                     }
11006
11007                   dwarf2_const_value_attr (attr, type, name,
11008                                            &cu->comp_unit_obstack, cu,
11009                                            &value, &bytes, &baton);
11010
11011                   if (TYPE_NOSIGN (type))
11012                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11013                        changed, this can use value_print instead.  */
11014                     c_printchar (value, type, &buf);
11015                   else
11016                     {
11017                       struct value_print_options opts;
11018
11019                       if (baton != NULL)
11020                         v = dwarf2_evaluate_loc_desc (type, NULL,
11021                                                       baton->data,
11022                                                       baton->size,
11023                                                       baton->per_cu);
11024                       else if (bytes != NULL)
11025                         {
11026                           v = allocate_value (type);
11027                           memcpy (value_contents_writeable (v), bytes,
11028                                   TYPE_LENGTH (type));
11029                         }
11030                       else
11031                         v = value_from_longest (type, value);
11032
11033                       /* Specify decimal so that we do not depend on
11034                          the radix.  */
11035                       get_formatted_print_options (&opts, 'd');
11036                       opts.raw = 1;
11037                       value_print (v, &buf, &opts);
11038                       release_value (v);
11039                       value_free (v);
11040                     }
11041                 }
11042
11043               die->building_fullname = 0;
11044
11045               if (!first)
11046                 {
11047                   /* Close the argument list, with a space if necessary
11048                      (nested templates).  */
11049                   if (!buf.empty () && buf.string ().back () == '>')
11050                     buf.puts (" >");
11051                   else
11052                     buf.puts (">");
11053                 }
11054             }
11055
11056           /* For C++ methods, append formal parameter type
11057              information, if PHYSNAME.  */
11058
11059           if (physname && die->tag == DW_TAG_subprogram
11060               && cu->language == language_cplus)
11061             {
11062               struct type *type = read_type_die (die, cu);
11063
11064               c_type_print_args (type, &buf, 1, cu->language,
11065                                  &type_print_raw_options);
11066
11067               if (cu->language == language_cplus)
11068                 {
11069                   /* Assume that an artificial first parameter is
11070                      "this", but do not crash if it is not.  RealView
11071                      marks unnamed (and thus unused) parameters as
11072                      artificial; there is no way to differentiate
11073                      the two cases.  */
11074                   if (TYPE_NFIELDS (type) > 0
11075                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11076                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11077                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11078                                                                         0))))
11079                     buf.puts (" const");
11080                 }
11081             }
11082
11083           const std::string &intermediate_name = buf.string ();
11084
11085           if (cu->language == language_cplus)
11086             canonical_name
11087               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11088                                           &objfile->per_bfd->storage_obstack);
11089
11090           /* If we only computed INTERMEDIATE_NAME, or if
11091              INTERMEDIATE_NAME is already canonical, then we need to
11092              copy it to the appropriate obstack.  */
11093           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11094             name = ((const char *)
11095                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11096                                    intermediate_name.c_str (),
11097                                    intermediate_name.length ()));
11098           else
11099             name = canonical_name;
11100         }
11101     }
11102
11103   return name;
11104 }
11105
11106 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11107    If scope qualifiers are appropriate they will be added.  The result
11108    will be allocated on the storage_obstack, or NULL if the DIE does
11109    not have a name.  NAME may either be from a previous call to
11110    dwarf2_name or NULL.
11111
11112    The output string will be canonicalized (if C++).  */
11113
11114 static const char *
11115 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11116 {
11117   return dwarf2_compute_name (name, die, cu, 0);
11118 }
11119
11120 /* Construct a physname for the given DIE in CU.  NAME may either be
11121    from a previous call to dwarf2_name or NULL.  The result will be
11122    allocated on the objfile_objstack or NULL if the DIE does not have a
11123    name.
11124
11125    The output string will be canonicalized (if C++).  */
11126
11127 static const char *
11128 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11129 {
11130   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11131   const char *retval, *mangled = NULL, *canon = NULL;
11132   int need_copy = 1;
11133
11134   /* In this case dwarf2_compute_name is just a shortcut not building anything
11135      on its own.  */
11136   if (!die_needs_namespace (die, cu))
11137     return dwarf2_compute_name (name, die, cu, 1);
11138
11139   mangled = dw2_linkage_name (die, cu);
11140
11141   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11142      See https://github.com/rust-lang/rust/issues/32925.  */
11143   if (cu->language == language_rust && mangled != NULL
11144       && strchr (mangled, '{') != NULL)
11145     mangled = NULL;
11146
11147   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11148      has computed.  */
11149   gdb::unique_xmalloc_ptr<char> demangled;
11150   if (mangled != NULL)
11151     {
11152
11153       if (cu->language == language_go)
11154         {
11155           /* This is a lie, but we already lie to the caller new_symbol.
11156              new_symbol assumes we return the mangled name.
11157              This just undoes that lie until things are cleaned up.  */
11158         }
11159       else
11160         {
11161           /* Use DMGL_RET_DROP for C++ template functions to suppress
11162              their return type.  It is easier for GDB users to search
11163              for such functions as `name(params)' than `long name(params)'.
11164              In such case the minimal symbol names do not match the full
11165              symbol names but for template functions there is never a need
11166              to look up their definition from their declaration so
11167              the only disadvantage remains the minimal symbol variant
11168              `long name(params)' does not have the proper inferior type.  */
11169           demangled.reset (gdb_demangle (mangled,
11170                                          (DMGL_PARAMS | DMGL_ANSI
11171                                           | DMGL_RET_DROP)));
11172         }
11173       if (demangled)
11174         canon = demangled.get ();
11175       else
11176         {
11177           canon = mangled;
11178           need_copy = 0;
11179         }
11180     }
11181
11182   if (canon == NULL || check_physname)
11183     {
11184       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11185
11186       if (canon != NULL && strcmp (physname, canon) != 0)
11187         {
11188           /* It may not mean a bug in GDB.  The compiler could also
11189              compute DW_AT_linkage_name incorrectly.  But in such case
11190              GDB would need to be bug-to-bug compatible.  */
11191
11192           complaint (&symfile_complaints,
11193                      _("Computed physname <%s> does not match demangled <%s> "
11194                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11195                      physname, canon, mangled, sect_offset_str (die->sect_off),
11196                      objfile_name (objfile));
11197
11198           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11199              is available here - over computed PHYSNAME.  It is safer
11200              against both buggy GDB and buggy compilers.  */
11201
11202           retval = canon;
11203         }
11204       else
11205         {
11206           retval = physname;
11207           need_copy = 0;
11208         }
11209     }
11210   else
11211     retval = canon;
11212
11213   if (need_copy)
11214     retval = ((const char *)
11215               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11216                              retval, strlen (retval)));
11217
11218   return retval;
11219 }
11220
11221 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11222    a new symbol for it.
11223
11224    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11225
11226 static int
11227 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11228 {
11229   struct attribute *attr;
11230
11231   /* If the die does not have a name, this is not a namespace
11232      alias.  */
11233   attr = dwarf2_attr (die, DW_AT_name, cu);
11234   if (attr != NULL)
11235     {
11236       int num;
11237       struct die_info *d = die;
11238       struct dwarf2_cu *imported_cu = cu;
11239
11240       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11241          keep inspecting DIEs until we hit the underlying import.  */
11242 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11243       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11244         {
11245           attr = dwarf2_attr (d, DW_AT_import, cu);
11246           if (attr == NULL)
11247             break;
11248
11249           d = follow_die_ref (d, attr, &imported_cu);
11250           if (d->tag != DW_TAG_imported_declaration)
11251             break;
11252         }
11253
11254       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11255         {
11256           complaint (&symfile_complaints,
11257                      _("DIE at %s has too many recursively imported "
11258                        "declarations"), sect_offset_str (d->sect_off));
11259           return 0;
11260         }
11261
11262       if (attr != NULL)
11263         {
11264           struct type *type;
11265           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11266
11267           type = get_die_type_at_offset (sect_off, cu->per_cu);
11268           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11269             {
11270               /* This declaration is a global namespace alias.  Add
11271                  a symbol for it whose type is the aliased namespace.  */
11272               new_symbol (die, type, cu);
11273               return 1;
11274             }
11275         }
11276     }
11277
11278   return 0;
11279 }
11280
11281 /* Return the using directives repository (global or local?) to use in the
11282    current context for LANGUAGE.
11283
11284    For Ada, imported declarations can materialize renamings, which *may* be
11285    global.  However it is impossible (for now?) in DWARF to distinguish
11286    "external" imported declarations and "static" ones.  As all imported
11287    declarations seem to be static in all other languages, make them all CU-wide
11288    global only in Ada.  */
11289
11290 static struct using_direct **
11291 using_directives (enum language language)
11292 {
11293   if (language == language_ada && context_stack_depth == 0)
11294     return &global_using_directives;
11295   else
11296     return &local_using_directives;
11297 }
11298
11299 /* Read the import statement specified by the given die and record it.  */
11300
11301 static void
11302 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11303 {
11304   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11305   struct attribute *import_attr;
11306   struct die_info *imported_die, *child_die;
11307   struct dwarf2_cu *imported_cu;
11308   const char *imported_name;
11309   const char *imported_name_prefix;
11310   const char *canonical_name;
11311   const char *import_alias;
11312   const char *imported_declaration = NULL;
11313   const char *import_prefix;
11314   std::vector<const char *> excludes;
11315
11316   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11317   if (import_attr == NULL)
11318     {
11319       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11320                  dwarf_tag_name (die->tag));
11321       return;
11322     }
11323
11324   imported_cu = cu;
11325   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11326   imported_name = dwarf2_name (imported_die, imported_cu);
11327   if (imported_name == NULL)
11328     {
11329       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11330
11331         The import in the following code:
11332         namespace A
11333           {
11334             typedef int B;
11335           }
11336
11337         int main ()
11338           {
11339             using A::B;
11340             B b;
11341             return b;
11342           }
11343
11344         ...
11345          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11346             <52>   DW_AT_decl_file   : 1
11347             <53>   DW_AT_decl_line   : 6
11348             <54>   DW_AT_import      : <0x75>
11349          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11350             <59>   DW_AT_name        : B
11351             <5b>   DW_AT_decl_file   : 1
11352             <5c>   DW_AT_decl_line   : 2
11353             <5d>   DW_AT_type        : <0x6e>
11354         ...
11355          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11356             <76>   DW_AT_byte_size   : 4
11357             <77>   DW_AT_encoding    : 5        (signed)
11358
11359         imports the wrong die ( 0x75 instead of 0x58 ).
11360         This case will be ignored until the gcc bug is fixed.  */
11361       return;
11362     }
11363
11364   /* Figure out the local name after import.  */
11365   import_alias = dwarf2_name (die, cu);
11366
11367   /* Figure out where the statement is being imported to.  */
11368   import_prefix = determine_prefix (die, cu);
11369
11370   /* Figure out what the scope of the imported die is and prepend it
11371      to the name of the imported die.  */
11372   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11373
11374   if (imported_die->tag != DW_TAG_namespace
11375       && imported_die->tag != DW_TAG_module)
11376     {
11377       imported_declaration = imported_name;
11378       canonical_name = imported_name_prefix;
11379     }
11380   else if (strlen (imported_name_prefix) > 0)
11381     canonical_name = obconcat (&objfile->objfile_obstack,
11382                                imported_name_prefix,
11383                                (cu->language == language_d ? "." : "::"),
11384                                imported_name, (char *) NULL);
11385   else
11386     canonical_name = imported_name;
11387
11388   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11389     for (child_die = die->child; child_die && child_die->tag;
11390          child_die = sibling_die (child_die))
11391       {
11392         /* DWARF-4: A Fortran use statement with a “rename list” may be
11393            represented by an imported module entry with an import attribute
11394            referring to the module and owned entries corresponding to those
11395            entities that are renamed as part of being imported.  */
11396
11397         if (child_die->tag != DW_TAG_imported_declaration)
11398           {
11399             complaint (&symfile_complaints,
11400                        _("child DW_TAG_imported_declaration expected "
11401                          "- DIE at %s [in module %s]"),
11402                        sect_offset_str (child_die->sect_off),
11403                        objfile_name (objfile));
11404             continue;
11405           }
11406
11407         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11408         if (import_attr == NULL)
11409           {
11410             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11411                        dwarf_tag_name (child_die->tag));
11412             continue;
11413           }
11414
11415         imported_cu = cu;
11416         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11417                                               &imported_cu);
11418         imported_name = dwarf2_name (imported_die, imported_cu);
11419         if (imported_name == NULL)
11420           {
11421             complaint (&symfile_complaints,
11422                        _("child DW_TAG_imported_declaration has unknown "
11423                          "imported name - DIE at %s [in module %s]"),
11424                        sect_offset_str (child_die->sect_off),
11425                        objfile_name (objfile));
11426             continue;
11427           }
11428
11429         excludes.push_back (imported_name);
11430
11431         process_die (child_die, cu);
11432       }
11433
11434   add_using_directive (using_directives (cu->language),
11435                        import_prefix,
11436                        canonical_name,
11437                        import_alias,
11438                        imported_declaration,
11439                        excludes,
11440                        0,
11441                        &objfile->objfile_obstack);
11442 }
11443
11444 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11445    types, but gives them a size of zero.  Starting with version 14,
11446    ICC is compatible with GCC.  */
11447
11448 static int
11449 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11450 {
11451   if (!cu->checked_producer)
11452     check_producer (cu);
11453
11454   return cu->producer_is_icc_lt_14;
11455 }
11456
11457 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11458    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11459    this, it was first present in GCC release 4.3.0.  */
11460
11461 static int
11462 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11463 {
11464   if (!cu->checked_producer)
11465     check_producer (cu);
11466
11467   return cu->producer_is_gcc_lt_4_3;
11468 }
11469
11470 static file_and_directory
11471 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11472 {
11473   file_and_directory res;
11474
11475   /* Find the filename.  Do not use dwarf2_name here, since the filename
11476      is not a source language identifier.  */
11477   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11478   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11479
11480   if (res.comp_dir == NULL
11481       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11482       && IS_ABSOLUTE_PATH (res.name))
11483     {
11484       res.comp_dir_storage = ldirname (res.name);
11485       if (!res.comp_dir_storage.empty ())
11486         res.comp_dir = res.comp_dir_storage.c_str ();
11487     }
11488   if (res.comp_dir != NULL)
11489     {
11490       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11491          directory, get rid of it.  */
11492       const char *cp = strchr (res.comp_dir, ':');
11493
11494       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11495         res.comp_dir = cp + 1;
11496     }
11497
11498   if (res.name == NULL)
11499     res.name = "<unknown>";
11500
11501   return res;
11502 }
11503
11504 /* Handle DW_AT_stmt_list for a compilation unit.
11505    DIE is the DW_TAG_compile_unit die for CU.
11506    COMP_DIR is the compilation directory.  LOWPC is passed to
11507    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11508
11509 static void
11510 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11511                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11512 {
11513   struct dwarf2_per_objfile *dwarf2_per_objfile
11514     = cu->per_cu->dwarf2_per_objfile;
11515   struct objfile *objfile = dwarf2_per_objfile->objfile;
11516   struct attribute *attr;
11517   struct line_header line_header_local;
11518   hashval_t line_header_local_hash;
11519   void **slot;
11520   int decode_mapping;
11521
11522   gdb_assert (! cu->per_cu->is_debug_types);
11523
11524   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11525   if (attr == NULL)
11526     return;
11527
11528   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11529
11530   /* The line header hash table is only created if needed (it exists to
11531      prevent redundant reading of the line table for partial_units).
11532      If we're given a partial_unit, we'll need it.  If we're given a
11533      compile_unit, then use the line header hash table if it's already
11534      created, but don't create one just yet.  */
11535
11536   if (dwarf2_per_objfile->line_header_hash == NULL
11537       && die->tag == DW_TAG_partial_unit)
11538     {
11539       dwarf2_per_objfile->line_header_hash
11540         = htab_create_alloc_ex (127, line_header_hash_voidp,
11541                                 line_header_eq_voidp,
11542                                 free_line_header_voidp,
11543                                 &objfile->objfile_obstack,
11544                                 hashtab_obstack_allocate,
11545                                 dummy_obstack_deallocate);
11546     }
11547
11548   line_header_local.sect_off = line_offset;
11549   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11550   line_header_local_hash = line_header_hash (&line_header_local);
11551   if (dwarf2_per_objfile->line_header_hash != NULL)
11552     {
11553       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11554                                        &line_header_local,
11555                                        line_header_local_hash, NO_INSERT);
11556
11557       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11558          is not present in *SLOT (since if there is something in *SLOT then
11559          it will be for a partial_unit).  */
11560       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11561         {
11562           gdb_assert (*slot != NULL);
11563           cu->line_header = (struct line_header *) *slot;
11564           return;
11565         }
11566     }
11567
11568   /* dwarf_decode_line_header does not yet provide sufficient information.
11569      We always have to call also dwarf_decode_lines for it.  */
11570   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11571   if (lh == NULL)
11572     return;
11573
11574   cu->line_header = lh.release ();
11575   cu->line_header_die_owner = die;
11576
11577   if (dwarf2_per_objfile->line_header_hash == NULL)
11578     slot = NULL;
11579   else
11580     {
11581       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11582                                        &line_header_local,
11583                                        line_header_local_hash, INSERT);
11584       gdb_assert (slot != NULL);
11585     }
11586   if (slot != NULL && *slot == NULL)
11587     {
11588       /* This newly decoded line number information unit will be owned
11589          by line_header_hash hash table.  */
11590       *slot = cu->line_header;
11591       cu->line_header_die_owner = NULL;
11592     }
11593   else
11594     {
11595       /* We cannot free any current entry in (*slot) as that struct line_header
11596          may be already used by multiple CUs.  Create only temporary decoded
11597          line_header for this CU - it may happen at most once for each line
11598          number information unit.  And if we're not using line_header_hash
11599          then this is what we want as well.  */
11600       gdb_assert (die->tag != DW_TAG_partial_unit);
11601     }
11602   decode_mapping = (die->tag != DW_TAG_partial_unit);
11603   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11604                       decode_mapping);
11605
11606 }
11607
11608 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11609
11610 static void
11611 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11612 {
11613   struct dwarf2_per_objfile *dwarf2_per_objfile
11614     = cu->per_cu->dwarf2_per_objfile;
11615   struct objfile *objfile = dwarf2_per_objfile->objfile;
11616   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11617   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11618   CORE_ADDR highpc = ((CORE_ADDR) 0);
11619   struct attribute *attr;
11620   struct die_info *child_die;
11621   CORE_ADDR baseaddr;
11622
11623   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11624
11625   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11626
11627   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11628      from finish_block.  */
11629   if (lowpc == ((CORE_ADDR) -1))
11630     lowpc = highpc;
11631   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11632
11633   file_and_directory fnd = find_file_and_directory (die, cu);
11634
11635   prepare_one_comp_unit (cu, die, cu->language);
11636
11637   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11638      standardised yet.  As a workaround for the language detection we fall
11639      back to the DW_AT_producer string.  */
11640   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11641     cu->language = language_opencl;
11642
11643   /* Similar hack for Go.  */
11644   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11645     set_cu_language (DW_LANG_Go, cu);
11646
11647   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11648
11649   /* Decode line number information if present.  We do this before
11650      processing child DIEs, so that the line header table is available
11651      for DW_AT_decl_file.  */
11652   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11653
11654   /* Process all dies in compilation unit.  */
11655   if (die->child != NULL)
11656     {
11657       child_die = die->child;
11658       while (child_die && child_die->tag)
11659         {
11660           process_die (child_die, cu);
11661           child_die = sibling_die (child_die);
11662         }
11663     }
11664
11665   /* Decode macro information, if present.  Dwarf 2 macro information
11666      refers to information in the line number info statement program
11667      header, so we can only read it if we've read the header
11668      successfully.  */
11669   attr = dwarf2_attr (die, DW_AT_macros, cu);
11670   if (attr == NULL)
11671     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11672   if (attr && cu->line_header)
11673     {
11674       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11675         complaint (&symfile_complaints,
11676                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11677
11678       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11679     }
11680   else
11681     {
11682       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11683       if (attr && cu->line_header)
11684         {
11685           unsigned int macro_offset = DW_UNSND (attr);
11686
11687           dwarf_decode_macros (cu, macro_offset, 0);
11688         }
11689     }
11690 }
11691
11692 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11693    Create the set of symtabs used by this TU, or if this TU is sharing
11694    symtabs with another TU and the symtabs have already been created
11695    then restore those symtabs in the line header.
11696    We don't need the pc/line-number mapping for type units.  */
11697
11698 static void
11699 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11700 {
11701   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11702   struct type_unit_group *tu_group;
11703   int first_time;
11704   struct attribute *attr;
11705   unsigned int i;
11706   struct signatured_type *sig_type;
11707
11708   gdb_assert (per_cu->is_debug_types);
11709   sig_type = (struct signatured_type *) per_cu;
11710
11711   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11712
11713   /* If we're using .gdb_index (includes -readnow) then
11714      per_cu->type_unit_group may not have been set up yet.  */
11715   if (sig_type->type_unit_group == NULL)
11716     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11717   tu_group = sig_type->type_unit_group;
11718
11719   /* If we've already processed this stmt_list there's no real need to
11720      do it again, we could fake it and just recreate the part we need
11721      (file name,index -> symtab mapping).  If data shows this optimization
11722      is useful we can do it then.  */
11723   first_time = tu_group->compunit_symtab == NULL;
11724
11725   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11726      debug info.  */
11727   line_header_up lh;
11728   if (attr != NULL)
11729     {
11730       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11731       lh = dwarf_decode_line_header (line_offset, cu);
11732     }
11733   if (lh == NULL)
11734     {
11735       if (first_time)
11736         dwarf2_start_symtab (cu, "", NULL, 0);
11737       else
11738         {
11739           gdb_assert (tu_group->symtabs == NULL);
11740           restart_symtab (tu_group->compunit_symtab, "", 0);
11741         }
11742       return;
11743     }
11744
11745   cu->line_header = lh.release ();
11746   cu->line_header_die_owner = die;
11747
11748   if (first_time)
11749     {
11750       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11751
11752       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11753          still initializing it, and our caller (a few levels up)
11754          process_full_type_unit still needs to know if this is the first
11755          time.  */
11756
11757       tu_group->num_symtabs = cu->line_header->file_names.size ();
11758       tu_group->symtabs = XNEWVEC (struct symtab *,
11759                                    cu->line_header->file_names.size ());
11760
11761       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11762         {
11763           file_entry &fe = cu->line_header->file_names[i];
11764
11765           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11766
11767           if (current_subfile->symtab == NULL)
11768             {
11769               /* NOTE: start_subfile will recognize when it's been
11770                  passed a file it has already seen.  So we can't
11771                  assume there's a simple mapping from
11772                  cu->line_header->file_names to subfiles, plus
11773                  cu->line_header->file_names may contain dups.  */
11774               current_subfile->symtab
11775                 = allocate_symtab (cust, current_subfile->name);
11776             }
11777
11778           fe.symtab = current_subfile->symtab;
11779           tu_group->symtabs[i] = fe.symtab;
11780         }
11781     }
11782   else
11783     {
11784       restart_symtab (tu_group->compunit_symtab, "", 0);
11785
11786       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11787         {
11788           file_entry &fe = cu->line_header->file_names[i];
11789
11790           fe.symtab = tu_group->symtabs[i];
11791         }
11792     }
11793
11794   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11795      so they don't have a "real" (so to speak) symtab anyway.
11796      There is later code that will assign the main symtab to all symbols
11797      that don't have one.  We need to handle the case of a symbol with a
11798      missing symtab (DW_AT_decl_file) anyway.  */
11799 }
11800
11801 /* Process DW_TAG_type_unit.
11802    For TUs we want to skip the first top level sibling if it's not the
11803    actual type being defined by this TU.  In this case the first top
11804    level sibling is there to provide context only.  */
11805
11806 static void
11807 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11808 {
11809   struct die_info *child_die;
11810
11811   prepare_one_comp_unit (cu, die, language_minimal);
11812
11813   /* Initialize (or reinitialize) the machinery for building symtabs.
11814      We do this before processing child DIEs, so that the line header table
11815      is available for DW_AT_decl_file.  */
11816   setup_type_unit_groups (die, cu);
11817
11818   if (die->child != NULL)
11819     {
11820       child_die = die->child;
11821       while (child_die && child_die->tag)
11822         {
11823           process_die (child_die, cu);
11824           child_die = sibling_die (child_die);
11825         }
11826     }
11827 }
11828 \f
11829 /* DWO/DWP files.
11830
11831    http://gcc.gnu.org/wiki/DebugFission
11832    http://gcc.gnu.org/wiki/DebugFissionDWP
11833
11834    To simplify handling of both DWO files ("object" files with the DWARF info)
11835    and DWP files (a file with the DWOs packaged up into one file), we treat
11836    DWP files as having a collection of virtual DWO files.  */
11837
11838 static hashval_t
11839 hash_dwo_file (const void *item)
11840 {
11841   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11842   hashval_t hash;
11843
11844   hash = htab_hash_string (dwo_file->dwo_name);
11845   if (dwo_file->comp_dir != NULL)
11846     hash += htab_hash_string (dwo_file->comp_dir);
11847   return hash;
11848 }
11849
11850 static int
11851 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11852 {
11853   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11854   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11855
11856   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11857     return 0;
11858   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11859     return lhs->comp_dir == rhs->comp_dir;
11860   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11861 }
11862
11863 /* Allocate a hash table for DWO files.  */
11864
11865 static htab_t
11866 allocate_dwo_file_hash_table (struct objfile *objfile)
11867 {
11868   return htab_create_alloc_ex (41,
11869                                hash_dwo_file,
11870                                eq_dwo_file,
11871                                NULL,
11872                                &objfile->objfile_obstack,
11873                                hashtab_obstack_allocate,
11874                                dummy_obstack_deallocate);
11875 }
11876
11877 /* Lookup DWO file DWO_NAME.  */
11878
11879 static void **
11880 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11881                       const char *dwo_name,
11882                       const char *comp_dir)
11883 {
11884   struct dwo_file find_entry;
11885   void **slot;
11886
11887   if (dwarf2_per_objfile->dwo_files == NULL)
11888     dwarf2_per_objfile->dwo_files
11889       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11890
11891   memset (&find_entry, 0, sizeof (find_entry));
11892   find_entry.dwo_name = dwo_name;
11893   find_entry.comp_dir = comp_dir;
11894   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11895
11896   return slot;
11897 }
11898
11899 static hashval_t
11900 hash_dwo_unit (const void *item)
11901 {
11902   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11903
11904   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11905   return dwo_unit->signature;
11906 }
11907
11908 static int
11909 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11910 {
11911   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11912   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11913
11914   /* The signature is assumed to be unique within the DWO file.
11915      So while object file CU dwo_id's always have the value zero,
11916      that's OK, assuming each object file DWO file has only one CU,
11917      and that's the rule for now.  */
11918   return lhs->signature == rhs->signature;
11919 }
11920
11921 /* Allocate a hash table for DWO CUs,TUs.
11922    There is one of these tables for each of CUs,TUs for each DWO file.  */
11923
11924 static htab_t
11925 allocate_dwo_unit_table (struct objfile *objfile)
11926 {
11927   /* Start out with a pretty small number.
11928      Generally DWO files contain only one CU and maybe some TUs.  */
11929   return htab_create_alloc_ex (3,
11930                                hash_dwo_unit,
11931                                eq_dwo_unit,
11932                                NULL,
11933                                &objfile->objfile_obstack,
11934                                hashtab_obstack_allocate,
11935                                dummy_obstack_deallocate);
11936 }
11937
11938 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11939
11940 struct create_dwo_cu_data
11941 {
11942   struct dwo_file *dwo_file;
11943   struct dwo_unit dwo_unit;
11944 };
11945
11946 /* die_reader_func for create_dwo_cu.  */
11947
11948 static void
11949 create_dwo_cu_reader (const struct die_reader_specs *reader,
11950                       const gdb_byte *info_ptr,
11951                       struct die_info *comp_unit_die,
11952                       int has_children,
11953                       void *datap)
11954 {
11955   struct dwarf2_cu *cu = reader->cu;
11956   sect_offset sect_off = cu->per_cu->sect_off;
11957   struct dwarf2_section_info *section = cu->per_cu->section;
11958   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11959   struct dwo_file *dwo_file = data->dwo_file;
11960   struct dwo_unit *dwo_unit = &data->dwo_unit;
11961   struct attribute *attr;
11962
11963   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11964   if (attr == NULL)
11965     {
11966       complaint (&symfile_complaints,
11967                  _("Dwarf Error: debug entry at offset %s is missing"
11968                    " its dwo_id [in module %s]"),
11969                  sect_offset_str (sect_off), dwo_file->dwo_name);
11970       return;
11971     }
11972
11973   dwo_unit->dwo_file = dwo_file;
11974   dwo_unit->signature = DW_UNSND (attr);
11975   dwo_unit->section = section;
11976   dwo_unit->sect_off = sect_off;
11977   dwo_unit->length = cu->per_cu->length;
11978
11979   if (dwarf_read_debug)
11980     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11981                         sect_offset_str (sect_off),
11982                         hex_string (dwo_unit->signature));
11983 }
11984
11985 /* Create the dwo_units for the CUs in a DWO_FILE.
11986    Note: This function processes DWO files only, not DWP files.  */
11987
11988 static void
11989 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11990                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11991                        htab_t &cus_htab)
11992 {
11993   struct objfile *objfile = dwarf2_per_objfile->objfile;
11994   const gdb_byte *info_ptr, *end_ptr;
11995
11996   dwarf2_read_section (objfile, &section);
11997   info_ptr = section.buffer;
11998
11999   if (info_ptr == NULL)
12000     return;
12001
12002   if (dwarf_read_debug)
12003     {
12004       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12005                           get_section_name (&section),
12006                           get_section_file_name (&section));
12007     }
12008
12009   end_ptr = info_ptr + section.size;
12010   while (info_ptr < end_ptr)
12011     {
12012       struct dwarf2_per_cu_data per_cu;
12013       struct create_dwo_cu_data create_dwo_cu_data;
12014       struct dwo_unit *dwo_unit;
12015       void **slot;
12016       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12017
12018       memset (&create_dwo_cu_data.dwo_unit, 0,
12019               sizeof (create_dwo_cu_data.dwo_unit));
12020       memset (&per_cu, 0, sizeof (per_cu));
12021       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12022       per_cu.is_debug_types = 0;
12023       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12024       per_cu.section = &section;
12025       create_dwo_cu_data.dwo_file = &dwo_file;
12026
12027       init_cutu_and_read_dies_no_follow (
12028           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12029       info_ptr += per_cu.length;
12030
12031       // If the unit could not be parsed, skip it.
12032       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12033         continue;
12034
12035       if (cus_htab == NULL)
12036         cus_htab = allocate_dwo_unit_table (objfile);
12037
12038       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12039       *dwo_unit = create_dwo_cu_data.dwo_unit;
12040       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12041       gdb_assert (slot != NULL);
12042       if (*slot != NULL)
12043         {
12044           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12045           sect_offset dup_sect_off = dup_cu->sect_off;
12046
12047           complaint (&symfile_complaints,
12048                      _("debug cu entry at offset %s is duplicate to"
12049                        " the entry at offset %s, signature %s"),
12050                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
12051                      hex_string (dwo_unit->signature));
12052         }
12053       *slot = (void *)dwo_unit;
12054     }
12055 }
12056
12057 /* DWP file .debug_{cu,tu}_index section format:
12058    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12059
12060    DWP Version 1:
12061
12062    Both index sections have the same format, and serve to map a 64-bit
12063    signature to a set of section numbers.  Each section begins with a header,
12064    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12065    indexes, and a pool of 32-bit section numbers.  The index sections will be
12066    aligned at 8-byte boundaries in the file.
12067
12068    The index section header consists of:
12069
12070     V, 32 bit version number
12071     -, 32 bits unused
12072     N, 32 bit number of compilation units or type units in the index
12073     M, 32 bit number of slots in the hash table
12074
12075    Numbers are recorded using the byte order of the application binary.
12076
12077    The hash table begins at offset 16 in the section, and consists of an array
12078    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12079    order of the application binary).  Unused slots in the hash table are 0.
12080    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12081
12082    The parallel table begins immediately after the hash table
12083    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12084    array of 32-bit indexes (using the byte order of the application binary),
12085    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12086    table contains a 32-bit index into the pool of section numbers.  For unused
12087    hash table slots, the corresponding entry in the parallel table will be 0.
12088
12089    The pool of section numbers begins immediately following the hash table
12090    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12091    section numbers consists of an array of 32-bit words (using the byte order
12092    of the application binary).  Each item in the array is indexed starting
12093    from 0.  The hash table entry provides the index of the first section
12094    number in the set.  Additional section numbers in the set follow, and the
12095    set is terminated by a 0 entry (section number 0 is not used in ELF).
12096
12097    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12098    section must be the first entry in the set, and the .debug_abbrev.dwo must
12099    be the second entry. Other members of the set may follow in any order.
12100
12101    ---
12102
12103    DWP Version 2:
12104
12105    DWP Version 2 combines all the .debug_info, etc. sections into one,
12106    and the entries in the index tables are now offsets into these sections.
12107    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12108    section.
12109
12110    Index Section Contents:
12111     Header
12112     Hash Table of Signatures   dwp_hash_table.hash_table
12113     Parallel Table of Indices  dwp_hash_table.unit_table
12114     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12115     Table of Section Sizes     dwp_hash_table.v2.sizes
12116
12117    The index section header consists of:
12118
12119     V, 32 bit version number
12120     L, 32 bit number of columns in the table of section offsets
12121     N, 32 bit number of compilation units or type units in the index
12122     M, 32 bit number of slots in the hash table
12123
12124    Numbers are recorded using the byte order of the application binary.
12125
12126    The hash table has the same format as version 1.
12127    The parallel table of indices has the same format as version 1,
12128    except that the entries are origin-1 indices into the table of sections
12129    offsets and the table of section sizes.
12130
12131    The table of offsets begins immediately following the parallel table
12132    (at offset 16 + 12 * M from the beginning of the section).  The table is
12133    a two-dimensional array of 32-bit words (using the byte order of the
12134    application binary), with L columns and N+1 rows, in row-major order.
12135    Each row in the array is indexed starting from 0.  The first row provides
12136    a key to the remaining rows: each column in this row provides an identifier
12137    for a debug section, and the offsets in the same column of subsequent rows
12138    refer to that section.  The section identifiers are:
12139
12140     DW_SECT_INFO         1  .debug_info.dwo
12141     DW_SECT_TYPES        2  .debug_types.dwo
12142     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12143     DW_SECT_LINE         4  .debug_line.dwo
12144     DW_SECT_LOC          5  .debug_loc.dwo
12145     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12146     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12147     DW_SECT_MACRO        8  .debug_macro.dwo
12148
12149    The offsets provided by the CU and TU index sections are the base offsets
12150    for the contributions made by each CU or TU to the corresponding section
12151    in the package file.  Each CU and TU header contains an abbrev_offset
12152    field, used to find the abbreviations table for that CU or TU within the
12153    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12154    be interpreted as relative to the base offset given in the index section.
12155    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12156    should be interpreted as relative to the base offset for .debug_line.dwo,
12157    and offsets into other debug sections obtained from DWARF attributes should
12158    also be interpreted as relative to the corresponding base offset.
12159
12160    The table of sizes begins immediately following the table of offsets.
12161    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12162    with L columns and N rows, in row-major order.  Each row in the array is
12163    indexed starting from 1 (row 0 is shared by the two tables).
12164
12165    ---
12166
12167    Hash table lookup is handled the same in version 1 and 2:
12168
12169    We assume that N and M will not exceed 2^32 - 1.
12170    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12171
12172    Given a 64-bit compilation unit signature or a type signature S, an entry
12173    in the hash table is located as follows:
12174
12175    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12176       the low-order k bits all set to 1.
12177
12178    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12179
12180    3) If the hash table entry at index H matches the signature, use that
12181       entry.  If the hash table entry at index H is unused (all zeroes),
12182       terminate the search: the signature is not present in the table.
12183
12184    4) Let H = (H + H') modulo M. Repeat at Step 3.
12185
12186    Because M > N and H' and M are relatively prime, the search is guaranteed
12187    to stop at an unused slot or find the match.  */
12188
12189 /* Create a hash table to map DWO IDs to their CU/TU entry in
12190    .debug_{info,types}.dwo in DWP_FILE.
12191    Returns NULL if there isn't one.
12192    Note: This function processes DWP files only, not DWO files.  */
12193
12194 static struct dwp_hash_table *
12195 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12196                        struct dwp_file *dwp_file, int is_debug_types)
12197 {
12198   struct objfile *objfile = dwarf2_per_objfile->objfile;
12199   bfd *dbfd = dwp_file->dbfd;
12200   const gdb_byte *index_ptr, *index_end;
12201   struct dwarf2_section_info *index;
12202   uint32_t version, nr_columns, nr_units, nr_slots;
12203   struct dwp_hash_table *htab;
12204
12205   if (is_debug_types)
12206     index = &dwp_file->sections.tu_index;
12207   else
12208     index = &dwp_file->sections.cu_index;
12209
12210   if (dwarf2_section_empty_p (index))
12211     return NULL;
12212   dwarf2_read_section (objfile, index);
12213
12214   index_ptr = index->buffer;
12215   index_end = index_ptr + index->size;
12216
12217   version = read_4_bytes (dbfd, index_ptr);
12218   index_ptr += 4;
12219   if (version == 2)
12220     nr_columns = read_4_bytes (dbfd, index_ptr);
12221   else
12222     nr_columns = 0;
12223   index_ptr += 4;
12224   nr_units = read_4_bytes (dbfd, index_ptr);
12225   index_ptr += 4;
12226   nr_slots = read_4_bytes (dbfd, index_ptr);
12227   index_ptr += 4;
12228
12229   if (version != 1 && version != 2)
12230     {
12231       error (_("Dwarf Error: unsupported DWP file version (%s)"
12232                " [in module %s]"),
12233              pulongest (version), dwp_file->name);
12234     }
12235   if (nr_slots != (nr_slots & -nr_slots))
12236     {
12237       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12238                " is not power of 2 [in module %s]"),
12239              pulongest (nr_slots), dwp_file->name);
12240     }
12241
12242   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12243   htab->version = version;
12244   htab->nr_columns = nr_columns;
12245   htab->nr_units = nr_units;
12246   htab->nr_slots = nr_slots;
12247   htab->hash_table = index_ptr;
12248   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12249
12250   /* Exit early if the table is empty.  */
12251   if (nr_slots == 0 || nr_units == 0
12252       || (version == 2 && nr_columns == 0))
12253     {
12254       /* All must be zero.  */
12255       if (nr_slots != 0 || nr_units != 0
12256           || (version == 2 && nr_columns != 0))
12257         {
12258           complaint (&symfile_complaints,
12259                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12260                        " all zero [in modules %s]"),
12261                      dwp_file->name);
12262         }
12263       return htab;
12264     }
12265
12266   if (version == 1)
12267     {
12268       htab->section_pool.v1.indices =
12269         htab->unit_table + sizeof (uint32_t) * nr_slots;
12270       /* It's harder to decide whether the section is too small in v1.
12271          V1 is deprecated anyway so we punt.  */
12272     }
12273   else
12274     {
12275       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12276       int *ids = htab->section_pool.v2.section_ids;
12277       /* Reverse map for error checking.  */
12278       int ids_seen[DW_SECT_MAX + 1];
12279       int i;
12280
12281       if (nr_columns < 2)
12282         {
12283           error (_("Dwarf Error: bad DWP hash table, too few columns"
12284                    " in section table [in module %s]"),
12285                  dwp_file->name);
12286         }
12287       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12288         {
12289           error (_("Dwarf Error: bad DWP hash table, too many columns"
12290                    " in section table [in module %s]"),
12291                  dwp_file->name);
12292         }
12293       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12294       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12295       for (i = 0; i < nr_columns; ++i)
12296         {
12297           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12298
12299           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12300             {
12301               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12302                        " in section table [in module %s]"),
12303                      id, dwp_file->name);
12304             }
12305           if (ids_seen[id] != -1)
12306             {
12307               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12308                        " id %d in section table [in module %s]"),
12309                      id, dwp_file->name);
12310             }
12311           ids_seen[id] = i;
12312           ids[i] = id;
12313         }
12314       /* Must have exactly one info or types section.  */
12315       if (((ids_seen[DW_SECT_INFO] != -1)
12316            + (ids_seen[DW_SECT_TYPES] != -1))
12317           != 1)
12318         {
12319           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12320                    " DWO info/types section [in module %s]"),
12321                  dwp_file->name);
12322         }
12323       /* Must have an abbrev section.  */
12324       if (ids_seen[DW_SECT_ABBREV] == -1)
12325         {
12326           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12327                    " section [in module %s]"),
12328                  dwp_file->name);
12329         }
12330       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12331       htab->section_pool.v2.sizes =
12332         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12333                                          * nr_units * nr_columns);
12334       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12335                                           * nr_units * nr_columns))
12336           > index_end)
12337         {
12338           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12339                    " [in module %s]"),
12340                  dwp_file->name);
12341         }
12342     }
12343
12344   return htab;
12345 }
12346
12347 /* Update SECTIONS with the data from SECTP.
12348
12349    This function is like the other "locate" section routines that are
12350    passed to bfd_map_over_sections, but in this context the sections to
12351    read comes from the DWP V1 hash table, not the full ELF section table.
12352
12353    The result is non-zero for success, or zero if an error was found.  */
12354
12355 static int
12356 locate_v1_virtual_dwo_sections (asection *sectp,
12357                                 struct virtual_v1_dwo_sections *sections)
12358 {
12359   const struct dwop_section_names *names = &dwop_section_names;
12360
12361   if (section_is_p (sectp->name, &names->abbrev_dwo))
12362     {
12363       /* There can be only one.  */
12364       if (sections->abbrev.s.section != NULL)
12365         return 0;
12366       sections->abbrev.s.section = sectp;
12367       sections->abbrev.size = bfd_get_section_size (sectp);
12368     }
12369   else if (section_is_p (sectp->name, &names->info_dwo)
12370            || section_is_p (sectp->name, &names->types_dwo))
12371     {
12372       /* There can be only one.  */
12373       if (sections->info_or_types.s.section != NULL)
12374         return 0;
12375       sections->info_or_types.s.section = sectp;
12376       sections->info_or_types.size = bfd_get_section_size (sectp);
12377     }
12378   else if (section_is_p (sectp->name, &names->line_dwo))
12379     {
12380       /* There can be only one.  */
12381       if (sections->line.s.section != NULL)
12382         return 0;
12383       sections->line.s.section = sectp;
12384       sections->line.size = bfd_get_section_size (sectp);
12385     }
12386   else if (section_is_p (sectp->name, &names->loc_dwo))
12387     {
12388       /* There can be only one.  */
12389       if (sections->loc.s.section != NULL)
12390         return 0;
12391       sections->loc.s.section = sectp;
12392       sections->loc.size = bfd_get_section_size (sectp);
12393     }
12394   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12395     {
12396       /* There can be only one.  */
12397       if (sections->macinfo.s.section != NULL)
12398         return 0;
12399       sections->macinfo.s.section = sectp;
12400       sections->macinfo.size = bfd_get_section_size (sectp);
12401     }
12402   else if (section_is_p (sectp->name, &names->macro_dwo))
12403     {
12404       /* There can be only one.  */
12405       if (sections->macro.s.section != NULL)
12406         return 0;
12407       sections->macro.s.section = sectp;
12408       sections->macro.size = bfd_get_section_size (sectp);
12409     }
12410   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12411     {
12412       /* There can be only one.  */
12413       if (sections->str_offsets.s.section != NULL)
12414         return 0;
12415       sections->str_offsets.s.section = sectp;
12416       sections->str_offsets.size = bfd_get_section_size (sectp);
12417     }
12418   else
12419     {
12420       /* No other kind of section is valid.  */
12421       return 0;
12422     }
12423
12424   return 1;
12425 }
12426
12427 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12428    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12429    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12430    This is for DWP version 1 files.  */
12431
12432 static struct dwo_unit *
12433 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12434                            struct dwp_file *dwp_file,
12435                            uint32_t unit_index,
12436                            const char *comp_dir,
12437                            ULONGEST signature, int is_debug_types)
12438 {
12439   struct objfile *objfile = dwarf2_per_objfile->objfile;
12440   const struct dwp_hash_table *dwp_htab =
12441     is_debug_types ? dwp_file->tus : dwp_file->cus;
12442   bfd *dbfd = dwp_file->dbfd;
12443   const char *kind = is_debug_types ? "TU" : "CU";
12444   struct dwo_file *dwo_file;
12445   struct dwo_unit *dwo_unit;
12446   struct virtual_v1_dwo_sections sections;
12447   void **dwo_file_slot;
12448   int i;
12449
12450   gdb_assert (dwp_file->version == 1);
12451
12452   if (dwarf_read_debug)
12453     {
12454       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12455                           kind,
12456                           pulongest (unit_index), hex_string (signature),
12457                           dwp_file->name);
12458     }
12459
12460   /* Fetch the sections of this DWO unit.
12461      Put a limit on the number of sections we look for so that bad data
12462      doesn't cause us to loop forever.  */
12463
12464 #define MAX_NR_V1_DWO_SECTIONS \
12465   (1 /* .debug_info or .debug_types */ \
12466    + 1 /* .debug_abbrev */ \
12467    + 1 /* .debug_line */ \
12468    + 1 /* .debug_loc */ \
12469    + 1 /* .debug_str_offsets */ \
12470    + 1 /* .debug_macro or .debug_macinfo */ \
12471    + 1 /* trailing zero */)
12472
12473   memset (&sections, 0, sizeof (sections));
12474
12475   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12476     {
12477       asection *sectp;
12478       uint32_t section_nr =
12479         read_4_bytes (dbfd,
12480                       dwp_htab->section_pool.v1.indices
12481                       + (unit_index + i) * sizeof (uint32_t));
12482
12483       if (section_nr == 0)
12484         break;
12485       if (section_nr >= dwp_file->num_sections)
12486         {
12487           error (_("Dwarf Error: bad DWP hash table, section number too large"
12488                    " [in module %s]"),
12489                  dwp_file->name);
12490         }
12491
12492       sectp = dwp_file->elf_sections[section_nr];
12493       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12494         {
12495           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12496                    " [in module %s]"),
12497                  dwp_file->name);
12498         }
12499     }
12500
12501   if (i < 2
12502       || dwarf2_section_empty_p (&sections.info_or_types)
12503       || dwarf2_section_empty_p (&sections.abbrev))
12504     {
12505       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12506                " [in module %s]"),
12507              dwp_file->name);
12508     }
12509   if (i == MAX_NR_V1_DWO_SECTIONS)
12510     {
12511       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12512                " [in module %s]"),
12513              dwp_file->name);
12514     }
12515
12516   /* It's easier for the rest of the code if we fake a struct dwo_file and
12517      have dwo_unit "live" in that.  At least for now.
12518
12519      The DWP file can be made up of a random collection of CUs and TUs.
12520      However, for each CU + set of TUs that came from the same original DWO
12521      file, we can combine them back into a virtual DWO file to save space
12522      (fewer struct dwo_file objects to allocate).  Remember that for really
12523      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12524
12525   std::string virtual_dwo_name =
12526     string_printf ("virtual-dwo/%d-%d-%d-%d",
12527                    get_section_id (&sections.abbrev),
12528                    get_section_id (&sections.line),
12529                    get_section_id (&sections.loc),
12530                    get_section_id (&sections.str_offsets));
12531   /* Can we use an existing virtual DWO file?  */
12532   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12533                                         virtual_dwo_name.c_str (),
12534                                         comp_dir);
12535   /* Create one if necessary.  */
12536   if (*dwo_file_slot == NULL)
12537     {
12538       if (dwarf_read_debug)
12539         {
12540           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12541                               virtual_dwo_name.c_str ());
12542         }
12543       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12544       dwo_file->dwo_name
12545         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12546                                         virtual_dwo_name.c_str (),
12547                                         virtual_dwo_name.size ());
12548       dwo_file->comp_dir = comp_dir;
12549       dwo_file->sections.abbrev = sections.abbrev;
12550       dwo_file->sections.line = sections.line;
12551       dwo_file->sections.loc = sections.loc;
12552       dwo_file->sections.macinfo = sections.macinfo;
12553       dwo_file->sections.macro = sections.macro;
12554       dwo_file->sections.str_offsets = sections.str_offsets;
12555       /* The "str" section is global to the entire DWP file.  */
12556       dwo_file->sections.str = dwp_file->sections.str;
12557       /* The info or types section is assigned below to dwo_unit,
12558          there's no need to record it in dwo_file.
12559          Also, we can't simply record type sections in dwo_file because
12560          we record a pointer into the vector in dwo_unit.  As we collect more
12561          types we'll grow the vector and eventually have to reallocate space
12562          for it, invalidating all copies of pointers into the previous
12563          contents.  */
12564       *dwo_file_slot = dwo_file;
12565     }
12566   else
12567     {
12568       if (dwarf_read_debug)
12569         {
12570           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12571                               virtual_dwo_name.c_str ());
12572         }
12573       dwo_file = (struct dwo_file *) *dwo_file_slot;
12574     }
12575
12576   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12577   dwo_unit->dwo_file = dwo_file;
12578   dwo_unit->signature = signature;
12579   dwo_unit->section =
12580     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12581   *dwo_unit->section = sections.info_or_types;
12582   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12583
12584   return dwo_unit;
12585 }
12586
12587 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12588    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12589    piece within that section used by a TU/CU, return a virtual section
12590    of just that piece.  */
12591
12592 static struct dwarf2_section_info
12593 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12594                        struct dwarf2_section_info *section,
12595                        bfd_size_type offset, bfd_size_type size)
12596 {
12597   struct dwarf2_section_info result;
12598   asection *sectp;
12599
12600   gdb_assert (section != NULL);
12601   gdb_assert (!section->is_virtual);
12602
12603   memset (&result, 0, sizeof (result));
12604   result.s.containing_section = section;
12605   result.is_virtual = 1;
12606
12607   if (size == 0)
12608     return result;
12609
12610   sectp = get_section_bfd_section (section);
12611
12612   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12613      bounds of the real section.  This is a pretty-rare event, so just
12614      flag an error (easier) instead of a warning and trying to cope.  */
12615   if (sectp == NULL
12616       || offset + size > bfd_get_section_size (sectp))
12617     {
12618       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12619                " in section %s [in module %s]"),
12620              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12621              objfile_name (dwarf2_per_objfile->objfile));
12622     }
12623
12624   result.virtual_offset = offset;
12625   result.size = size;
12626   return result;
12627 }
12628
12629 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12630    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12631    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12632    This is for DWP version 2 files.  */
12633
12634 static struct dwo_unit *
12635 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12636                            struct dwp_file *dwp_file,
12637                            uint32_t unit_index,
12638                            const char *comp_dir,
12639                            ULONGEST signature, int is_debug_types)
12640 {
12641   struct objfile *objfile = dwarf2_per_objfile->objfile;
12642   const struct dwp_hash_table *dwp_htab =
12643     is_debug_types ? dwp_file->tus : dwp_file->cus;
12644   bfd *dbfd = dwp_file->dbfd;
12645   const char *kind = is_debug_types ? "TU" : "CU";
12646   struct dwo_file *dwo_file;
12647   struct dwo_unit *dwo_unit;
12648   struct virtual_v2_dwo_sections sections;
12649   void **dwo_file_slot;
12650   int i;
12651
12652   gdb_assert (dwp_file->version == 2);
12653
12654   if (dwarf_read_debug)
12655     {
12656       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12657                           kind,
12658                           pulongest (unit_index), hex_string (signature),
12659                           dwp_file->name);
12660     }
12661
12662   /* Fetch the section offsets of this DWO unit.  */
12663
12664   memset (&sections, 0, sizeof (sections));
12665
12666   for (i = 0; i < dwp_htab->nr_columns; ++i)
12667     {
12668       uint32_t offset = read_4_bytes (dbfd,
12669                                       dwp_htab->section_pool.v2.offsets
12670                                       + (((unit_index - 1) * dwp_htab->nr_columns
12671                                           + i)
12672                                          * sizeof (uint32_t)));
12673       uint32_t size = read_4_bytes (dbfd,
12674                                     dwp_htab->section_pool.v2.sizes
12675                                     + (((unit_index - 1) * dwp_htab->nr_columns
12676                                         + i)
12677                                        * sizeof (uint32_t)));
12678
12679       switch (dwp_htab->section_pool.v2.section_ids[i])
12680         {
12681         case DW_SECT_INFO:
12682         case DW_SECT_TYPES:
12683           sections.info_or_types_offset = offset;
12684           sections.info_or_types_size = size;
12685           break;
12686         case DW_SECT_ABBREV:
12687           sections.abbrev_offset = offset;
12688           sections.abbrev_size = size;
12689           break;
12690         case DW_SECT_LINE:
12691           sections.line_offset = offset;
12692           sections.line_size = size;
12693           break;
12694         case DW_SECT_LOC:
12695           sections.loc_offset = offset;
12696           sections.loc_size = size;
12697           break;
12698         case DW_SECT_STR_OFFSETS:
12699           sections.str_offsets_offset = offset;
12700           sections.str_offsets_size = size;
12701           break;
12702         case DW_SECT_MACINFO:
12703           sections.macinfo_offset = offset;
12704           sections.macinfo_size = size;
12705           break;
12706         case DW_SECT_MACRO:
12707           sections.macro_offset = offset;
12708           sections.macro_size = size;
12709           break;
12710         }
12711     }
12712
12713   /* It's easier for the rest of the code if we fake a struct dwo_file and
12714      have dwo_unit "live" in that.  At least for now.
12715
12716      The DWP file can be made up of a random collection of CUs and TUs.
12717      However, for each CU + set of TUs that came from the same original DWO
12718      file, we can combine them back into a virtual DWO file to save space
12719      (fewer struct dwo_file objects to allocate).  Remember that for really
12720      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12721
12722   std::string virtual_dwo_name =
12723     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12724                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12725                    (long) (sections.line_size ? sections.line_offset : 0),
12726                    (long) (sections.loc_size ? sections.loc_offset : 0),
12727                    (long) (sections.str_offsets_size
12728                            ? sections.str_offsets_offset : 0));
12729   /* Can we use an existing virtual DWO file?  */
12730   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12731                                         virtual_dwo_name.c_str (),
12732                                         comp_dir);
12733   /* Create one if necessary.  */
12734   if (*dwo_file_slot == NULL)
12735     {
12736       if (dwarf_read_debug)
12737         {
12738           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12739                               virtual_dwo_name.c_str ());
12740         }
12741       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12742       dwo_file->dwo_name
12743         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12744                                         virtual_dwo_name.c_str (),
12745                                         virtual_dwo_name.size ());
12746       dwo_file->comp_dir = comp_dir;
12747       dwo_file->sections.abbrev =
12748         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12749                                sections.abbrev_offset, sections.abbrev_size);
12750       dwo_file->sections.line =
12751         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12752                                sections.line_offset, sections.line_size);
12753       dwo_file->sections.loc =
12754         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12755                                sections.loc_offset, sections.loc_size);
12756       dwo_file->sections.macinfo =
12757         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12758                                sections.macinfo_offset, sections.macinfo_size);
12759       dwo_file->sections.macro =
12760         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12761                                sections.macro_offset, sections.macro_size);
12762       dwo_file->sections.str_offsets =
12763         create_dwp_v2_section (dwarf2_per_objfile,
12764                                &dwp_file->sections.str_offsets,
12765                                sections.str_offsets_offset,
12766                                sections.str_offsets_size);
12767       /* The "str" section is global to the entire DWP file.  */
12768       dwo_file->sections.str = dwp_file->sections.str;
12769       /* The info or types section is assigned below to dwo_unit,
12770          there's no need to record it in dwo_file.
12771          Also, we can't simply record type sections in dwo_file because
12772          we record a pointer into the vector in dwo_unit.  As we collect more
12773          types we'll grow the vector and eventually have to reallocate space
12774          for it, invalidating all copies of pointers into the previous
12775          contents.  */
12776       *dwo_file_slot = dwo_file;
12777     }
12778   else
12779     {
12780       if (dwarf_read_debug)
12781         {
12782           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12783                               virtual_dwo_name.c_str ());
12784         }
12785       dwo_file = (struct dwo_file *) *dwo_file_slot;
12786     }
12787
12788   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12789   dwo_unit->dwo_file = dwo_file;
12790   dwo_unit->signature = signature;
12791   dwo_unit->section =
12792     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12793   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12794                                               is_debug_types
12795                                               ? &dwp_file->sections.types
12796                                               : &dwp_file->sections.info,
12797                                               sections.info_or_types_offset,
12798                                               sections.info_or_types_size);
12799   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12800
12801   return dwo_unit;
12802 }
12803
12804 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12805    Returns NULL if the signature isn't found.  */
12806
12807 static struct dwo_unit *
12808 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12809                         struct dwp_file *dwp_file, const char *comp_dir,
12810                         ULONGEST signature, int is_debug_types)
12811 {
12812   const struct dwp_hash_table *dwp_htab =
12813     is_debug_types ? dwp_file->tus : dwp_file->cus;
12814   bfd *dbfd = dwp_file->dbfd;
12815   uint32_t mask = dwp_htab->nr_slots - 1;
12816   uint32_t hash = signature & mask;
12817   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12818   unsigned int i;
12819   void **slot;
12820   struct dwo_unit find_dwo_cu;
12821
12822   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12823   find_dwo_cu.signature = signature;
12824   slot = htab_find_slot (is_debug_types
12825                          ? dwp_file->loaded_tus
12826                          : dwp_file->loaded_cus,
12827                          &find_dwo_cu, INSERT);
12828
12829   if (*slot != NULL)
12830     return (struct dwo_unit *) *slot;
12831
12832   /* Use a for loop so that we don't loop forever on bad debug info.  */
12833   for (i = 0; i < dwp_htab->nr_slots; ++i)
12834     {
12835       ULONGEST signature_in_table;
12836
12837       signature_in_table =
12838         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12839       if (signature_in_table == signature)
12840         {
12841           uint32_t unit_index =
12842             read_4_bytes (dbfd,
12843                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12844
12845           if (dwp_file->version == 1)
12846             {
12847               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12848                                                  dwp_file, unit_index,
12849                                                  comp_dir, signature,
12850                                                  is_debug_types);
12851             }
12852           else
12853             {
12854               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12855                                                  dwp_file, unit_index,
12856                                                  comp_dir, signature,
12857                                                  is_debug_types);
12858             }
12859           return (struct dwo_unit *) *slot;
12860         }
12861       if (signature_in_table == 0)
12862         return NULL;
12863       hash = (hash + hash2) & mask;
12864     }
12865
12866   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12867            " [in module %s]"),
12868          dwp_file->name);
12869 }
12870
12871 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12872    Open the file specified by FILE_NAME and hand it off to BFD for
12873    preliminary analysis.  Return a newly initialized bfd *, which
12874    includes a canonicalized copy of FILE_NAME.
12875    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12876    SEARCH_CWD is true if the current directory is to be searched.
12877    It will be searched before debug-file-directory.
12878    If successful, the file is added to the bfd include table of the
12879    objfile's bfd (see gdb_bfd_record_inclusion).
12880    If unable to find/open the file, return NULL.
12881    NOTE: This function is derived from symfile_bfd_open.  */
12882
12883 static gdb_bfd_ref_ptr
12884 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12885                     const char *file_name, int is_dwp, int search_cwd)
12886 {
12887   int desc;
12888   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12889      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12890      to debug_file_directory.  */
12891   const char *search_path;
12892   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12893
12894   gdb::unique_xmalloc_ptr<char> search_path_holder;
12895   if (search_cwd)
12896     {
12897       if (*debug_file_directory != '\0')
12898         {
12899           search_path_holder.reset (concat (".", dirname_separator_string,
12900                                             debug_file_directory,
12901                                             (char *) NULL));
12902           search_path = search_path_holder.get ();
12903         }
12904       else
12905         search_path = ".";
12906     }
12907   else
12908     search_path = debug_file_directory;
12909
12910   openp_flags flags = OPF_RETURN_REALPATH;
12911   if (is_dwp)
12912     flags |= OPF_SEARCH_IN_PATH;
12913
12914   gdb::unique_xmalloc_ptr<char> absolute_name;
12915   desc = openp (search_path, flags, file_name,
12916                 O_RDONLY | O_BINARY, &absolute_name);
12917   if (desc < 0)
12918     return NULL;
12919
12920   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12921                                          gnutarget, desc));
12922   if (sym_bfd == NULL)
12923     return NULL;
12924   bfd_set_cacheable (sym_bfd.get (), 1);
12925
12926   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12927     return NULL;
12928
12929   /* Success.  Record the bfd as having been included by the objfile's bfd.
12930      This is important because things like demangled_names_hash lives in the
12931      objfile's per_bfd space and may have references to things like symbol
12932      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12933   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12934
12935   return sym_bfd;
12936 }
12937
12938 /* Try to open DWO file FILE_NAME.
12939    COMP_DIR is the DW_AT_comp_dir attribute.
12940    The result is the bfd handle of the file.
12941    If there is a problem finding or opening the file, return NULL.
12942    Upon success, the canonicalized path of the file is stored in the bfd,
12943    same as symfile_bfd_open.  */
12944
12945 static gdb_bfd_ref_ptr
12946 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12947                const char *file_name, const char *comp_dir)
12948 {
12949   if (IS_ABSOLUTE_PATH (file_name))
12950     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12951                                0 /*is_dwp*/, 0 /*search_cwd*/);
12952
12953   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12954
12955   if (comp_dir != NULL)
12956     {
12957       char *path_to_try = concat (comp_dir, SLASH_STRING,
12958                                   file_name, (char *) NULL);
12959
12960       /* NOTE: If comp_dir is a relative path, this will also try the
12961          search path, which seems useful.  */
12962       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12963                                                 path_to_try,
12964                                                 0 /*is_dwp*/,
12965                                                 1 /*search_cwd*/));
12966       xfree (path_to_try);
12967       if (abfd != NULL)
12968         return abfd;
12969     }
12970
12971   /* That didn't work, try debug-file-directory, which, despite its name,
12972      is a list of paths.  */
12973
12974   if (*debug_file_directory == '\0')
12975     return NULL;
12976
12977   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12978                              0 /*is_dwp*/, 1 /*search_cwd*/);
12979 }
12980
12981 /* This function is mapped across the sections and remembers the offset and
12982    size of each of the DWO debugging sections we are interested in.  */
12983
12984 static void
12985 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12986 {
12987   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12988   const struct dwop_section_names *names = &dwop_section_names;
12989
12990   if (section_is_p (sectp->name, &names->abbrev_dwo))
12991     {
12992       dwo_sections->abbrev.s.section = sectp;
12993       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12994     }
12995   else if (section_is_p (sectp->name, &names->info_dwo))
12996     {
12997       dwo_sections->info.s.section = sectp;
12998       dwo_sections->info.size = bfd_get_section_size (sectp);
12999     }
13000   else if (section_is_p (sectp->name, &names->line_dwo))
13001     {
13002       dwo_sections->line.s.section = sectp;
13003       dwo_sections->line.size = bfd_get_section_size (sectp);
13004     }
13005   else if (section_is_p (sectp->name, &names->loc_dwo))
13006     {
13007       dwo_sections->loc.s.section = sectp;
13008       dwo_sections->loc.size = bfd_get_section_size (sectp);
13009     }
13010   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13011     {
13012       dwo_sections->macinfo.s.section = sectp;
13013       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13014     }
13015   else if (section_is_p (sectp->name, &names->macro_dwo))
13016     {
13017       dwo_sections->macro.s.section = sectp;
13018       dwo_sections->macro.size = bfd_get_section_size (sectp);
13019     }
13020   else if (section_is_p (sectp->name, &names->str_dwo))
13021     {
13022       dwo_sections->str.s.section = sectp;
13023       dwo_sections->str.size = bfd_get_section_size (sectp);
13024     }
13025   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13026     {
13027       dwo_sections->str_offsets.s.section = sectp;
13028       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13029     }
13030   else if (section_is_p (sectp->name, &names->types_dwo))
13031     {
13032       struct dwarf2_section_info type_section;
13033
13034       memset (&type_section, 0, sizeof (type_section));
13035       type_section.s.section = sectp;
13036       type_section.size = bfd_get_section_size (sectp);
13037       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13038                      &type_section);
13039     }
13040 }
13041
13042 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13043    by PER_CU.  This is for the non-DWP case.
13044    The result is NULL if DWO_NAME can't be found.  */
13045
13046 static struct dwo_file *
13047 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13048                         const char *dwo_name, const char *comp_dir)
13049 {
13050   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13051   struct objfile *objfile = dwarf2_per_objfile->objfile;
13052   struct dwo_file *dwo_file;
13053   struct cleanup *cleanups;
13054
13055   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13056   if (dbfd == NULL)
13057     {
13058       if (dwarf_read_debug)
13059         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13060       return NULL;
13061     }
13062   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13063   dwo_file->dwo_name = dwo_name;
13064   dwo_file->comp_dir = comp_dir;
13065   dwo_file->dbfd = dbfd.release ();
13066
13067   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13068   cleanup_data->dwo_file = dwo_file;
13069   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13070
13071   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13072
13073   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13074                          &dwo_file->sections);
13075
13076   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13077                          dwo_file->cus);
13078
13079   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13080                                  dwo_file->sections.types, dwo_file->tus);
13081
13082   discard_cleanups (cleanups);
13083
13084   if (dwarf_read_debug)
13085     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13086
13087   return dwo_file;
13088 }
13089
13090 /* This function is mapped across the sections and remembers the offset and
13091    size of each of the DWP debugging sections common to version 1 and 2 that
13092    we are interested in.  */
13093
13094 static void
13095 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13096                                    void *dwp_file_ptr)
13097 {
13098   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13099   const struct dwop_section_names *names = &dwop_section_names;
13100   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13101
13102   /* Record the ELF section number for later lookup: this is what the
13103      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13104   gdb_assert (elf_section_nr < dwp_file->num_sections);
13105   dwp_file->elf_sections[elf_section_nr] = sectp;
13106
13107   /* Look for specific sections that we need.  */
13108   if (section_is_p (sectp->name, &names->str_dwo))
13109     {
13110       dwp_file->sections.str.s.section = sectp;
13111       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13112     }
13113   else if (section_is_p (sectp->name, &names->cu_index))
13114     {
13115       dwp_file->sections.cu_index.s.section = sectp;
13116       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13117     }
13118   else if (section_is_p (sectp->name, &names->tu_index))
13119     {
13120       dwp_file->sections.tu_index.s.section = sectp;
13121       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13122     }
13123 }
13124
13125 /* This function is mapped across the sections and remembers the offset and
13126    size of each of the DWP version 2 debugging sections that we are interested
13127    in.  This is split into a separate function because we don't know if we
13128    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13129
13130 static void
13131 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13132 {
13133   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13134   const struct dwop_section_names *names = &dwop_section_names;
13135   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13136
13137   /* Record the ELF section number for later lookup: this is what the
13138      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13139   gdb_assert (elf_section_nr < dwp_file->num_sections);
13140   dwp_file->elf_sections[elf_section_nr] = sectp;
13141
13142   /* Look for specific sections that we need.  */
13143   if (section_is_p (sectp->name, &names->abbrev_dwo))
13144     {
13145       dwp_file->sections.abbrev.s.section = sectp;
13146       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13147     }
13148   else if (section_is_p (sectp->name, &names->info_dwo))
13149     {
13150       dwp_file->sections.info.s.section = sectp;
13151       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13152     }
13153   else if (section_is_p (sectp->name, &names->line_dwo))
13154     {
13155       dwp_file->sections.line.s.section = sectp;
13156       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13157     }
13158   else if (section_is_p (sectp->name, &names->loc_dwo))
13159     {
13160       dwp_file->sections.loc.s.section = sectp;
13161       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13162     }
13163   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13164     {
13165       dwp_file->sections.macinfo.s.section = sectp;
13166       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13167     }
13168   else if (section_is_p (sectp->name, &names->macro_dwo))
13169     {
13170       dwp_file->sections.macro.s.section = sectp;
13171       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13172     }
13173   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13174     {
13175       dwp_file->sections.str_offsets.s.section = sectp;
13176       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13177     }
13178   else if (section_is_p (sectp->name, &names->types_dwo))
13179     {
13180       dwp_file->sections.types.s.section = sectp;
13181       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13182     }
13183 }
13184
13185 /* Hash function for dwp_file loaded CUs/TUs.  */
13186
13187 static hashval_t
13188 hash_dwp_loaded_cutus (const void *item)
13189 {
13190   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13191
13192   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13193   return dwo_unit->signature;
13194 }
13195
13196 /* Equality function for dwp_file loaded CUs/TUs.  */
13197
13198 static int
13199 eq_dwp_loaded_cutus (const void *a, const void *b)
13200 {
13201   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13202   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13203
13204   return dua->signature == dub->signature;
13205 }
13206
13207 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13208
13209 static htab_t
13210 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13211 {
13212   return htab_create_alloc_ex (3,
13213                                hash_dwp_loaded_cutus,
13214                                eq_dwp_loaded_cutus,
13215                                NULL,
13216                                &objfile->objfile_obstack,
13217                                hashtab_obstack_allocate,
13218                                dummy_obstack_deallocate);
13219 }
13220
13221 /* Try to open DWP file FILE_NAME.
13222    The result is the bfd handle of the file.
13223    If there is a problem finding or opening the file, return NULL.
13224    Upon success, the canonicalized path of the file is stored in the bfd,
13225    same as symfile_bfd_open.  */
13226
13227 static gdb_bfd_ref_ptr
13228 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13229                const char *file_name)
13230 {
13231   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13232                                             1 /*is_dwp*/,
13233                                             1 /*search_cwd*/));
13234   if (abfd != NULL)
13235     return abfd;
13236
13237   /* Work around upstream bug 15652.
13238      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13239      [Whether that's a "bug" is debatable, but it is getting in our way.]
13240      We have no real idea where the dwp file is, because gdb's realpath-ing
13241      of the executable's path may have discarded the needed info.
13242      [IWBN if the dwp file name was recorded in the executable, akin to
13243      .gnu_debuglink, but that doesn't exist yet.]
13244      Strip the directory from FILE_NAME and search again.  */
13245   if (*debug_file_directory != '\0')
13246     {
13247       /* Don't implicitly search the current directory here.
13248          If the user wants to search "." to handle this case,
13249          it must be added to debug-file-directory.  */
13250       return try_open_dwop_file (dwarf2_per_objfile,
13251                                  lbasename (file_name), 1 /*is_dwp*/,
13252                                  0 /*search_cwd*/);
13253     }
13254
13255   return NULL;
13256 }
13257
13258 /* Initialize the use of the DWP file for the current objfile.
13259    By convention the name of the DWP file is ${objfile}.dwp.
13260    The result is NULL if it can't be found.  */
13261
13262 static struct dwp_file *
13263 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13264 {
13265   struct objfile *objfile = dwarf2_per_objfile->objfile;
13266   struct dwp_file *dwp_file;
13267
13268   /* Try to find first .dwp for the binary file before any symbolic links
13269      resolving.  */
13270
13271   /* If the objfile is a debug file, find the name of the real binary
13272      file and get the name of dwp file from there.  */
13273   std::string dwp_name;
13274   if (objfile->separate_debug_objfile_backlink != NULL)
13275     {
13276       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13277       const char *backlink_basename = lbasename (backlink->original_name);
13278
13279       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13280     }
13281   else
13282     dwp_name = objfile->original_name;
13283
13284   dwp_name += ".dwp";
13285
13286   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13287   if (dbfd == NULL
13288       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13289     {
13290       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13291       dwp_name = objfile_name (objfile);
13292       dwp_name += ".dwp";
13293       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13294     }
13295
13296   if (dbfd == NULL)
13297     {
13298       if (dwarf_read_debug)
13299         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13300       return NULL;
13301     }
13302   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13303   dwp_file->name = bfd_get_filename (dbfd.get ());
13304   dwp_file->dbfd = dbfd.release ();
13305
13306   /* +1: section 0 is unused */
13307   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13308   dwp_file->elf_sections =
13309     OBSTACK_CALLOC (&objfile->objfile_obstack,
13310                     dwp_file->num_sections, asection *);
13311
13312   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13313                          dwp_file);
13314
13315   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13316
13317   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13318
13319   /* The DWP file version is stored in the hash table.  Oh well.  */
13320   if (dwp_file->cus && dwp_file->tus
13321       && dwp_file->cus->version != dwp_file->tus->version)
13322     {
13323       /* Technically speaking, we should try to limp along, but this is
13324          pretty bizarre.  We use pulongest here because that's the established
13325          portability solution (e.g, we cannot use %u for uint32_t).  */
13326       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13327                " TU version %s [in DWP file %s]"),
13328              pulongest (dwp_file->cus->version),
13329              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13330     }
13331
13332   if (dwp_file->cus)
13333     dwp_file->version = dwp_file->cus->version;
13334   else if (dwp_file->tus)
13335     dwp_file->version = dwp_file->tus->version;
13336   else
13337     dwp_file->version = 2;
13338
13339   if (dwp_file->version == 2)
13340     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13341                            dwp_file);
13342
13343   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13344   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13345
13346   if (dwarf_read_debug)
13347     {
13348       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13349       fprintf_unfiltered (gdb_stdlog,
13350                           "    %s CUs, %s TUs\n",
13351                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13352                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13353     }
13354
13355   return dwp_file;
13356 }
13357
13358 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13359
13360 static struct dwp_file *
13361 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13362 {
13363   if (! dwarf2_per_objfile->dwp_checked)
13364     {
13365       dwarf2_per_objfile->dwp_file
13366         = open_and_init_dwp_file (dwarf2_per_objfile);
13367       dwarf2_per_objfile->dwp_checked = 1;
13368     }
13369   return dwarf2_per_objfile->dwp_file;
13370 }
13371
13372 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13373    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13374    or in the DWP file for the objfile, referenced by THIS_UNIT.
13375    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13376    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13377
13378    This is called, for example, when wanting to read a variable with a
13379    complex location.  Therefore we don't want to do file i/o for every call.
13380    Therefore we don't want to look for a DWO file on every call.
13381    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13382    then we check if we've already seen DWO_NAME, and only THEN do we check
13383    for a DWO file.
13384
13385    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13386    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13387
13388 static struct dwo_unit *
13389 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13390                  const char *dwo_name, const char *comp_dir,
13391                  ULONGEST signature, int is_debug_types)
13392 {
13393   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13394   struct objfile *objfile = dwarf2_per_objfile->objfile;
13395   const char *kind = is_debug_types ? "TU" : "CU";
13396   void **dwo_file_slot;
13397   struct dwo_file *dwo_file;
13398   struct dwp_file *dwp_file;
13399
13400   /* First see if there's a DWP file.
13401      If we have a DWP file but didn't find the DWO inside it, don't
13402      look for the original DWO file.  It makes gdb behave differently
13403      depending on whether one is debugging in the build tree.  */
13404
13405   dwp_file = get_dwp_file (dwarf2_per_objfile);
13406   if (dwp_file != NULL)
13407     {
13408       const struct dwp_hash_table *dwp_htab =
13409         is_debug_types ? dwp_file->tus : dwp_file->cus;
13410
13411       if (dwp_htab != NULL)
13412         {
13413           struct dwo_unit *dwo_cutu =
13414             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13415                                     signature, is_debug_types);
13416
13417           if (dwo_cutu != NULL)
13418             {
13419               if (dwarf_read_debug)
13420                 {
13421                   fprintf_unfiltered (gdb_stdlog,
13422                                       "Virtual DWO %s %s found: @%s\n",
13423                                       kind, hex_string (signature),
13424                                       host_address_to_string (dwo_cutu));
13425                 }
13426               return dwo_cutu;
13427             }
13428         }
13429     }
13430   else
13431     {
13432       /* No DWP file, look for the DWO file.  */
13433
13434       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13435                                             dwo_name, comp_dir);
13436       if (*dwo_file_slot == NULL)
13437         {
13438           /* Read in the file and build a table of the CUs/TUs it contains.  */
13439           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13440         }
13441       /* NOTE: This will be NULL if unable to open the file.  */
13442       dwo_file = (struct dwo_file *) *dwo_file_slot;
13443
13444       if (dwo_file != NULL)
13445         {
13446           struct dwo_unit *dwo_cutu = NULL;
13447
13448           if (is_debug_types && dwo_file->tus)
13449             {
13450               struct dwo_unit find_dwo_cutu;
13451
13452               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13453               find_dwo_cutu.signature = signature;
13454               dwo_cutu
13455                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13456             }
13457           else if (!is_debug_types && dwo_file->cus)
13458             {
13459               struct dwo_unit find_dwo_cutu;
13460
13461               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13462               find_dwo_cutu.signature = signature;
13463               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13464                                                        &find_dwo_cutu);
13465             }
13466
13467           if (dwo_cutu != NULL)
13468             {
13469               if (dwarf_read_debug)
13470                 {
13471                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13472                                       kind, dwo_name, hex_string (signature),
13473                                       host_address_to_string (dwo_cutu));
13474                 }
13475               return dwo_cutu;
13476             }
13477         }
13478     }
13479
13480   /* We didn't find it.  This could mean a dwo_id mismatch, or
13481      someone deleted the DWO/DWP file, or the search path isn't set up
13482      correctly to find the file.  */
13483
13484   if (dwarf_read_debug)
13485     {
13486       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13487                           kind, dwo_name, hex_string (signature));
13488     }
13489
13490   /* This is a warning and not a complaint because it can be caused by
13491      pilot error (e.g., user accidentally deleting the DWO).  */
13492   {
13493     /* Print the name of the DWP file if we looked there, helps the user
13494        better diagnose the problem.  */
13495     std::string dwp_text;
13496
13497     if (dwp_file != NULL)
13498       dwp_text = string_printf (" [in DWP file %s]",
13499                                 lbasename (dwp_file->name));
13500
13501     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13502                " [in module %s]"),
13503              kind, dwo_name, hex_string (signature),
13504              dwp_text.c_str (),
13505              this_unit->is_debug_types ? "TU" : "CU",
13506              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13507   }
13508   return NULL;
13509 }
13510
13511 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13512    See lookup_dwo_cutu_unit for details.  */
13513
13514 static struct dwo_unit *
13515 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13516                       const char *dwo_name, const char *comp_dir,
13517                       ULONGEST signature)
13518 {
13519   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13520 }
13521
13522 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13523    See lookup_dwo_cutu_unit for details.  */
13524
13525 static struct dwo_unit *
13526 lookup_dwo_type_unit (struct signatured_type *this_tu,
13527                       const char *dwo_name, const char *comp_dir)
13528 {
13529   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13530 }
13531
13532 /* Traversal function for queue_and_load_all_dwo_tus.  */
13533
13534 static int
13535 queue_and_load_dwo_tu (void **slot, void *info)
13536 {
13537   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13538   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13539   ULONGEST signature = dwo_unit->signature;
13540   struct signatured_type *sig_type =
13541     lookup_dwo_signatured_type (per_cu->cu, signature);
13542
13543   if (sig_type != NULL)
13544     {
13545       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13546
13547       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13548          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13549          while processing PER_CU.  */
13550       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13551         load_full_type_unit (sig_cu);
13552       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13553     }
13554
13555   return 1;
13556 }
13557
13558 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13559    The DWO may have the only definition of the type, though it may not be
13560    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13561    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13562
13563 static void
13564 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13565 {
13566   struct dwo_unit *dwo_unit;
13567   struct dwo_file *dwo_file;
13568
13569   gdb_assert (!per_cu->is_debug_types);
13570   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13571   gdb_assert (per_cu->cu != NULL);
13572
13573   dwo_unit = per_cu->cu->dwo_unit;
13574   gdb_assert (dwo_unit != NULL);
13575
13576   dwo_file = dwo_unit->dwo_file;
13577   if (dwo_file->tus != NULL)
13578     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13579 }
13580
13581 /* Free all resources associated with DWO_FILE.
13582    Close the DWO file and munmap the sections.
13583    All memory should be on the objfile obstack.  */
13584
13585 static void
13586 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13587 {
13588
13589   /* Note: dbfd is NULL for virtual DWO files.  */
13590   gdb_bfd_unref (dwo_file->dbfd);
13591
13592   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13593 }
13594
13595 /* Wrapper for free_dwo_file for use in cleanups.  */
13596
13597 static void
13598 free_dwo_file_cleanup (void *arg)
13599 {
13600   struct free_dwo_file_cleanup_data *data
13601     = (struct free_dwo_file_cleanup_data *) arg;
13602   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13603
13604   free_dwo_file (data->dwo_file, objfile);
13605
13606   xfree (data);
13607 }
13608
13609 /* Traversal function for free_dwo_files.  */
13610
13611 static int
13612 free_dwo_file_from_slot (void **slot, void *info)
13613 {
13614   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13615   struct objfile *objfile = (struct objfile *) info;
13616
13617   free_dwo_file (dwo_file, objfile);
13618
13619   return 1;
13620 }
13621
13622 /* Free all resources associated with DWO_FILES.  */
13623
13624 static void
13625 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13626 {
13627   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13628 }
13629 \f
13630 /* Read in various DIEs.  */
13631
13632 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13633    Inherit only the children of the DW_AT_abstract_origin DIE not being
13634    already referenced by DW_AT_abstract_origin from the children of the
13635    current DIE.  */
13636
13637 static void
13638 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13639 {
13640   struct die_info *child_die;
13641   sect_offset *offsetp;
13642   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13643   struct die_info *origin_die;
13644   /* Iterator of the ORIGIN_DIE children.  */
13645   struct die_info *origin_child_die;
13646   struct attribute *attr;
13647   struct dwarf2_cu *origin_cu;
13648   struct pending **origin_previous_list_in_scope;
13649
13650   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13651   if (!attr)
13652     return;
13653
13654   /* Note that following die references may follow to a die in a
13655      different cu.  */
13656
13657   origin_cu = cu;
13658   origin_die = follow_die_ref (die, attr, &origin_cu);
13659
13660   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13661      symbols in.  */
13662   origin_previous_list_in_scope = origin_cu->list_in_scope;
13663   origin_cu->list_in_scope = cu->list_in_scope;
13664
13665   if (die->tag != origin_die->tag
13666       && !(die->tag == DW_TAG_inlined_subroutine
13667            && origin_die->tag == DW_TAG_subprogram))
13668     complaint (&symfile_complaints,
13669                _("DIE %s and its abstract origin %s have different tags"),
13670                sect_offset_str (die->sect_off),
13671                sect_offset_str (origin_die->sect_off));
13672
13673   std::vector<sect_offset> offsets;
13674
13675   for (child_die = die->child;
13676        child_die && child_die->tag;
13677        child_die = sibling_die (child_die))
13678     {
13679       struct die_info *child_origin_die;
13680       struct dwarf2_cu *child_origin_cu;
13681
13682       /* We are trying to process concrete instance entries:
13683          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13684          it's not relevant to our analysis here. i.e. detecting DIEs that are
13685          present in the abstract instance but not referenced in the concrete
13686          one.  */
13687       if (child_die->tag == DW_TAG_call_site
13688           || child_die->tag == DW_TAG_GNU_call_site)
13689         continue;
13690
13691       /* For each CHILD_DIE, find the corresponding child of
13692          ORIGIN_DIE.  If there is more than one layer of
13693          DW_AT_abstract_origin, follow them all; there shouldn't be,
13694          but GCC versions at least through 4.4 generate this (GCC PR
13695          40573).  */
13696       child_origin_die = child_die;
13697       child_origin_cu = cu;
13698       while (1)
13699         {
13700           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13701                               child_origin_cu);
13702           if (attr == NULL)
13703             break;
13704           child_origin_die = follow_die_ref (child_origin_die, attr,
13705                                              &child_origin_cu);
13706         }
13707
13708       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13709          counterpart may exist.  */
13710       if (child_origin_die != child_die)
13711         {
13712           if (child_die->tag != child_origin_die->tag
13713               && !(child_die->tag == DW_TAG_inlined_subroutine
13714                    && child_origin_die->tag == DW_TAG_subprogram))
13715             complaint (&symfile_complaints,
13716                        _("Child DIE %s and its abstract origin %s have "
13717                          "different tags"),
13718                        sect_offset_str (child_die->sect_off),
13719                        sect_offset_str (child_origin_die->sect_off));
13720           if (child_origin_die->parent != origin_die)
13721             complaint (&symfile_complaints,
13722                        _("Child DIE %s and its abstract origin %s have "
13723                          "different parents"),
13724                        sect_offset_str (child_die->sect_off),
13725                        sect_offset_str (child_origin_die->sect_off));
13726           else
13727             offsets.push_back (child_origin_die->sect_off);
13728         }
13729     }
13730   std::sort (offsets.begin (), offsets.end ());
13731   sect_offset *offsets_end = offsets.data () + offsets.size ();
13732   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13733     if (offsetp[-1] == *offsetp)
13734       complaint (&symfile_complaints,
13735                  _("Multiple children of DIE %s refer "
13736                    "to DIE %s as their abstract origin"),
13737                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13738
13739   offsetp = offsets.data ();
13740   origin_child_die = origin_die->child;
13741   while (origin_child_die && origin_child_die->tag)
13742     {
13743       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13744       while (offsetp < offsets_end
13745              && *offsetp < origin_child_die->sect_off)
13746         offsetp++;
13747       if (offsetp >= offsets_end
13748           || *offsetp > origin_child_die->sect_off)
13749         {
13750           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13751              Check whether we're already processing ORIGIN_CHILD_DIE.
13752              This can happen with mutually referenced abstract_origins.
13753              PR 16581.  */
13754           if (!origin_child_die->in_process)
13755             process_die (origin_child_die, origin_cu);
13756         }
13757       origin_child_die = sibling_die (origin_child_die);
13758     }
13759   origin_cu->list_in_scope = origin_previous_list_in_scope;
13760 }
13761
13762 static void
13763 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13764 {
13765   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13766   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13767   struct context_stack *newobj;
13768   CORE_ADDR lowpc;
13769   CORE_ADDR highpc;
13770   struct die_info *child_die;
13771   struct attribute *attr, *call_line, *call_file;
13772   const char *name;
13773   CORE_ADDR baseaddr;
13774   struct block *block;
13775   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13776   std::vector<struct symbol *> template_args;
13777   struct template_symbol *templ_func = NULL;
13778
13779   if (inlined_func)
13780     {
13781       /* If we do not have call site information, we can't show the
13782          caller of this inlined function.  That's too confusing, so
13783          only use the scope for local variables.  */
13784       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13785       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13786       if (call_line == NULL || call_file == NULL)
13787         {
13788           read_lexical_block_scope (die, cu);
13789           return;
13790         }
13791     }
13792
13793   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13794
13795   name = dwarf2_name (die, cu);
13796
13797   /* Ignore functions with missing or empty names.  These are actually
13798      illegal according to the DWARF standard.  */
13799   if (name == NULL)
13800     {
13801       complaint (&symfile_complaints,
13802                  _("missing name for subprogram DIE at %s"),
13803                  sect_offset_str (die->sect_off));
13804       return;
13805     }
13806
13807   /* Ignore functions with missing or invalid low and high pc attributes.  */
13808   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13809       <= PC_BOUNDS_INVALID)
13810     {
13811       attr = dwarf2_attr (die, DW_AT_external, cu);
13812       if (!attr || !DW_UNSND (attr))
13813         complaint (&symfile_complaints,
13814                    _("cannot get low and high bounds "
13815                      "for subprogram DIE at %s"),
13816                    sect_offset_str (die->sect_off));
13817       return;
13818     }
13819
13820   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13821   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13822
13823   /* If we have any template arguments, then we must allocate a
13824      different sort of symbol.  */
13825   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13826     {
13827       if (child_die->tag == DW_TAG_template_type_param
13828           || child_die->tag == DW_TAG_template_value_param)
13829         {
13830           templ_func = allocate_template_symbol (objfile);
13831           templ_func->subclass = SYMBOL_TEMPLATE;
13832           break;
13833         }
13834     }
13835
13836   newobj = push_context (0, lowpc);
13837   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13838                              (struct symbol *) templ_func);
13839
13840   /* If there is a location expression for DW_AT_frame_base, record
13841      it.  */
13842   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13843   if (attr)
13844     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13845
13846   /* If there is a location for the static link, record it.  */
13847   newobj->static_link = NULL;
13848   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13849   if (attr)
13850     {
13851       newobj->static_link
13852         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13853       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13854     }
13855
13856   cu->list_in_scope = &local_symbols;
13857
13858   if (die->child != NULL)
13859     {
13860       child_die = die->child;
13861       while (child_die && child_die->tag)
13862         {
13863           if (child_die->tag == DW_TAG_template_type_param
13864               || child_die->tag == DW_TAG_template_value_param)
13865             {
13866               struct symbol *arg = new_symbol (child_die, NULL, cu);
13867
13868               if (arg != NULL)
13869                 template_args.push_back (arg);
13870             }
13871           else
13872             process_die (child_die, cu);
13873           child_die = sibling_die (child_die);
13874         }
13875     }
13876
13877   inherit_abstract_dies (die, cu);
13878
13879   /* If we have a DW_AT_specification, we might need to import using
13880      directives from the context of the specification DIE.  See the
13881      comment in determine_prefix.  */
13882   if (cu->language == language_cplus
13883       && dwarf2_attr (die, DW_AT_specification, cu))
13884     {
13885       struct dwarf2_cu *spec_cu = cu;
13886       struct die_info *spec_die = die_specification (die, &spec_cu);
13887
13888       while (spec_die)
13889         {
13890           child_die = spec_die->child;
13891           while (child_die && child_die->tag)
13892             {
13893               if (child_die->tag == DW_TAG_imported_module)
13894                 process_die (child_die, spec_cu);
13895               child_die = sibling_die (child_die);
13896             }
13897
13898           /* In some cases, GCC generates specification DIEs that
13899              themselves contain DW_AT_specification attributes.  */
13900           spec_die = die_specification (spec_die, &spec_cu);
13901         }
13902     }
13903
13904   newobj = pop_context ();
13905   /* Make a block for the local symbols within.  */
13906   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13907                         newobj->static_link, lowpc, highpc);
13908
13909   /* For C++, set the block's scope.  */
13910   if ((cu->language == language_cplus
13911        || cu->language == language_fortran
13912        || cu->language == language_d
13913        || cu->language == language_rust)
13914       && cu->processing_has_namespace_info)
13915     block_set_scope (block, determine_prefix (die, cu),
13916                      &objfile->objfile_obstack);
13917
13918   /* If we have address ranges, record them.  */
13919   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13920
13921   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13922
13923   /* Attach template arguments to function.  */
13924   if (!template_args.empty ())
13925     {
13926       gdb_assert (templ_func != NULL);
13927
13928       templ_func->n_template_arguments = template_args.size ();
13929       templ_func->template_arguments
13930         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13931                      templ_func->n_template_arguments);
13932       memcpy (templ_func->template_arguments,
13933               template_args.data (),
13934               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13935     }
13936
13937   /* In C++, we can have functions nested inside functions (e.g., when
13938      a function declares a class that has methods).  This means that
13939      when we finish processing a function scope, we may need to go
13940      back to building a containing block's symbol lists.  */
13941   local_symbols = newobj->locals;
13942   local_using_directives = newobj->local_using_directives;
13943
13944   /* If we've finished processing a top-level function, subsequent
13945      symbols go in the file symbol list.  */
13946   if (outermost_context_p ())
13947     cu->list_in_scope = &file_symbols;
13948 }
13949
13950 /* Process all the DIES contained within a lexical block scope.  Start
13951    a new scope, process the dies, and then close the scope.  */
13952
13953 static void
13954 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13955 {
13956   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13957   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13958   struct context_stack *newobj;
13959   CORE_ADDR lowpc, highpc;
13960   struct die_info *child_die;
13961   CORE_ADDR baseaddr;
13962
13963   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13964
13965   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13966   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13967      as multiple lexical blocks?  Handling children in a sane way would
13968      be nasty.  Might be easier to properly extend generic blocks to
13969      describe ranges.  */
13970   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13971     {
13972     case PC_BOUNDS_NOT_PRESENT:
13973       /* DW_TAG_lexical_block has no attributes, process its children as if
13974          there was no wrapping by that DW_TAG_lexical_block.
13975          GCC does no longer produces such DWARF since GCC r224161.  */
13976       for (child_die = die->child;
13977            child_die != NULL && child_die->tag;
13978            child_die = sibling_die (child_die))
13979         process_die (child_die, cu);
13980       return;
13981     case PC_BOUNDS_INVALID:
13982       return;
13983     }
13984   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13985   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13986
13987   push_context (0, lowpc);
13988   if (die->child != NULL)
13989     {
13990       child_die = die->child;
13991       while (child_die && child_die->tag)
13992         {
13993           process_die (child_die, cu);
13994           child_die = sibling_die (child_die);
13995         }
13996     }
13997   inherit_abstract_dies (die, cu);
13998   newobj = pop_context ();
13999
14000   if (local_symbols != NULL || local_using_directives != NULL)
14001     {
14002       struct block *block
14003         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14004                         newobj->start_addr, highpc);
14005
14006       /* Note that recording ranges after traversing children, as we
14007          do here, means that recording a parent's ranges entails
14008          walking across all its children's ranges as they appear in
14009          the address map, which is quadratic behavior.
14010
14011          It would be nicer to record the parent's ranges before
14012          traversing its children, simply overriding whatever you find
14013          there.  But since we don't even decide whether to create a
14014          block until after we've traversed its children, that's hard
14015          to do.  */
14016       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14017     }
14018   local_symbols = newobj->locals;
14019   local_using_directives = newobj->local_using_directives;
14020 }
14021
14022 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14023
14024 static void
14025 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14026 {
14027   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14028   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14029   CORE_ADDR pc, baseaddr;
14030   struct attribute *attr;
14031   struct call_site *call_site, call_site_local;
14032   void **slot;
14033   int nparams;
14034   struct die_info *child_die;
14035
14036   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14037
14038   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14039   if (attr == NULL)
14040     {
14041       /* This was a pre-DWARF-5 GNU extension alias
14042          for DW_AT_call_return_pc.  */
14043       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14044     }
14045   if (!attr)
14046     {
14047       complaint (&symfile_complaints,
14048                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14049                    "DIE %s [in module %s]"),
14050                  sect_offset_str (die->sect_off), objfile_name (objfile));
14051       return;
14052     }
14053   pc = attr_value_as_address (attr) + baseaddr;
14054   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14055
14056   if (cu->call_site_htab == NULL)
14057     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14058                                                NULL, &objfile->objfile_obstack,
14059                                                hashtab_obstack_allocate, NULL);
14060   call_site_local.pc = pc;
14061   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14062   if (*slot != NULL)
14063     {
14064       complaint (&symfile_complaints,
14065                  _("Duplicate PC %s for DW_TAG_call_site "
14066                    "DIE %s [in module %s]"),
14067                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
14068                  objfile_name (objfile));
14069       return;
14070     }
14071
14072   /* Count parameters at the caller.  */
14073
14074   nparams = 0;
14075   for (child_die = die->child; child_die && child_die->tag;
14076        child_die = sibling_die (child_die))
14077     {
14078       if (child_die->tag != DW_TAG_call_site_parameter
14079           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14080         {
14081           complaint (&symfile_complaints,
14082                      _("Tag %d is not DW_TAG_call_site_parameter in "
14083                        "DW_TAG_call_site child DIE %s [in module %s]"),
14084                      child_die->tag, sect_offset_str (child_die->sect_off),
14085                      objfile_name (objfile));
14086           continue;
14087         }
14088
14089       nparams++;
14090     }
14091
14092   call_site
14093     = ((struct call_site *)
14094        obstack_alloc (&objfile->objfile_obstack,
14095                       sizeof (*call_site)
14096                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14097   *slot = call_site;
14098   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14099   call_site->pc = pc;
14100
14101   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14102       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14103     {
14104       struct die_info *func_die;
14105
14106       /* Skip also over DW_TAG_inlined_subroutine.  */
14107       for (func_die = die->parent;
14108            func_die && func_die->tag != DW_TAG_subprogram
14109            && func_die->tag != DW_TAG_subroutine_type;
14110            func_die = func_die->parent);
14111
14112       /* DW_AT_call_all_calls is a superset
14113          of DW_AT_call_all_tail_calls.  */
14114       if (func_die
14115           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14116           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14117           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14118           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14119         {
14120           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14121              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14122              both the initial caller containing the real return address PC and
14123              the final callee containing the current PC of a chain of tail
14124              calls do not need to have the tail call list complete.  But any
14125              function candidate for a virtual tail call frame searched via
14126              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14127              determined unambiguously.  */
14128         }
14129       else
14130         {
14131           struct type *func_type = NULL;
14132
14133           if (func_die)
14134             func_type = get_die_type (func_die, cu);
14135           if (func_type != NULL)
14136             {
14137               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14138
14139               /* Enlist this call site to the function.  */
14140               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14141               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14142             }
14143           else
14144             complaint (&symfile_complaints,
14145                        _("Cannot find function owning DW_TAG_call_site "
14146                          "DIE %s [in module %s]"),
14147                        sect_offset_str (die->sect_off), objfile_name (objfile));
14148         }
14149     }
14150
14151   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14152   if (attr == NULL)
14153     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14154   if (attr == NULL)
14155     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14156   if (attr == NULL)
14157     {
14158       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14159       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14160     }
14161   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14162   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14163     /* Keep NULL DWARF_BLOCK.  */;
14164   else if (attr_form_is_block (attr))
14165     {
14166       struct dwarf2_locexpr_baton *dlbaton;
14167
14168       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14169       dlbaton->data = DW_BLOCK (attr)->data;
14170       dlbaton->size = DW_BLOCK (attr)->size;
14171       dlbaton->per_cu = cu->per_cu;
14172
14173       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14174     }
14175   else if (attr_form_is_ref (attr))
14176     {
14177       struct dwarf2_cu *target_cu = cu;
14178       struct die_info *target_die;
14179
14180       target_die = follow_die_ref (die, attr, &target_cu);
14181       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14182       if (die_is_declaration (target_die, target_cu))
14183         {
14184           const char *target_physname;
14185
14186           /* Prefer the mangled name; otherwise compute the demangled one.  */
14187           target_physname = dw2_linkage_name (target_die, target_cu);
14188           if (target_physname == NULL)
14189             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14190           if (target_physname == NULL)
14191             complaint (&symfile_complaints,
14192                        _("DW_AT_call_target target DIE has invalid "
14193                          "physname, for referencing DIE %s [in module %s]"),
14194                        sect_offset_str (die->sect_off), objfile_name (objfile));
14195           else
14196             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14197         }
14198       else
14199         {
14200           CORE_ADDR lowpc;
14201
14202           /* DW_AT_entry_pc should be preferred.  */
14203           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14204               <= PC_BOUNDS_INVALID)
14205             complaint (&symfile_complaints,
14206                        _("DW_AT_call_target target DIE has invalid "
14207                          "low pc, for referencing DIE %s [in module %s]"),
14208                        sect_offset_str (die->sect_off), objfile_name (objfile));
14209           else
14210             {
14211               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14212               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14213             }
14214         }
14215     }
14216   else
14217     complaint (&symfile_complaints,
14218                _("DW_TAG_call_site DW_AT_call_target is neither "
14219                  "block nor reference, for DIE %s [in module %s]"),
14220                sect_offset_str (die->sect_off), objfile_name (objfile));
14221
14222   call_site->per_cu = cu->per_cu;
14223
14224   for (child_die = die->child;
14225        child_die && child_die->tag;
14226        child_die = sibling_die (child_die))
14227     {
14228       struct call_site_parameter *parameter;
14229       struct attribute *loc, *origin;
14230
14231       if (child_die->tag != DW_TAG_call_site_parameter
14232           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14233         {
14234           /* Already printed the complaint above.  */
14235           continue;
14236         }
14237
14238       gdb_assert (call_site->parameter_count < nparams);
14239       parameter = &call_site->parameter[call_site->parameter_count];
14240
14241       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14242          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14243          register is contained in DW_AT_call_value.  */
14244
14245       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14246       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14247       if (origin == NULL)
14248         {
14249           /* This was a pre-DWARF-5 GNU extension alias
14250              for DW_AT_call_parameter.  */
14251           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14252         }
14253       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14254         {
14255           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14256
14257           sect_offset sect_off
14258             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14259           if (!offset_in_cu_p (&cu->header, sect_off))
14260             {
14261               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14262                  binding can be done only inside one CU.  Such referenced DIE
14263                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14264               complaint (&symfile_complaints,
14265                          _("DW_AT_call_parameter offset is not in CU for "
14266                            "DW_TAG_call_site child DIE %s [in module %s]"),
14267                          sect_offset_str (child_die->sect_off),
14268                          objfile_name (objfile));
14269               continue;
14270             }
14271           parameter->u.param_cu_off
14272             = (cu_offset) (sect_off - cu->header.sect_off);
14273         }
14274       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14275         {
14276           complaint (&symfile_complaints,
14277                      _("No DW_FORM_block* DW_AT_location for "
14278                        "DW_TAG_call_site child DIE %s [in module %s]"),
14279                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14280           continue;
14281         }
14282       else
14283         {
14284           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14285             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14286           if (parameter->u.dwarf_reg != -1)
14287             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14288           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14289                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14290                                              &parameter->u.fb_offset))
14291             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14292           else
14293             {
14294               complaint (&symfile_complaints,
14295                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14296                            "for DW_FORM_block* DW_AT_location is supported for "
14297                            "DW_TAG_call_site child DIE %s "
14298                            "[in module %s]"),
14299                          sect_offset_str (child_die->sect_off),
14300                          objfile_name (objfile));
14301               continue;
14302             }
14303         }
14304
14305       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14306       if (attr == NULL)
14307         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14308       if (!attr_form_is_block (attr))
14309         {
14310           complaint (&symfile_complaints,
14311                      _("No DW_FORM_block* DW_AT_call_value for "
14312                        "DW_TAG_call_site child DIE %s [in module %s]"),
14313                      sect_offset_str (child_die->sect_off),
14314                      objfile_name (objfile));
14315           continue;
14316         }
14317       parameter->value = DW_BLOCK (attr)->data;
14318       parameter->value_size = DW_BLOCK (attr)->size;
14319
14320       /* Parameters are not pre-cleared by memset above.  */
14321       parameter->data_value = NULL;
14322       parameter->data_value_size = 0;
14323       call_site->parameter_count++;
14324
14325       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14326       if (attr == NULL)
14327         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14328       if (attr)
14329         {
14330           if (!attr_form_is_block (attr))
14331             complaint (&symfile_complaints,
14332                        _("No DW_FORM_block* DW_AT_call_data_value for "
14333                          "DW_TAG_call_site child DIE %s [in module %s]"),
14334                        sect_offset_str (child_die->sect_off),
14335                        objfile_name (objfile));
14336           else
14337             {
14338               parameter->data_value = DW_BLOCK (attr)->data;
14339               parameter->data_value_size = DW_BLOCK (attr)->size;
14340             }
14341         }
14342     }
14343 }
14344
14345 /* Helper function for read_variable.  If DIE represents a virtual
14346    table, then return the type of the concrete object that is
14347    associated with the virtual table.  Otherwise, return NULL.  */
14348
14349 static struct type *
14350 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14351 {
14352   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14353   if (attr == NULL)
14354     return NULL;
14355
14356   /* Find the type DIE.  */
14357   struct die_info *type_die = NULL;
14358   struct dwarf2_cu *type_cu = cu;
14359
14360   if (attr_form_is_ref (attr))
14361     type_die = follow_die_ref (die, attr, &type_cu);
14362   if (type_die == NULL)
14363     return NULL;
14364
14365   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14366     return NULL;
14367   return die_containing_type (type_die, type_cu);
14368 }
14369
14370 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14371
14372 static void
14373 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14374 {
14375   struct rust_vtable_symbol *storage = NULL;
14376
14377   if (cu->language == language_rust)
14378     {
14379       struct type *containing_type = rust_containing_type (die, cu);
14380
14381       if (containing_type != NULL)
14382         {
14383           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14384
14385           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14386                                     struct rust_vtable_symbol);
14387           initialize_objfile_symbol (storage);
14388           storage->concrete_type = containing_type;
14389           storage->subclass = SYMBOL_RUST_VTABLE;
14390         }
14391     }
14392
14393   new_symbol (die, NULL, cu, storage);
14394 }
14395
14396 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14397    reading .debug_rnglists.
14398    Callback's type should be:
14399     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14400    Return true if the attributes are present and valid, otherwise,
14401    return false.  */
14402
14403 template <typename Callback>
14404 static bool
14405 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14406                          Callback &&callback)
14407 {
14408   struct dwarf2_per_objfile *dwarf2_per_objfile
14409     = cu->per_cu->dwarf2_per_objfile;
14410   struct objfile *objfile = dwarf2_per_objfile->objfile;
14411   bfd *obfd = objfile->obfd;
14412   /* Base address selection entry.  */
14413   CORE_ADDR base;
14414   int found_base;
14415   const gdb_byte *buffer;
14416   CORE_ADDR baseaddr;
14417   bool overflow = false;
14418
14419   found_base = cu->base_known;
14420   base = cu->base_address;
14421
14422   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14423   if (offset >= dwarf2_per_objfile->rnglists.size)
14424     {
14425       complaint (&symfile_complaints,
14426                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14427                  offset);
14428       return false;
14429     }
14430   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14431
14432   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14433
14434   while (1)
14435     {
14436       /* Initialize it due to a false compiler warning.  */
14437       CORE_ADDR range_beginning = 0, range_end = 0;
14438       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14439                                  + dwarf2_per_objfile->rnglists.size);
14440       unsigned int bytes_read;
14441
14442       if (buffer == buf_end)
14443         {
14444           overflow = true;
14445           break;
14446         }
14447       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14448       switch (rlet)
14449         {
14450         case DW_RLE_end_of_list:
14451           break;
14452         case DW_RLE_base_address:
14453           if (buffer + cu->header.addr_size > buf_end)
14454             {
14455               overflow = true;
14456               break;
14457             }
14458           base = read_address (obfd, buffer, cu, &bytes_read);
14459           found_base = 1;
14460           buffer += bytes_read;
14461           break;
14462         case DW_RLE_start_length:
14463           if (buffer + cu->header.addr_size > buf_end)
14464             {
14465               overflow = true;
14466               break;
14467             }
14468           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14469           buffer += bytes_read;
14470           range_end = (range_beginning
14471                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14472           buffer += bytes_read;
14473           if (buffer > buf_end)
14474             {
14475               overflow = true;
14476               break;
14477             }
14478           break;
14479         case DW_RLE_offset_pair:
14480           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14481           buffer += bytes_read;
14482           if (buffer > buf_end)
14483             {
14484               overflow = true;
14485               break;
14486             }
14487           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14488           buffer += bytes_read;
14489           if (buffer > buf_end)
14490             {
14491               overflow = true;
14492               break;
14493             }
14494           break;
14495         case DW_RLE_start_end:
14496           if (buffer + 2 * cu->header.addr_size > buf_end)
14497             {
14498               overflow = true;
14499               break;
14500             }
14501           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14502           buffer += bytes_read;
14503           range_end = read_address (obfd, buffer, cu, &bytes_read);
14504           buffer += bytes_read;
14505           break;
14506         default:
14507           complaint (&symfile_complaints,
14508                      _("Invalid .debug_rnglists data (no base address)"));
14509           return false;
14510         }
14511       if (rlet == DW_RLE_end_of_list || overflow)
14512         break;
14513       if (rlet == DW_RLE_base_address)
14514         continue;
14515
14516       if (!found_base)
14517         {
14518           /* We have no valid base address for the ranges
14519              data.  */
14520           complaint (&symfile_complaints,
14521                      _("Invalid .debug_rnglists data (no base address)"));
14522           return false;
14523         }
14524
14525       if (range_beginning > range_end)
14526         {
14527           /* Inverted range entries are invalid.  */
14528           complaint (&symfile_complaints,
14529                      _("Invalid .debug_rnglists data (inverted range)"));
14530           return false;
14531         }
14532
14533       /* Empty range entries have no effect.  */
14534       if (range_beginning == range_end)
14535         continue;
14536
14537       range_beginning += base;
14538       range_end += base;
14539
14540       /* A not-uncommon case of bad debug info.
14541          Don't pollute the addrmap with bad data.  */
14542       if (range_beginning + baseaddr == 0
14543           && !dwarf2_per_objfile->has_section_at_zero)
14544         {
14545           complaint (&symfile_complaints,
14546                      _(".debug_rnglists entry has start address of zero"
14547                        " [in module %s]"), objfile_name (objfile));
14548           continue;
14549         }
14550
14551       callback (range_beginning, range_end);
14552     }
14553
14554   if (overflow)
14555     {
14556       complaint (&symfile_complaints,
14557                  _("Offset %d is not terminated "
14558                    "for DW_AT_ranges attribute"),
14559                  offset);
14560       return false;
14561     }
14562
14563   return true;
14564 }
14565
14566 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14567    Callback's type should be:
14568     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14569    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14570
14571 template <typename Callback>
14572 static int
14573 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14574                        Callback &&callback)
14575 {
14576   struct dwarf2_per_objfile *dwarf2_per_objfile
14577       = cu->per_cu->dwarf2_per_objfile;
14578   struct objfile *objfile = dwarf2_per_objfile->objfile;
14579   struct comp_unit_head *cu_header = &cu->header;
14580   bfd *obfd = objfile->obfd;
14581   unsigned int addr_size = cu_header->addr_size;
14582   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14583   /* Base address selection entry.  */
14584   CORE_ADDR base;
14585   int found_base;
14586   unsigned int dummy;
14587   const gdb_byte *buffer;
14588   CORE_ADDR baseaddr;
14589
14590   if (cu_header->version >= 5)
14591     return dwarf2_rnglists_process (offset, cu, callback);
14592
14593   found_base = cu->base_known;
14594   base = cu->base_address;
14595
14596   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14597   if (offset >= dwarf2_per_objfile->ranges.size)
14598     {
14599       complaint (&symfile_complaints,
14600                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14601                  offset);
14602       return 0;
14603     }
14604   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14605
14606   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14607
14608   while (1)
14609     {
14610       CORE_ADDR range_beginning, range_end;
14611
14612       range_beginning = read_address (obfd, buffer, cu, &dummy);
14613       buffer += addr_size;
14614       range_end = read_address (obfd, buffer, cu, &dummy);
14615       buffer += addr_size;
14616       offset += 2 * addr_size;
14617
14618       /* An end of list marker is a pair of zero addresses.  */
14619       if (range_beginning == 0 && range_end == 0)
14620         /* Found the end of list entry.  */
14621         break;
14622
14623       /* Each base address selection entry is a pair of 2 values.
14624          The first is the largest possible address, the second is
14625          the base address.  Check for a base address here.  */
14626       if ((range_beginning & mask) == mask)
14627         {
14628           /* If we found the largest possible address, then we already
14629              have the base address in range_end.  */
14630           base = range_end;
14631           found_base = 1;
14632           continue;
14633         }
14634
14635       if (!found_base)
14636         {
14637           /* We have no valid base address for the ranges
14638              data.  */
14639           complaint (&symfile_complaints,
14640                      _("Invalid .debug_ranges data (no base address)"));
14641           return 0;
14642         }
14643
14644       if (range_beginning > range_end)
14645         {
14646           /* Inverted range entries are invalid.  */
14647           complaint (&symfile_complaints,
14648                      _("Invalid .debug_ranges data (inverted range)"));
14649           return 0;
14650         }
14651
14652       /* Empty range entries have no effect.  */
14653       if (range_beginning == range_end)
14654         continue;
14655
14656       range_beginning += base;
14657       range_end += base;
14658
14659       /* A not-uncommon case of bad debug info.
14660          Don't pollute the addrmap with bad data.  */
14661       if (range_beginning + baseaddr == 0
14662           && !dwarf2_per_objfile->has_section_at_zero)
14663         {
14664           complaint (&symfile_complaints,
14665                      _(".debug_ranges entry has start address of zero"
14666                        " [in module %s]"), objfile_name (objfile));
14667           continue;
14668         }
14669
14670       callback (range_beginning, range_end);
14671     }
14672
14673   return 1;
14674 }
14675
14676 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14677    Return 1 if the attributes are present and valid, otherwise, return 0.
14678    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14679
14680 static int
14681 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14682                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14683                     struct partial_symtab *ranges_pst)
14684 {
14685   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14686   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14687   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14688                                        SECT_OFF_TEXT (objfile));
14689   int low_set = 0;
14690   CORE_ADDR low = 0;
14691   CORE_ADDR high = 0;
14692   int retval;
14693
14694   retval = dwarf2_ranges_process (offset, cu,
14695     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14696     {
14697       if (ranges_pst != NULL)
14698         {
14699           CORE_ADDR lowpc;
14700           CORE_ADDR highpc;
14701
14702           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14703                                               range_beginning + baseaddr);
14704           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14705                                                range_end + baseaddr);
14706           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14707                              ranges_pst);
14708         }
14709
14710       /* FIXME: This is recording everything as a low-high
14711          segment of consecutive addresses.  We should have a
14712          data structure for discontiguous block ranges
14713          instead.  */
14714       if (! low_set)
14715         {
14716           low = range_beginning;
14717           high = range_end;
14718           low_set = 1;
14719         }
14720       else
14721         {
14722           if (range_beginning < low)
14723             low = range_beginning;
14724           if (range_end > high)
14725             high = range_end;
14726         }
14727     });
14728   if (!retval)
14729     return 0;
14730
14731   if (! low_set)
14732     /* If the first entry is an end-of-list marker, the range
14733        describes an empty scope, i.e. no instructions.  */
14734     return 0;
14735
14736   if (low_return)
14737     *low_return = low;
14738   if (high_return)
14739     *high_return = high;
14740   return 1;
14741 }
14742
14743 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14744    definition for the return value.  *LOWPC and *HIGHPC are set iff
14745    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14746
14747 static enum pc_bounds_kind
14748 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14749                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14750                       struct partial_symtab *pst)
14751 {
14752   struct dwarf2_per_objfile *dwarf2_per_objfile
14753     = cu->per_cu->dwarf2_per_objfile;
14754   struct attribute *attr;
14755   struct attribute *attr_high;
14756   CORE_ADDR low = 0;
14757   CORE_ADDR high = 0;
14758   enum pc_bounds_kind ret;
14759
14760   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14761   if (attr_high)
14762     {
14763       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14764       if (attr)
14765         {
14766           low = attr_value_as_address (attr);
14767           high = attr_value_as_address (attr_high);
14768           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14769             high += low;
14770         }
14771       else
14772         /* Found high w/o low attribute.  */
14773         return PC_BOUNDS_INVALID;
14774
14775       /* Found consecutive range of addresses.  */
14776       ret = PC_BOUNDS_HIGH_LOW;
14777     }
14778   else
14779     {
14780       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14781       if (attr != NULL)
14782         {
14783           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14784              We take advantage of the fact that DW_AT_ranges does not appear
14785              in DW_TAG_compile_unit of DWO files.  */
14786           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14787           unsigned int ranges_offset = (DW_UNSND (attr)
14788                                         + (need_ranges_base
14789                                            ? cu->ranges_base
14790                                            : 0));
14791
14792           /* Value of the DW_AT_ranges attribute is the offset in the
14793              .debug_ranges section.  */
14794           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14795             return PC_BOUNDS_INVALID;
14796           /* Found discontinuous range of addresses.  */
14797           ret = PC_BOUNDS_RANGES;
14798         }
14799       else
14800         return PC_BOUNDS_NOT_PRESENT;
14801     }
14802
14803   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14804   if (high <= low)
14805     return PC_BOUNDS_INVALID;
14806
14807   /* When using the GNU linker, .gnu.linkonce. sections are used to
14808      eliminate duplicate copies of functions and vtables and such.
14809      The linker will arbitrarily choose one and discard the others.
14810      The AT_*_pc values for such functions refer to local labels in
14811      these sections.  If the section from that file was discarded, the
14812      labels are not in the output, so the relocs get a value of 0.
14813      If this is a discarded function, mark the pc bounds as invalid,
14814      so that GDB will ignore it.  */
14815   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14816     return PC_BOUNDS_INVALID;
14817
14818   *lowpc = low;
14819   if (highpc)
14820     *highpc = high;
14821   return ret;
14822 }
14823
14824 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14825    its low and high PC addresses.  Do nothing if these addresses could not
14826    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14827    and HIGHPC to the high address if greater than HIGHPC.  */
14828
14829 static void
14830 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14831                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14832                                  struct dwarf2_cu *cu)
14833 {
14834   CORE_ADDR low, high;
14835   struct die_info *child = die->child;
14836
14837   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14838     {
14839       *lowpc = std::min (*lowpc, low);
14840       *highpc = std::max (*highpc, high);
14841     }
14842
14843   /* If the language does not allow nested subprograms (either inside
14844      subprograms or lexical blocks), we're done.  */
14845   if (cu->language != language_ada)
14846     return;
14847
14848   /* Check all the children of the given DIE.  If it contains nested
14849      subprograms, then check their pc bounds.  Likewise, we need to
14850      check lexical blocks as well, as they may also contain subprogram
14851      definitions.  */
14852   while (child && child->tag)
14853     {
14854       if (child->tag == DW_TAG_subprogram
14855           || child->tag == DW_TAG_lexical_block)
14856         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14857       child = sibling_die (child);
14858     }
14859 }
14860
14861 /* Get the low and high pc's represented by the scope DIE, and store
14862    them in *LOWPC and *HIGHPC.  If the correct values can't be
14863    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14864
14865 static void
14866 get_scope_pc_bounds (struct die_info *die,
14867                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14868                      struct dwarf2_cu *cu)
14869 {
14870   CORE_ADDR best_low = (CORE_ADDR) -1;
14871   CORE_ADDR best_high = (CORE_ADDR) 0;
14872   CORE_ADDR current_low, current_high;
14873
14874   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14875       >= PC_BOUNDS_RANGES)
14876     {
14877       best_low = current_low;
14878       best_high = current_high;
14879     }
14880   else
14881     {
14882       struct die_info *child = die->child;
14883
14884       while (child && child->tag)
14885         {
14886           switch (child->tag) {
14887           case DW_TAG_subprogram:
14888             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14889             break;
14890           case DW_TAG_namespace:
14891           case DW_TAG_module:
14892             /* FIXME: carlton/2004-01-16: Should we do this for
14893                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14894                that current GCC's always emit the DIEs corresponding
14895                to definitions of methods of classes as children of a
14896                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14897                the DIEs giving the declarations, which could be
14898                anywhere).  But I don't see any reason why the
14899                standards says that they have to be there.  */
14900             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14901
14902             if (current_low != ((CORE_ADDR) -1))
14903               {
14904                 best_low = std::min (best_low, current_low);
14905                 best_high = std::max (best_high, current_high);
14906               }
14907             break;
14908           default:
14909             /* Ignore.  */
14910             break;
14911           }
14912
14913           child = sibling_die (child);
14914         }
14915     }
14916
14917   *lowpc = best_low;
14918   *highpc = best_high;
14919 }
14920
14921 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14922    in DIE.  */
14923
14924 static void
14925 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14926                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14927 {
14928   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14929   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14930   struct attribute *attr;
14931   struct attribute *attr_high;
14932
14933   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14934   if (attr_high)
14935     {
14936       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14937       if (attr)
14938         {
14939           CORE_ADDR low = attr_value_as_address (attr);
14940           CORE_ADDR high = attr_value_as_address (attr_high);
14941
14942           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14943             high += low;
14944
14945           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14946           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14947           record_block_range (block, low, high - 1);
14948         }
14949     }
14950
14951   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14952   if (attr)
14953     {
14954       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14955          We take advantage of the fact that DW_AT_ranges does not appear
14956          in DW_TAG_compile_unit of DWO files.  */
14957       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14958
14959       /* The value of the DW_AT_ranges attribute is the offset of the
14960          address range list in the .debug_ranges section.  */
14961       unsigned long offset = (DW_UNSND (attr)
14962                               + (need_ranges_base ? cu->ranges_base : 0));
14963       const gdb_byte *buffer;
14964
14965       /* For some target architectures, but not others, the
14966          read_address function sign-extends the addresses it returns.
14967          To recognize base address selection entries, we need a
14968          mask.  */
14969       unsigned int addr_size = cu->header.addr_size;
14970       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14971
14972       /* The base address, to which the next pair is relative.  Note
14973          that this 'base' is a DWARF concept: most entries in a range
14974          list are relative, to reduce the number of relocs against the
14975          debugging information.  This is separate from this function's
14976          'baseaddr' argument, which GDB uses to relocate debugging
14977          information from a shared library based on the address at
14978          which the library was loaded.  */
14979       CORE_ADDR base = cu->base_address;
14980       int base_known = cu->base_known;
14981
14982       dwarf2_ranges_process (offset, cu,
14983         [&] (CORE_ADDR start, CORE_ADDR end)
14984         {
14985           start += baseaddr;
14986           end += baseaddr;
14987           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14988           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14989           record_block_range (block, start, end - 1);
14990         });
14991     }
14992 }
14993
14994 /* Check whether the producer field indicates either of GCC < 4.6, or the
14995    Intel C/C++ compiler, and cache the result in CU.  */
14996
14997 static void
14998 check_producer (struct dwarf2_cu *cu)
14999 {
15000   int major, minor;
15001
15002   if (cu->producer == NULL)
15003     {
15004       /* For unknown compilers expect their behavior is DWARF version
15005          compliant.
15006
15007          GCC started to support .debug_types sections by -gdwarf-4 since
15008          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15009          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15010          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15011          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15012     }
15013   else if (producer_is_gcc (cu->producer, &major, &minor))
15014     {
15015       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15016       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15017     }
15018   else if (producer_is_icc (cu->producer, &major, &minor))
15019     cu->producer_is_icc_lt_14 = major < 14;
15020   else
15021     {
15022       /* For other non-GCC compilers, expect their behavior is DWARF version
15023          compliant.  */
15024     }
15025
15026   cu->checked_producer = 1;
15027 }
15028
15029 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15030    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15031    during 4.6.0 experimental.  */
15032
15033 static int
15034 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15035 {
15036   if (!cu->checked_producer)
15037     check_producer (cu);
15038
15039   return cu->producer_is_gxx_lt_4_6;
15040 }
15041
15042 /* Return the default accessibility type if it is not overriden by
15043    DW_AT_accessibility.  */
15044
15045 static enum dwarf_access_attribute
15046 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15047 {
15048   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15049     {
15050       /* The default DWARF 2 accessibility for members is public, the default
15051          accessibility for inheritance is private.  */
15052
15053       if (die->tag != DW_TAG_inheritance)
15054         return DW_ACCESS_public;
15055       else
15056         return DW_ACCESS_private;
15057     }
15058   else
15059     {
15060       /* DWARF 3+ defines the default accessibility a different way.  The same
15061          rules apply now for DW_TAG_inheritance as for the members and it only
15062          depends on the container kind.  */
15063
15064       if (die->parent->tag == DW_TAG_class_type)
15065         return DW_ACCESS_private;
15066       else
15067         return DW_ACCESS_public;
15068     }
15069 }
15070
15071 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15072    offset.  If the attribute was not found return 0, otherwise return
15073    1.  If it was found but could not properly be handled, set *OFFSET
15074    to 0.  */
15075
15076 static int
15077 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15078                              LONGEST *offset)
15079 {
15080   struct attribute *attr;
15081
15082   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15083   if (attr != NULL)
15084     {
15085       *offset = 0;
15086
15087       /* Note that we do not check for a section offset first here.
15088          This is because DW_AT_data_member_location is new in DWARF 4,
15089          so if we see it, we can assume that a constant form is really
15090          a constant and not a section offset.  */
15091       if (attr_form_is_constant (attr))
15092         *offset = dwarf2_get_attr_constant_value (attr, 0);
15093       else if (attr_form_is_section_offset (attr))
15094         dwarf2_complex_location_expr_complaint ();
15095       else if (attr_form_is_block (attr))
15096         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15097       else
15098         dwarf2_complex_location_expr_complaint ();
15099
15100       return 1;
15101     }
15102
15103   return 0;
15104 }
15105
15106 /* Add an aggregate field to the field list.  */
15107
15108 static void
15109 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15110                   struct dwarf2_cu *cu)
15111 {
15112   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15113   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15114   struct nextfield *new_field;
15115   struct attribute *attr;
15116   struct field *fp;
15117   const char *fieldname = "";
15118
15119   /* Allocate a new field list entry and link it in.  */
15120   new_field = XNEW (struct nextfield);
15121   make_cleanup (xfree, new_field);
15122   memset (new_field, 0, sizeof (struct nextfield));
15123
15124   if (die->tag == DW_TAG_inheritance)
15125     {
15126       new_field->next = fip->baseclasses;
15127       fip->baseclasses = new_field;
15128     }
15129   else
15130     {
15131       new_field->next = fip->fields;
15132       fip->fields = new_field;
15133     }
15134   fip->nfields++;
15135
15136   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15137   if (attr)
15138     new_field->accessibility = DW_UNSND (attr);
15139   else
15140     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15141   if (new_field->accessibility != DW_ACCESS_public)
15142     fip->non_public_fields = 1;
15143
15144   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15145   if (attr)
15146     new_field->virtuality = DW_UNSND (attr);
15147   else
15148     new_field->virtuality = DW_VIRTUALITY_none;
15149
15150   fp = &new_field->field;
15151
15152   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15153     {
15154       LONGEST offset;
15155
15156       /* Data member other than a C++ static data member.  */
15157
15158       /* Get type of field.  */
15159       fp->type = die_type (die, cu);
15160
15161       SET_FIELD_BITPOS (*fp, 0);
15162
15163       /* Get bit size of field (zero if none).  */
15164       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15165       if (attr)
15166         {
15167           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15168         }
15169       else
15170         {
15171           FIELD_BITSIZE (*fp) = 0;
15172         }
15173
15174       /* Get bit offset of field.  */
15175       if (handle_data_member_location (die, cu, &offset))
15176         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15177       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15178       if (attr)
15179         {
15180           if (gdbarch_bits_big_endian (gdbarch))
15181             {
15182               /* For big endian bits, the DW_AT_bit_offset gives the
15183                  additional bit offset from the MSB of the containing
15184                  anonymous object to the MSB of the field.  We don't
15185                  have to do anything special since we don't need to
15186                  know the size of the anonymous object.  */
15187               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15188             }
15189           else
15190             {
15191               /* For little endian bits, compute the bit offset to the
15192                  MSB of the anonymous object, subtract off the number of
15193                  bits from the MSB of the field to the MSB of the
15194                  object, and then subtract off the number of bits of
15195                  the field itself.  The result is the bit offset of
15196                  the LSB of the field.  */
15197               int anonymous_size;
15198               int bit_offset = DW_UNSND (attr);
15199
15200               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15201               if (attr)
15202                 {
15203                   /* The size of the anonymous object containing
15204                      the bit field is explicit, so use the
15205                      indicated size (in bytes).  */
15206                   anonymous_size = DW_UNSND (attr);
15207                 }
15208               else
15209                 {
15210                   /* The size of the anonymous object containing
15211                      the bit field must be inferred from the type
15212                      attribute of the data member containing the
15213                      bit field.  */
15214                   anonymous_size = TYPE_LENGTH (fp->type);
15215                 }
15216               SET_FIELD_BITPOS (*fp,
15217                                 (FIELD_BITPOS (*fp)
15218                                  + anonymous_size * bits_per_byte
15219                                  - bit_offset - FIELD_BITSIZE (*fp)));
15220             }
15221         }
15222       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15223       if (attr != NULL)
15224         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15225                                 + dwarf2_get_attr_constant_value (attr, 0)));
15226
15227       /* Get name of field.  */
15228       fieldname = dwarf2_name (die, cu);
15229       if (fieldname == NULL)
15230         fieldname = "";
15231
15232       /* The name is already allocated along with this objfile, so we don't
15233          need to duplicate it for the type.  */
15234       fp->name = fieldname;
15235
15236       /* Change accessibility for artificial fields (e.g. virtual table
15237          pointer or virtual base class pointer) to private.  */
15238       if (dwarf2_attr (die, DW_AT_artificial, cu))
15239         {
15240           FIELD_ARTIFICIAL (*fp) = 1;
15241           new_field->accessibility = DW_ACCESS_private;
15242           fip->non_public_fields = 1;
15243         }
15244     }
15245   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15246     {
15247       /* C++ static member.  */
15248
15249       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15250          is a declaration, but all versions of G++ as of this writing
15251          (so through at least 3.2.1) incorrectly generate
15252          DW_TAG_variable tags.  */
15253
15254       const char *physname;
15255
15256       /* Get name of field.  */
15257       fieldname = dwarf2_name (die, cu);
15258       if (fieldname == NULL)
15259         return;
15260
15261       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15262       if (attr
15263           /* Only create a symbol if this is an external value.
15264              new_symbol checks this and puts the value in the global symbol
15265              table, which we want.  If it is not external, new_symbol
15266              will try to put the value in cu->list_in_scope which is wrong.  */
15267           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15268         {
15269           /* A static const member, not much different than an enum as far as
15270              we're concerned, except that we can support more types.  */
15271           new_symbol (die, NULL, cu);
15272         }
15273
15274       /* Get physical name.  */
15275       physname = dwarf2_physname (fieldname, die, cu);
15276
15277       /* The name is already allocated along with this objfile, so we don't
15278          need to duplicate it for the type.  */
15279       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15280       FIELD_TYPE (*fp) = die_type (die, cu);
15281       FIELD_NAME (*fp) = fieldname;
15282     }
15283   else if (die->tag == DW_TAG_inheritance)
15284     {
15285       LONGEST offset;
15286
15287       /* C++ base class field.  */
15288       if (handle_data_member_location (die, cu, &offset))
15289         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15290       FIELD_BITSIZE (*fp) = 0;
15291       FIELD_TYPE (*fp) = die_type (die, cu);
15292       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15293       fip->nbaseclasses++;
15294     }
15295 }
15296
15297 /* Can the type given by DIE define another type?  */
15298
15299 static bool
15300 type_can_define_types (const struct die_info *die)
15301 {
15302   switch (die->tag)
15303     {
15304     case DW_TAG_typedef:
15305     case DW_TAG_class_type:
15306     case DW_TAG_structure_type:
15307     case DW_TAG_union_type:
15308     case DW_TAG_enumeration_type:
15309       return true;
15310
15311     default:
15312       return false;
15313     }
15314 }
15315
15316 /* Add a type definition defined in the scope of the FIP's class.  */
15317
15318 static void
15319 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15320                       struct dwarf2_cu *cu)
15321 {
15322   struct decl_field_list *new_field;
15323   struct decl_field *fp;
15324
15325   /* Allocate a new field list entry and link it in.  */
15326   new_field = XCNEW (struct decl_field_list);
15327   make_cleanup (xfree, new_field);
15328
15329   gdb_assert (type_can_define_types (die));
15330
15331   fp = &new_field->field;
15332
15333   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15334   fp->name = dwarf2_name (die, cu);
15335   fp->type = read_type_die (die, cu);
15336
15337   /* Save accessibility.  */
15338   enum dwarf_access_attribute accessibility;
15339   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15340   if (attr != NULL)
15341     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15342   else
15343     accessibility = dwarf2_default_access_attribute (die, cu);
15344   switch (accessibility)
15345     {
15346     case DW_ACCESS_public:
15347       /* The assumed value if neither private nor protected.  */
15348       break;
15349     case DW_ACCESS_private:
15350       fp->is_private = 1;
15351       break;
15352     case DW_ACCESS_protected:
15353       fp->is_protected = 1;
15354       break;
15355     default:
15356       complaint (&symfile_complaints,
15357                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15358     }
15359
15360   if (die->tag == DW_TAG_typedef)
15361     {
15362       new_field->next = fip->typedef_field_list;
15363       fip->typedef_field_list = new_field;
15364       fip->typedef_field_list_count++;
15365     }
15366   else
15367     {
15368       new_field->next = fip->nested_types_list;
15369       fip->nested_types_list = new_field;
15370       fip->nested_types_list_count++;
15371     }
15372 }
15373
15374 /* Create the vector of fields, and attach it to the type.  */
15375
15376 static void
15377 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15378                               struct dwarf2_cu *cu)
15379 {
15380   int nfields = fip->nfields;
15381
15382   /* Record the field count, allocate space for the array of fields,
15383      and create blank accessibility bitfields if necessary.  */
15384   TYPE_NFIELDS (type) = nfields;
15385   TYPE_FIELDS (type) = (struct field *)
15386     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15387   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15388
15389   if (fip->non_public_fields && cu->language != language_ada)
15390     {
15391       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15392
15393       TYPE_FIELD_PRIVATE_BITS (type) =
15394         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15395       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15396
15397       TYPE_FIELD_PROTECTED_BITS (type) =
15398         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15399       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15400
15401       TYPE_FIELD_IGNORE_BITS (type) =
15402         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15403       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15404     }
15405
15406   /* If the type has baseclasses, allocate and clear a bit vector for
15407      TYPE_FIELD_VIRTUAL_BITS.  */
15408   if (fip->nbaseclasses && cu->language != language_ada)
15409     {
15410       int num_bytes = B_BYTES (fip->nbaseclasses);
15411       unsigned char *pointer;
15412
15413       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15414       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15415       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15416       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15417       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15418     }
15419
15420   /* Copy the saved-up fields into the field vector.  Start from the head of
15421      the list, adding to the tail of the field array, so that they end up in
15422      the same order in the array in which they were added to the list.  */
15423   while (nfields-- > 0)
15424     {
15425       struct nextfield *fieldp;
15426
15427       if (fip->fields)
15428         {
15429           fieldp = fip->fields;
15430           fip->fields = fieldp->next;
15431         }
15432       else
15433         {
15434           fieldp = fip->baseclasses;
15435           fip->baseclasses = fieldp->next;
15436         }
15437
15438       TYPE_FIELD (type, nfields) = fieldp->field;
15439       switch (fieldp->accessibility)
15440         {
15441         case DW_ACCESS_private:
15442           if (cu->language != language_ada)
15443             SET_TYPE_FIELD_PRIVATE (type, nfields);
15444           break;
15445
15446         case DW_ACCESS_protected:
15447           if (cu->language != language_ada)
15448             SET_TYPE_FIELD_PROTECTED (type, nfields);
15449           break;
15450
15451         case DW_ACCESS_public:
15452           break;
15453
15454         default:
15455           /* Unknown accessibility.  Complain and treat it as public.  */
15456           {
15457             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15458                        fieldp->accessibility);
15459           }
15460           break;
15461         }
15462       if (nfields < fip->nbaseclasses)
15463         {
15464           switch (fieldp->virtuality)
15465             {
15466             case DW_VIRTUALITY_virtual:
15467             case DW_VIRTUALITY_pure_virtual:
15468               if (cu->language == language_ada)
15469                 error (_("unexpected virtuality in component of Ada type"));
15470               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15471               break;
15472             }
15473         }
15474     }
15475 }
15476
15477 /* Return true if this member function is a constructor, false
15478    otherwise.  */
15479
15480 static int
15481 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15482 {
15483   const char *fieldname;
15484   const char *type_name;
15485   int len;
15486
15487   if (die->parent == NULL)
15488     return 0;
15489
15490   if (die->parent->tag != DW_TAG_structure_type
15491       && die->parent->tag != DW_TAG_union_type
15492       && die->parent->tag != DW_TAG_class_type)
15493     return 0;
15494
15495   fieldname = dwarf2_name (die, cu);
15496   type_name = dwarf2_name (die->parent, cu);
15497   if (fieldname == NULL || type_name == NULL)
15498     return 0;
15499
15500   len = strlen (fieldname);
15501   return (strncmp (fieldname, type_name, len) == 0
15502           && (type_name[len] == '\0' || type_name[len] == '<'));
15503 }
15504
15505 /* Add a member function to the proper fieldlist.  */
15506
15507 static void
15508 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15509                       struct type *type, struct dwarf2_cu *cu)
15510 {
15511   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15512   struct attribute *attr;
15513   struct fnfieldlist *flp;
15514   int i;
15515   struct fn_field *fnp;
15516   const char *fieldname;
15517   struct nextfnfield *new_fnfield;
15518   struct type *this_type;
15519   enum dwarf_access_attribute accessibility;
15520
15521   if (cu->language == language_ada)
15522     error (_("unexpected member function in Ada type"));
15523
15524   /* Get name of member function.  */
15525   fieldname = dwarf2_name (die, cu);
15526   if (fieldname == NULL)
15527     return;
15528
15529   /* Look up member function name in fieldlist.  */
15530   for (i = 0; i < fip->nfnfields; i++)
15531     {
15532       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15533         break;
15534     }
15535
15536   /* Create new list element if necessary.  */
15537   if (i < fip->nfnfields)
15538     flp = &fip->fnfieldlists[i];
15539   else
15540     {
15541       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15542         {
15543           fip->fnfieldlists = (struct fnfieldlist *)
15544             xrealloc (fip->fnfieldlists,
15545                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15546                       * sizeof (struct fnfieldlist));
15547           if (fip->nfnfields == 0)
15548             make_cleanup (free_current_contents, &fip->fnfieldlists);
15549         }
15550       flp = &fip->fnfieldlists[fip->nfnfields];
15551       flp->name = fieldname;
15552       flp->length = 0;
15553       flp->head = NULL;
15554       i = fip->nfnfields++;
15555     }
15556
15557   /* Create a new member function field and chain it to the field list
15558      entry.  */
15559   new_fnfield = XNEW (struct nextfnfield);
15560   make_cleanup (xfree, new_fnfield);
15561   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15562   new_fnfield->next = flp->head;
15563   flp->head = new_fnfield;
15564   flp->length++;
15565
15566   /* Fill in the member function field info.  */
15567   fnp = &new_fnfield->fnfield;
15568
15569   /* Delay processing of the physname until later.  */
15570   if (cu->language == language_cplus)
15571     {
15572       add_to_method_list (type, i, flp->length - 1, fieldname,
15573                           die, cu);
15574     }
15575   else
15576     {
15577       const char *physname = dwarf2_physname (fieldname, die, cu);
15578       fnp->physname = physname ? physname : "";
15579     }
15580
15581   fnp->type = alloc_type (objfile);
15582   this_type = read_type_die (die, cu);
15583   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15584     {
15585       int nparams = TYPE_NFIELDS (this_type);
15586
15587       /* TYPE is the domain of this method, and THIS_TYPE is the type
15588            of the method itself (TYPE_CODE_METHOD).  */
15589       smash_to_method_type (fnp->type, type,
15590                             TYPE_TARGET_TYPE (this_type),
15591                             TYPE_FIELDS (this_type),
15592                             TYPE_NFIELDS (this_type),
15593                             TYPE_VARARGS (this_type));
15594
15595       /* Handle static member functions.
15596          Dwarf2 has no clean way to discern C++ static and non-static
15597          member functions.  G++ helps GDB by marking the first
15598          parameter for non-static member functions (which is the this
15599          pointer) as artificial.  We obtain this information from
15600          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15601       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15602         fnp->voffset = VOFFSET_STATIC;
15603     }
15604   else
15605     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15606                dwarf2_full_name (fieldname, die, cu));
15607
15608   /* Get fcontext from DW_AT_containing_type if present.  */
15609   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15610     fnp->fcontext = die_containing_type (die, cu);
15611
15612   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15613      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15614
15615   /* Get accessibility.  */
15616   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15617   if (attr)
15618     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15619   else
15620     accessibility = dwarf2_default_access_attribute (die, cu);
15621   switch (accessibility)
15622     {
15623     case DW_ACCESS_private:
15624       fnp->is_private = 1;
15625       break;
15626     case DW_ACCESS_protected:
15627       fnp->is_protected = 1;
15628       break;
15629     }
15630
15631   /* Check for artificial methods.  */
15632   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15633   if (attr && DW_UNSND (attr) != 0)
15634     fnp->is_artificial = 1;
15635
15636   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15637
15638   /* Get index in virtual function table if it is a virtual member
15639      function.  For older versions of GCC, this is an offset in the
15640      appropriate virtual table, as specified by DW_AT_containing_type.
15641      For everyone else, it is an expression to be evaluated relative
15642      to the object address.  */
15643
15644   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15645   if (attr)
15646     {
15647       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15648         {
15649           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15650             {
15651               /* Old-style GCC.  */
15652               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15653             }
15654           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15655                    || (DW_BLOCK (attr)->size > 1
15656                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15657                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15658             {
15659               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15660               if ((fnp->voffset % cu->header.addr_size) != 0)
15661                 dwarf2_complex_location_expr_complaint ();
15662               else
15663                 fnp->voffset /= cu->header.addr_size;
15664               fnp->voffset += 2;
15665             }
15666           else
15667             dwarf2_complex_location_expr_complaint ();
15668
15669           if (!fnp->fcontext)
15670             {
15671               /* If there is no `this' field and no DW_AT_containing_type,
15672                  we cannot actually find a base class context for the
15673                  vtable!  */
15674               if (TYPE_NFIELDS (this_type) == 0
15675                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15676                 {
15677                   complaint (&symfile_complaints,
15678                              _("cannot determine context for virtual member "
15679                                "function \"%s\" (offset %s)"),
15680                              fieldname, sect_offset_str (die->sect_off));
15681                 }
15682               else
15683                 {
15684                   fnp->fcontext
15685                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15686                 }
15687             }
15688         }
15689       else if (attr_form_is_section_offset (attr))
15690         {
15691           dwarf2_complex_location_expr_complaint ();
15692         }
15693       else
15694         {
15695           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15696                                                  fieldname);
15697         }
15698     }
15699   else
15700     {
15701       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15702       if (attr && DW_UNSND (attr))
15703         {
15704           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15705           complaint (&symfile_complaints,
15706                      _("Member function \"%s\" (offset %s) is virtual "
15707                        "but the vtable offset is not specified"),
15708                      fieldname, sect_offset_str (die->sect_off));
15709           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15710           TYPE_CPLUS_DYNAMIC (type) = 1;
15711         }
15712     }
15713 }
15714
15715 /* Create the vector of member function fields, and attach it to the type.  */
15716
15717 static void
15718 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15719                                  struct dwarf2_cu *cu)
15720 {
15721   struct fnfieldlist *flp;
15722   int i;
15723
15724   if (cu->language == language_ada)
15725     error (_("unexpected member functions in Ada type"));
15726
15727   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15728   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15729     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15730
15731   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15732     {
15733       struct nextfnfield *nfp = flp->head;
15734       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15735       int k;
15736
15737       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15738       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15739       fn_flp->fn_fields = (struct fn_field *)
15740         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15741       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15742         fn_flp->fn_fields[k] = nfp->fnfield;
15743     }
15744
15745   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15746 }
15747
15748 /* Returns non-zero if NAME is the name of a vtable member in CU's
15749    language, zero otherwise.  */
15750 static int
15751 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15752 {
15753   static const char vptr[] = "_vptr";
15754
15755   /* Look for the C++ form of the vtable.  */
15756   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15757     return 1;
15758
15759   return 0;
15760 }
15761
15762 /* GCC outputs unnamed structures that are really pointers to member
15763    functions, with the ABI-specified layout.  If TYPE describes
15764    such a structure, smash it into a member function type.
15765
15766    GCC shouldn't do this; it should just output pointer to member DIEs.
15767    This is GCC PR debug/28767.  */
15768
15769 static void
15770 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15771 {
15772   struct type *pfn_type, *self_type, *new_type;
15773
15774   /* Check for a structure with no name and two children.  */
15775   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15776     return;
15777
15778   /* Check for __pfn and __delta members.  */
15779   if (TYPE_FIELD_NAME (type, 0) == NULL
15780       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15781       || TYPE_FIELD_NAME (type, 1) == NULL
15782       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15783     return;
15784
15785   /* Find the type of the method.  */
15786   pfn_type = TYPE_FIELD_TYPE (type, 0);
15787   if (pfn_type == NULL
15788       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15789       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15790     return;
15791
15792   /* Look for the "this" argument.  */
15793   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15794   if (TYPE_NFIELDS (pfn_type) == 0
15795       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15796       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15797     return;
15798
15799   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15800   new_type = alloc_type (objfile);
15801   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15802                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15803                         TYPE_VARARGS (pfn_type));
15804   smash_to_methodptr_type (type, new_type);
15805 }
15806
15807
15808 /* Called when we find the DIE that starts a structure or union scope
15809    (definition) to create a type for the structure or union.  Fill in
15810    the type's name and general properties; the members will not be
15811    processed until process_structure_scope.  A symbol table entry for
15812    the type will also not be done until process_structure_scope (assuming
15813    the type has a name).
15814
15815    NOTE: we need to call these functions regardless of whether or not the
15816    DIE has a DW_AT_name attribute, since it might be an anonymous
15817    structure or union.  This gets the type entered into our set of
15818    user defined types.  */
15819
15820 static struct type *
15821 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15822 {
15823   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15824   struct type *type;
15825   struct attribute *attr;
15826   const char *name;
15827
15828   /* If the definition of this type lives in .debug_types, read that type.
15829      Don't follow DW_AT_specification though, that will take us back up
15830      the chain and we want to go down.  */
15831   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15832   if (attr)
15833     {
15834       type = get_DW_AT_signature_type (die, attr, cu);
15835
15836       /* The type's CU may not be the same as CU.
15837          Ensure TYPE is recorded with CU in die_type_hash.  */
15838       return set_die_type (die, type, cu);
15839     }
15840
15841   type = alloc_type (objfile);
15842   INIT_CPLUS_SPECIFIC (type);
15843
15844   name = dwarf2_name (die, cu);
15845   if (name != NULL)
15846     {
15847       if (cu->language == language_cplus
15848           || cu->language == language_d
15849           || cu->language == language_rust)
15850         {
15851           const char *full_name = dwarf2_full_name (name, die, cu);
15852
15853           /* dwarf2_full_name might have already finished building the DIE's
15854              type.  If so, there is no need to continue.  */
15855           if (get_die_type (die, cu) != NULL)
15856             return get_die_type (die, cu);
15857
15858           TYPE_TAG_NAME (type) = full_name;
15859           if (die->tag == DW_TAG_structure_type
15860               || die->tag == DW_TAG_class_type)
15861             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15862         }
15863       else
15864         {
15865           /* The name is already allocated along with this objfile, so
15866              we don't need to duplicate it for the type.  */
15867           TYPE_TAG_NAME (type) = name;
15868           if (die->tag == DW_TAG_class_type)
15869             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15870         }
15871     }
15872
15873   if (die->tag == DW_TAG_structure_type)
15874     {
15875       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15876     }
15877   else if (die->tag == DW_TAG_union_type)
15878     {
15879       TYPE_CODE (type) = TYPE_CODE_UNION;
15880     }
15881   else
15882     {
15883       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15884     }
15885
15886   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15887     TYPE_DECLARED_CLASS (type) = 1;
15888
15889   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15890   if (attr)
15891     {
15892       if (attr_form_is_constant (attr))
15893         TYPE_LENGTH (type) = DW_UNSND (attr);
15894       else
15895         {
15896           /* For the moment, dynamic type sizes are not supported
15897              by GDB's struct type.  The actual size is determined
15898              on-demand when resolving the type of a given object,
15899              so set the type's length to zero for now.  Otherwise,
15900              we record an expression as the length, and that expression
15901              could lead to a very large value, which could eventually
15902              lead to us trying to allocate that much memory when creating
15903              a value of that type.  */
15904           TYPE_LENGTH (type) = 0;
15905         }
15906     }
15907   else
15908     {
15909       TYPE_LENGTH (type) = 0;
15910     }
15911
15912   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15913     {
15914       /* ICC<14 does not output the required DW_AT_declaration on
15915          incomplete types, but gives them a size of zero.  */
15916       TYPE_STUB (type) = 1;
15917     }
15918   else
15919     TYPE_STUB_SUPPORTED (type) = 1;
15920
15921   if (die_is_declaration (die, cu))
15922     TYPE_STUB (type) = 1;
15923   else if (attr == NULL && die->child == NULL
15924            && producer_is_realview (cu->producer))
15925     /* RealView does not output the required DW_AT_declaration
15926        on incomplete types.  */
15927     TYPE_STUB (type) = 1;
15928
15929   /* We need to add the type field to the die immediately so we don't
15930      infinitely recurse when dealing with pointers to the structure
15931      type within the structure itself.  */
15932   set_die_type (die, type, cu);
15933
15934   /* set_die_type should be already done.  */
15935   set_descriptive_type (type, die, cu);
15936
15937   return type;
15938 }
15939
15940 /* Finish creating a structure or union type, including filling in
15941    its members and creating a symbol for it.  */
15942
15943 static void
15944 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15945 {
15946   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15947   struct die_info *child_die;
15948   struct type *type;
15949
15950   type = get_die_type (die, cu);
15951   if (type == NULL)
15952     type = read_structure_type (die, cu);
15953
15954   if (die->child != NULL && ! die_is_declaration (die, cu))
15955     {
15956       struct field_info fi;
15957       std::vector<struct symbol *> template_args;
15958       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15959
15960       memset (&fi, 0, sizeof (struct field_info));
15961
15962       child_die = die->child;
15963
15964       while (child_die && child_die->tag)
15965         {
15966           if (child_die->tag == DW_TAG_member
15967               || child_die->tag == DW_TAG_variable)
15968             {
15969               /* NOTE: carlton/2002-11-05: A C++ static data member
15970                  should be a DW_TAG_member that is a declaration, but
15971                  all versions of G++ as of this writing (so through at
15972                  least 3.2.1) incorrectly generate DW_TAG_variable
15973                  tags for them instead.  */
15974               dwarf2_add_field (&fi, child_die, cu);
15975             }
15976           else if (child_die->tag == DW_TAG_subprogram)
15977             {
15978               /* Rust doesn't have member functions in the C++ sense.
15979                  However, it does emit ordinary functions as children
15980                  of a struct DIE.  */
15981               if (cu->language == language_rust)
15982                 read_func_scope (child_die, cu);
15983               else
15984                 {
15985                   /* C++ member function.  */
15986                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15987                 }
15988             }
15989           else if (child_die->tag == DW_TAG_inheritance)
15990             {
15991               /* C++ base class field.  */
15992               dwarf2_add_field (&fi, child_die, cu);
15993             }
15994           else if (type_can_define_types (child_die))
15995             dwarf2_add_type_defn (&fi, child_die, cu);
15996           else if (child_die->tag == DW_TAG_template_type_param
15997                    || child_die->tag == DW_TAG_template_value_param)
15998             {
15999               struct symbol *arg = new_symbol (child_die, NULL, cu);
16000
16001               if (arg != NULL)
16002                 template_args.push_back (arg);
16003             }
16004
16005           child_die = sibling_die (child_die);
16006         }
16007
16008       /* Attach template arguments to type.  */
16009       if (!template_args.empty ())
16010         {
16011           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16012           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16013           TYPE_TEMPLATE_ARGUMENTS (type)
16014             = XOBNEWVEC (&objfile->objfile_obstack,
16015                          struct symbol *,
16016                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16017           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16018                   template_args.data (),
16019                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16020                    * sizeof (struct symbol *)));
16021         }
16022
16023       /* Attach fields and member functions to the type.  */
16024       if (fi.nfields)
16025         dwarf2_attach_fields_to_type (&fi, type, cu);
16026       if (fi.nfnfields)
16027         {
16028           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16029
16030           /* Get the type which refers to the base class (possibly this
16031              class itself) which contains the vtable pointer for the current
16032              class from the DW_AT_containing_type attribute.  This use of
16033              DW_AT_containing_type is a GNU extension.  */
16034
16035           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16036             {
16037               struct type *t = die_containing_type (die, cu);
16038
16039               set_type_vptr_basetype (type, t);
16040               if (type == t)
16041                 {
16042                   int i;
16043
16044                   /* Our own class provides vtbl ptr.  */
16045                   for (i = TYPE_NFIELDS (t) - 1;
16046                        i >= TYPE_N_BASECLASSES (t);
16047                        --i)
16048                     {
16049                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16050
16051                       if (is_vtable_name (fieldname, cu))
16052                         {
16053                           set_type_vptr_fieldno (type, i);
16054                           break;
16055                         }
16056                     }
16057
16058                   /* Complain if virtual function table field not found.  */
16059                   if (i < TYPE_N_BASECLASSES (t))
16060                     complaint (&symfile_complaints,
16061                                _("virtual function table pointer "
16062                                  "not found when defining class '%s'"),
16063                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16064                                "");
16065                 }
16066               else
16067                 {
16068                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16069                 }
16070             }
16071           else if (cu->producer
16072                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16073             {
16074               /* The IBM XLC compiler does not provide direct indication
16075                  of the containing type, but the vtable pointer is
16076                  always named __vfp.  */
16077
16078               int i;
16079
16080               for (i = TYPE_NFIELDS (type) - 1;
16081                    i >= TYPE_N_BASECLASSES (type);
16082                    --i)
16083                 {
16084                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16085                     {
16086                       set_type_vptr_fieldno (type, i);
16087                       set_type_vptr_basetype (type, type);
16088                       break;
16089                     }
16090                 }
16091             }
16092         }
16093
16094       /* Copy fi.typedef_field_list linked list elements content into the
16095          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16096       if (fi.typedef_field_list)
16097         {
16098           int i = fi.typedef_field_list_count;
16099
16100           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16101           TYPE_TYPEDEF_FIELD_ARRAY (type)
16102             = ((struct decl_field *)
16103                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16104           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16105
16106           /* Reverse the list order to keep the debug info elements order.  */
16107           while (--i >= 0)
16108             {
16109               struct decl_field *dest, *src;
16110
16111               dest = &TYPE_TYPEDEF_FIELD (type, i);
16112               src = &fi.typedef_field_list->field;
16113               fi.typedef_field_list = fi.typedef_field_list->next;
16114               *dest = *src;
16115             }
16116         }
16117
16118       /* Copy fi.nested_types_list linked list elements content into the
16119          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16120       if (fi.nested_types_list != NULL && cu->language != language_ada)
16121         {
16122           int i = fi.nested_types_list_count;
16123
16124           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16125           TYPE_NESTED_TYPES_ARRAY (type)
16126             = ((struct decl_field *)
16127                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16128           TYPE_NESTED_TYPES_COUNT (type) = i;
16129
16130           /* Reverse the list order to keep the debug info elements order.  */
16131           while (--i >= 0)
16132             {
16133               struct decl_field *dest, *src;
16134
16135               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16136               src = &fi.nested_types_list->field;
16137               fi.nested_types_list = fi.nested_types_list->next;
16138               *dest = *src;
16139             }
16140         }
16141
16142       do_cleanups (back_to);
16143     }
16144
16145   quirk_gcc_member_function_pointer (type, objfile);
16146
16147   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16148      snapshots) has been known to create a die giving a declaration
16149      for a class that has, as a child, a die giving a definition for a
16150      nested class.  So we have to process our children even if the
16151      current die is a declaration.  Normally, of course, a declaration
16152      won't have any children at all.  */
16153
16154   child_die = die->child;
16155
16156   while (child_die != NULL && child_die->tag)
16157     {
16158       if (child_die->tag == DW_TAG_member
16159           || child_die->tag == DW_TAG_variable
16160           || child_die->tag == DW_TAG_inheritance
16161           || child_die->tag == DW_TAG_template_value_param
16162           || child_die->tag == DW_TAG_template_type_param)
16163         {
16164           /* Do nothing.  */
16165         }
16166       else
16167         process_die (child_die, cu);
16168
16169       child_die = sibling_die (child_die);
16170     }
16171
16172   /* Do not consider external references.  According to the DWARF standard,
16173      these DIEs are identified by the fact that they have no byte_size
16174      attribute, and a declaration attribute.  */
16175   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16176       || !die_is_declaration (die, cu))
16177     new_symbol (die, type, cu);
16178 }
16179
16180 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16181    update TYPE using some information only available in DIE's children.  */
16182
16183 static void
16184 update_enumeration_type_from_children (struct die_info *die,
16185                                        struct type *type,
16186                                        struct dwarf2_cu *cu)
16187 {
16188   struct die_info *child_die;
16189   int unsigned_enum = 1;
16190   int flag_enum = 1;
16191   ULONGEST mask = 0;
16192
16193   auto_obstack obstack;
16194
16195   for (child_die = die->child;
16196        child_die != NULL && child_die->tag;
16197        child_die = sibling_die (child_die))
16198     {
16199       struct attribute *attr;
16200       LONGEST value;
16201       const gdb_byte *bytes;
16202       struct dwarf2_locexpr_baton *baton;
16203       const char *name;
16204
16205       if (child_die->tag != DW_TAG_enumerator)
16206         continue;
16207
16208       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16209       if (attr == NULL)
16210         continue;
16211
16212       name = dwarf2_name (child_die, cu);
16213       if (name == NULL)
16214         name = "<anonymous enumerator>";
16215
16216       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16217                                &value, &bytes, &baton);
16218       if (value < 0)
16219         {
16220           unsigned_enum = 0;
16221           flag_enum = 0;
16222         }
16223       else if ((mask & value) != 0)
16224         flag_enum = 0;
16225       else
16226         mask |= value;
16227
16228       /* If we already know that the enum type is neither unsigned, nor
16229          a flag type, no need to look at the rest of the enumerates.  */
16230       if (!unsigned_enum && !flag_enum)
16231         break;
16232     }
16233
16234   if (unsigned_enum)
16235     TYPE_UNSIGNED (type) = 1;
16236   if (flag_enum)
16237     TYPE_FLAG_ENUM (type) = 1;
16238 }
16239
16240 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16241    complete the type's fields yet, or create any symbols.  */
16242
16243 static struct type *
16244 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16245 {
16246   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16247   struct type *type;
16248   struct attribute *attr;
16249   const char *name;
16250
16251   /* If the definition of this type lives in .debug_types, read that type.
16252      Don't follow DW_AT_specification though, that will take us back up
16253      the chain and we want to go down.  */
16254   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16255   if (attr)
16256     {
16257       type = get_DW_AT_signature_type (die, attr, cu);
16258
16259       /* The type's CU may not be the same as CU.
16260          Ensure TYPE is recorded with CU in die_type_hash.  */
16261       return set_die_type (die, type, cu);
16262     }
16263
16264   type = alloc_type (objfile);
16265
16266   TYPE_CODE (type) = TYPE_CODE_ENUM;
16267   name = dwarf2_full_name (NULL, die, cu);
16268   if (name != NULL)
16269     TYPE_TAG_NAME (type) = name;
16270
16271   attr = dwarf2_attr (die, DW_AT_type, cu);
16272   if (attr != NULL)
16273     {
16274       struct type *underlying_type = die_type (die, cu);
16275
16276       TYPE_TARGET_TYPE (type) = underlying_type;
16277     }
16278
16279   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16280   if (attr)
16281     {
16282       TYPE_LENGTH (type) = DW_UNSND (attr);
16283     }
16284   else
16285     {
16286       TYPE_LENGTH (type) = 0;
16287     }
16288
16289   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16290      declared as private in the package spec, and then defined only
16291      inside the package body.  Such types are known as Taft Amendment
16292      Types.  When another package uses such a type, an incomplete DIE
16293      may be generated by the compiler.  */
16294   if (die_is_declaration (die, cu))
16295     TYPE_STUB (type) = 1;
16296
16297   /* Finish the creation of this type by using the enum's children.
16298      We must call this even when the underlying type has been provided
16299      so that we can determine if we're looking at a "flag" enum.  */
16300   update_enumeration_type_from_children (die, type, cu);
16301
16302   /* If this type has an underlying type that is not a stub, then we
16303      may use its attributes.  We always use the "unsigned" attribute
16304      in this situation, because ordinarily we guess whether the type
16305      is unsigned -- but the guess can be wrong and the underlying type
16306      can tell us the reality.  However, we defer to a local size
16307      attribute if one exists, because this lets the compiler override
16308      the underlying type if needed.  */
16309   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16310     {
16311       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16312       if (TYPE_LENGTH (type) == 0)
16313         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16314     }
16315
16316   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16317
16318   return set_die_type (die, type, cu);
16319 }
16320
16321 /* Given a pointer to a die which begins an enumeration, process all
16322    the dies that define the members of the enumeration, and create the
16323    symbol for the enumeration type.
16324
16325    NOTE: We reverse the order of the element list.  */
16326
16327 static void
16328 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16329 {
16330   struct type *this_type;
16331
16332   this_type = get_die_type (die, cu);
16333   if (this_type == NULL)
16334     this_type = read_enumeration_type (die, cu);
16335
16336   if (die->child != NULL)
16337     {
16338       struct die_info *child_die;
16339       struct symbol *sym;
16340       struct field *fields = NULL;
16341       int num_fields = 0;
16342       const char *name;
16343
16344       child_die = die->child;
16345       while (child_die && child_die->tag)
16346         {
16347           if (child_die->tag != DW_TAG_enumerator)
16348             {
16349               process_die (child_die, cu);
16350             }
16351           else
16352             {
16353               name = dwarf2_name (child_die, cu);
16354               if (name)
16355                 {
16356                   sym = new_symbol (child_die, this_type, cu);
16357
16358                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16359                     {
16360                       fields = (struct field *)
16361                         xrealloc (fields,
16362                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16363                                   * sizeof (struct field));
16364                     }
16365
16366                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16367                   FIELD_TYPE (fields[num_fields]) = NULL;
16368                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16369                   FIELD_BITSIZE (fields[num_fields]) = 0;
16370
16371                   num_fields++;
16372                 }
16373             }
16374
16375           child_die = sibling_die (child_die);
16376         }
16377
16378       if (num_fields)
16379         {
16380           TYPE_NFIELDS (this_type) = num_fields;
16381           TYPE_FIELDS (this_type) = (struct field *)
16382             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16383           memcpy (TYPE_FIELDS (this_type), fields,
16384                   sizeof (struct field) * num_fields);
16385           xfree (fields);
16386         }
16387     }
16388
16389   /* If we are reading an enum from a .debug_types unit, and the enum
16390      is a declaration, and the enum is not the signatured type in the
16391      unit, then we do not want to add a symbol for it.  Adding a
16392      symbol would in some cases obscure the true definition of the
16393      enum, giving users an incomplete type when the definition is
16394      actually available.  Note that we do not want to do this for all
16395      enums which are just declarations, because C++0x allows forward
16396      enum declarations.  */
16397   if (cu->per_cu->is_debug_types
16398       && die_is_declaration (die, cu))
16399     {
16400       struct signatured_type *sig_type;
16401
16402       sig_type = (struct signatured_type *) cu->per_cu;
16403       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16404       if (sig_type->type_offset_in_section != die->sect_off)
16405         return;
16406     }
16407
16408   new_symbol (die, this_type, cu);
16409 }
16410
16411 /* Extract all information from a DW_TAG_array_type DIE and put it in
16412    the DIE's type field.  For now, this only handles one dimensional
16413    arrays.  */
16414
16415 static struct type *
16416 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16417 {
16418   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16419   struct die_info *child_die;
16420   struct type *type;
16421   struct type *element_type, *range_type, *index_type;
16422   struct attribute *attr;
16423   const char *name;
16424   struct dynamic_prop *byte_stride_prop = NULL;
16425   unsigned int bit_stride = 0;
16426
16427   element_type = die_type (die, cu);
16428
16429   /* The die_type call above may have already set the type for this DIE.  */
16430   type = get_die_type (die, cu);
16431   if (type)
16432     return type;
16433
16434   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16435   if (attr != NULL)
16436     {
16437       int stride_ok;
16438
16439       byte_stride_prop
16440         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16441       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16442       if (!stride_ok)
16443         {
16444           complaint (&symfile_complaints,
16445                      _("unable to read array DW_AT_byte_stride "
16446                        " - DIE at %s [in module %s]"),
16447                      sect_offset_str (die->sect_off),
16448                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16449           /* Ignore this attribute.  We will likely not be able to print
16450              arrays of this type correctly, but there is little we can do
16451              to help if we cannot read the attribute's value.  */
16452           byte_stride_prop = NULL;
16453         }
16454     }
16455
16456   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16457   if (attr != NULL)
16458     bit_stride = DW_UNSND (attr);
16459
16460   /* Irix 6.2 native cc creates array types without children for
16461      arrays with unspecified length.  */
16462   if (die->child == NULL)
16463     {
16464       index_type = objfile_type (objfile)->builtin_int;
16465       range_type = create_static_range_type (NULL, index_type, 0, -1);
16466       type = create_array_type_with_stride (NULL, element_type, range_type,
16467                                             byte_stride_prop, bit_stride);
16468       return set_die_type (die, type, cu);
16469     }
16470
16471   std::vector<struct type *> range_types;
16472   child_die = die->child;
16473   while (child_die && child_die->tag)
16474     {
16475       if (child_die->tag == DW_TAG_subrange_type)
16476         {
16477           struct type *child_type = read_type_die (child_die, cu);
16478
16479           if (child_type != NULL)
16480             {
16481               /* The range type was succesfully read.  Save it for the
16482                  array type creation.  */
16483               range_types.push_back (child_type);
16484             }
16485         }
16486       child_die = sibling_die (child_die);
16487     }
16488
16489   /* Dwarf2 dimensions are output from left to right, create the
16490      necessary array types in backwards order.  */
16491
16492   type = element_type;
16493
16494   if (read_array_order (die, cu) == DW_ORD_col_major)
16495     {
16496       int i = 0;
16497
16498       while (i < range_types.size ())
16499         type = create_array_type_with_stride (NULL, type, range_types[i++],
16500                                               byte_stride_prop, bit_stride);
16501     }
16502   else
16503     {
16504       size_t ndim = range_types.size ();
16505       while (ndim-- > 0)
16506         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16507                                               byte_stride_prop, bit_stride);
16508     }
16509
16510   /* Understand Dwarf2 support for vector types (like they occur on
16511      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16512      array type.  This is not part of the Dwarf2/3 standard yet, but a
16513      custom vendor extension.  The main difference between a regular
16514      array and the vector variant is that vectors are passed by value
16515      to functions.  */
16516   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16517   if (attr)
16518     make_vector_type (type);
16519
16520   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16521      implementation may choose to implement triple vectors using this
16522      attribute.  */
16523   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16524   if (attr)
16525     {
16526       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16527         TYPE_LENGTH (type) = DW_UNSND (attr);
16528       else
16529         complaint (&symfile_complaints,
16530                    _("DW_AT_byte_size for array type smaller "
16531                      "than the total size of elements"));
16532     }
16533
16534   name = dwarf2_name (die, cu);
16535   if (name)
16536     TYPE_NAME (type) = name;
16537
16538   /* Install the type in the die.  */
16539   set_die_type (die, type, cu);
16540
16541   /* set_die_type should be already done.  */
16542   set_descriptive_type (type, die, cu);
16543
16544   return type;
16545 }
16546
16547 static enum dwarf_array_dim_ordering
16548 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16549 {
16550   struct attribute *attr;
16551
16552   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16553
16554   if (attr)
16555     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16556
16557   /* GNU F77 is a special case, as at 08/2004 array type info is the
16558      opposite order to the dwarf2 specification, but data is still
16559      laid out as per normal fortran.
16560
16561      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16562      version checking.  */
16563
16564   if (cu->language == language_fortran
16565       && cu->producer && strstr (cu->producer, "GNU F77"))
16566     {
16567       return DW_ORD_row_major;
16568     }
16569
16570   switch (cu->language_defn->la_array_ordering)
16571     {
16572     case array_column_major:
16573       return DW_ORD_col_major;
16574     case array_row_major:
16575     default:
16576       return DW_ORD_row_major;
16577     };
16578 }
16579
16580 /* Extract all information from a DW_TAG_set_type DIE and put it in
16581    the DIE's type field.  */
16582
16583 static struct type *
16584 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16585 {
16586   struct type *domain_type, *set_type;
16587   struct attribute *attr;
16588
16589   domain_type = die_type (die, cu);
16590
16591   /* The die_type call above may have already set the type for this DIE.  */
16592   set_type = get_die_type (die, cu);
16593   if (set_type)
16594     return set_type;
16595
16596   set_type = create_set_type (NULL, domain_type);
16597
16598   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16599   if (attr)
16600     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16601
16602   return set_die_type (die, set_type, cu);
16603 }
16604
16605 /* A helper for read_common_block that creates a locexpr baton.
16606    SYM is the symbol which we are marking as computed.
16607    COMMON_DIE is the DIE for the common block.
16608    COMMON_LOC is the location expression attribute for the common
16609    block itself.
16610    MEMBER_LOC is the location expression attribute for the particular
16611    member of the common block that we are processing.
16612    CU is the CU from which the above come.  */
16613
16614 static void
16615 mark_common_block_symbol_computed (struct symbol *sym,
16616                                    struct die_info *common_die,
16617                                    struct attribute *common_loc,
16618                                    struct attribute *member_loc,
16619                                    struct dwarf2_cu *cu)
16620 {
16621   struct dwarf2_per_objfile *dwarf2_per_objfile
16622     = cu->per_cu->dwarf2_per_objfile;
16623   struct objfile *objfile = dwarf2_per_objfile->objfile;
16624   struct dwarf2_locexpr_baton *baton;
16625   gdb_byte *ptr;
16626   unsigned int cu_off;
16627   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16628   LONGEST offset = 0;
16629
16630   gdb_assert (common_loc && member_loc);
16631   gdb_assert (attr_form_is_block (common_loc));
16632   gdb_assert (attr_form_is_block (member_loc)
16633               || attr_form_is_constant (member_loc));
16634
16635   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16636   baton->per_cu = cu->per_cu;
16637   gdb_assert (baton->per_cu);
16638
16639   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16640
16641   if (attr_form_is_constant (member_loc))
16642     {
16643       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16644       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16645     }
16646   else
16647     baton->size += DW_BLOCK (member_loc)->size;
16648
16649   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16650   baton->data = ptr;
16651
16652   *ptr++ = DW_OP_call4;
16653   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16654   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16655   ptr += 4;
16656
16657   if (attr_form_is_constant (member_loc))
16658     {
16659       *ptr++ = DW_OP_addr;
16660       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16661       ptr += cu->header.addr_size;
16662     }
16663   else
16664     {
16665       /* We have to copy the data here, because DW_OP_call4 will only
16666          use a DW_AT_location attribute.  */
16667       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16668       ptr += DW_BLOCK (member_loc)->size;
16669     }
16670
16671   *ptr++ = DW_OP_plus;
16672   gdb_assert (ptr - baton->data == baton->size);
16673
16674   SYMBOL_LOCATION_BATON (sym) = baton;
16675   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16676 }
16677
16678 /* Create appropriate locally-scoped variables for all the
16679    DW_TAG_common_block entries.  Also create a struct common_block
16680    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16681    is used to sepate the common blocks name namespace from regular
16682    variable names.  */
16683
16684 static void
16685 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16686 {
16687   struct attribute *attr;
16688
16689   attr = dwarf2_attr (die, DW_AT_location, cu);
16690   if (attr)
16691     {
16692       /* Support the .debug_loc offsets.  */
16693       if (attr_form_is_block (attr))
16694         {
16695           /* Ok.  */
16696         }
16697       else if (attr_form_is_section_offset (attr))
16698         {
16699           dwarf2_complex_location_expr_complaint ();
16700           attr = NULL;
16701         }
16702       else
16703         {
16704           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16705                                                  "common block member");
16706           attr = NULL;
16707         }
16708     }
16709
16710   if (die->child != NULL)
16711     {
16712       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16713       struct die_info *child_die;
16714       size_t n_entries = 0, size;
16715       struct common_block *common_block;
16716       struct symbol *sym;
16717
16718       for (child_die = die->child;
16719            child_die && child_die->tag;
16720            child_die = sibling_die (child_die))
16721         ++n_entries;
16722
16723       size = (sizeof (struct common_block)
16724               + (n_entries - 1) * sizeof (struct symbol *));
16725       common_block
16726         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16727                                                  size);
16728       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16729       common_block->n_entries = 0;
16730
16731       for (child_die = die->child;
16732            child_die && child_die->tag;
16733            child_die = sibling_die (child_die))
16734         {
16735           /* Create the symbol in the DW_TAG_common_block block in the current
16736              symbol scope.  */
16737           sym = new_symbol (child_die, NULL, cu);
16738           if (sym != NULL)
16739             {
16740               struct attribute *member_loc;
16741
16742               common_block->contents[common_block->n_entries++] = sym;
16743
16744               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16745                                         cu);
16746               if (member_loc)
16747                 {
16748                   /* GDB has handled this for a long time, but it is
16749                      not specified by DWARF.  It seems to have been
16750                      emitted by gfortran at least as recently as:
16751                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16752                   complaint (&symfile_complaints,
16753                              _("Variable in common block has "
16754                                "DW_AT_data_member_location "
16755                                "- DIE at %s [in module %s]"),
16756                                sect_offset_str (child_die->sect_off),
16757                              objfile_name (objfile));
16758
16759                   if (attr_form_is_section_offset (member_loc))
16760                     dwarf2_complex_location_expr_complaint ();
16761                   else if (attr_form_is_constant (member_loc)
16762                            || attr_form_is_block (member_loc))
16763                     {
16764                       if (attr)
16765                         mark_common_block_symbol_computed (sym, die, attr,
16766                                                            member_loc, cu);
16767                     }
16768                   else
16769                     dwarf2_complex_location_expr_complaint ();
16770                 }
16771             }
16772         }
16773
16774       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16775       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16776     }
16777 }
16778
16779 /* Create a type for a C++ namespace.  */
16780
16781 static struct type *
16782 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16783 {
16784   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16785   const char *previous_prefix, *name;
16786   int is_anonymous;
16787   struct type *type;
16788
16789   /* For extensions, reuse the type of the original namespace.  */
16790   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16791     {
16792       struct die_info *ext_die;
16793       struct dwarf2_cu *ext_cu = cu;
16794
16795       ext_die = dwarf2_extension (die, &ext_cu);
16796       type = read_type_die (ext_die, ext_cu);
16797
16798       /* EXT_CU may not be the same as CU.
16799          Ensure TYPE is recorded with CU in die_type_hash.  */
16800       return set_die_type (die, type, cu);
16801     }
16802
16803   name = namespace_name (die, &is_anonymous, cu);
16804
16805   /* Now build the name of the current namespace.  */
16806
16807   previous_prefix = determine_prefix (die, cu);
16808   if (previous_prefix[0] != '\0')
16809     name = typename_concat (&objfile->objfile_obstack,
16810                             previous_prefix, name, 0, cu);
16811
16812   /* Create the type.  */
16813   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16814   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16815
16816   return set_die_type (die, type, cu);
16817 }
16818
16819 /* Read a namespace scope.  */
16820
16821 static void
16822 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16823 {
16824   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16825   int is_anonymous;
16826
16827   /* Add a symbol associated to this if we haven't seen the namespace
16828      before.  Also, add a using directive if it's an anonymous
16829      namespace.  */
16830
16831   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16832     {
16833       struct type *type;
16834
16835       type = read_type_die (die, cu);
16836       new_symbol (die, type, cu);
16837
16838       namespace_name (die, &is_anonymous, cu);
16839       if (is_anonymous)
16840         {
16841           const char *previous_prefix = determine_prefix (die, cu);
16842
16843           std::vector<const char *> excludes;
16844           add_using_directive (using_directives (cu->language),
16845                                previous_prefix, TYPE_NAME (type), NULL,
16846                                NULL, excludes, 0, &objfile->objfile_obstack);
16847         }
16848     }
16849
16850   if (die->child != NULL)
16851     {
16852       struct die_info *child_die = die->child;
16853
16854       while (child_die && child_die->tag)
16855         {
16856           process_die (child_die, cu);
16857           child_die = sibling_die (child_die);
16858         }
16859     }
16860 }
16861
16862 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16863    imported module.  Still we need that type as local Fortran "use ... only"
16864    declaration imports depend on the created type in determine_prefix.  */
16865
16866 static struct type *
16867 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16868 {
16869   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16870   const char *module_name;
16871   struct type *type;
16872
16873   module_name = dwarf2_name (die, cu);
16874   if (!module_name)
16875     complaint (&symfile_complaints,
16876                _("DW_TAG_module has no name, offset %s"),
16877                sect_offset_str (die->sect_off));
16878   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16879
16880   /* determine_prefix uses TYPE_TAG_NAME.  */
16881   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16882
16883   return set_die_type (die, type, cu);
16884 }
16885
16886 /* Read a Fortran module.  */
16887
16888 static void
16889 read_module (struct die_info *die, struct dwarf2_cu *cu)
16890 {
16891   struct die_info *child_die = die->child;
16892   struct type *type;
16893
16894   type = read_type_die (die, cu);
16895   new_symbol (die, type, cu);
16896
16897   while (child_die && child_die->tag)
16898     {
16899       process_die (child_die, cu);
16900       child_die = sibling_die (child_die);
16901     }
16902 }
16903
16904 /* Return the name of the namespace represented by DIE.  Set
16905    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16906    namespace.  */
16907
16908 static const char *
16909 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16910 {
16911   struct die_info *current_die;
16912   const char *name = NULL;
16913
16914   /* Loop through the extensions until we find a name.  */
16915
16916   for (current_die = die;
16917        current_die != NULL;
16918        current_die = dwarf2_extension (die, &cu))
16919     {
16920       /* We don't use dwarf2_name here so that we can detect the absence
16921          of a name -> anonymous namespace.  */
16922       name = dwarf2_string_attr (die, DW_AT_name, cu);
16923
16924       if (name != NULL)
16925         break;
16926     }
16927
16928   /* Is it an anonymous namespace?  */
16929
16930   *is_anonymous = (name == NULL);
16931   if (*is_anonymous)
16932     name = CP_ANONYMOUS_NAMESPACE_STR;
16933
16934   return name;
16935 }
16936
16937 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16938    the user defined type vector.  */
16939
16940 static struct type *
16941 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16942 {
16943   struct gdbarch *gdbarch
16944     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16945   struct comp_unit_head *cu_header = &cu->header;
16946   struct type *type;
16947   struct attribute *attr_byte_size;
16948   struct attribute *attr_address_class;
16949   int byte_size, addr_class;
16950   struct type *target_type;
16951
16952   target_type = die_type (die, cu);
16953
16954   /* The die_type call above may have already set the type for this DIE.  */
16955   type = get_die_type (die, cu);
16956   if (type)
16957     return type;
16958
16959   type = lookup_pointer_type (target_type);
16960
16961   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16962   if (attr_byte_size)
16963     byte_size = DW_UNSND (attr_byte_size);
16964   else
16965     byte_size = cu_header->addr_size;
16966
16967   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16968   if (attr_address_class)
16969     addr_class = DW_UNSND (attr_address_class);
16970   else
16971     addr_class = DW_ADDR_none;
16972
16973   /* If the pointer size or address class is different than the
16974      default, create a type variant marked as such and set the
16975      length accordingly.  */
16976   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16977     {
16978       if (gdbarch_address_class_type_flags_p (gdbarch))
16979         {
16980           int type_flags;
16981
16982           type_flags = gdbarch_address_class_type_flags
16983                          (gdbarch, byte_size, addr_class);
16984           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16985                       == 0);
16986           type = make_type_with_address_space (type, type_flags);
16987         }
16988       else if (TYPE_LENGTH (type) != byte_size)
16989         {
16990           complaint (&symfile_complaints,
16991                      _("invalid pointer size %d"), byte_size);
16992         }
16993       else
16994         {
16995           /* Should we also complain about unhandled address classes?  */
16996         }
16997     }
16998
16999   TYPE_LENGTH (type) = byte_size;
17000   return set_die_type (die, type, cu);
17001 }
17002
17003 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17004    the user defined type vector.  */
17005
17006 static struct type *
17007 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17008 {
17009   struct type *type;
17010   struct type *to_type;
17011   struct type *domain;
17012
17013   to_type = die_type (die, cu);
17014   domain = die_containing_type (die, cu);
17015
17016   /* The calls above may have already set the type for this DIE.  */
17017   type = get_die_type (die, cu);
17018   if (type)
17019     return type;
17020
17021   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17022     type = lookup_methodptr_type (to_type);
17023   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17024     {
17025       struct type *new_type
17026         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17027
17028       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17029                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17030                             TYPE_VARARGS (to_type));
17031       type = lookup_methodptr_type (new_type);
17032     }
17033   else
17034     type = lookup_memberptr_type (to_type, domain);
17035
17036   return set_die_type (die, type, cu);
17037 }
17038
17039 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17040    the user defined type vector.  */
17041
17042 static struct type *
17043 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17044                           enum type_code refcode)
17045 {
17046   struct comp_unit_head *cu_header = &cu->header;
17047   struct type *type, *target_type;
17048   struct attribute *attr;
17049
17050   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17051
17052   target_type = die_type (die, cu);
17053
17054   /* The die_type call above may have already set the type for this DIE.  */
17055   type = get_die_type (die, cu);
17056   if (type)
17057     return type;
17058
17059   type = lookup_reference_type (target_type, refcode);
17060   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17061   if (attr)
17062     {
17063       TYPE_LENGTH (type) = DW_UNSND (attr);
17064     }
17065   else
17066     {
17067       TYPE_LENGTH (type) = cu_header->addr_size;
17068     }
17069   return set_die_type (die, type, cu);
17070 }
17071
17072 /* Add the given cv-qualifiers to the element type of the array.  GCC
17073    outputs DWARF type qualifiers that apply to an array, not the
17074    element type.  But GDB relies on the array element type to carry
17075    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17076    specification.  */
17077
17078 static struct type *
17079 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17080                    struct type *base_type, int cnst, int voltl)
17081 {
17082   struct type *el_type, *inner_array;
17083
17084   base_type = copy_type (base_type);
17085   inner_array = base_type;
17086
17087   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17088     {
17089       TYPE_TARGET_TYPE (inner_array) =
17090         copy_type (TYPE_TARGET_TYPE (inner_array));
17091       inner_array = TYPE_TARGET_TYPE (inner_array);
17092     }
17093
17094   el_type = TYPE_TARGET_TYPE (inner_array);
17095   cnst |= TYPE_CONST (el_type);
17096   voltl |= TYPE_VOLATILE (el_type);
17097   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17098
17099   return set_die_type (die, base_type, cu);
17100 }
17101
17102 static struct type *
17103 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17104 {
17105   struct type *base_type, *cv_type;
17106
17107   base_type = die_type (die, cu);
17108
17109   /* The die_type call above may have already set the type for this DIE.  */
17110   cv_type = get_die_type (die, cu);
17111   if (cv_type)
17112     return cv_type;
17113
17114   /* In case the const qualifier is applied to an array type, the element type
17115      is so qualified, not the array type (section 6.7.3 of C99).  */
17116   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17117     return add_array_cv_type (die, cu, base_type, 1, 0);
17118
17119   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17120   return set_die_type (die, cv_type, cu);
17121 }
17122
17123 static struct type *
17124 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17125 {
17126   struct type *base_type, *cv_type;
17127
17128   base_type = die_type (die, cu);
17129
17130   /* The die_type call above may have already set the type for this DIE.  */
17131   cv_type = get_die_type (die, cu);
17132   if (cv_type)
17133     return cv_type;
17134
17135   /* In case the volatile qualifier is applied to an array type, the
17136      element type is so qualified, not the array type (section 6.7.3
17137      of C99).  */
17138   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17139     return add_array_cv_type (die, cu, base_type, 0, 1);
17140
17141   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17142   return set_die_type (die, cv_type, cu);
17143 }
17144
17145 /* Handle DW_TAG_restrict_type.  */
17146
17147 static struct type *
17148 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17149 {
17150   struct type *base_type, *cv_type;
17151
17152   base_type = die_type (die, cu);
17153
17154   /* The die_type call above may have already set the type for this DIE.  */
17155   cv_type = get_die_type (die, cu);
17156   if (cv_type)
17157     return cv_type;
17158
17159   cv_type = make_restrict_type (base_type);
17160   return set_die_type (die, cv_type, cu);
17161 }
17162
17163 /* Handle DW_TAG_atomic_type.  */
17164
17165 static struct type *
17166 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17167 {
17168   struct type *base_type, *cv_type;
17169
17170   base_type = die_type (die, cu);
17171
17172   /* The die_type call above may have already set the type for this DIE.  */
17173   cv_type = get_die_type (die, cu);
17174   if (cv_type)
17175     return cv_type;
17176
17177   cv_type = make_atomic_type (base_type);
17178   return set_die_type (die, cv_type, cu);
17179 }
17180
17181 /* Extract all information from a DW_TAG_string_type DIE and add to
17182    the user defined type vector.  It isn't really a user defined type,
17183    but it behaves like one, with other DIE's using an AT_user_def_type
17184    attribute to reference it.  */
17185
17186 static struct type *
17187 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17188 {
17189   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17190   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17191   struct type *type, *range_type, *index_type, *char_type;
17192   struct attribute *attr;
17193   unsigned int length;
17194
17195   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17196   if (attr)
17197     {
17198       length = DW_UNSND (attr);
17199     }
17200   else
17201     {
17202       /* Check for the DW_AT_byte_size attribute.  */
17203       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17204       if (attr)
17205         {
17206           length = DW_UNSND (attr);
17207         }
17208       else
17209         {
17210           length = 1;
17211         }
17212     }
17213
17214   index_type = objfile_type (objfile)->builtin_int;
17215   range_type = create_static_range_type (NULL, index_type, 1, length);
17216   char_type = language_string_char_type (cu->language_defn, gdbarch);
17217   type = create_string_type (NULL, char_type, range_type);
17218
17219   return set_die_type (die, type, cu);
17220 }
17221
17222 /* Assuming that DIE corresponds to a function, returns nonzero
17223    if the function is prototyped.  */
17224
17225 static int
17226 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17227 {
17228   struct attribute *attr;
17229
17230   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17231   if (attr && (DW_UNSND (attr) != 0))
17232     return 1;
17233
17234   /* The DWARF standard implies that the DW_AT_prototyped attribute
17235      is only meaninful for C, but the concept also extends to other
17236      languages that allow unprototyped functions (Eg: Objective C).
17237      For all other languages, assume that functions are always
17238      prototyped.  */
17239   if (cu->language != language_c
17240       && cu->language != language_objc
17241       && cu->language != language_opencl)
17242     return 1;
17243
17244   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17245      prototyped and unprototyped functions; default to prototyped,
17246      since that is more common in modern code (and RealView warns
17247      about unprototyped functions).  */
17248   if (producer_is_realview (cu->producer))
17249     return 1;
17250
17251   return 0;
17252 }
17253
17254 /* Handle DIES due to C code like:
17255
17256    struct foo
17257    {
17258    int (*funcp)(int a, long l);
17259    int b;
17260    };
17261
17262    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17263
17264 static struct type *
17265 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17266 {
17267   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17268   struct type *type;            /* Type that this function returns.  */
17269   struct type *ftype;           /* Function that returns above type.  */
17270   struct attribute *attr;
17271
17272   type = die_type (die, cu);
17273
17274   /* The die_type call above may have already set the type for this DIE.  */
17275   ftype = get_die_type (die, cu);
17276   if (ftype)
17277     return ftype;
17278
17279   ftype = lookup_function_type (type);
17280
17281   if (prototyped_function_p (die, cu))
17282     TYPE_PROTOTYPED (ftype) = 1;
17283
17284   /* Store the calling convention in the type if it's available in
17285      the subroutine die.  Otherwise set the calling convention to
17286      the default value DW_CC_normal.  */
17287   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17288   if (attr)
17289     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17290   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17291     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17292   else
17293     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17294
17295   /* Record whether the function returns normally to its caller or not
17296      if the DWARF producer set that information.  */
17297   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17298   if (attr && (DW_UNSND (attr) != 0))
17299     TYPE_NO_RETURN (ftype) = 1;
17300
17301   /* We need to add the subroutine type to the die immediately so
17302      we don't infinitely recurse when dealing with parameters
17303      declared as the same subroutine type.  */
17304   set_die_type (die, ftype, cu);
17305
17306   if (die->child != NULL)
17307     {
17308       struct type *void_type = objfile_type (objfile)->builtin_void;
17309       struct die_info *child_die;
17310       int nparams, iparams;
17311
17312       /* Count the number of parameters.
17313          FIXME: GDB currently ignores vararg functions, but knows about
17314          vararg member functions.  */
17315       nparams = 0;
17316       child_die = die->child;
17317       while (child_die && child_die->tag)
17318         {
17319           if (child_die->tag == DW_TAG_formal_parameter)
17320             nparams++;
17321           else if (child_die->tag == DW_TAG_unspecified_parameters)
17322             TYPE_VARARGS (ftype) = 1;
17323           child_die = sibling_die (child_die);
17324         }
17325
17326       /* Allocate storage for parameters and fill them in.  */
17327       TYPE_NFIELDS (ftype) = nparams;
17328       TYPE_FIELDS (ftype) = (struct field *)
17329         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17330
17331       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17332          even if we error out during the parameters reading below.  */
17333       for (iparams = 0; iparams < nparams; iparams++)
17334         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17335
17336       iparams = 0;
17337       child_die = die->child;
17338       while (child_die && child_die->tag)
17339         {
17340           if (child_die->tag == DW_TAG_formal_parameter)
17341             {
17342               struct type *arg_type;
17343
17344               /* DWARF version 2 has no clean way to discern C++
17345                  static and non-static member functions.  G++ helps
17346                  GDB by marking the first parameter for non-static
17347                  member functions (which is the this pointer) as
17348                  artificial.  We pass this information to
17349                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17350
17351                  DWARF version 3 added DW_AT_object_pointer, which GCC
17352                  4.5 does not yet generate.  */
17353               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17354               if (attr)
17355                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17356               else
17357                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17358               arg_type = die_type (child_die, cu);
17359
17360               /* RealView does not mark THIS as const, which the testsuite
17361                  expects.  GCC marks THIS as const in method definitions,
17362                  but not in the class specifications (GCC PR 43053).  */
17363               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17364                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17365                 {
17366                   int is_this = 0;
17367                   struct dwarf2_cu *arg_cu = cu;
17368                   const char *name = dwarf2_name (child_die, cu);
17369
17370                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17371                   if (attr)
17372                     {
17373                       /* If the compiler emits this, use it.  */
17374                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17375                         is_this = 1;
17376                     }
17377                   else if (name && strcmp (name, "this") == 0)
17378                     /* Function definitions will have the argument names.  */
17379                     is_this = 1;
17380                   else if (name == NULL && iparams == 0)
17381                     /* Declarations may not have the names, so like
17382                        elsewhere in GDB, assume an artificial first
17383                        argument is "this".  */
17384                     is_this = 1;
17385
17386                   if (is_this)
17387                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17388                                              arg_type, 0);
17389                 }
17390
17391               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17392               iparams++;
17393             }
17394           child_die = sibling_die (child_die);
17395         }
17396     }
17397
17398   return ftype;
17399 }
17400
17401 static struct type *
17402 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17403 {
17404   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17405   const char *name = NULL;
17406   struct type *this_type, *target_type;
17407
17408   name = dwarf2_full_name (NULL, die, cu);
17409   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17410   TYPE_TARGET_STUB (this_type) = 1;
17411   set_die_type (die, this_type, cu);
17412   target_type = die_type (die, cu);
17413   if (target_type != this_type)
17414     TYPE_TARGET_TYPE (this_type) = target_type;
17415   else
17416     {
17417       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17418          spec and cause infinite loops in GDB.  */
17419       complaint (&symfile_complaints,
17420                  _("Self-referential DW_TAG_typedef "
17421                    "- DIE at %s [in module %s]"),
17422                  sect_offset_str (die->sect_off), objfile_name (objfile));
17423       TYPE_TARGET_TYPE (this_type) = NULL;
17424     }
17425   return this_type;
17426 }
17427
17428 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17429    (which may be different from NAME) to the architecture back-end to allow
17430    it to guess the correct format if necessary.  */
17431
17432 static struct type *
17433 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17434                         const char *name_hint)
17435 {
17436   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17437   const struct floatformat **format;
17438   struct type *type;
17439
17440   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17441   if (format)
17442     type = init_float_type (objfile, bits, name, format);
17443   else
17444     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17445
17446   return type;
17447 }
17448
17449 /* Find a representation of a given base type and install
17450    it in the TYPE field of the die.  */
17451
17452 static struct type *
17453 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17454 {
17455   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17456   struct type *type;
17457   struct attribute *attr;
17458   int encoding = 0, bits = 0;
17459   const char *name;
17460
17461   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17462   if (attr)
17463     {
17464       encoding = DW_UNSND (attr);
17465     }
17466   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17467   if (attr)
17468     {
17469       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17470     }
17471   name = dwarf2_name (die, cu);
17472   if (!name)
17473     {
17474       complaint (&symfile_complaints,
17475                  _("DW_AT_name missing from DW_TAG_base_type"));
17476     }
17477
17478   switch (encoding)
17479     {
17480       case DW_ATE_address:
17481         /* Turn DW_ATE_address into a void * pointer.  */
17482         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17483         type = init_pointer_type (objfile, bits, name, type);
17484         break;
17485       case DW_ATE_boolean:
17486         type = init_boolean_type (objfile, bits, 1, name);
17487         break;
17488       case DW_ATE_complex_float:
17489         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17490         type = init_complex_type (objfile, name, type);
17491         break;
17492       case DW_ATE_decimal_float:
17493         type = init_decfloat_type (objfile, bits, name);
17494         break;
17495       case DW_ATE_float:
17496         type = dwarf2_init_float_type (objfile, bits, name, name);
17497         break;
17498       case DW_ATE_signed:
17499         type = init_integer_type (objfile, bits, 0, name);
17500         break;
17501       case DW_ATE_unsigned:
17502         if (cu->language == language_fortran
17503             && name
17504             && startswith (name, "character("))
17505           type = init_character_type (objfile, bits, 1, name);
17506         else
17507           type = init_integer_type (objfile, bits, 1, name);
17508         break;
17509       case DW_ATE_signed_char:
17510         if (cu->language == language_ada || cu->language == language_m2
17511             || cu->language == language_pascal
17512             || cu->language == language_fortran)
17513           type = init_character_type (objfile, bits, 0, name);
17514         else
17515           type = init_integer_type (objfile, bits, 0, name);
17516         break;
17517       case DW_ATE_unsigned_char:
17518         if (cu->language == language_ada || cu->language == language_m2
17519             || cu->language == language_pascal
17520             || cu->language == language_fortran
17521             || cu->language == language_rust)
17522           type = init_character_type (objfile, bits, 1, name);
17523         else
17524           type = init_integer_type (objfile, bits, 1, name);
17525         break;
17526       case DW_ATE_UTF:
17527         {
17528           gdbarch *arch = get_objfile_arch (objfile);
17529
17530           if (bits == 16)
17531             type = builtin_type (arch)->builtin_char16;
17532           else if (bits == 32)
17533             type = builtin_type (arch)->builtin_char32;
17534           else
17535             {
17536               complaint (&symfile_complaints,
17537                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17538                          bits);
17539               type = init_integer_type (objfile, bits, 1, name);
17540             }
17541           return set_die_type (die, type, cu);
17542         }
17543         break;
17544
17545       default:
17546         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17547                    dwarf_type_encoding_name (encoding));
17548         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17549         break;
17550     }
17551
17552   if (name && strcmp (name, "char") == 0)
17553     TYPE_NOSIGN (type) = 1;
17554
17555   return set_die_type (die, type, cu);
17556 }
17557
17558 /* Parse dwarf attribute if it's a block, reference or constant and put the
17559    resulting value of the attribute into struct bound_prop.
17560    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17561
17562 static int
17563 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17564                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17565 {
17566   struct dwarf2_property_baton *baton;
17567   struct obstack *obstack
17568     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17569
17570   if (attr == NULL || prop == NULL)
17571     return 0;
17572
17573   if (attr_form_is_block (attr))
17574     {
17575       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17576       baton->referenced_type = NULL;
17577       baton->locexpr.per_cu = cu->per_cu;
17578       baton->locexpr.size = DW_BLOCK (attr)->size;
17579       baton->locexpr.data = DW_BLOCK (attr)->data;
17580       prop->data.baton = baton;
17581       prop->kind = PROP_LOCEXPR;
17582       gdb_assert (prop->data.baton != NULL);
17583     }
17584   else if (attr_form_is_ref (attr))
17585     {
17586       struct dwarf2_cu *target_cu = cu;
17587       struct die_info *target_die;
17588       struct attribute *target_attr;
17589
17590       target_die = follow_die_ref (die, attr, &target_cu);
17591       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17592       if (target_attr == NULL)
17593         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17594                                    target_cu);
17595       if (target_attr == NULL)
17596         return 0;
17597
17598       switch (target_attr->name)
17599         {
17600           case DW_AT_location:
17601             if (attr_form_is_section_offset (target_attr))
17602               {
17603                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17604                 baton->referenced_type = die_type (target_die, target_cu);
17605                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17606                 prop->data.baton = baton;
17607                 prop->kind = PROP_LOCLIST;
17608                 gdb_assert (prop->data.baton != NULL);
17609               }
17610             else if (attr_form_is_block (target_attr))
17611               {
17612                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17613                 baton->referenced_type = die_type (target_die, target_cu);
17614                 baton->locexpr.per_cu = cu->per_cu;
17615                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17616                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17617                 prop->data.baton = baton;
17618                 prop->kind = PROP_LOCEXPR;
17619                 gdb_assert (prop->data.baton != NULL);
17620               }
17621             else
17622               {
17623                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17624                                                        "dynamic property");
17625                 return 0;
17626               }
17627             break;
17628           case DW_AT_data_member_location:
17629             {
17630               LONGEST offset;
17631
17632               if (!handle_data_member_location (target_die, target_cu,
17633                                                 &offset))
17634                 return 0;
17635
17636               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17637               baton->referenced_type = read_type_die (target_die->parent,
17638                                                       target_cu);
17639               baton->offset_info.offset = offset;
17640               baton->offset_info.type = die_type (target_die, target_cu);
17641               prop->data.baton = baton;
17642               prop->kind = PROP_ADDR_OFFSET;
17643               break;
17644             }
17645         }
17646     }
17647   else if (attr_form_is_constant (attr))
17648     {
17649       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17650       prop->kind = PROP_CONST;
17651     }
17652   else
17653     {
17654       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17655                                              dwarf2_name (die, cu));
17656       return 0;
17657     }
17658
17659   return 1;
17660 }
17661
17662 /* Read the given DW_AT_subrange DIE.  */
17663
17664 static struct type *
17665 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17666 {
17667   struct type *base_type, *orig_base_type;
17668   struct type *range_type;
17669   struct attribute *attr;
17670   struct dynamic_prop low, high;
17671   int low_default_is_valid;
17672   int high_bound_is_count = 0;
17673   const char *name;
17674   LONGEST negative_mask;
17675
17676   orig_base_type = die_type (die, cu);
17677   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17678      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17679      creating the range type, but we use the result of check_typedef
17680      when examining properties of the type.  */
17681   base_type = check_typedef (orig_base_type);
17682
17683   /* The die_type call above may have already set the type for this DIE.  */
17684   range_type = get_die_type (die, cu);
17685   if (range_type)
17686     return range_type;
17687
17688   low.kind = PROP_CONST;
17689   high.kind = PROP_CONST;
17690   high.data.const_val = 0;
17691
17692   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17693      omitting DW_AT_lower_bound.  */
17694   switch (cu->language)
17695     {
17696     case language_c:
17697     case language_cplus:
17698       low.data.const_val = 0;
17699       low_default_is_valid = 1;
17700       break;
17701     case language_fortran:
17702       low.data.const_val = 1;
17703       low_default_is_valid = 1;
17704       break;
17705     case language_d:
17706     case language_objc:
17707     case language_rust:
17708       low.data.const_val = 0;
17709       low_default_is_valid = (cu->header.version >= 4);
17710       break;
17711     case language_ada:
17712     case language_m2:
17713     case language_pascal:
17714       low.data.const_val = 1;
17715       low_default_is_valid = (cu->header.version >= 4);
17716       break;
17717     default:
17718       low.data.const_val = 0;
17719       low_default_is_valid = 0;
17720       break;
17721     }
17722
17723   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17724   if (attr)
17725     attr_to_dynamic_prop (attr, die, cu, &low);
17726   else if (!low_default_is_valid)
17727     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17728                                       "- DIE at %s [in module %s]"),
17729                sect_offset_str (die->sect_off),
17730                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17731
17732   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17733   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17734     {
17735       attr = dwarf2_attr (die, DW_AT_count, cu);
17736       if (attr_to_dynamic_prop (attr, die, cu, &high))
17737         {
17738           /* If bounds are constant do the final calculation here.  */
17739           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17740             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17741           else
17742             high_bound_is_count = 1;
17743         }
17744     }
17745
17746   /* Dwarf-2 specifications explicitly allows to create subrange types
17747      without specifying a base type.
17748      In that case, the base type must be set to the type of
17749      the lower bound, upper bound or count, in that order, if any of these
17750      three attributes references an object that has a type.
17751      If no base type is found, the Dwarf-2 specifications say that
17752      a signed integer type of size equal to the size of an address should
17753      be used.
17754      For the following C code: `extern char gdb_int [];'
17755      GCC produces an empty range DIE.
17756      FIXME: muller/2010-05-28: Possible references to object for low bound,
17757      high bound or count are not yet handled by this code.  */
17758   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17759     {
17760       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17761       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17762       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17763       struct type *int_type = objfile_type (objfile)->builtin_int;
17764
17765       /* Test "int", "long int", and "long long int" objfile types,
17766          and select the first one having a size above or equal to the
17767          architecture address size.  */
17768       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17769         base_type = int_type;
17770       else
17771         {
17772           int_type = objfile_type (objfile)->builtin_long;
17773           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17774             base_type = int_type;
17775           else
17776             {
17777               int_type = objfile_type (objfile)->builtin_long_long;
17778               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17779                 base_type = int_type;
17780             }
17781         }
17782     }
17783
17784   /* Normally, the DWARF producers are expected to use a signed
17785      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17786      But this is unfortunately not always the case, as witnessed
17787      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17788      is used instead.  To work around that ambiguity, we treat
17789      the bounds as signed, and thus sign-extend their values, when
17790      the base type is signed.  */
17791   negative_mask =
17792     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17793   if (low.kind == PROP_CONST
17794       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17795     low.data.const_val |= negative_mask;
17796   if (high.kind == PROP_CONST
17797       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17798     high.data.const_val |= negative_mask;
17799
17800   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17801
17802   if (high_bound_is_count)
17803     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17804
17805   /* Ada expects an empty array on no boundary attributes.  */
17806   if (attr == NULL && cu->language != language_ada)
17807     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17808
17809   name = dwarf2_name (die, cu);
17810   if (name)
17811     TYPE_NAME (range_type) = name;
17812
17813   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17814   if (attr)
17815     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17816
17817   set_die_type (die, range_type, cu);
17818
17819   /* set_die_type should be already done.  */
17820   set_descriptive_type (range_type, die, cu);
17821
17822   return range_type;
17823 }
17824
17825 static struct type *
17826 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17827 {
17828   struct type *type;
17829
17830   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17831                     NULL);
17832   TYPE_NAME (type) = dwarf2_name (die, cu);
17833
17834   /* In Ada, an unspecified type is typically used when the description
17835      of the type is defered to a different unit.  When encountering
17836      such a type, we treat it as a stub, and try to resolve it later on,
17837      when needed.  */
17838   if (cu->language == language_ada)
17839     TYPE_STUB (type) = 1;
17840
17841   return set_die_type (die, type, cu);
17842 }
17843
17844 /* Read a single die and all its descendents.  Set the die's sibling
17845    field to NULL; set other fields in the die correctly, and set all
17846    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17847    location of the info_ptr after reading all of those dies.  PARENT
17848    is the parent of the die in question.  */
17849
17850 static struct die_info *
17851 read_die_and_children (const struct die_reader_specs *reader,
17852                        const gdb_byte *info_ptr,
17853                        const gdb_byte **new_info_ptr,
17854                        struct die_info *parent)
17855 {
17856   struct die_info *die;
17857   const gdb_byte *cur_ptr;
17858   int has_children;
17859
17860   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17861   if (die == NULL)
17862     {
17863       *new_info_ptr = cur_ptr;
17864       return NULL;
17865     }
17866   store_in_ref_table (die, reader->cu);
17867
17868   if (has_children)
17869     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17870   else
17871     {
17872       die->child = NULL;
17873       *new_info_ptr = cur_ptr;
17874     }
17875
17876   die->sibling = NULL;
17877   die->parent = parent;
17878   return die;
17879 }
17880
17881 /* Read a die, all of its descendents, and all of its siblings; set
17882    all of the fields of all of the dies correctly.  Arguments are as
17883    in read_die_and_children.  */
17884
17885 static struct die_info *
17886 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17887                          const gdb_byte *info_ptr,
17888                          const gdb_byte **new_info_ptr,
17889                          struct die_info *parent)
17890 {
17891   struct die_info *first_die, *last_sibling;
17892   const gdb_byte *cur_ptr;
17893
17894   cur_ptr = info_ptr;
17895   first_die = last_sibling = NULL;
17896
17897   while (1)
17898     {
17899       struct die_info *die
17900         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17901
17902       if (die == NULL)
17903         {
17904           *new_info_ptr = cur_ptr;
17905           return first_die;
17906         }
17907
17908       if (!first_die)
17909         first_die = die;
17910       else
17911         last_sibling->sibling = die;
17912
17913       last_sibling = die;
17914     }
17915 }
17916
17917 /* Read a die, all of its descendents, and all of its siblings; set
17918    all of the fields of all of the dies correctly.  Arguments are as
17919    in read_die_and_children.
17920    This the main entry point for reading a DIE and all its children.  */
17921
17922 static struct die_info *
17923 read_die_and_siblings (const struct die_reader_specs *reader,
17924                        const gdb_byte *info_ptr,
17925                        const gdb_byte **new_info_ptr,
17926                        struct die_info *parent)
17927 {
17928   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17929                                                   new_info_ptr, parent);
17930
17931   if (dwarf_die_debug)
17932     {
17933       fprintf_unfiltered (gdb_stdlog,
17934                           "Read die from %s@0x%x of %s:\n",
17935                           get_section_name (reader->die_section),
17936                           (unsigned) (info_ptr - reader->die_section->buffer),
17937                           bfd_get_filename (reader->abfd));
17938       dump_die (die, dwarf_die_debug);
17939     }
17940
17941   return die;
17942 }
17943
17944 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17945    attributes.
17946    The caller is responsible for filling in the extra attributes
17947    and updating (*DIEP)->num_attrs.
17948    Set DIEP to point to a newly allocated die with its information,
17949    except for its child, sibling, and parent fields.
17950    Set HAS_CHILDREN to tell whether the die has children or not.  */
17951
17952 static const gdb_byte *
17953 read_full_die_1 (const struct die_reader_specs *reader,
17954                  struct die_info **diep, const gdb_byte *info_ptr,
17955                  int *has_children, int num_extra_attrs)
17956 {
17957   unsigned int abbrev_number, bytes_read, i;
17958   struct abbrev_info *abbrev;
17959   struct die_info *die;
17960   struct dwarf2_cu *cu = reader->cu;
17961   bfd *abfd = reader->abfd;
17962
17963   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17964   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17965   info_ptr += bytes_read;
17966   if (!abbrev_number)
17967     {
17968       *diep = NULL;
17969       *has_children = 0;
17970       return info_ptr;
17971     }
17972
17973   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17974   if (!abbrev)
17975     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17976            abbrev_number,
17977            bfd_get_filename (abfd));
17978
17979   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17980   die->sect_off = sect_off;
17981   die->tag = abbrev->tag;
17982   die->abbrev = abbrev_number;
17983
17984   /* Make the result usable.
17985      The caller needs to update num_attrs after adding the extra
17986      attributes.  */
17987   die->num_attrs = abbrev->num_attrs;
17988
17989   for (i = 0; i < abbrev->num_attrs; ++i)
17990     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17991                                info_ptr);
17992
17993   *diep = die;
17994   *has_children = abbrev->has_children;
17995   return info_ptr;
17996 }
17997
17998 /* Read a die and all its attributes.
17999    Set DIEP to point to a newly allocated die with its information,
18000    except for its child, sibling, and parent fields.
18001    Set HAS_CHILDREN to tell whether the die has children or not.  */
18002
18003 static const gdb_byte *
18004 read_full_die (const struct die_reader_specs *reader,
18005                struct die_info **diep, const gdb_byte *info_ptr,
18006                int *has_children)
18007 {
18008   const gdb_byte *result;
18009
18010   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18011
18012   if (dwarf_die_debug)
18013     {
18014       fprintf_unfiltered (gdb_stdlog,
18015                           "Read die from %s@0x%x of %s:\n",
18016                           get_section_name (reader->die_section),
18017                           (unsigned) (info_ptr - reader->die_section->buffer),
18018                           bfd_get_filename (reader->abfd));
18019       dump_die (*diep, dwarf_die_debug);
18020     }
18021
18022   return result;
18023 }
18024 \f
18025 /* Abbreviation tables.
18026
18027    In DWARF version 2, the description of the debugging information is
18028    stored in a separate .debug_abbrev section.  Before we read any
18029    dies from a section we read in all abbreviations and install them
18030    in a hash table.  */
18031
18032 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18033
18034 struct abbrev_info *
18035 abbrev_table::alloc_abbrev ()
18036 {
18037   struct abbrev_info *abbrev;
18038
18039   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18040   memset (abbrev, 0, sizeof (struct abbrev_info));
18041
18042   return abbrev;
18043 }
18044
18045 /* Add an abbreviation to the table.  */
18046
18047 void
18048 abbrev_table::add_abbrev (unsigned int abbrev_number,
18049                           struct abbrev_info *abbrev)
18050 {
18051   unsigned int hash_number;
18052
18053   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18054   abbrev->next = m_abbrevs[hash_number];
18055   m_abbrevs[hash_number] = abbrev;
18056 }
18057
18058 /* Look up an abbrev in the table.
18059    Returns NULL if the abbrev is not found.  */
18060
18061 struct abbrev_info *
18062 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18063 {
18064   unsigned int hash_number;
18065   struct abbrev_info *abbrev;
18066
18067   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18068   abbrev = m_abbrevs[hash_number];
18069
18070   while (abbrev)
18071     {
18072       if (abbrev->number == abbrev_number)
18073         return abbrev;
18074       abbrev = abbrev->next;
18075     }
18076   return NULL;
18077 }
18078
18079 /* Read in an abbrev table.  */
18080
18081 static abbrev_table_up
18082 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18083                          struct dwarf2_section_info *section,
18084                          sect_offset sect_off)
18085 {
18086   struct objfile *objfile = dwarf2_per_objfile->objfile;
18087   bfd *abfd = get_section_bfd_owner (section);
18088   const gdb_byte *abbrev_ptr;
18089   struct abbrev_info *cur_abbrev;
18090   unsigned int abbrev_number, bytes_read, abbrev_name;
18091   unsigned int abbrev_form;
18092   struct attr_abbrev *cur_attrs;
18093   unsigned int allocated_attrs;
18094
18095   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18096
18097   dwarf2_read_section (objfile, section);
18098   abbrev_ptr = section->buffer + to_underlying (sect_off);
18099   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18100   abbrev_ptr += bytes_read;
18101
18102   allocated_attrs = ATTR_ALLOC_CHUNK;
18103   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18104
18105   /* Loop until we reach an abbrev number of 0.  */
18106   while (abbrev_number)
18107     {
18108       cur_abbrev = abbrev_table->alloc_abbrev ();
18109
18110       /* read in abbrev header */
18111       cur_abbrev->number = abbrev_number;
18112       cur_abbrev->tag
18113         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18114       abbrev_ptr += bytes_read;
18115       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18116       abbrev_ptr += 1;
18117
18118       /* now read in declarations */
18119       for (;;)
18120         {
18121           LONGEST implicit_const;
18122
18123           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18124           abbrev_ptr += bytes_read;
18125           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18126           abbrev_ptr += bytes_read;
18127           if (abbrev_form == DW_FORM_implicit_const)
18128             {
18129               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18130                                                    &bytes_read);
18131               abbrev_ptr += bytes_read;
18132             }
18133           else
18134             {
18135               /* Initialize it due to a false compiler warning.  */
18136               implicit_const = -1;
18137             }
18138
18139           if (abbrev_name == 0)
18140             break;
18141
18142           if (cur_abbrev->num_attrs == allocated_attrs)
18143             {
18144               allocated_attrs += ATTR_ALLOC_CHUNK;
18145               cur_attrs
18146                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18147             }
18148
18149           cur_attrs[cur_abbrev->num_attrs].name
18150             = (enum dwarf_attribute) abbrev_name;
18151           cur_attrs[cur_abbrev->num_attrs].form
18152             = (enum dwarf_form) abbrev_form;
18153           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18154           ++cur_abbrev->num_attrs;
18155         }
18156
18157       cur_abbrev->attrs =
18158         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18159                    cur_abbrev->num_attrs);
18160       memcpy (cur_abbrev->attrs, cur_attrs,
18161               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18162
18163       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18164
18165       /* Get next abbreviation.
18166          Under Irix6 the abbreviations for a compilation unit are not
18167          always properly terminated with an abbrev number of 0.
18168          Exit loop if we encounter an abbreviation which we have
18169          already read (which means we are about to read the abbreviations
18170          for the next compile unit) or if the end of the abbreviation
18171          table is reached.  */
18172       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18173         break;
18174       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18175       abbrev_ptr += bytes_read;
18176       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18177         break;
18178     }
18179
18180   xfree (cur_attrs);
18181   return abbrev_table;
18182 }
18183
18184 /* Returns nonzero if TAG represents a type that we might generate a partial
18185    symbol for.  */
18186
18187 static int
18188 is_type_tag_for_partial (int tag)
18189 {
18190   switch (tag)
18191     {
18192 #if 0
18193     /* Some types that would be reasonable to generate partial symbols for,
18194        that we don't at present.  */
18195     case DW_TAG_array_type:
18196     case DW_TAG_file_type:
18197     case DW_TAG_ptr_to_member_type:
18198     case DW_TAG_set_type:
18199     case DW_TAG_string_type:
18200     case DW_TAG_subroutine_type:
18201 #endif
18202     case DW_TAG_base_type:
18203     case DW_TAG_class_type:
18204     case DW_TAG_interface_type:
18205     case DW_TAG_enumeration_type:
18206     case DW_TAG_structure_type:
18207     case DW_TAG_subrange_type:
18208     case DW_TAG_typedef:
18209     case DW_TAG_union_type:
18210       return 1;
18211     default:
18212       return 0;
18213     }
18214 }
18215
18216 /* Load all DIEs that are interesting for partial symbols into memory.  */
18217
18218 static struct partial_die_info *
18219 load_partial_dies (const struct die_reader_specs *reader,
18220                    const gdb_byte *info_ptr, int building_psymtab)
18221 {
18222   struct dwarf2_cu *cu = reader->cu;
18223   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18224   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18225   unsigned int bytes_read;
18226   unsigned int load_all = 0;
18227   int nesting_level = 1;
18228
18229   parent_die = NULL;
18230   last_die = NULL;
18231
18232   gdb_assert (cu->per_cu != NULL);
18233   if (cu->per_cu->load_all_dies)
18234     load_all = 1;
18235
18236   cu->partial_dies
18237     = htab_create_alloc_ex (cu->header.length / 12,
18238                             partial_die_hash,
18239                             partial_die_eq,
18240                             NULL,
18241                             &cu->comp_unit_obstack,
18242                             hashtab_obstack_allocate,
18243                             dummy_obstack_deallocate);
18244
18245   while (1)
18246     {
18247       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18248
18249       /* A NULL abbrev means the end of a series of children.  */
18250       if (abbrev == NULL)
18251         {
18252           if (--nesting_level == 0)
18253             return first_die;
18254
18255           info_ptr += bytes_read;
18256           last_die = parent_die;
18257           parent_die = parent_die->die_parent;
18258           continue;
18259         }
18260
18261       /* Check for template arguments.  We never save these; if
18262          they're seen, we just mark the parent, and go on our way.  */
18263       if (parent_die != NULL
18264           && cu->language == language_cplus
18265           && (abbrev->tag == DW_TAG_template_type_param
18266               || abbrev->tag == DW_TAG_template_value_param))
18267         {
18268           parent_die->has_template_arguments = 1;
18269
18270           if (!load_all)
18271             {
18272               /* We don't need a partial DIE for the template argument.  */
18273               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18274               continue;
18275             }
18276         }
18277
18278       /* We only recurse into c++ subprograms looking for template arguments.
18279          Skip their other children.  */
18280       if (!load_all
18281           && cu->language == language_cplus
18282           && parent_die != NULL
18283           && parent_die->tag == DW_TAG_subprogram)
18284         {
18285           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18286           continue;
18287         }
18288
18289       /* Check whether this DIE is interesting enough to save.  Normally
18290          we would not be interested in members here, but there may be
18291          later variables referencing them via DW_AT_specification (for
18292          static members).  */
18293       if (!load_all
18294           && !is_type_tag_for_partial (abbrev->tag)
18295           && abbrev->tag != DW_TAG_constant
18296           && abbrev->tag != DW_TAG_enumerator
18297           && abbrev->tag != DW_TAG_subprogram
18298           && abbrev->tag != DW_TAG_inlined_subroutine
18299           && abbrev->tag != DW_TAG_lexical_block
18300           && abbrev->tag != DW_TAG_variable
18301           && abbrev->tag != DW_TAG_namespace
18302           && abbrev->tag != DW_TAG_module
18303           && abbrev->tag != DW_TAG_member
18304           && abbrev->tag != DW_TAG_imported_unit
18305           && abbrev->tag != DW_TAG_imported_declaration)
18306         {
18307           /* Otherwise we skip to the next sibling, if any.  */
18308           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18309           continue;
18310         }
18311
18312       struct partial_die_info pdi;
18313
18314       memset (&pdi, 0, sizeof (pdi));
18315       info_ptr = read_partial_die (reader, &pdi, *abbrev, bytes_read,
18316                                    info_ptr);
18317
18318       /* This two-pass algorithm for processing partial symbols has a
18319          high cost in cache pressure.  Thus, handle some simple cases
18320          here which cover the majority of C partial symbols.  DIEs
18321          which neither have specification tags in them, nor could have
18322          specification tags elsewhere pointing at them, can simply be
18323          processed and discarded.
18324
18325          This segment is also optional; scan_partial_symbols and
18326          add_partial_symbol will handle these DIEs if we chain
18327          them in normally.  When compilers which do not emit large
18328          quantities of duplicate debug information are more common,
18329          this code can probably be removed.  */
18330
18331       /* Any complete simple types at the top level (pretty much all
18332          of them, for a language without namespaces), can be processed
18333          directly.  */
18334       if (parent_die == NULL
18335           && pdi.has_specification == 0
18336           && pdi.is_declaration == 0
18337           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18338               || pdi.tag == DW_TAG_base_type
18339               || pdi.tag == DW_TAG_subrange_type))
18340         {
18341           if (building_psymtab && pdi.name != NULL)
18342             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18343                                  VAR_DOMAIN, LOC_TYPEDEF,
18344                                  &objfile->static_psymbols,
18345                                  0, cu->language, objfile);
18346           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18347           continue;
18348         }
18349
18350       /* The exception for DW_TAG_typedef with has_children above is
18351          a workaround of GCC PR debug/47510.  In the case of this complaint
18352          type_name_no_tag_or_error will error on such types later.
18353
18354          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18355          it could not find the child DIEs referenced later, this is checked
18356          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18357
18358       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18359         complaint (&symfile_complaints,
18360                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18361                      "- DIE at %s [in module %s]"),
18362                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18363
18364       /* If we're at the second level, and we're an enumerator, and
18365          our parent has no specification (meaning possibly lives in a
18366          namespace elsewhere), then we can add the partial symbol now
18367          instead of queueing it.  */
18368       if (pdi.tag == DW_TAG_enumerator
18369           && parent_die != NULL
18370           && parent_die->die_parent == NULL
18371           && parent_die->tag == DW_TAG_enumeration_type
18372           && parent_die->has_specification == 0)
18373         {
18374           if (pdi.name == NULL)
18375             complaint (&symfile_complaints,
18376                        _("malformed enumerator DIE ignored"));
18377           else if (building_psymtab)
18378             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18379                                  VAR_DOMAIN, LOC_CONST,
18380                                  cu->language == language_cplus
18381                                  ? &objfile->global_psymbols
18382                                  : &objfile->static_psymbols,
18383                                  0, cu->language, objfile);
18384
18385           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18386           continue;
18387         }
18388
18389       struct partial_die_info *part_die
18390           = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18391
18392       memcpy (part_die, &pdi, sizeof (pdi));
18393       /* We'll save this DIE so link it in.  */
18394       part_die->die_parent = parent_die;
18395       part_die->die_sibling = NULL;
18396       part_die->die_child = NULL;
18397
18398       if (last_die && last_die == parent_die)
18399         last_die->die_child = part_die;
18400       else if (last_die)
18401         last_die->die_sibling = part_die;
18402
18403       last_die = part_die;
18404
18405       if (first_die == NULL)
18406         first_die = part_die;
18407
18408       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18409          find interesting need to be in the hash table, because we
18410          also have the parent/sibling/child chains; only those that we
18411          might refer to by offset later during partial symbol reading.
18412
18413          For now this means things that might have be the target of a
18414          DW_AT_specification, DW_AT_abstract_origin, or
18415          DW_AT_extension.  DW_AT_extension will refer only to
18416          namespaces; DW_AT_abstract_origin refers to functions (and
18417          many things under the function DIE, but we do not recurse
18418          into function DIEs during partial symbol reading) and
18419          possibly variables as well; DW_AT_specification refers to
18420          declarations.  Declarations ought to have the DW_AT_declaration
18421          flag.  It happens that GCC forgets to put it in sometimes, but
18422          only for functions, not for types.
18423
18424          Adding more things than necessary to the hash table is harmless
18425          except for the performance cost.  Adding too few will result in
18426          wasted time in find_partial_die, when we reread the compilation
18427          unit with load_all_dies set.  */
18428
18429       if (load_all
18430           || abbrev->tag == DW_TAG_constant
18431           || abbrev->tag == DW_TAG_subprogram
18432           || abbrev->tag == DW_TAG_variable
18433           || abbrev->tag == DW_TAG_namespace
18434           || part_die->is_declaration)
18435         {
18436           void **slot;
18437
18438           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18439                                            to_underlying (part_die->sect_off),
18440                                            INSERT);
18441           *slot = part_die;
18442         }
18443
18444       /* For some DIEs we want to follow their children (if any).  For C
18445          we have no reason to follow the children of structures; for other
18446          languages we have to, so that we can get at method physnames
18447          to infer fully qualified class names, for DW_AT_specification,
18448          and for C++ template arguments.  For C++, we also look one level
18449          inside functions to find template arguments (if the name of the
18450          function does not already contain the template arguments).
18451
18452          For Ada, we need to scan the children of subprograms and lexical
18453          blocks as well because Ada allows the definition of nested
18454          entities that could be interesting for the debugger, such as
18455          nested subprograms for instance.  */
18456       if (last_die->has_children
18457           && (load_all
18458               || last_die->tag == DW_TAG_namespace
18459               || last_die->tag == DW_TAG_module
18460               || last_die->tag == DW_TAG_enumeration_type
18461               || (cu->language == language_cplus
18462                   && last_die->tag == DW_TAG_subprogram
18463                   && (last_die->name == NULL
18464                       || strchr (last_die->name, '<') == NULL))
18465               || (cu->language != language_c
18466                   && (last_die->tag == DW_TAG_class_type
18467                       || last_die->tag == DW_TAG_interface_type
18468                       || last_die->tag == DW_TAG_structure_type
18469                       || last_die->tag == DW_TAG_union_type))
18470               || (cu->language == language_ada
18471                   && (last_die->tag == DW_TAG_subprogram
18472                       || last_die->tag == DW_TAG_lexical_block))))
18473         {
18474           nesting_level++;
18475           parent_die = last_die;
18476           continue;
18477         }
18478
18479       /* Otherwise we skip to the next sibling, if any.  */
18480       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18481
18482       /* Back to the top, do it again.  */
18483     }
18484 }
18485
18486 /* Read a minimal amount of information into the minimal die structure.  */
18487
18488 static const gdb_byte *
18489 read_partial_die (const struct die_reader_specs *reader,
18490                   struct partial_die_info *part_die,
18491                   const struct abbrev_info &abbrev, unsigned int abbrev_len,
18492                   const gdb_byte *info_ptr)
18493 {
18494   struct dwarf2_cu *cu = reader->cu;
18495   struct dwarf2_per_objfile *dwarf2_per_objfile
18496     = cu->per_cu->dwarf2_per_objfile;
18497   struct objfile *objfile = dwarf2_per_objfile->objfile;
18498   const gdb_byte *buffer = reader->buffer;
18499   unsigned int i;
18500   struct attribute attr;
18501   int has_low_pc_attr = 0;
18502   int has_high_pc_attr = 0;
18503   int high_pc_relative = 0;
18504
18505   memset (part_die, 0, sizeof (struct partial_die_info));
18506
18507   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18508
18509   info_ptr += abbrev_len;
18510
18511   part_die->tag = abbrev.tag;
18512   part_die->has_children = abbrev.has_children;
18513
18514   for (i = 0; i < abbrev.num_attrs; ++i)
18515     {
18516       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18517
18518       /* Store the data if it is of an attribute we want to keep in a
18519          partial symbol table.  */
18520       switch (attr.name)
18521         {
18522         case DW_AT_name:
18523           switch (part_die->tag)
18524             {
18525             case DW_TAG_compile_unit:
18526             case DW_TAG_partial_unit:
18527             case DW_TAG_type_unit:
18528               /* Compilation units have a DW_AT_name that is a filename, not
18529                  a source language identifier.  */
18530             case DW_TAG_enumeration_type:
18531             case DW_TAG_enumerator:
18532               /* These tags always have simple identifiers already; no need
18533                  to canonicalize them.  */
18534               part_die->name = DW_STRING (&attr);
18535               break;
18536             default:
18537               part_die->name
18538                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18539                                             &objfile->per_bfd->storage_obstack);
18540               break;
18541             }
18542           break;
18543         case DW_AT_linkage_name:
18544         case DW_AT_MIPS_linkage_name:
18545           /* Note that both forms of linkage name might appear.  We
18546              assume they will be the same, and we only store the last
18547              one we see.  */
18548           if (cu->language == language_ada)
18549             part_die->name = DW_STRING (&attr);
18550           part_die->linkage_name = DW_STRING (&attr);
18551           break;
18552         case DW_AT_low_pc:
18553           has_low_pc_attr = 1;
18554           part_die->lowpc = attr_value_as_address (&attr);
18555           break;
18556         case DW_AT_high_pc:
18557           has_high_pc_attr = 1;
18558           part_die->highpc = attr_value_as_address (&attr);
18559           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18560                 high_pc_relative = 1;
18561           break;
18562         case DW_AT_location:
18563           /* Support the .debug_loc offsets.  */
18564           if (attr_form_is_block (&attr))
18565             {
18566                part_die->d.locdesc = DW_BLOCK (&attr);
18567             }
18568           else if (attr_form_is_section_offset (&attr))
18569             {
18570               dwarf2_complex_location_expr_complaint ();
18571             }
18572           else
18573             {
18574               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18575                                                      "partial symbol information");
18576             }
18577           break;
18578         case DW_AT_external:
18579           part_die->is_external = DW_UNSND (&attr);
18580           break;
18581         case DW_AT_declaration:
18582           part_die->is_declaration = DW_UNSND (&attr);
18583           break;
18584         case DW_AT_type:
18585           part_die->has_type = 1;
18586           break;
18587         case DW_AT_abstract_origin:
18588         case DW_AT_specification:
18589         case DW_AT_extension:
18590           part_die->has_specification = 1;
18591           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18592           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18593                                    || cu->per_cu->is_dwz);
18594           break;
18595         case DW_AT_sibling:
18596           /* Ignore absolute siblings, they might point outside of
18597              the current compile unit.  */
18598           if (attr.form == DW_FORM_ref_addr)
18599             complaint (&symfile_complaints,
18600                        _("ignoring absolute DW_AT_sibling"));
18601           else
18602             {
18603               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18604               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18605
18606               if (sibling_ptr < info_ptr)
18607                 complaint (&symfile_complaints,
18608                            _("DW_AT_sibling points backwards"));
18609               else if (sibling_ptr > reader->buffer_end)
18610                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18611               else
18612                 part_die->sibling = sibling_ptr;
18613             }
18614           break;
18615         case DW_AT_byte_size:
18616           part_die->has_byte_size = 1;
18617           break;
18618         case DW_AT_const_value:
18619           part_die->has_const_value = 1;
18620           break;
18621         case DW_AT_calling_convention:
18622           /* DWARF doesn't provide a way to identify a program's source-level
18623              entry point.  DW_AT_calling_convention attributes are only meant
18624              to describe functions' calling conventions.
18625
18626              However, because it's a necessary piece of information in
18627              Fortran, and before DWARF 4 DW_CC_program was the only
18628              piece of debugging information whose definition refers to
18629              a 'main program' at all, several compilers marked Fortran
18630              main programs with DW_CC_program --- even when those
18631              functions use the standard calling conventions.
18632
18633              Although DWARF now specifies a way to provide this
18634              information, we support this practice for backward
18635              compatibility.  */
18636           if (DW_UNSND (&attr) == DW_CC_program
18637               && cu->language == language_fortran)
18638             part_die->main_subprogram = 1;
18639           break;
18640         case DW_AT_inline:
18641           if (DW_UNSND (&attr) == DW_INL_inlined
18642               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18643             part_die->may_be_inlined = 1;
18644           break;
18645
18646         case DW_AT_import:
18647           if (part_die->tag == DW_TAG_imported_unit)
18648             {
18649               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18650               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18651                                   || cu->per_cu->is_dwz);
18652             }
18653           break;
18654
18655         case DW_AT_main_subprogram:
18656           part_die->main_subprogram = DW_UNSND (&attr);
18657           break;
18658
18659         default:
18660           break;
18661         }
18662     }
18663
18664   if (high_pc_relative)
18665     part_die->highpc += part_die->lowpc;
18666
18667   if (has_low_pc_attr && has_high_pc_attr)
18668     {
18669       /* When using the GNU linker, .gnu.linkonce. sections are used to
18670          eliminate duplicate copies of functions and vtables and such.
18671          The linker will arbitrarily choose one and discard the others.
18672          The AT_*_pc values for such functions refer to local labels in
18673          these sections.  If the section from that file was discarded, the
18674          labels are not in the output, so the relocs get a value of 0.
18675          If this is a discarded function, mark the pc bounds as invalid,
18676          so that GDB will ignore it.  */
18677       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18678         {
18679           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18680
18681           complaint (&symfile_complaints,
18682                      _("DW_AT_low_pc %s is zero "
18683                        "for DIE at %s [in module %s]"),
18684                      paddress (gdbarch, part_die->lowpc),
18685                      sect_offset_str (part_die->sect_off),
18686                      objfile_name (objfile));
18687         }
18688       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18689       else if (part_die->lowpc >= part_die->highpc)
18690         {
18691           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18692
18693           complaint (&symfile_complaints,
18694                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18695                        "for DIE at %s [in module %s]"),
18696                      paddress (gdbarch, part_die->lowpc),
18697                      paddress (gdbarch, part_die->highpc),
18698                      sect_offset_str (part_die->sect_off),
18699                      objfile_name (objfile));
18700         }
18701       else
18702         part_die->has_pc_info = 1;
18703     }
18704
18705   return info_ptr;
18706 }
18707
18708 /* Find a cached partial DIE at OFFSET in CU.  */
18709
18710 struct partial_die_info *
18711 dwarf2_cu::find_partial_die (sect_offset sect_off)
18712 {
18713   struct partial_die_info *lookup_die = NULL;
18714   struct partial_die_info part_die;
18715
18716   part_die.sect_off = sect_off;
18717   lookup_die = ((struct partial_die_info *)
18718                 htab_find_with_hash (partial_dies, &part_die,
18719                                      to_underlying (sect_off)));
18720
18721   return lookup_die;
18722 }
18723
18724 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18725    except in the case of .debug_types DIEs which do not reference
18726    outside their CU (they do however referencing other types via
18727    DW_FORM_ref_sig8).  */
18728
18729 static struct partial_die_info *
18730 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18731 {
18732   struct dwarf2_per_objfile *dwarf2_per_objfile
18733     = cu->per_cu->dwarf2_per_objfile;
18734   struct objfile *objfile = dwarf2_per_objfile->objfile;
18735   struct dwarf2_per_cu_data *per_cu = NULL;
18736   struct partial_die_info *pd = NULL;
18737
18738   if (offset_in_dwz == cu->per_cu->is_dwz
18739       && offset_in_cu_p (&cu->header, sect_off))
18740     {
18741       pd = cu->find_partial_die (sect_off);
18742       if (pd != NULL)
18743         return pd;
18744       /* We missed recording what we needed.
18745          Load all dies and try again.  */
18746       per_cu = cu->per_cu;
18747     }
18748   else
18749     {
18750       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18751       if (cu->per_cu->is_debug_types)
18752         {
18753           error (_("Dwarf Error: Type Unit at offset %s contains"
18754                    " external reference to offset %s [in module %s].\n"),
18755                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18756                  bfd_get_filename (objfile->obfd));
18757         }
18758       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18759                                                  dwarf2_per_objfile);
18760
18761       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18762         load_partial_comp_unit (per_cu);
18763
18764       per_cu->cu->last_used = 0;
18765       pd = per_cu->cu->find_partial_die (sect_off);
18766     }
18767
18768   /* If we didn't find it, and not all dies have been loaded,
18769      load them all and try again.  */
18770
18771   if (pd == NULL && per_cu->load_all_dies == 0)
18772     {
18773       per_cu->load_all_dies = 1;
18774
18775       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18776          THIS_CU->cu may already be in use.  So we can't just free it and
18777          replace its DIEs with the ones we read in.  Instead, we leave those
18778          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18779          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18780          set.  */
18781       load_partial_comp_unit (per_cu);
18782
18783       pd = per_cu->cu->find_partial_die (sect_off);
18784     }
18785
18786   if (pd == NULL)
18787     internal_error (__FILE__, __LINE__,
18788                     _("could not find partial DIE %s "
18789                       "in cache [from module %s]\n"),
18790                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18791   return pd;
18792 }
18793
18794 /* See if we can figure out if the class lives in a namespace.  We do
18795    this by looking for a member function; its demangled name will
18796    contain namespace info, if there is any.  */
18797
18798 static void
18799 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18800                                   struct dwarf2_cu *cu)
18801 {
18802   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18803      what template types look like, because the demangler
18804      frequently doesn't give the same name as the debug info.  We
18805      could fix this by only using the demangled name to get the
18806      prefix (but see comment in read_structure_type).  */
18807
18808   struct partial_die_info *real_pdi;
18809   struct partial_die_info *child_pdi;
18810
18811   /* If this DIE (this DIE's specification, if any) has a parent, then
18812      we should not do this.  We'll prepend the parent's fully qualified
18813      name when we create the partial symbol.  */
18814
18815   real_pdi = struct_pdi;
18816   while (real_pdi->has_specification)
18817     real_pdi = find_partial_die (real_pdi->spec_offset,
18818                                  real_pdi->spec_is_dwz, cu);
18819
18820   if (real_pdi->die_parent != NULL)
18821     return;
18822
18823   for (child_pdi = struct_pdi->die_child;
18824        child_pdi != NULL;
18825        child_pdi = child_pdi->die_sibling)
18826     {
18827       if (child_pdi->tag == DW_TAG_subprogram
18828           && child_pdi->linkage_name != NULL)
18829         {
18830           char *actual_class_name
18831             = language_class_name_from_physname (cu->language_defn,
18832                                                  child_pdi->linkage_name);
18833           if (actual_class_name != NULL)
18834             {
18835               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18836               struct_pdi->name
18837                 = ((const char *)
18838                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18839                                   actual_class_name,
18840                                   strlen (actual_class_name)));
18841               xfree (actual_class_name);
18842             }
18843           break;
18844         }
18845     }
18846 }
18847
18848 /* Adjust PART_DIE before generating a symbol for it.  This function
18849    may set the is_external flag or change the DIE's name.  */
18850
18851 static void
18852 fixup_partial_die (struct partial_die_info *part_die,
18853                    struct dwarf2_cu *cu)
18854 {
18855   /* Once we've fixed up a die, there's no point in doing so again.
18856      This also avoids a memory leak if we were to call
18857      guess_partial_die_structure_name multiple times.  */
18858   if (part_die->fixup_called)
18859     return;
18860
18861   /* If we found a reference attribute and the DIE has no name, try
18862      to find a name in the referred to DIE.  */
18863
18864   if (part_die->name == NULL && part_die->has_specification)
18865     {
18866       struct partial_die_info *spec_die;
18867
18868       spec_die = find_partial_die (part_die->spec_offset,
18869                                    part_die->spec_is_dwz, cu);
18870
18871       fixup_partial_die (spec_die, cu);
18872
18873       if (spec_die->name)
18874         {
18875           part_die->name = spec_die->name;
18876
18877           /* Copy DW_AT_external attribute if it is set.  */
18878           if (spec_die->is_external)
18879             part_die->is_external = spec_die->is_external;
18880         }
18881     }
18882
18883   /* Set default names for some unnamed DIEs.  */
18884
18885   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18886     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18887
18888   /* If there is no parent die to provide a namespace, and there are
18889      children, see if we can determine the namespace from their linkage
18890      name.  */
18891   if (cu->language == language_cplus
18892       && !VEC_empty (dwarf2_section_info_def,
18893                      cu->per_cu->dwarf2_per_objfile->types)
18894       && part_die->die_parent == NULL
18895       && part_die->has_children
18896       && (part_die->tag == DW_TAG_class_type
18897           || part_die->tag == DW_TAG_structure_type
18898           || part_die->tag == DW_TAG_union_type))
18899     guess_partial_die_structure_name (part_die, cu);
18900
18901   /* GCC might emit a nameless struct or union that has a linkage
18902      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18903   if (part_die->name == NULL
18904       && (part_die->tag == DW_TAG_class_type
18905           || part_die->tag == DW_TAG_interface_type
18906           || part_die->tag == DW_TAG_structure_type
18907           || part_die->tag == DW_TAG_union_type)
18908       && part_die->linkage_name != NULL)
18909     {
18910       char *demangled;
18911
18912       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18913       if (demangled)
18914         {
18915           const char *base;
18916
18917           /* Strip any leading namespaces/classes, keep only the base name.
18918              DW_AT_name for named DIEs does not contain the prefixes.  */
18919           base = strrchr (demangled, ':');
18920           if (base && base > demangled && base[-1] == ':')
18921             base++;
18922           else
18923             base = demangled;
18924
18925           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18926           part_die->name
18927             = ((const char *)
18928                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18929                               base, strlen (base)));
18930           xfree (demangled);
18931         }
18932     }
18933
18934   part_die->fixup_called = 1;
18935 }
18936
18937 /* Read an attribute value described by an attribute form.  */
18938
18939 static const gdb_byte *
18940 read_attribute_value (const struct die_reader_specs *reader,
18941                       struct attribute *attr, unsigned form,
18942                       LONGEST implicit_const, const gdb_byte *info_ptr)
18943 {
18944   struct dwarf2_cu *cu = reader->cu;
18945   struct dwarf2_per_objfile *dwarf2_per_objfile
18946     = cu->per_cu->dwarf2_per_objfile;
18947   struct objfile *objfile = dwarf2_per_objfile->objfile;
18948   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18949   bfd *abfd = reader->abfd;
18950   struct comp_unit_head *cu_header = &cu->header;
18951   unsigned int bytes_read;
18952   struct dwarf_block *blk;
18953
18954   attr->form = (enum dwarf_form) form;
18955   switch (form)
18956     {
18957     case DW_FORM_ref_addr:
18958       if (cu->header.version == 2)
18959         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18960       else
18961         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18962                                        &cu->header, &bytes_read);
18963       info_ptr += bytes_read;
18964       break;
18965     case DW_FORM_GNU_ref_alt:
18966       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18967       info_ptr += bytes_read;
18968       break;
18969     case DW_FORM_addr:
18970       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18971       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18972       info_ptr += bytes_read;
18973       break;
18974     case DW_FORM_block2:
18975       blk = dwarf_alloc_block (cu);
18976       blk->size = read_2_bytes (abfd, info_ptr);
18977       info_ptr += 2;
18978       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18979       info_ptr += blk->size;
18980       DW_BLOCK (attr) = blk;
18981       break;
18982     case DW_FORM_block4:
18983       blk = dwarf_alloc_block (cu);
18984       blk->size = read_4_bytes (abfd, info_ptr);
18985       info_ptr += 4;
18986       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18987       info_ptr += blk->size;
18988       DW_BLOCK (attr) = blk;
18989       break;
18990     case DW_FORM_data2:
18991       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18992       info_ptr += 2;
18993       break;
18994     case DW_FORM_data4:
18995       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18996       info_ptr += 4;
18997       break;
18998     case DW_FORM_data8:
18999       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19000       info_ptr += 8;
19001       break;
19002     case DW_FORM_data16:
19003       blk = dwarf_alloc_block (cu);
19004       blk->size = 16;
19005       blk->data = read_n_bytes (abfd, info_ptr, 16);
19006       info_ptr += 16;
19007       DW_BLOCK (attr) = blk;
19008       break;
19009     case DW_FORM_sec_offset:
19010       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19011       info_ptr += bytes_read;
19012       break;
19013     case DW_FORM_string:
19014       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19015       DW_STRING_IS_CANONICAL (attr) = 0;
19016       info_ptr += bytes_read;
19017       break;
19018     case DW_FORM_strp:
19019       if (!cu->per_cu->is_dwz)
19020         {
19021           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19022                                                    abfd, info_ptr, cu_header,
19023                                                    &bytes_read);
19024           DW_STRING_IS_CANONICAL (attr) = 0;
19025           info_ptr += bytes_read;
19026           break;
19027         }
19028       /* FALLTHROUGH */
19029     case DW_FORM_line_strp:
19030       if (!cu->per_cu->is_dwz)
19031         {
19032           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19033                                                         abfd, info_ptr,
19034                                                         cu_header, &bytes_read);
19035           DW_STRING_IS_CANONICAL (attr) = 0;
19036           info_ptr += bytes_read;
19037           break;
19038         }
19039       /* FALLTHROUGH */
19040     case DW_FORM_GNU_strp_alt:
19041       {
19042         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19043         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19044                                           &bytes_read);
19045
19046         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19047                                                           dwz, str_offset);
19048         DW_STRING_IS_CANONICAL (attr) = 0;
19049         info_ptr += bytes_read;
19050       }
19051       break;
19052     case DW_FORM_exprloc:
19053     case DW_FORM_block:
19054       blk = dwarf_alloc_block (cu);
19055       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19056       info_ptr += bytes_read;
19057       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19058       info_ptr += blk->size;
19059       DW_BLOCK (attr) = blk;
19060       break;
19061     case DW_FORM_block1:
19062       blk = dwarf_alloc_block (cu);
19063       blk->size = read_1_byte (abfd, info_ptr);
19064       info_ptr += 1;
19065       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19066       info_ptr += blk->size;
19067       DW_BLOCK (attr) = blk;
19068       break;
19069     case DW_FORM_data1:
19070       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19071       info_ptr += 1;
19072       break;
19073     case DW_FORM_flag:
19074       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19075       info_ptr += 1;
19076       break;
19077     case DW_FORM_flag_present:
19078       DW_UNSND (attr) = 1;
19079       break;
19080     case DW_FORM_sdata:
19081       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19082       info_ptr += bytes_read;
19083       break;
19084     case DW_FORM_udata:
19085       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19086       info_ptr += bytes_read;
19087       break;
19088     case DW_FORM_ref1:
19089       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19090                          + read_1_byte (abfd, info_ptr));
19091       info_ptr += 1;
19092       break;
19093     case DW_FORM_ref2:
19094       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19095                          + read_2_bytes (abfd, info_ptr));
19096       info_ptr += 2;
19097       break;
19098     case DW_FORM_ref4:
19099       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19100                          + read_4_bytes (abfd, info_ptr));
19101       info_ptr += 4;
19102       break;
19103     case DW_FORM_ref8:
19104       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19105                          + read_8_bytes (abfd, info_ptr));
19106       info_ptr += 8;
19107       break;
19108     case DW_FORM_ref_sig8:
19109       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19110       info_ptr += 8;
19111       break;
19112     case DW_FORM_ref_udata:
19113       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19114                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19115       info_ptr += bytes_read;
19116       break;
19117     case DW_FORM_indirect:
19118       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19119       info_ptr += bytes_read;
19120       if (form == DW_FORM_implicit_const)
19121         {
19122           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19123           info_ptr += bytes_read;
19124         }
19125       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19126                                        info_ptr);
19127       break;
19128     case DW_FORM_implicit_const:
19129       DW_SND (attr) = implicit_const;
19130       break;
19131     case DW_FORM_GNU_addr_index:
19132       if (reader->dwo_file == NULL)
19133         {
19134           /* For now flag a hard error.
19135              Later we can turn this into a complaint.  */
19136           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19137                  dwarf_form_name (form),
19138                  bfd_get_filename (abfd));
19139         }
19140       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19141       info_ptr += bytes_read;
19142       break;
19143     case DW_FORM_GNU_str_index:
19144       if (reader->dwo_file == NULL)
19145         {
19146           /* For now flag a hard error.
19147              Later we can turn this into a complaint if warranted.  */
19148           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19149                  dwarf_form_name (form),
19150                  bfd_get_filename (abfd));
19151         }
19152       {
19153         ULONGEST str_index =
19154           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19155
19156         DW_STRING (attr) = read_str_index (reader, str_index);
19157         DW_STRING_IS_CANONICAL (attr) = 0;
19158         info_ptr += bytes_read;
19159       }
19160       break;
19161     default:
19162       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19163              dwarf_form_name (form),
19164              bfd_get_filename (abfd));
19165     }
19166
19167   /* Super hack.  */
19168   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19169     attr->form = DW_FORM_GNU_ref_alt;
19170
19171   /* We have seen instances where the compiler tried to emit a byte
19172      size attribute of -1 which ended up being encoded as an unsigned
19173      0xffffffff.  Although 0xffffffff is technically a valid size value,
19174      an object of this size seems pretty unlikely so we can relatively
19175      safely treat these cases as if the size attribute was invalid and
19176      treat them as zero by default.  */
19177   if (attr->name == DW_AT_byte_size
19178       && form == DW_FORM_data4
19179       && DW_UNSND (attr) >= 0xffffffff)
19180     {
19181       complaint
19182         (&symfile_complaints,
19183          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19184          hex_string (DW_UNSND (attr)));
19185       DW_UNSND (attr) = 0;
19186     }
19187
19188   return info_ptr;
19189 }
19190
19191 /* Read an attribute described by an abbreviated attribute.  */
19192
19193 static const gdb_byte *
19194 read_attribute (const struct die_reader_specs *reader,
19195                 struct attribute *attr, struct attr_abbrev *abbrev,
19196                 const gdb_byte *info_ptr)
19197 {
19198   attr->name = abbrev->name;
19199   return read_attribute_value (reader, attr, abbrev->form,
19200                                abbrev->implicit_const, info_ptr);
19201 }
19202
19203 /* Read dwarf information from a buffer.  */
19204
19205 static unsigned int
19206 read_1_byte (bfd *abfd, const gdb_byte *buf)
19207 {
19208   return bfd_get_8 (abfd, buf);
19209 }
19210
19211 static int
19212 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19213 {
19214   return bfd_get_signed_8 (abfd, buf);
19215 }
19216
19217 static unsigned int
19218 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19219 {
19220   return bfd_get_16 (abfd, buf);
19221 }
19222
19223 static int
19224 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19225 {
19226   return bfd_get_signed_16 (abfd, buf);
19227 }
19228
19229 static unsigned int
19230 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19231 {
19232   return bfd_get_32 (abfd, buf);
19233 }
19234
19235 static int
19236 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19237 {
19238   return bfd_get_signed_32 (abfd, buf);
19239 }
19240
19241 static ULONGEST
19242 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19243 {
19244   return bfd_get_64 (abfd, buf);
19245 }
19246
19247 static CORE_ADDR
19248 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19249               unsigned int *bytes_read)
19250 {
19251   struct comp_unit_head *cu_header = &cu->header;
19252   CORE_ADDR retval = 0;
19253
19254   if (cu_header->signed_addr_p)
19255     {
19256       switch (cu_header->addr_size)
19257         {
19258         case 2:
19259           retval = bfd_get_signed_16 (abfd, buf);
19260           break;
19261         case 4:
19262           retval = bfd_get_signed_32 (abfd, buf);
19263           break;
19264         case 8:
19265           retval = bfd_get_signed_64 (abfd, buf);
19266           break;
19267         default:
19268           internal_error (__FILE__, __LINE__,
19269                           _("read_address: bad switch, signed [in module %s]"),
19270                           bfd_get_filename (abfd));
19271         }
19272     }
19273   else
19274     {
19275       switch (cu_header->addr_size)
19276         {
19277         case 2:
19278           retval = bfd_get_16 (abfd, buf);
19279           break;
19280         case 4:
19281           retval = bfd_get_32 (abfd, buf);
19282           break;
19283         case 8:
19284           retval = bfd_get_64 (abfd, buf);
19285           break;
19286         default:
19287           internal_error (__FILE__, __LINE__,
19288                           _("read_address: bad switch, "
19289                             "unsigned [in module %s]"),
19290                           bfd_get_filename (abfd));
19291         }
19292     }
19293
19294   *bytes_read = cu_header->addr_size;
19295   return retval;
19296 }
19297
19298 /* Read the initial length from a section.  The (draft) DWARF 3
19299    specification allows the initial length to take up either 4 bytes
19300    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19301    bytes describe the length and all offsets will be 8 bytes in length
19302    instead of 4.
19303
19304    An older, non-standard 64-bit format is also handled by this
19305    function.  The older format in question stores the initial length
19306    as an 8-byte quantity without an escape value.  Lengths greater
19307    than 2^32 aren't very common which means that the initial 4 bytes
19308    is almost always zero.  Since a length value of zero doesn't make
19309    sense for the 32-bit format, this initial zero can be considered to
19310    be an escape value which indicates the presence of the older 64-bit
19311    format.  As written, the code can't detect (old format) lengths
19312    greater than 4GB.  If it becomes necessary to handle lengths
19313    somewhat larger than 4GB, we could allow other small values (such
19314    as the non-sensical values of 1, 2, and 3) to also be used as
19315    escape values indicating the presence of the old format.
19316
19317    The value returned via bytes_read should be used to increment the
19318    relevant pointer after calling read_initial_length().
19319
19320    [ Note:  read_initial_length() and read_offset() are based on the
19321      document entitled "DWARF Debugging Information Format", revision
19322      3, draft 8, dated November 19, 2001.  This document was obtained
19323      from:
19324
19325         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19326
19327      This document is only a draft and is subject to change.  (So beware.)
19328
19329      Details regarding the older, non-standard 64-bit format were
19330      determined empirically by examining 64-bit ELF files produced by
19331      the SGI toolchain on an IRIX 6.5 machine.
19332
19333      - Kevin, July 16, 2002
19334    ] */
19335
19336 static LONGEST
19337 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19338 {
19339   LONGEST length = bfd_get_32 (abfd, buf);
19340
19341   if (length == 0xffffffff)
19342     {
19343       length = bfd_get_64 (abfd, buf + 4);
19344       *bytes_read = 12;
19345     }
19346   else if (length == 0)
19347     {
19348       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19349       length = bfd_get_64 (abfd, buf);
19350       *bytes_read = 8;
19351     }
19352   else
19353     {
19354       *bytes_read = 4;
19355     }
19356
19357   return length;
19358 }
19359
19360 /* Cover function for read_initial_length.
19361    Returns the length of the object at BUF, and stores the size of the
19362    initial length in *BYTES_READ and stores the size that offsets will be in
19363    *OFFSET_SIZE.
19364    If the initial length size is not equivalent to that specified in
19365    CU_HEADER then issue a complaint.
19366    This is useful when reading non-comp-unit headers.  */
19367
19368 static LONGEST
19369 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19370                                         const struct comp_unit_head *cu_header,
19371                                         unsigned int *bytes_read,
19372                                         unsigned int *offset_size)
19373 {
19374   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19375
19376   gdb_assert (cu_header->initial_length_size == 4
19377               || cu_header->initial_length_size == 8
19378               || cu_header->initial_length_size == 12);
19379
19380   if (cu_header->initial_length_size != *bytes_read)
19381     complaint (&symfile_complaints,
19382                _("intermixed 32-bit and 64-bit DWARF sections"));
19383
19384   *offset_size = (*bytes_read == 4) ? 4 : 8;
19385   return length;
19386 }
19387
19388 /* Read an offset from the data stream.  The size of the offset is
19389    given by cu_header->offset_size.  */
19390
19391 static LONGEST
19392 read_offset (bfd *abfd, const gdb_byte *buf,
19393              const struct comp_unit_head *cu_header,
19394              unsigned int *bytes_read)
19395 {
19396   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19397
19398   *bytes_read = cu_header->offset_size;
19399   return offset;
19400 }
19401
19402 /* Read an offset from the data stream.  */
19403
19404 static LONGEST
19405 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19406 {
19407   LONGEST retval = 0;
19408
19409   switch (offset_size)
19410     {
19411     case 4:
19412       retval = bfd_get_32 (abfd, buf);
19413       break;
19414     case 8:
19415       retval = bfd_get_64 (abfd, buf);
19416       break;
19417     default:
19418       internal_error (__FILE__, __LINE__,
19419                       _("read_offset_1: bad switch [in module %s]"),
19420                       bfd_get_filename (abfd));
19421     }
19422
19423   return retval;
19424 }
19425
19426 static const gdb_byte *
19427 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19428 {
19429   /* If the size of a host char is 8 bits, we can return a pointer
19430      to the buffer, otherwise we have to copy the data to a buffer
19431      allocated on the temporary obstack.  */
19432   gdb_assert (HOST_CHAR_BIT == 8);
19433   return buf;
19434 }
19435
19436 static const char *
19437 read_direct_string (bfd *abfd, const gdb_byte *buf,
19438                     unsigned int *bytes_read_ptr)
19439 {
19440   /* If the size of a host char is 8 bits, we can return a pointer
19441      to the string, otherwise we have to copy the string to a buffer
19442      allocated on the temporary obstack.  */
19443   gdb_assert (HOST_CHAR_BIT == 8);
19444   if (*buf == '\0')
19445     {
19446       *bytes_read_ptr = 1;
19447       return NULL;
19448     }
19449   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19450   return (const char *) buf;
19451 }
19452
19453 /* Return pointer to string at section SECT offset STR_OFFSET with error
19454    reporting strings FORM_NAME and SECT_NAME.  */
19455
19456 static const char *
19457 read_indirect_string_at_offset_from (struct objfile *objfile,
19458                                      bfd *abfd, LONGEST str_offset,
19459                                      struct dwarf2_section_info *sect,
19460                                      const char *form_name,
19461                                      const char *sect_name)
19462 {
19463   dwarf2_read_section (objfile, sect);
19464   if (sect->buffer == NULL)
19465     error (_("%s used without %s section [in module %s]"),
19466            form_name, sect_name, bfd_get_filename (abfd));
19467   if (str_offset >= sect->size)
19468     error (_("%s pointing outside of %s section [in module %s]"),
19469            form_name, sect_name, bfd_get_filename (abfd));
19470   gdb_assert (HOST_CHAR_BIT == 8);
19471   if (sect->buffer[str_offset] == '\0')
19472     return NULL;
19473   return (const char *) (sect->buffer + str_offset);
19474 }
19475
19476 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19477
19478 static const char *
19479 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19480                                 bfd *abfd, LONGEST str_offset)
19481 {
19482   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19483                                               abfd, str_offset,
19484                                               &dwarf2_per_objfile->str,
19485                                               "DW_FORM_strp", ".debug_str");
19486 }
19487
19488 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19489
19490 static const char *
19491 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19492                                      bfd *abfd, LONGEST str_offset)
19493 {
19494   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19495                                               abfd, str_offset,
19496                                               &dwarf2_per_objfile->line_str,
19497                                               "DW_FORM_line_strp",
19498                                               ".debug_line_str");
19499 }
19500
19501 /* Read a string at offset STR_OFFSET in the .debug_str section from
19502    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19503    the string consists of a single NUL byte, return NULL; otherwise
19504    return a pointer to the string.  */
19505
19506 static const char *
19507 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19508                                LONGEST str_offset)
19509 {
19510   dwarf2_read_section (objfile, &dwz->str);
19511
19512   if (dwz->str.buffer == NULL)
19513     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19514              "section [in module %s]"),
19515            bfd_get_filename (dwz->dwz_bfd));
19516   if (str_offset >= dwz->str.size)
19517     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19518              ".debug_str section [in module %s]"),
19519            bfd_get_filename (dwz->dwz_bfd));
19520   gdb_assert (HOST_CHAR_BIT == 8);
19521   if (dwz->str.buffer[str_offset] == '\0')
19522     return NULL;
19523   return (const char *) (dwz->str.buffer + str_offset);
19524 }
19525
19526 /* Return pointer to string at .debug_str offset as read from BUF.
19527    BUF is assumed to be in a compilation unit described by CU_HEADER.
19528    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19529
19530 static const char *
19531 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19532                       const gdb_byte *buf,
19533                       const struct comp_unit_head *cu_header,
19534                       unsigned int *bytes_read_ptr)
19535 {
19536   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19537
19538   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19539 }
19540
19541 /* Return pointer to string at .debug_line_str offset as read from BUF.
19542    BUF is assumed to be in a compilation unit described by CU_HEADER.
19543    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19544
19545 static const char *
19546 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19547                            bfd *abfd, const gdb_byte *buf,
19548                            const struct comp_unit_head *cu_header,
19549                            unsigned int *bytes_read_ptr)
19550 {
19551   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19552
19553   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19554                                               str_offset);
19555 }
19556
19557 ULONGEST
19558 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19559                           unsigned int *bytes_read_ptr)
19560 {
19561   ULONGEST result;
19562   unsigned int num_read;
19563   int shift;
19564   unsigned char byte;
19565
19566   result = 0;
19567   shift = 0;
19568   num_read = 0;
19569   while (1)
19570     {
19571       byte = bfd_get_8 (abfd, buf);
19572       buf++;
19573       num_read++;
19574       result |= ((ULONGEST) (byte & 127) << shift);
19575       if ((byte & 128) == 0)
19576         {
19577           break;
19578         }
19579       shift += 7;
19580     }
19581   *bytes_read_ptr = num_read;
19582   return result;
19583 }
19584
19585 static LONGEST
19586 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19587                     unsigned int *bytes_read_ptr)
19588 {
19589   LONGEST result;
19590   int shift, num_read;
19591   unsigned char byte;
19592
19593   result = 0;
19594   shift = 0;
19595   num_read = 0;
19596   while (1)
19597     {
19598       byte = bfd_get_8 (abfd, buf);
19599       buf++;
19600       num_read++;
19601       result |= ((LONGEST) (byte & 127) << shift);
19602       shift += 7;
19603       if ((byte & 128) == 0)
19604         {
19605           break;
19606         }
19607     }
19608   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19609     result |= -(((LONGEST) 1) << shift);
19610   *bytes_read_ptr = num_read;
19611   return result;
19612 }
19613
19614 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19615    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19616    ADDR_SIZE is the size of addresses from the CU header.  */
19617
19618 static CORE_ADDR
19619 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19620                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19621 {
19622   struct objfile *objfile = dwarf2_per_objfile->objfile;
19623   bfd *abfd = objfile->obfd;
19624   const gdb_byte *info_ptr;
19625
19626   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19627   if (dwarf2_per_objfile->addr.buffer == NULL)
19628     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19629            objfile_name (objfile));
19630   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19631     error (_("DW_FORM_addr_index pointing outside of "
19632              ".debug_addr section [in module %s]"),
19633            objfile_name (objfile));
19634   info_ptr = (dwarf2_per_objfile->addr.buffer
19635               + addr_base + addr_index * addr_size);
19636   if (addr_size == 4)
19637     return bfd_get_32 (abfd, info_ptr);
19638   else
19639     return bfd_get_64 (abfd, info_ptr);
19640 }
19641
19642 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19643
19644 static CORE_ADDR
19645 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19646 {
19647   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19648                             cu->addr_base, cu->header.addr_size);
19649 }
19650
19651 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19652
19653 static CORE_ADDR
19654 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19655                              unsigned int *bytes_read)
19656 {
19657   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19658   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19659
19660   return read_addr_index (cu, addr_index);
19661 }
19662
19663 /* Data structure to pass results from dwarf2_read_addr_index_reader
19664    back to dwarf2_read_addr_index.  */
19665
19666 struct dwarf2_read_addr_index_data
19667 {
19668   ULONGEST addr_base;
19669   int addr_size;
19670 };
19671
19672 /* die_reader_func for dwarf2_read_addr_index.  */
19673
19674 static void
19675 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19676                                const gdb_byte *info_ptr,
19677                                struct die_info *comp_unit_die,
19678                                int has_children,
19679                                void *data)
19680 {
19681   struct dwarf2_cu *cu = reader->cu;
19682   struct dwarf2_read_addr_index_data *aidata =
19683     (struct dwarf2_read_addr_index_data *) data;
19684
19685   aidata->addr_base = cu->addr_base;
19686   aidata->addr_size = cu->header.addr_size;
19687 }
19688
19689 /* Given an index in .debug_addr, fetch the value.
19690    NOTE: This can be called during dwarf expression evaluation,
19691    long after the debug information has been read, and thus per_cu->cu
19692    may no longer exist.  */
19693
19694 CORE_ADDR
19695 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19696                         unsigned int addr_index)
19697 {
19698   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19699   struct objfile *objfile = dwarf2_per_objfile->objfile;
19700   struct dwarf2_cu *cu = per_cu->cu;
19701   ULONGEST addr_base;
19702   int addr_size;
19703
19704   /* We need addr_base and addr_size.
19705      If we don't have PER_CU->cu, we have to get it.
19706      Nasty, but the alternative is storing the needed info in PER_CU,
19707      which at this point doesn't seem justified: it's not clear how frequently
19708      it would get used and it would increase the size of every PER_CU.
19709      Entry points like dwarf2_per_cu_addr_size do a similar thing
19710      so we're not in uncharted territory here.
19711      Alas we need to be a bit more complicated as addr_base is contained
19712      in the DIE.
19713
19714      We don't need to read the entire CU(/TU).
19715      We just need the header and top level die.
19716
19717      IWBN to use the aging mechanism to let us lazily later discard the CU.
19718      For now we skip this optimization.  */
19719
19720   if (cu != NULL)
19721     {
19722       addr_base = cu->addr_base;
19723       addr_size = cu->header.addr_size;
19724     }
19725   else
19726     {
19727       struct dwarf2_read_addr_index_data aidata;
19728
19729       /* Note: We can't use init_cutu_and_read_dies_simple here,
19730          we need addr_base.  */
19731       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19732                                dwarf2_read_addr_index_reader, &aidata);
19733       addr_base = aidata.addr_base;
19734       addr_size = aidata.addr_size;
19735     }
19736
19737   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19738                             addr_size);
19739 }
19740
19741 /* Given a DW_FORM_GNU_str_index, fetch the string.
19742    This is only used by the Fission support.  */
19743
19744 static const char *
19745 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19746 {
19747   struct dwarf2_cu *cu = reader->cu;
19748   struct dwarf2_per_objfile *dwarf2_per_objfile
19749     = cu->per_cu->dwarf2_per_objfile;
19750   struct objfile *objfile = dwarf2_per_objfile->objfile;
19751   const char *objf_name = objfile_name (objfile);
19752   bfd *abfd = objfile->obfd;
19753   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19754   struct dwarf2_section_info *str_offsets_section =
19755     &reader->dwo_file->sections.str_offsets;
19756   const gdb_byte *info_ptr;
19757   ULONGEST str_offset;
19758   static const char form_name[] = "DW_FORM_GNU_str_index";
19759
19760   dwarf2_read_section (objfile, str_section);
19761   dwarf2_read_section (objfile, str_offsets_section);
19762   if (str_section->buffer == NULL)
19763     error (_("%s used without .debug_str.dwo section"
19764              " in CU at offset %s [in module %s]"),
19765            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19766   if (str_offsets_section->buffer == NULL)
19767     error (_("%s used without .debug_str_offsets.dwo section"
19768              " in CU at offset %s [in module %s]"),
19769            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19770   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19771     error (_("%s pointing outside of .debug_str_offsets.dwo"
19772              " section in CU at offset %s [in module %s]"),
19773            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19774   info_ptr = (str_offsets_section->buffer
19775               + str_index * cu->header.offset_size);
19776   if (cu->header.offset_size == 4)
19777     str_offset = bfd_get_32 (abfd, info_ptr);
19778   else
19779     str_offset = bfd_get_64 (abfd, info_ptr);
19780   if (str_offset >= str_section->size)
19781     error (_("Offset from %s pointing outside of"
19782              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19783            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19784   return (const char *) (str_section->buffer + str_offset);
19785 }
19786
19787 /* Return the length of an LEB128 number in BUF.  */
19788
19789 static int
19790 leb128_size (const gdb_byte *buf)
19791 {
19792   const gdb_byte *begin = buf;
19793   gdb_byte byte;
19794
19795   while (1)
19796     {
19797       byte = *buf++;
19798       if ((byte & 128) == 0)
19799         return buf - begin;
19800     }
19801 }
19802
19803 static void
19804 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19805 {
19806   switch (lang)
19807     {
19808     case DW_LANG_C89:
19809     case DW_LANG_C99:
19810     case DW_LANG_C11:
19811     case DW_LANG_C:
19812     case DW_LANG_UPC:
19813       cu->language = language_c;
19814       break;
19815     case DW_LANG_Java:
19816     case DW_LANG_C_plus_plus:
19817     case DW_LANG_C_plus_plus_11:
19818     case DW_LANG_C_plus_plus_14:
19819       cu->language = language_cplus;
19820       break;
19821     case DW_LANG_D:
19822       cu->language = language_d;
19823       break;
19824     case DW_LANG_Fortran77:
19825     case DW_LANG_Fortran90:
19826     case DW_LANG_Fortran95:
19827     case DW_LANG_Fortran03:
19828     case DW_LANG_Fortran08:
19829       cu->language = language_fortran;
19830       break;
19831     case DW_LANG_Go:
19832       cu->language = language_go;
19833       break;
19834     case DW_LANG_Mips_Assembler:
19835       cu->language = language_asm;
19836       break;
19837     case DW_LANG_Ada83:
19838     case DW_LANG_Ada95:
19839       cu->language = language_ada;
19840       break;
19841     case DW_LANG_Modula2:
19842       cu->language = language_m2;
19843       break;
19844     case DW_LANG_Pascal83:
19845       cu->language = language_pascal;
19846       break;
19847     case DW_LANG_ObjC:
19848       cu->language = language_objc;
19849       break;
19850     case DW_LANG_Rust:
19851     case DW_LANG_Rust_old:
19852       cu->language = language_rust;
19853       break;
19854     case DW_LANG_Cobol74:
19855     case DW_LANG_Cobol85:
19856     default:
19857       cu->language = language_minimal;
19858       break;
19859     }
19860   cu->language_defn = language_def (cu->language);
19861 }
19862
19863 /* Return the named attribute or NULL if not there.  */
19864
19865 static struct attribute *
19866 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19867 {
19868   for (;;)
19869     {
19870       unsigned int i;
19871       struct attribute *spec = NULL;
19872
19873       for (i = 0; i < die->num_attrs; ++i)
19874         {
19875           if (die->attrs[i].name == name)
19876             return &die->attrs[i];
19877           if (die->attrs[i].name == DW_AT_specification
19878               || die->attrs[i].name == DW_AT_abstract_origin)
19879             spec = &die->attrs[i];
19880         }
19881
19882       if (!spec)
19883         break;
19884
19885       die = follow_die_ref (die, spec, &cu);
19886     }
19887
19888   return NULL;
19889 }
19890
19891 /* Return the named attribute or NULL if not there,
19892    but do not follow DW_AT_specification, etc.
19893    This is for use in contexts where we're reading .debug_types dies.
19894    Following DW_AT_specification, DW_AT_abstract_origin will take us
19895    back up the chain, and we want to go down.  */
19896
19897 static struct attribute *
19898 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19899 {
19900   unsigned int i;
19901
19902   for (i = 0; i < die->num_attrs; ++i)
19903     if (die->attrs[i].name == name)
19904       return &die->attrs[i];
19905
19906   return NULL;
19907 }
19908
19909 /* Return the string associated with a string-typed attribute, or NULL if it
19910    is either not found or is of an incorrect type.  */
19911
19912 static const char *
19913 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19914 {
19915   struct attribute *attr;
19916   const char *str = NULL;
19917
19918   attr = dwarf2_attr (die, name, cu);
19919
19920   if (attr != NULL)
19921     {
19922       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19923           || attr->form == DW_FORM_string
19924           || attr->form == DW_FORM_GNU_str_index
19925           || attr->form == DW_FORM_GNU_strp_alt)
19926         str = DW_STRING (attr);
19927       else
19928         complaint (&symfile_complaints,
19929                    _("string type expected for attribute %s for "
19930                      "DIE at %s in module %s"),
19931                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19932                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19933     }
19934
19935   return str;
19936 }
19937
19938 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19939    and holds a non-zero value.  This function should only be used for
19940    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19941
19942 static int
19943 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19944 {
19945   struct attribute *attr = dwarf2_attr (die, name, cu);
19946
19947   return (attr && DW_UNSND (attr));
19948 }
19949
19950 static int
19951 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19952 {
19953   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19954      which value is non-zero.  However, we have to be careful with
19955      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19956      (via dwarf2_flag_true_p) follows this attribute.  So we may
19957      end up accidently finding a declaration attribute that belongs
19958      to a different DIE referenced by the specification attribute,
19959      even though the given DIE does not have a declaration attribute.  */
19960   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19961           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19962 }
19963
19964 /* Return the die giving the specification for DIE, if there is
19965    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19966    containing the return value on output.  If there is no
19967    specification, but there is an abstract origin, that is
19968    returned.  */
19969
19970 static struct die_info *
19971 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19972 {
19973   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19974                                              *spec_cu);
19975
19976   if (spec_attr == NULL)
19977     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19978
19979   if (spec_attr == NULL)
19980     return NULL;
19981   else
19982     return follow_die_ref (die, spec_attr, spec_cu);
19983 }
19984
19985 /* Stub for free_line_header to match void * callback types.  */
19986
19987 static void
19988 free_line_header_voidp (void *arg)
19989 {
19990   struct line_header *lh = (struct line_header *) arg;
19991
19992   delete lh;
19993 }
19994
19995 void
19996 line_header::add_include_dir (const char *include_dir)
19997 {
19998   if (dwarf_line_debug >= 2)
19999     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20000                         include_dirs.size () + 1, include_dir);
20001
20002   include_dirs.push_back (include_dir);
20003 }
20004
20005 void
20006 line_header::add_file_name (const char *name,
20007                             dir_index d_index,
20008                             unsigned int mod_time,
20009                             unsigned int length)
20010 {
20011   if (dwarf_line_debug >= 2)
20012     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20013                         (unsigned) file_names.size () + 1, name);
20014
20015   file_names.emplace_back (name, d_index, mod_time, length);
20016 }
20017
20018 /* A convenience function to find the proper .debug_line section for a CU.  */
20019
20020 static struct dwarf2_section_info *
20021 get_debug_line_section (struct dwarf2_cu *cu)
20022 {
20023   struct dwarf2_section_info *section;
20024   struct dwarf2_per_objfile *dwarf2_per_objfile
20025     = cu->per_cu->dwarf2_per_objfile;
20026
20027   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20028      DWO file.  */
20029   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20030     section = &cu->dwo_unit->dwo_file->sections.line;
20031   else if (cu->per_cu->is_dwz)
20032     {
20033       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20034
20035       section = &dwz->line;
20036     }
20037   else
20038     section = &dwarf2_per_objfile->line;
20039
20040   return section;
20041 }
20042
20043 /* Read directory or file name entry format, starting with byte of
20044    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20045    entries count and the entries themselves in the described entry
20046    format.  */
20047
20048 static void
20049 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20050                         bfd *abfd, const gdb_byte **bufp,
20051                         struct line_header *lh,
20052                         const struct comp_unit_head *cu_header,
20053                         void (*callback) (struct line_header *lh,
20054                                           const char *name,
20055                                           dir_index d_index,
20056                                           unsigned int mod_time,
20057                                           unsigned int length))
20058 {
20059   gdb_byte format_count, formati;
20060   ULONGEST data_count, datai;
20061   const gdb_byte *buf = *bufp;
20062   const gdb_byte *format_header_data;
20063   unsigned int bytes_read;
20064
20065   format_count = read_1_byte (abfd, buf);
20066   buf += 1;
20067   format_header_data = buf;
20068   for (formati = 0; formati < format_count; formati++)
20069     {
20070       read_unsigned_leb128 (abfd, buf, &bytes_read);
20071       buf += bytes_read;
20072       read_unsigned_leb128 (abfd, buf, &bytes_read);
20073       buf += bytes_read;
20074     }
20075
20076   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20077   buf += bytes_read;
20078   for (datai = 0; datai < data_count; datai++)
20079     {
20080       const gdb_byte *format = format_header_data;
20081       struct file_entry fe;
20082
20083       for (formati = 0; formati < format_count; formati++)
20084         {
20085           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20086           format += bytes_read;
20087
20088           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20089           format += bytes_read;
20090
20091           gdb::optional<const char *> string;
20092           gdb::optional<unsigned int> uint;
20093
20094           switch (form)
20095             {
20096             case DW_FORM_string:
20097               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20098               buf += bytes_read;
20099               break;
20100
20101             case DW_FORM_line_strp:
20102               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20103                                                          abfd, buf,
20104                                                          cu_header,
20105                                                          &bytes_read));
20106               buf += bytes_read;
20107               break;
20108
20109             case DW_FORM_data1:
20110               uint.emplace (read_1_byte (abfd, buf));
20111               buf += 1;
20112               break;
20113
20114             case DW_FORM_data2:
20115               uint.emplace (read_2_bytes (abfd, buf));
20116               buf += 2;
20117               break;
20118
20119             case DW_FORM_data4:
20120               uint.emplace (read_4_bytes (abfd, buf));
20121               buf += 4;
20122               break;
20123
20124             case DW_FORM_data8:
20125               uint.emplace (read_8_bytes (abfd, buf));
20126               buf += 8;
20127               break;
20128
20129             case DW_FORM_udata:
20130               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20131               buf += bytes_read;
20132               break;
20133
20134             case DW_FORM_block:
20135               /* It is valid only for DW_LNCT_timestamp which is ignored by
20136                  current GDB.  */
20137               break;
20138             }
20139
20140           switch (content_type)
20141             {
20142             case DW_LNCT_path:
20143               if (string.has_value ())
20144                 fe.name = *string;
20145               break;
20146             case DW_LNCT_directory_index:
20147               if (uint.has_value ())
20148                 fe.d_index = (dir_index) *uint;
20149               break;
20150             case DW_LNCT_timestamp:
20151               if (uint.has_value ())
20152                 fe.mod_time = *uint;
20153               break;
20154             case DW_LNCT_size:
20155               if (uint.has_value ())
20156                 fe.length = *uint;
20157               break;
20158             case DW_LNCT_MD5:
20159               break;
20160             default:
20161               complaint (&symfile_complaints,
20162                          _("Unknown format content type %s"),
20163                          pulongest (content_type));
20164             }
20165         }
20166
20167       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20168     }
20169
20170   *bufp = buf;
20171 }
20172
20173 /* Read the statement program header starting at OFFSET in
20174    .debug_line, or .debug_line.dwo.  Return a pointer
20175    to a struct line_header, allocated using xmalloc.
20176    Returns NULL if there is a problem reading the header, e.g., if it
20177    has a version we don't understand.
20178
20179    NOTE: the strings in the include directory and file name tables of
20180    the returned object point into the dwarf line section buffer,
20181    and must not be freed.  */
20182
20183 static line_header_up
20184 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20185 {
20186   const gdb_byte *line_ptr;
20187   unsigned int bytes_read, offset_size;
20188   int i;
20189   const char *cur_dir, *cur_file;
20190   struct dwarf2_section_info *section;
20191   bfd *abfd;
20192   struct dwarf2_per_objfile *dwarf2_per_objfile
20193     = cu->per_cu->dwarf2_per_objfile;
20194
20195   section = get_debug_line_section (cu);
20196   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20197   if (section->buffer == NULL)
20198     {
20199       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20200         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20201       else
20202         complaint (&symfile_complaints, _("missing .debug_line section"));
20203       return 0;
20204     }
20205
20206   /* We can't do this until we know the section is non-empty.
20207      Only then do we know we have such a section.  */
20208   abfd = get_section_bfd_owner (section);
20209
20210   /* Make sure that at least there's room for the total_length field.
20211      That could be 12 bytes long, but we're just going to fudge that.  */
20212   if (to_underlying (sect_off) + 4 >= section->size)
20213     {
20214       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20215       return 0;
20216     }
20217
20218   line_header_up lh (new line_header ());
20219
20220   lh->sect_off = sect_off;
20221   lh->offset_in_dwz = cu->per_cu->is_dwz;
20222
20223   line_ptr = section->buffer + to_underlying (sect_off);
20224
20225   /* Read in the header.  */
20226   lh->total_length =
20227     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20228                                             &bytes_read, &offset_size);
20229   line_ptr += bytes_read;
20230   if (line_ptr + lh->total_length > (section->buffer + section->size))
20231     {
20232       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20233       return 0;
20234     }
20235   lh->statement_program_end = line_ptr + lh->total_length;
20236   lh->version = read_2_bytes (abfd, line_ptr);
20237   line_ptr += 2;
20238   if (lh->version > 5)
20239     {
20240       /* This is a version we don't understand.  The format could have
20241          changed in ways we don't handle properly so just punt.  */
20242       complaint (&symfile_complaints,
20243                  _("unsupported version in .debug_line section"));
20244       return NULL;
20245     }
20246   if (lh->version >= 5)
20247     {
20248       gdb_byte segment_selector_size;
20249
20250       /* Skip address size.  */
20251       read_1_byte (abfd, line_ptr);
20252       line_ptr += 1;
20253
20254       segment_selector_size = read_1_byte (abfd, line_ptr);
20255       line_ptr += 1;
20256       if (segment_selector_size != 0)
20257         {
20258           complaint (&symfile_complaints,
20259                      _("unsupported segment selector size %u "
20260                        "in .debug_line section"),
20261                      segment_selector_size);
20262           return NULL;
20263         }
20264     }
20265   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20266   line_ptr += offset_size;
20267   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20268   line_ptr += 1;
20269   if (lh->version >= 4)
20270     {
20271       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20272       line_ptr += 1;
20273     }
20274   else
20275     lh->maximum_ops_per_instruction = 1;
20276
20277   if (lh->maximum_ops_per_instruction == 0)
20278     {
20279       lh->maximum_ops_per_instruction = 1;
20280       complaint (&symfile_complaints,
20281                  _("invalid maximum_ops_per_instruction "
20282                    "in `.debug_line' section"));
20283     }
20284
20285   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20286   line_ptr += 1;
20287   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20288   line_ptr += 1;
20289   lh->line_range = read_1_byte (abfd, line_ptr);
20290   line_ptr += 1;
20291   lh->opcode_base = read_1_byte (abfd, line_ptr);
20292   line_ptr += 1;
20293   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20294
20295   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20296   for (i = 1; i < lh->opcode_base; ++i)
20297     {
20298       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20299       line_ptr += 1;
20300     }
20301
20302   if (lh->version >= 5)
20303     {
20304       /* Read directory table.  */
20305       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20306                               &cu->header,
20307                               [] (struct line_header *lh, const char *name,
20308                                   dir_index d_index, unsigned int mod_time,
20309                                   unsigned int length)
20310         {
20311           lh->add_include_dir (name);
20312         });
20313
20314       /* Read file name table.  */
20315       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20316                               &cu->header,
20317                               [] (struct line_header *lh, const char *name,
20318                                   dir_index d_index, unsigned int mod_time,
20319                                   unsigned int length)
20320         {
20321           lh->add_file_name (name, d_index, mod_time, length);
20322         });
20323     }
20324   else
20325     {
20326       /* Read directory table.  */
20327       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20328         {
20329           line_ptr += bytes_read;
20330           lh->add_include_dir (cur_dir);
20331         }
20332       line_ptr += bytes_read;
20333
20334       /* Read file name table.  */
20335       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20336         {
20337           unsigned int mod_time, length;
20338           dir_index d_index;
20339
20340           line_ptr += bytes_read;
20341           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20342           line_ptr += bytes_read;
20343           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20344           line_ptr += bytes_read;
20345           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20346           line_ptr += bytes_read;
20347
20348           lh->add_file_name (cur_file, d_index, mod_time, length);
20349         }
20350       line_ptr += bytes_read;
20351     }
20352   lh->statement_program_start = line_ptr;
20353
20354   if (line_ptr > (section->buffer + section->size))
20355     complaint (&symfile_complaints,
20356                _("line number info header doesn't "
20357                  "fit in `.debug_line' section"));
20358
20359   return lh;
20360 }
20361
20362 /* Subroutine of dwarf_decode_lines to simplify it.
20363    Return the file name of the psymtab for included file FILE_INDEX
20364    in line header LH of PST.
20365    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20366    If space for the result is malloc'd, *NAME_HOLDER will be set.
20367    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20368
20369 static const char *
20370 psymtab_include_file_name (const struct line_header *lh, int file_index,
20371                            const struct partial_symtab *pst,
20372                            const char *comp_dir,
20373                            gdb::unique_xmalloc_ptr<char> *name_holder)
20374 {
20375   const file_entry &fe = lh->file_names[file_index];
20376   const char *include_name = fe.name;
20377   const char *include_name_to_compare = include_name;
20378   const char *pst_filename;
20379   int file_is_pst;
20380
20381   const char *dir_name = fe.include_dir (lh);
20382
20383   gdb::unique_xmalloc_ptr<char> hold_compare;
20384   if (!IS_ABSOLUTE_PATH (include_name)
20385       && (dir_name != NULL || comp_dir != NULL))
20386     {
20387       /* Avoid creating a duplicate psymtab for PST.
20388          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20389          Before we do the comparison, however, we need to account
20390          for DIR_NAME and COMP_DIR.
20391          First prepend dir_name (if non-NULL).  If we still don't
20392          have an absolute path prepend comp_dir (if non-NULL).
20393          However, the directory we record in the include-file's
20394          psymtab does not contain COMP_DIR (to match the
20395          corresponding symtab(s)).
20396
20397          Example:
20398
20399          bash$ cd /tmp
20400          bash$ gcc -g ./hello.c
20401          include_name = "hello.c"
20402          dir_name = "."
20403          DW_AT_comp_dir = comp_dir = "/tmp"
20404          DW_AT_name = "./hello.c"
20405
20406       */
20407
20408       if (dir_name != NULL)
20409         {
20410           name_holder->reset (concat (dir_name, SLASH_STRING,
20411                                       include_name, (char *) NULL));
20412           include_name = name_holder->get ();
20413           include_name_to_compare = include_name;
20414         }
20415       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20416         {
20417           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20418                                       include_name, (char *) NULL));
20419           include_name_to_compare = hold_compare.get ();
20420         }
20421     }
20422
20423   pst_filename = pst->filename;
20424   gdb::unique_xmalloc_ptr<char> copied_name;
20425   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20426     {
20427       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20428                                  pst_filename, (char *) NULL));
20429       pst_filename = copied_name.get ();
20430     }
20431
20432   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20433
20434   if (file_is_pst)
20435     return NULL;
20436   return include_name;
20437 }
20438
20439 /* State machine to track the state of the line number program.  */
20440
20441 class lnp_state_machine
20442 {
20443 public:
20444   /* Initialize a machine state for the start of a line number
20445      program.  */
20446   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20447
20448   file_entry *current_file ()
20449   {
20450     /* lh->file_names is 0-based, but the file name numbers in the
20451        statement program are 1-based.  */
20452     return m_line_header->file_name_at (m_file);
20453   }
20454
20455   /* Record the line in the state machine.  END_SEQUENCE is true if
20456      we're processing the end of a sequence.  */
20457   void record_line (bool end_sequence);
20458
20459   /* Check address and if invalid nop-out the rest of the lines in this
20460      sequence.  */
20461   void check_line_address (struct dwarf2_cu *cu,
20462                            const gdb_byte *line_ptr,
20463                            CORE_ADDR lowpc, CORE_ADDR address);
20464
20465   void handle_set_discriminator (unsigned int discriminator)
20466   {
20467     m_discriminator = discriminator;
20468     m_line_has_non_zero_discriminator |= discriminator != 0;
20469   }
20470
20471   /* Handle DW_LNE_set_address.  */
20472   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20473   {
20474     m_op_index = 0;
20475     address += baseaddr;
20476     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20477   }
20478
20479   /* Handle DW_LNS_advance_pc.  */
20480   void handle_advance_pc (CORE_ADDR adjust);
20481
20482   /* Handle a special opcode.  */
20483   void handle_special_opcode (unsigned char op_code);
20484
20485   /* Handle DW_LNS_advance_line.  */
20486   void handle_advance_line (int line_delta)
20487   {
20488     advance_line (line_delta);
20489   }
20490
20491   /* Handle DW_LNS_set_file.  */
20492   void handle_set_file (file_name_index file);
20493
20494   /* Handle DW_LNS_negate_stmt.  */
20495   void handle_negate_stmt ()
20496   {
20497     m_is_stmt = !m_is_stmt;
20498   }
20499
20500   /* Handle DW_LNS_const_add_pc.  */
20501   void handle_const_add_pc ();
20502
20503   /* Handle DW_LNS_fixed_advance_pc.  */
20504   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20505   {
20506     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20507     m_op_index = 0;
20508   }
20509
20510   /* Handle DW_LNS_copy.  */
20511   void handle_copy ()
20512   {
20513     record_line (false);
20514     m_discriminator = 0;
20515   }
20516
20517   /* Handle DW_LNE_end_sequence.  */
20518   void handle_end_sequence ()
20519   {
20520     m_record_line_callback = ::record_line;
20521   }
20522
20523 private:
20524   /* Advance the line by LINE_DELTA.  */
20525   void advance_line (int line_delta)
20526   {
20527     m_line += line_delta;
20528
20529     if (line_delta != 0)
20530       m_line_has_non_zero_discriminator = m_discriminator != 0;
20531   }
20532
20533   gdbarch *m_gdbarch;
20534
20535   /* True if we're recording lines.
20536      Otherwise we're building partial symtabs and are just interested in
20537      finding include files mentioned by the line number program.  */
20538   bool m_record_lines_p;
20539
20540   /* The line number header.  */
20541   line_header *m_line_header;
20542
20543   /* These are part of the standard DWARF line number state machine,
20544      and initialized according to the DWARF spec.  */
20545
20546   unsigned char m_op_index = 0;
20547   /* The line table index (1-based) of the current file.  */
20548   file_name_index m_file = (file_name_index) 1;
20549   unsigned int m_line = 1;
20550
20551   /* These are initialized in the constructor.  */
20552
20553   CORE_ADDR m_address;
20554   bool m_is_stmt;
20555   unsigned int m_discriminator;
20556
20557   /* Additional bits of state we need to track.  */
20558
20559   /* The last file that we called dwarf2_start_subfile for.
20560      This is only used for TLLs.  */
20561   unsigned int m_last_file = 0;
20562   /* The last file a line number was recorded for.  */
20563   struct subfile *m_last_subfile = NULL;
20564
20565   /* The function to call to record a line.  */
20566   record_line_ftype *m_record_line_callback = NULL;
20567
20568   /* The last line number that was recorded, used to coalesce
20569      consecutive entries for the same line.  This can happen, for
20570      example, when discriminators are present.  PR 17276.  */
20571   unsigned int m_last_line = 0;
20572   bool m_line_has_non_zero_discriminator = false;
20573 };
20574
20575 void
20576 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20577 {
20578   CORE_ADDR addr_adj = (((m_op_index + adjust)
20579                          / m_line_header->maximum_ops_per_instruction)
20580                         * m_line_header->minimum_instruction_length);
20581   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20582   m_op_index = ((m_op_index + adjust)
20583                 % m_line_header->maximum_ops_per_instruction);
20584 }
20585
20586 void
20587 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20588 {
20589   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20590   CORE_ADDR addr_adj = (((m_op_index
20591                           + (adj_opcode / m_line_header->line_range))
20592                          / m_line_header->maximum_ops_per_instruction)
20593                         * m_line_header->minimum_instruction_length);
20594   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20595   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20596                 % m_line_header->maximum_ops_per_instruction);
20597
20598   int line_delta = (m_line_header->line_base
20599                     + (adj_opcode % m_line_header->line_range));
20600   advance_line (line_delta);
20601   record_line (false);
20602   m_discriminator = 0;
20603 }
20604
20605 void
20606 lnp_state_machine::handle_set_file (file_name_index file)
20607 {
20608   m_file = file;
20609
20610   const file_entry *fe = current_file ();
20611   if (fe == NULL)
20612     dwarf2_debug_line_missing_file_complaint ();
20613   else if (m_record_lines_p)
20614     {
20615       const char *dir = fe->include_dir (m_line_header);
20616
20617       m_last_subfile = current_subfile;
20618       m_line_has_non_zero_discriminator = m_discriminator != 0;
20619       dwarf2_start_subfile (fe->name, dir);
20620     }
20621 }
20622
20623 void
20624 lnp_state_machine::handle_const_add_pc ()
20625 {
20626   CORE_ADDR adjust
20627     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20628
20629   CORE_ADDR addr_adj
20630     = (((m_op_index + adjust)
20631         / m_line_header->maximum_ops_per_instruction)
20632        * m_line_header->minimum_instruction_length);
20633
20634   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20635   m_op_index = ((m_op_index + adjust)
20636                 % m_line_header->maximum_ops_per_instruction);
20637 }
20638
20639 /* Ignore this record_line request.  */
20640
20641 static void
20642 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20643 {
20644   return;
20645 }
20646
20647 /* Return non-zero if we should add LINE to the line number table.
20648    LINE is the line to add, LAST_LINE is the last line that was added,
20649    LAST_SUBFILE is the subfile for LAST_LINE.
20650    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20651    had a non-zero discriminator.
20652
20653    We have to be careful in the presence of discriminators.
20654    E.g., for this line:
20655
20656      for (i = 0; i < 100000; i++);
20657
20658    clang can emit four line number entries for that one line,
20659    each with a different discriminator.
20660    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20661
20662    However, we want gdb to coalesce all four entries into one.
20663    Otherwise the user could stepi into the middle of the line and
20664    gdb would get confused about whether the pc really was in the
20665    middle of the line.
20666
20667    Things are further complicated by the fact that two consecutive
20668    line number entries for the same line is a heuristic used by gcc
20669    to denote the end of the prologue.  So we can't just discard duplicate
20670    entries, we have to be selective about it.  The heuristic we use is
20671    that we only collapse consecutive entries for the same line if at least
20672    one of those entries has a non-zero discriminator.  PR 17276.
20673
20674    Note: Addresses in the line number state machine can never go backwards
20675    within one sequence, thus this coalescing is ok.  */
20676
20677 static int
20678 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20679                      int line_has_non_zero_discriminator,
20680                      struct subfile *last_subfile)
20681 {
20682   if (current_subfile != last_subfile)
20683     return 1;
20684   if (line != last_line)
20685     return 1;
20686   /* Same line for the same file that we've seen already.
20687      As a last check, for pr 17276, only record the line if the line
20688      has never had a non-zero discriminator.  */
20689   if (!line_has_non_zero_discriminator)
20690     return 1;
20691   return 0;
20692 }
20693
20694 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20695    in the line table of subfile SUBFILE.  */
20696
20697 static void
20698 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20699                      unsigned int line, CORE_ADDR address,
20700                      record_line_ftype p_record_line)
20701 {
20702   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20703
20704   if (dwarf_line_debug)
20705     {
20706       fprintf_unfiltered (gdb_stdlog,
20707                           "Recording line %u, file %s, address %s\n",
20708                           line, lbasename (subfile->name),
20709                           paddress (gdbarch, address));
20710     }
20711
20712   (*p_record_line) (subfile, line, addr);
20713 }
20714
20715 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20716    Mark the end of a set of line number records.
20717    The arguments are the same as for dwarf_record_line_1.
20718    If SUBFILE is NULL the request is ignored.  */
20719
20720 static void
20721 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20722                    CORE_ADDR address, record_line_ftype p_record_line)
20723 {
20724   if (subfile == NULL)
20725     return;
20726
20727   if (dwarf_line_debug)
20728     {
20729       fprintf_unfiltered (gdb_stdlog,
20730                           "Finishing current line, file %s, address %s\n",
20731                           lbasename (subfile->name),
20732                           paddress (gdbarch, address));
20733     }
20734
20735   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20736 }
20737
20738 void
20739 lnp_state_machine::record_line (bool end_sequence)
20740 {
20741   if (dwarf_line_debug)
20742     {
20743       fprintf_unfiltered (gdb_stdlog,
20744                           "Processing actual line %u: file %u,"
20745                           " address %s, is_stmt %u, discrim %u\n",
20746                           m_line, to_underlying (m_file),
20747                           paddress (m_gdbarch, m_address),
20748                           m_is_stmt, m_discriminator);
20749     }
20750
20751   file_entry *fe = current_file ();
20752
20753   if (fe == NULL)
20754     dwarf2_debug_line_missing_file_complaint ();
20755   /* For now we ignore lines not starting on an instruction boundary.
20756      But not when processing end_sequence for compatibility with the
20757      previous version of the code.  */
20758   else if (m_op_index == 0 || end_sequence)
20759     {
20760       fe->included_p = 1;
20761       if (m_record_lines_p && m_is_stmt)
20762         {
20763           if (m_last_subfile != current_subfile || end_sequence)
20764             {
20765               dwarf_finish_line (m_gdbarch, m_last_subfile,
20766                                  m_address, m_record_line_callback);
20767             }
20768
20769           if (!end_sequence)
20770             {
20771               if (dwarf_record_line_p (m_line, m_last_line,
20772                                        m_line_has_non_zero_discriminator,
20773                                        m_last_subfile))
20774                 {
20775                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20776                                        m_line, m_address,
20777                                        m_record_line_callback);
20778                 }
20779               m_last_subfile = current_subfile;
20780               m_last_line = m_line;
20781             }
20782         }
20783     }
20784 }
20785
20786 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20787                                       bool record_lines_p)
20788 {
20789   m_gdbarch = arch;
20790   m_record_lines_p = record_lines_p;
20791   m_line_header = lh;
20792
20793   m_record_line_callback = ::record_line;
20794
20795   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20796      was a line entry for it so that the backend has a chance to adjust it
20797      and also record it in case it needs it.  This is currently used by MIPS
20798      code, cf. `mips_adjust_dwarf2_line'.  */
20799   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20800   m_is_stmt = lh->default_is_stmt;
20801   m_discriminator = 0;
20802 }
20803
20804 void
20805 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20806                                        const gdb_byte *line_ptr,
20807                                        CORE_ADDR lowpc, CORE_ADDR address)
20808 {
20809   /* If address < lowpc then it's not a usable value, it's outside the
20810      pc range of the CU.  However, we restrict the test to only address
20811      values of zero to preserve GDB's previous behaviour which is to
20812      handle the specific case of a function being GC'd by the linker.  */
20813
20814   if (address == 0 && address < lowpc)
20815     {
20816       /* This line table is for a function which has been
20817          GCd by the linker.  Ignore it.  PR gdb/12528 */
20818
20819       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20820       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20821
20822       complaint (&symfile_complaints,
20823                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20824                  line_offset, objfile_name (objfile));
20825       m_record_line_callback = noop_record_line;
20826       /* Note: record_line_callback is left as noop_record_line until
20827          we see DW_LNE_end_sequence.  */
20828     }
20829 }
20830
20831 /* Subroutine of dwarf_decode_lines to simplify it.
20832    Process the line number information in LH.
20833    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20834    program in order to set included_p for every referenced header.  */
20835
20836 static void
20837 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20838                       const int decode_for_pst_p, CORE_ADDR lowpc)
20839 {
20840   const gdb_byte *line_ptr, *extended_end;
20841   const gdb_byte *line_end;
20842   unsigned int bytes_read, extended_len;
20843   unsigned char op_code, extended_op;
20844   CORE_ADDR baseaddr;
20845   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20846   bfd *abfd = objfile->obfd;
20847   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20848   /* True if we're recording line info (as opposed to building partial
20849      symtabs and just interested in finding include files mentioned by
20850      the line number program).  */
20851   bool record_lines_p = !decode_for_pst_p;
20852
20853   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20854
20855   line_ptr = lh->statement_program_start;
20856   line_end = lh->statement_program_end;
20857
20858   /* Read the statement sequences until there's nothing left.  */
20859   while (line_ptr < line_end)
20860     {
20861       /* The DWARF line number program state machine.  Reset the state
20862          machine at the start of each sequence.  */
20863       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20864       bool end_sequence = false;
20865
20866       if (record_lines_p)
20867         {
20868           /* Start a subfile for the current file of the state
20869              machine.  */
20870           const file_entry *fe = state_machine.current_file ();
20871
20872           if (fe != NULL)
20873             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20874         }
20875
20876       /* Decode the table.  */
20877       while (line_ptr < line_end && !end_sequence)
20878         {
20879           op_code = read_1_byte (abfd, line_ptr);
20880           line_ptr += 1;
20881
20882           if (op_code >= lh->opcode_base)
20883             {
20884               /* Special opcode.  */
20885               state_machine.handle_special_opcode (op_code);
20886             }
20887           else switch (op_code)
20888             {
20889             case DW_LNS_extended_op:
20890               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20891                                                    &bytes_read);
20892               line_ptr += bytes_read;
20893               extended_end = line_ptr + extended_len;
20894               extended_op = read_1_byte (abfd, line_ptr);
20895               line_ptr += 1;
20896               switch (extended_op)
20897                 {
20898                 case DW_LNE_end_sequence:
20899                   state_machine.handle_end_sequence ();
20900                   end_sequence = true;
20901                   break;
20902                 case DW_LNE_set_address:
20903                   {
20904                     CORE_ADDR address
20905                       = read_address (abfd, line_ptr, cu, &bytes_read);
20906                     line_ptr += bytes_read;
20907
20908                     state_machine.check_line_address (cu, line_ptr,
20909                                                       lowpc, address);
20910                     state_machine.handle_set_address (baseaddr, address);
20911                   }
20912                   break;
20913                 case DW_LNE_define_file:
20914                   {
20915                     const char *cur_file;
20916                     unsigned int mod_time, length;
20917                     dir_index dindex;
20918
20919                     cur_file = read_direct_string (abfd, line_ptr,
20920                                                    &bytes_read);
20921                     line_ptr += bytes_read;
20922                     dindex = (dir_index)
20923                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20924                     line_ptr += bytes_read;
20925                     mod_time =
20926                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20927                     line_ptr += bytes_read;
20928                     length =
20929                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20930                     line_ptr += bytes_read;
20931                     lh->add_file_name (cur_file, dindex, mod_time, length);
20932                   }
20933                   break;
20934                 case DW_LNE_set_discriminator:
20935                   {
20936                     /* The discriminator is not interesting to the
20937                        debugger; just ignore it.  We still need to
20938                        check its value though:
20939                        if there are consecutive entries for the same
20940                        (non-prologue) line we want to coalesce them.
20941                        PR 17276.  */
20942                     unsigned int discr
20943                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20944                     line_ptr += bytes_read;
20945
20946                     state_machine.handle_set_discriminator (discr);
20947                   }
20948                   break;
20949                 default:
20950                   complaint (&symfile_complaints,
20951                              _("mangled .debug_line section"));
20952                   return;
20953                 }
20954               /* Make sure that we parsed the extended op correctly.  If e.g.
20955                  we expected a different address size than the producer used,
20956                  we may have read the wrong number of bytes.  */
20957               if (line_ptr != extended_end)
20958                 {
20959                   complaint (&symfile_complaints,
20960                              _("mangled .debug_line section"));
20961                   return;
20962                 }
20963               break;
20964             case DW_LNS_copy:
20965               state_machine.handle_copy ();
20966               break;
20967             case DW_LNS_advance_pc:
20968               {
20969                 CORE_ADDR adjust
20970                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20971                 line_ptr += bytes_read;
20972
20973                 state_machine.handle_advance_pc (adjust);
20974               }
20975               break;
20976             case DW_LNS_advance_line:
20977               {
20978                 int line_delta
20979                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20980                 line_ptr += bytes_read;
20981
20982                 state_machine.handle_advance_line (line_delta);
20983               }
20984               break;
20985             case DW_LNS_set_file:
20986               {
20987                 file_name_index file
20988                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20989                                                             &bytes_read);
20990                 line_ptr += bytes_read;
20991
20992                 state_machine.handle_set_file (file);
20993               }
20994               break;
20995             case DW_LNS_set_column:
20996               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20997               line_ptr += bytes_read;
20998               break;
20999             case DW_LNS_negate_stmt:
21000               state_machine.handle_negate_stmt ();
21001               break;
21002             case DW_LNS_set_basic_block:
21003               break;
21004             /* Add to the address register of the state machine the
21005                address increment value corresponding to special opcode
21006                255.  I.e., this value is scaled by the minimum
21007                instruction length since special opcode 255 would have
21008                scaled the increment.  */
21009             case DW_LNS_const_add_pc:
21010               state_machine.handle_const_add_pc ();
21011               break;
21012             case DW_LNS_fixed_advance_pc:
21013               {
21014                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21015                 line_ptr += 2;
21016
21017                 state_machine.handle_fixed_advance_pc (addr_adj);
21018               }
21019               break;
21020             default:
21021               {
21022                 /* Unknown standard opcode, ignore it.  */
21023                 int i;
21024
21025                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21026                   {
21027                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21028                     line_ptr += bytes_read;
21029                   }
21030               }
21031             }
21032         }
21033
21034       if (!end_sequence)
21035         dwarf2_debug_line_missing_end_sequence_complaint ();
21036
21037       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21038          in which case we still finish recording the last line).  */
21039       state_machine.record_line (true);
21040     }
21041 }
21042
21043 /* Decode the Line Number Program (LNP) for the given line_header
21044    structure and CU.  The actual information extracted and the type
21045    of structures created from the LNP depends on the value of PST.
21046
21047    1. If PST is NULL, then this procedure uses the data from the program
21048       to create all necessary symbol tables, and their linetables.
21049
21050    2. If PST is not NULL, this procedure reads the program to determine
21051       the list of files included by the unit represented by PST, and
21052       builds all the associated partial symbol tables.
21053
21054    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21055    It is used for relative paths in the line table.
21056    NOTE: When processing partial symtabs (pst != NULL),
21057    comp_dir == pst->dirname.
21058
21059    NOTE: It is important that psymtabs have the same file name (via strcmp)
21060    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21061    symtab we don't use it in the name of the psymtabs we create.
21062    E.g. expand_line_sal requires this when finding psymtabs to expand.
21063    A good testcase for this is mb-inline.exp.
21064
21065    LOWPC is the lowest address in CU (or 0 if not known).
21066
21067    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21068    for its PC<->lines mapping information.  Otherwise only the filename
21069    table is read in.  */
21070
21071 static void
21072 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21073                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21074                     CORE_ADDR lowpc, int decode_mapping)
21075 {
21076   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21077   const int decode_for_pst_p = (pst != NULL);
21078
21079   if (decode_mapping)
21080     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21081
21082   if (decode_for_pst_p)
21083     {
21084       int file_index;
21085
21086       /* Now that we're done scanning the Line Header Program, we can
21087          create the psymtab of each included file.  */
21088       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21089         if (lh->file_names[file_index].included_p == 1)
21090           {
21091             gdb::unique_xmalloc_ptr<char> name_holder;
21092             const char *include_name =
21093               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21094                                          &name_holder);
21095             if (include_name != NULL)
21096               dwarf2_create_include_psymtab (include_name, pst, objfile);
21097           }
21098     }
21099   else
21100     {
21101       /* Make sure a symtab is created for every file, even files
21102          which contain only variables (i.e. no code with associated
21103          line numbers).  */
21104       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21105       int i;
21106
21107       for (i = 0; i < lh->file_names.size (); i++)
21108         {
21109           file_entry &fe = lh->file_names[i];
21110
21111           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21112
21113           if (current_subfile->symtab == NULL)
21114             {
21115               current_subfile->symtab
21116                 = allocate_symtab (cust, current_subfile->name);
21117             }
21118           fe.symtab = current_subfile->symtab;
21119         }
21120     }
21121 }
21122
21123 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21124    DIRNAME the name of the source directory which contains FILENAME
21125    or NULL if not known.
21126    This routine tries to keep line numbers from identical absolute and
21127    relative file names in a common subfile.
21128
21129    Using the `list' example from the GDB testsuite, which resides in
21130    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21131    of /srcdir/list0.c yields the following debugging information for list0.c:
21132
21133    DW_AT_name:          /srcdir/list0.c
21134    DW_AT_comp_dir:      /compdir
21135    files.files[0].name: list0.h
21136    files.files[0].dir:  /srcdir
21137    files.files[1].name: list0.c
21138    files.files[1].dir:  /srcdir
21139
21140    The line number information for list0.c has to end up in a single
21141    subfile, so that `break /srcdir/list0.c:1' works as expected.
21142    start_subfile will ensure that this happens provided that we pass the
21143    concatenation of files.files[1].dir and files.files[1].name as the
21144    subfile's name.  */
21145
21146 static void
21147 dwarf2_start_subfile (const char *filename, const char *dirname)
21148 {
21149   char *copy = NULL;
21150
21151   /* In order not to lose the line information directory,
21152      we concatenate it to the filename when it makes sense.
21153      Note that the Dwarf3 standard says (speaking of filenames in line
21154      information): ``The directory index is ignored for file names
21155      that represent full path names''.  Thus ignoring dirname in the
21156      `else' branch below isn't an issue.  */
21157
21158   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21159     {
21160       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21161       filename = copy;
21162     }
21163
21164   start_subfile (filename);
21165
21166   if (copy != NULL)
21167     xfree (copy);
21168 }
21169
21170 /* Start a symtab for DWARF.
21171    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21172
21173 static struct compunit_symtab *
21174 dwarf2_start_symtab (struct dwarf2_cu *cu,
21175                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21176 {
21177   struct compunit_symtab *cust
21178     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21179                     low_pc, cu->language);
21180
21181   record_debugformat ("DWARF 2");
21182   record_producer (cu->producer);
21183
21184   /* We assume that we're processing GCC output.  */
21185   processing_gcc_compilation = 2;
21186
21187   cu->processing_has_namespace_info = 0;
21188
21189   return cust;
21190 }
21191
21192 static void
21193 var_decode_location (struct attribute *attr, struct symbol *sym,
21194                      struct dwarf2_cu *cu)
21195 {
21196   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21197   struct comp_unit_head *cu_header = &cu->header;
21198
21199   /* NOTE drow/2003-01-30: There used to be a comment and some special
21200      code here to turn a symbol with DW_AT_external and a
21201      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21202      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21203      with some versions of binutils) where shared libraries could have
21204      relocations against symbols in their debug information - the
21205      minimal symbol would have the right address, but the debug info
21206      would not.  It's no longer necessary, because we will explicitly
21207      apply relocations when we read in the debug information now.  */
21208
21209   /* A DW_AT_location attribute with no contents indicates that a
21210      variable has been optimized away.  */
21211   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21212     {
21213       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21214       return;
21215     }
21216
21217   /* Handle one degenerate form of location expression specially, to
21218      preserve GDB's previous behavior when section offsets are
21219      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21220      then mark this symbol as LOC_STATIC.  */
21221
21222   if (attr_form_is_block (attr)
21223       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21224            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21225           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21226               && (DW_BLOCK (attr)->size
21227                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21228     {
21229       unsigned int dummy;
21230
21231       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21232         SYMBOL_VALUE_ADDRESS (sym) =
21233           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21234       else
21235         SYMBOL_VALUE_ADDRESS (sym) =
21236           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21237       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21238       fixup_symbol_section (sym, objfile);
21239       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21240                                               SYMBOL_SECTION (sym));
21241       return;
21242     }
21243
21244   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21245      expression evaluator, and use LOC_COMPUTED only when necessary
21246      (i.e. when the value of a register or memory location is
21247      referenced, or a thread-local block, etc.).  Then again, it might
21248      not be worthwhile.  I'm assuming that it isn't unless performance
21249      or memory numbers show me otherwise.  */
21250
21251   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21252
21253   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21254     cu->has_loclist = 1;
21255 }
21256
21257 /* Given a pointer to a DWARF information entry, figure out if we need
21258    to make a symbol table entry for it, and if so, create a new entry
21259    and return a pointer to it.
21260    If TYPE is NULL, determine symbol type from the die, otherwise
21261    used the passed type.
21262    If SPACE is not NULL, use it to hold the new symbol.  If it is
21263    NULL, allocate a new symbol on the objfile's obstack.  */
21264
21265 static struct symbol *
21266 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21267             struct symbol *space)
21268 {
21269   struct dwarf2_per_objfile *dwarf2_per_objfile
21270     = cu->per_cu->dwarf2_per_objfile;
21271   struct objfile *objfile = dwarf2_per_objfile->objfile;
21272   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21273   struct symbol *sym = NULL;
21274   const char *name;
21275   struct attribute *attr = NULL;
21276   struct attribute *attr2 = NULL;
21277   CORE_ADDR baseaddr;
21278   struct pending **list_to_add = NULL;
21279
21280   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21281
21282   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21283
21284   name = dwarf2_name (die, cu);
21285   if (name)
21286     {
21287       const char *linkagename;
21288       int suppress_add = 0;
21289
21290       if (space)
21291         sym = space;
21292       else
21293         sym = allocate_symbol (objfile);
21294       OBJSTAT (objfile, n_syms++);
21295
21296       /* Cache this symbol's name and the name's demangled form (if any).  */
21297       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21298       linkagename = dwarf2_physname (name, die, cu);
21299       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21300
21301       /* Fortran does not have mangling standard and the mangling does differ
21302          between gfortran, iFort etc.  */
21303       if (cu->language == language_fortran
21304           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21305         symbol_set_demangled_name (&(sym->ginfo),
21306                                    dwarf2_full_name (name, die, cu),
21307                                    NULL);
21308
21309       /* Default assumptions.
21310          Use the passed type or decode it from the die.  */
21311       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21312       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21313       if (type != NULL)
21314         SYMBOL_TYPE (sym) = type;
21315       else
21316         SYMBOL_TYPE (sym) = die_type (die, cu);
21317       attr = dwarf2_attr (die,
21318                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21319                           cu);
21320       if (attr)
21321         {
21322           SYMBOL_LINE (sym) = DW_UNSND (attr);
21323         }
21324
21325       attr = dwarf2_attr (die,
21326                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21327                           cu);
21328       if (attr)
21329         {
21330           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21331           struct file_entry *fe;
21332
21333           if (cu->line_header != NULL)
21334             fe = cu->line_header->file_name_at (file_index);
21335           else
21336             fe = NULL;
21337
21338           if (fe == NULL)
21339             complaint (&symfile_complaints,
21340                        _("file index out of range"));
21341           else
21342             symbol_set_symtab (sym, fe->symtab);
21343         }
21344
21345       switch (die->tag)
21346         {
21347         case DW_TAG_label:
21348           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21349           if (attr)
21350             {
21351               CORE_ADDR addr;
21352
21353               addr = attr_value_as_address (attr);
21354               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21355               SYMBOL_VALUE_ADDRESS (sym) = addr;
21356             }
21357           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21358           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21359           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21360           add_symbol_to_list (sym, cu->list_in_scope);
21361           break;
21362         case DW_TAG_subprogram:
21363           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21364              finish_block.  */
21365           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21366           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21367           if ((attr2 && (DW_UNSND (attr2) != 0))
21368               || cu->language == language_ada)
21369             {
21370               /* Subprograms marked external are stored as a global symbol.
21371                  Ada subprograms, whether marked external or not, are always
21372                  stored as a global symbol, because we want to be able to
21373                  access them globally.  For instance, we want to be able
21374                  to break on a nested subprogram without having to
21375                  specify the context.  */
21376               list_to_add = &global_symbols;
21377             }
21378           else
21379             {
21380               list_to_add = cu->list_in_scope;
21381             }
21382           break;
21383         case DW_TAG_inlined_subroutine:
21384           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21385              finish_block.  */
21386           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21387           SYMBOL_INLINED (sym) = 1;
21388           list_to_add = cu->list_in_scope;
21389           break;
21390         case DW_TAG_template_value_param:
21391           suppress_add = 1;
21392           /* Fall through.  */
21393         case DW_TAG_constant:
21394         case DW_TAG_variable:
21395         case DW_TAG_member:
21396           /* Compilation with minimal debug info may result in
21397              variables with missing type entries.  Change the
21398              misleading `void' type to something sensible.  */
21399           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21400             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21401
21402           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21403           /* In the case of DW_TAG_member, we should only be called for
21404              static const members.  */
21405           if (die->tag == DW_TAG_member)
21406             {
21407               /* dwarf2_add_field uses die_is_declaration,
21408                  so we do the same.  */
21409               gdb_assert (die_is_declaration (die, cu));
21410               gdb_assert (attr);
21411             }
21412           if (attr)
21413             {
21414               dwarf2_const_value (attr, sym, cu);
21415               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21416               if (!suppress_add)
21417                 {
21418                   if (attr2 && (DW_UNSND (attr2) != 0))
21419                     list_to_add = &global_symbols;
21420                   else
21421                     list_to_add = cu->list_in_scope;
21422                 }
21423               break;
21424             }
21425           attr = dwarf2_attr (die, DW_AT_location, cu);
21426           if (attr)
21427             {
21428               var_decode_location (attr, sym, cu);
21429               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21430
21431               /* Fortran explicitly imports any global symbols to the local
21432                  scope by DW_TAG_common_block.  */
21433               if (cu->language == language_fortran && die->parent
21434                   && die->parent->tag == DW_TAG_common_block)
21435                 attr2 = NULL;
21436
21437               if (SYMBOL_CLASS (sym) == LOC_STATIC
21438                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21439                   && !dwarf2_per_objfile->has_section_at_zero)
21440                 {
21441                   /* When a static variable is eliminated by the linker,
21442                      the corresponding debug information is not stripped
21443                      out, but the variable address is set to null;
21444                      do not add such variables into symbol table.  */
21445                 }
21446               else if (attr2 && (DW_UNSND (attr2) != 0))
21447                 {
21448                   /* Workaround gfortran PR debug/40040 - it uses
21449                      DW_AT_location for variables in -fPIC libraries which may
21450                      get overriden by other libraries/executable and get
21451                      a different address.  Resolve it by the minimal symbol
21452                      which may come from inferior's executable using copy
21453                      relocation.  Make this workaround only for gfortran as for
21454                      other compilers GDB cannot guess the minimal symbol
21455                      Fortran mangling kind.  */
21456                   if (cu->language == language_fortran && die->parent
21457                       && die->parent->tag == DW_TAG_module
21458                       && cu->producer
21459                       && startswith (cu->producer, "GNU Fortran"))
21460                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21461
21462                   /* A variable with DW_AT_external is never static,
21463                      but it may be block-scoped.  */
21464                   list_to_add = (cu->list_in_scope == &file_symbols
21465                                  ? &global_symbols : cu->list_in_scope);
21466                 }
21467               else
21468                 list_to_add = cu->list_in_scope;
21469             }
21470           else
21471             {
21472               /* We do not know the address of this symbol.
21473                  If it is an external symbol and we have type information
21474                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21475                  The address of the variable will then be determined from
21476                  the minimal symbol table whenever the variable is
21477                  referenced.  */
21478               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21479
21480               /* Fortran explicitly imports any global symbols to the local
21481                  scope by DW_TAG_common_block.  */
21482               if (cu->language == language_fortran && die->parent
21483                   && die->parent->tag == DW_TAG_common_block)
21484                 {
21485                   /* SYMBOL_CLASS doesn't matter here because
21486                      read_common_block is going to reset it.  */
21487                   if (!suppress_add)
21488                     list_to_add = cu->list_in_scope;
21489                 }
21490               else if (attr2 && (DW_UNSND (attr2) != 0)
21491                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21492                 {
21493                   /* A variable with DW_AT_external is never static, but it
21494                      may be block-scoped.  */
21495                   list_to_add = (cu->list_in_scope == &file_symbols
21496                                  ? &global_symbols : cu->list_in_scope);
21497
21498                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21499                 }
21500               else if (!die_is_declaration (die, cu))
21501                 {
21502                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21503                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21504                   if (!suppress_add)
21505                     list_to_add = cu->list_in_scope;
21506                 }
21507             }
21508           break;
21509         case DW_TAG_formal_parameter:
21510           /* If we are inside a function, mark this as an argument.  If
21511              not, we might be looking at an argument to an inlined function
21512              when we do not have enough information to show inlined frames;
21513              pretend it's a local variable in that case so that the user can
21514              still see it.  */
21515           if (context_stack_depth > 0
21516               && context_stack[context_stack_depth - 1].name != NULL)
21517             SYMBOL_IS_ARGUMENT (sym) = 1;
21518           attr = dwarf2_attr (die, DW_AT_location, cu);
21519           if (attr)
21520             {
21521               var_decode_location (attr, sym, cu);
21522             }
21523           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21524           if (attr)
21525             {
21526               dwarf2_const_value (attr, sym, cu);
21527             }
21528
21529           list_to_add = cu->list_in_scope;
21530           break;
21531         case DW_TAG_unspecified_parameters:
21532           /* From varargs functions; gdb doesn't seem to have any
21533              interest in this information, so just ignore it for now.
21534              (FIXME?) */
21535           break;
21536         case DW_TAG_template_type_param:
21537           suppress_add = 1;
21538           /* Fall through.  */
21539         case DW_TAG_class_type:
21540         case DW_TAG_interface_type:
21541         case DW_TAG_structure_type:
21542         case DW_TAG_union_type:
21543         case DW_TAG_set_type:
21544         case DW_TAG_enumeration_type:
21545           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21546           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21547
21548           {
21549             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21550                really ever be static objects: otherwise, if you try
21551                to, say, break of a class's method and you're in a file
21552                which doesn't mention that class, it won't work unless
21553                the check for all static symbols in lookup_symbol_aux
21554                saves you.  See the OtherFileClass tests in
21555                gdb.c++/namespace.exp.  */
21556
21557             if (!suppress_add)
21558               {
21559                 list_to_add = (cu->list_in_scope == &file_symbols
21560                                && cu->language == language_cplus
21561                                ? &global_symbols : cu->list_in_scope);
21562
21563                 /* The semantics of C++ state that "struct foo {
21564                    ... }" also defines a typedef for "foo".  */
21565                 if (cu->language == language_cplus
21566                     || cu->language == language_ada
21567                     || cu->language == language_d
21568                     || cu->language == language_rust)
21569                   {
21570                     /* The symbol's name is already allocated along
21571                        with this objfile, so we don't need to
21572                        duplicate it for the type.  */
21573                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21574                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21575                   }
21576               }
21577           }
21578           break;
21579         case DW_TAG_typedef:
21580           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21581           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21582           list_to_add = cu->list_in_scope;
21583           break;
21584         case DW_TAG_base_type:
21585         case DW_TAG_subrange_type:
21586           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21587           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21588           list_to_add = cu->list_in_scope;
21589           break;
21590         case DW_TAG_enumerator:
21591           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21592           if (attr)
21593             {
21594               dwarf2_const_value (attr, sym, cu);
21595             }
21596           {
21597             /* NOTE: carlton/2003-11-10: See comment above in the
21598                DW_TAG_class_type, etc. block.  */
21599
21600             list_to_add = (cu->list_in_scope == &file_symbols
21601                            && cu->language == language_cplus
21602                            ? &global_symbols : cu->list_in_scope);
21603           }
21604           break;
21605         case DW_TAG_imported_declaration:
21606         case DW_TAG_namespace:
21607           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21608           list_to_add = &global_symbols;
21609           break;
21610         case DW_TAG_module:
21611           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21612           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21613           list_to_add = &global_symbols;
21614           break;
21615         case DW_TAG_common_block:
21616           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21617           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21618           add_symbol_to_list (sym, cu->list_in_scope);
21619           break;
21620         default:
21621           /* Not a tag we recognize.  Hopefully we aren't processing
21622              trash data, but since we must specifically ignore things
21623              we don't recognize, there is nothing else we should do at
21624              this point.  */
21625           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21626                      dwarf_tag_name (die->tag));
21627           break;
21628         }
21629
21630       if (suppress_add)
21631         {
21632           sym->hash_next = objfile->template_symbols;
21633           objfile->template_symbols = sym;
21634           list_to_add = NULL;
21635         }
21636
21637       if (list_to_add != NULL)
21638         add_symbol_to_list (sym, list_to_add);
21639
21640       /* For the benefit of old versions of GCC, check for anonymous
21641          namespaces based on the demangled name.  */
21642       if (!cu->processing_has_namespace_info
21643           && cu->language == language_cplus)
21644         cp_scan_for_anonymous_namespaces (sym, objfile);
21645     }
21646   return (sym);
21647 }
21648
21649 /* Given an attr with a DW_FORM_dataN value in host byte order,
21650    zero-extend it as appropriate for the symbol's type.  The DWARF
21651    standard (v4) is not entirely clear about the meaning of using
21652    DW_FORM_dataN for a constant with a signed type, where the type is
21653    wider than the data.  The conclusion of a discussion on the DWARF
21654    list was that this is unspecified.  We choose to always zero-extend
21655    because that is the interpretation long in use by GCC.  */
21656
21657 static gdb_byte *
21658 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21659                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21660 {
21661   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21662   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21663                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21664   LONGEST l = DW_UNSND (attr);
21665
21666   if (bits < sizeof (*value) * 8)
21667     {
21668       l &= ((LONGEST) 1 << bits) - 1;
21669       *value = l;
21670     }
21671   else if (bits == sizeof (*value) * 8)
21672     *value = l;
21673   else
21674     {
21675       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21676       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21677       return bytes;
21678     }
21679
21680   return NULL;
21681 }
21682
21683 /* Read a constant value from an attribute.  Either set *VALUE, or if
21684    the value does not fit in *VALUE, set *BYTES - either already
21685    allocated on the objfile obstack, or newly allocated on OBSTACK,
21686    or, set *BATON, if we translated the constant to a location
21687    expression.  */
21688
21689 static void
21690 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21691                          const char *name, struct obstack *obstack,
21692                          struct dwarf2_cu *cu,
21693                          LONGEST *value, const gdb_byte **bytes,
21694                          struct dwarf2_locexpr_baton **baton)
21695 {
21696   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21697   struct comp_unit_head *cu_header = &cu->header;
21698   struct dwarf_block *blk;
21699   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21700                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21701
21702   *value = 0;
21703   *bytes = NULL;
21704   *baton = NULL;
21705
21706   switch (attr->form)
21707     {
21708     case DW_FORM_addr:
21709     case DW_FORM_GNU_addr_index:
21710       {
21711         gdb_byte *data;
21712
21713         if (TYPE_LENGTH (type) != cu_header->addr_size)
21714           dwarf2_const_value_length_mismatch_complaint (name,
21715                                                         cu_header->addr_size,
21716                                                         TYPE_LENGTH (type));
21717         /* Symbols of this form are reasonably rare, so we just
21718            piggyback on the existing location code rather than writing
21719            a new implementation of symbol_computed_ops.  */
21720         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21721         (*baton)->per_cu = cu->per_cu;
21722         gdb_assert ((*baton)->per_cu);
21723
21724         (*baton)->size = 2 + cu_header->addr_size;
21725         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21726         (*baton)->data = data;
21727
21728         data[0] = DW_OP_addr;
21729         store_unsigned_integer (&data[1], cu_header->addr_size,
21730                                 byte_order, DW_ADDR (attr));
21731         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21732       }
21733       break;
21734     case DW_FORM_string:
21735     case DW_FORM_strp:
21736     case DW_FORM_GNU_str_index:
21737     case DW_FORM_GNU_strp_alt:
21738       /* DW_STRING is already allocated on the objfile obstack, point
21739          directly to it.  */
21740       *bytes = (const gdb_byte *) DW_STRING (attr);
21741       break;
21742     case DW_FORM_block1:
21743     case DW_FORM_block2:
21744     case DW_FORM_block4:
21745     case DW_FORM_block:
21746     case DW_FORM_exprloc:
21747     case DW_FORM_data16:
21748       blk = DW_BLOCK (attr);
21749       if (TYPE_LENGTH (type) != blk->size)
21750         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21751                                                       TYPE_LENGTH (type));
21752       *bytes = blk->data;
21753       break;
21754
21755       /* The DW_AT_const_value attributes are supposed to carry the
21756          symbol's value "represented as it would be on the target
21757          architecture."  By the time we get here, it's already been
21758          converted to host endianness, so we just need to sign- or
21759          zero-extend it as appropriate.  */
21760     case DW_FORM_data1:
21761       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21762       break;
21763     case DW_FORM_data2:
21764       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21765       break;
21766     case DW_FORM_data4:
21767       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21768       break;
21769     case DW_FORM_data8:
21770       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21771       break;
21772
21773     case DW_FORM_sdata:
21774     case DW_FORM_implicit_const:
21775       *value = DW_SND (attr);
21776       break;
21777
21778     case DW_FORM_udata:
21779       *value = DW_UNSND (attr);
21780       break;
21781
21782     default:
21783       complaint (&symfile_complaints,
21784                  _("unsupported const value attribute form: '%s'"),
21785                  dwarf_form_name (attr->form));
21786       *value = 0;
21787       break;
21788     }
21789 }
21790
21791
21792 /* Copy constant value from an attribute to a symbol.  */
21793
21794 static void
21795 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21796                     struct dwarf2_cu *cu)
21797 {
21798   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21799   LONGEST value;
21800   const gdb_byte *bytes;
21801   struct dwarf2_locexpr_baton *baton;
21802
21803   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21804                            SYMBOL_PRINT_NAME (sym),
21805                            &objfile->objfile_obstack, cu,
21806                            &value, &bytes, &baton);
21807
21808   if (baton != NULL)
21809     {
21810       SYMBOL_LOCATION_BATON (sym) = baton;
21811       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21812     }
21813   else if (bytes != NULL)
21814      {
21815       SYMBOL_VALUE_BYTES (sym) = bytes;
21816       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21817     }
21818   else
21819     {
21820       SYMBOL_VALUE (sym) = value;
21821       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21822     }
21823 }
21824
21825 /* Return the type of the die in question using its DW_AT_type attribute.  */
21826
21827 static struct type *
21828 die_type (struct die_info *die, struct dwarf2_cu *cu)
21829 {
21830   struct attribute *type_attr;
21831
21832   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21833   if (!type_attr)
21834     {
21835       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21836       /* A missing DW_AT_type represents a void type.  */
21837       return objfile_type (objfile)->builtin_void;
21838     }
21839
21840   return lookup_die_type (die, type_attr, cu);
21841 }
21842
21843 /* True iff CU's producer generates GNAT Ada auxiliary information
21844    that allows to find parallel types through that information instead
21845    of having to do expensive parallel lookups by type name.  */
21846
21847 static int
21848 need_gnat_info (struct dwarf2_cu *cu)
21849 {
21850   /* Assume that the Ada compiler was GNAT, which always produces
21851      the auxiliary information.  */
21852   return (cu->language == language_ada);
21853 }
21854
21855 /* Return the auxiliary type of the die in question using its
21856    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21857    attribute is not present.  */
21858
21859 static struct type *
21860 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21861 {
21862   struct attribute *type_attr;
21863
21864   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21865   if (!type_attr)
21866     return NULL;
21867
21868   return lookup_die_type (die, type_attr, cu);
21869 }
21870
21871 /* If DIE has a descriptive_type attribute, then set the TYPE's
21872    descriptive type accordingly.  */
21873
21874 static void
21875 set_descriptive_type (struct type *type, struct die_info *die,
21876                       struct dwarf2_cu *cu)
21877 {
21878   struct type *descriptive_type = die_descriptive_type (die, cu);
21879
21880   if (descriptive_type)
21881     {
21882       ALLOCATE_GNAT_AUX_TYPE (type);
21883       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21884     }
21885 }
21886
21887 /* Return the containing type of the die in question using its
21888    DW_AT_containing_type attribute.  */
21889
21890 static struct type *
21891 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21892 {
21893   struct attribute *type_attr;
21894   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21895
21896   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21897   if (!type_attr)
21898     error (_("Dwarf Error: Problem turning containing type into gdb type "
21899              "[in module %s]"), objfile_name (objfile));
21900
21901   return lookup_die_type (die, type_attr, cu);
21902 }
21903
21904 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21905
21906 static struct type *
21907 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21908 {
21909   struct dwarf2_per_objfile *dwarf2_per_objfile
21910     = cu->per_cu->dwarf2_per_objfile;
21911   struct objfile *objfile = dwarf2_per_objfile->objfile;
21912   char *message, *saved;
21913
21914   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21915                         objfile_name (objfile),
21916                         sect_offset_str (cu->header.sect_off),
21917                         sect_offset_str (die->sect_off));
21918   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21919                                   message, strlen (message));
21920   xfree (message);
21921
21922   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21923 }
21924
21925 /* Look up the type of DIE in CU using its type attribute ATTR.
21926    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21927    DW_AT_containing_type.
21928    If there is no type substitute an error marker.  */
21929
21930 static struct type *
21931 lookup_die_type (struct die_info *die, const struct attribute *attr,
21932                  struct dwarf2_cu *cu)
21933 {
21934   struct dwarf2_per_objfile *dwarf2_per_objfile
21935     = cu->per_cu->dwarf2_per_objfile;
21936   struct objfile *objfile = dwarf2_per_objfile->objfile;
21937   struct type *this_type;
21938
21939   gdb_assert (attr->name == DW_AT_type
21940               || attr->name == DW_AT_GNAT_descriptive_type
21941               || attr->name == DW_AT_containing_type);
21942
21943   /* First see if we have it cached.  */
21944
21945   if (attr->form == DW_FORM_GNU_ref_alt)
21946     {
21947       struct dwarf2_per_cu_data *per_cu;
21948       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21949
21950       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21951                                                  dwarf2_per_objfile);
21952       this_type = get_die_type_at_offset (sect_off, per_cu);
21953     }
21954   else if (attr_form_is_ref (attr))
21955     {
21956       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21957
21958       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21959     }
21960   else if (attr->form == DW_FORM_ref_sig8)
21961     {
21962       ULONGEST signature = DW_SIGNATURE (attr);
21963
21964       return get_signatured_type (die, signature, cu);
21965     }
21966   else
21967     {
21968       complaint (&symfile_complaints,
21969                  _("Dwarf Error: Bad type attribute %s in DIE"
21970                    " at %s [in module %s]"),
21971                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21972                  objfile_name (objfile));
21973       return build_error_marker_type (cu, die);
21974     }
21975
21976   /* If not cached we need to read it in.  */
21977
21978   if (this_type == NULL)
21979     {
21980       struct die_info *type_die = NULL;
21981       struct dwarf2_cu *type_cu = cu;
21982
21983       if (attr_form_is_ref (attr))
21984         type_die = follow_die_ref (die, attr, &type_cu);
21985       if (type_die == NULL)
21986         return build_error_marker_type (cu, die);
21987       /* If we find the type now, it's probably because the type came
21988          from an inter-CU reference and the type's CU got expanded before
21989          ours.  */
21990       this_type = read_type_die (type_die, type_cu);
21991     }
21992
21993   /* If we still don't have a type use an error marker.  */
21994
21995   if (this_type == NULL)
21996     return build_error_marker_type (cu, die);
21997
21998   return this_type;
21999 }
22000
22001 /* Return the type in DIE, CU.
22002    Returns NULL for invalid types.
22003
22004    This first does a lookup in die_type_hash,
22005    and only reads the die in if necessary.
22006
22007    NOTE: This can be called when reading in partial or full symbols.  */
22008
22009 static struct type *
22010 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22011 {
22012   struct type *this_type;
22013
22014   this_type = get_die_type (die, cu);
22015   if (this_type)
22016     return this_type;
22017
22018   return read_type_die_1 (die, cu);
22019 }
22020
22021 /* Read the type in DIE, CU.
22022    Returns NULL for invalid types.  */
22023
22024 static struct type *
22025 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22026 {
22027   struct type *this_type = NULL;
22028
22029   switch (die->tag)
22030     {
22031     case DW_TAG_class_type:
22032     case DW_TAG_interface_type:
22033     case DW_TAG_structure_type:
22034     case DW_TAG_union_type:
22035       this_type = read_structure_type (die, cu);
22036       break;
22037     case DW_TAG_enumeration_type:
22038       this_type = read_enumeration_type (die, cu);
22039       break;
22040     case DW_TAG_subprogram:
22041     case DW_TAG_subroutine_type:
22042     case DW_TAG_inlined_subroutine:
22043       this_type = read_subroutine_type (die, cu);
22044       break;
22045     case DW_TAG_array_type:
22046       this_type = read_array_type (die, cu);
22047       break;
22048     case DW_TAG_set_type:
22049       this_type = read_set_type (die, cu);
22050       break;
22051     case DW_TAG_pointer_type:
22052       this_type = read_tag_pointer_type (die, cu);
22053       break;
22054     case DW_TAG_ptr_to_member_type:
22055       this_type = read_tag_ptr_to_member_type (die, cu);
22056       break;
22057     case DW_TAG_reference_type:
22058       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22059       break;
22060     case DW_TAG_rvalue_reference_type:
22061       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22062       break;
22063     case DW_TAG_const_type:
22064       this_type = read_tag_const_type (die, cu);
22065       break;
22066     case DW_TAG_volatile_type:
22067       this_type = read_tag_volatile_type (die, cu);
22068       break;
22069     case DW_TAG_restrict_type:
22070       this_type = read_tag_restrict_type (die, cu);
22071       break;
22072     case DW_TAG_string_type:
22073       this_type = read_tag_string_type (die, cu);
22074       break;
22075     case DW_TAG_typedef:
22076       this_type = read_typedef (die, cu);
22077       break;
22078     case DW_TAG_subrange_type:
22079       this_type = read_subrange_type (die, cu);
22080       break;
22081     case DW_TAG_base_type:
22082       this_type = read_base_type (die, cu);
22083       break;
22084     case DW_TAG_unspecified_type:
22085       this_type = read_unspecified_type (die, cu);
22086       break;
22087     case DW_TAG_namespace:
22088       this_type = read_namespace_type (die, cu);
22089       break;
22090     case DW_TAG_module:
22091       this_type = read_module_type (die, cu);
22092       break;
22093     case DW_TAG_atomic_type:
22094       this_type = read_tag_atomic_type (die, cu);
22095       break;
22096     default:
22097       complaint (&symfile_complaints,
22098                  _("unexpected tag in read_type_die: '%s'"),
22099                  dwarf_tag_name (die->tag));
22100       break;
22101     }
22102
22103   return this_type;
22104 }
22105
22106 /* See if we can figure out if the class lives in a namespace.  We do
22107    this by looking for a member function; its demangled name will
22108    contain namespace info, if there is any.
22109    Return the computed name or NULL.
22110    Space for the result is allocated on the objfile's obstack.
22111    This is the full-die version of guess_partial_die_structure_name.
22112    In this case we know DIE has no useful parent.  */
22113
22114 static char *
22115 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22116 {
22117   struct die_info *spec_die;
22118   struct dwarf2_cu *spec_cu;
22119   struct die_info *child;
22120   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22121
22122   spec_cu = cu;
22123   spec_die = die_specification (die, &spec_cu);
22124   if (spec_die != NULL)
22125     {
22126       die = spec_die;
22127       cu = spec_cu;
22128     }
22129
22130   for (child = die->child;
22131        child != NULL;
22132        child = child->sibling)
22133     {
22134       if (child->tag == DW_TAG_subprogram)
22135         {
22136           const char *linkage_name = dw2_linkage_name (child, cu);
22137
22138           if (linkage_name != NULL)
22139             {
22140               char *actual_name
22141                 = language_class_name_from_physname (cu->language_defn,
22142                                                      linkage_name);
22143               char *name = NULL;
22144
22145               if (actual_name != NULL)
22146                 {
22147                   const char *die_name = dwarf2_name (die, cu);
22148
22149                   if (die_name != NULL
22150                       && strcmp (die_name, actual_name) != 0)
22151                     {
22152                       /* Strip off the class name from the full name.
22153                          We want the prefix.  */
22154                       int die_name_len = strlen (die_name);
22155                       int actual_name_len = strlen (actual_name);
22156
22157                       /* Test for '::' as a sanity check.  */
22158                       if (actual_name_len > die_name_len + 2
22159                           && actual_name[actual_name_len
22160                                          - die_name_len - 1] == ':')
22161                         name = (char *) obstack_copy0 (
22162                           &objfile->per_bfd->storage_obstack,
22163                           actual_name, actual_name_len - die_name_len - 2);
22164                     }
22165                 }
22166               xfree (actual_name);
22167               return name;
22168             }
22169         }
22170     }
22171
22172   return NULL;
22173 }
22174
22175 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22176    prefix part in such case.  See
22177    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22178
22179 static const char *
22180 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22181 {
22182   struct attribute *attr;
22183   const char *base;
22184
22185   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22186       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22187     return NULL;
22188
22189   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22190     return NULL;
22191
22192   attr = dw2_linkage_name_attr (die, cu);
22193   if (attr == NULL || DW_STRING (attr) == NULL)
22194     return NULL;
22195
22196   /* dwarf2_name had to be already called.  */
22197   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22198
22199   /* Strip the base name, keep any leading namespaces/classes.  */
22200   base = strrchr (DW_STRING (attr), ':');
22201   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22202     return "";
22203
22204   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22205   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22206                                  DW_STRING (attr),
22207                                  &base[-1] - DW_STRING (attr));
22208 }
22209
22210 /* Return the name of the namespace/class that DIE is defined within,
22211    or "" if we can't tell.  The caller should not xfree the result.
22212
22213    For example, if we're within the method foo() in the following
22214    code:
22215
22216    namespace N {
22217      class C {
22218        void foo () {
22219        }
22220      };
22221    }
22222
22223    then determine_prefix on foo's die will return "N::C".  */
22224
22225 static const char *
22226 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22227 {
22228   struct dwarf2_per_objfile *dwarf2_per_objfile
22229     = cu->per_cu->dwarf2_per_objfile;
22230   struct die_info *parent, *spec_die;
22231   struct dwarf2_cu *spec_cu;
22232   struct type *parent_type;
22233   const char *retval;
22234
22235   if (cu->language != language_cplus
22236       && cu->language != language_fortran && cu->language != language_d
22237       && cu->language != language_rust)
22238     return "";
22239
22240   retval = anonymous_struct_prefix (die, cu);
22241   if (retval)
22242     return retval;
22243
22244   /* We have to be careful in the presence of DW_AT_specification.
22245      For example, with GCC 3.4, given the code
22246
22247      namespace N {
22248        void foo() {
22249          // Definition of N::foo.
22250        }
22251      }
22252
22253      then we'll have a tree of DIEs like this:
22254
22255      1: DW_TAG_compile_unit
22256        2: DW_TAG_namespace        // N
22257          3: DW_TAG_subprogram     // declaration of N::foo
22258        4: DW_TAG_subprogram       // definition of N::foo
22259             DW_AT_specification   // refers to die #3
22260
22261      Thus, when processing die #4, we have to pretend that we're in
22262      the context of its DW_AT_specification, namely the contex of die
22263      #3.  */
22264   spec_cu = cu;
22265   spec_die = die_specification (die, &spec_cu);
22266   if (spec_die == NULL)
22267     parent = die->parent;
22268   else
22269     {
22270       parent = spec_die->parent;
22271       cu = spec_cu;
22272     }
22273
22274   if (parent == NULL)
22275     return "";
22276   else if (parent->building_fullname)
22277     {
22278       const char *name;
22279       const char *parent_name;
22280
22281       /* It has been seen on RealView 2.2 built binaries,
22282          DW_TAG_template_type_param types actually _defined_ as
22283          children of the parent class:
22284
22285          enum E {};
22286          template class <class Enum> Class{};
22287          Class<enum E> class_e;
22288
22289          1: DW_TAG_class_type (Class)
22290            2: DW_TAG_enumeration_type (E)
22291              3: DW_TAG_enumerator (enum1:0)
22292              3: DW_TAG_enumerator (enum2:1)
22293              ...
22294            2: DW_TAG_template_type_param
22295               DW_AT_type  DW_FORM_ref_udata (E)
22296
22297          Besides being broken debug info, it can put GDB into an
22298          infinite loop.  Consider:
22299
22300          When we're building the full name for Class<E>, we'll start
22301          at Class, and go look over its template type parameters,
22302          finding E.  We'll then try to build the full name of E, and
22303          reach here.  We're now trying to build the full name of E,
22304          and look over the parent DIE for containing scope.  In the
22305          broken case, if we followed the parent DIE of E, we'd again
22306          find Class, and once again go look at its template type
22307          arguments, etc., etc.  Simply don't consider such parent die
22308          as source-level parent of this die (it can't be, the language
22309          doesn't allow it), and break the loop here.  */
22310       name = dwarf2_name (die, cu);
22311       parent_name = dwarf2_name (parent, cu);
22312       complaint (&symfile_complaints,
22313                  _("template param type '%s' defined within parent '%s'"),
22314                  name ? name : "<unknown>",
22315                  parent_name ? parent_name : "<unknown>");
22316       return "";
22317     }
22318   else
22319     switch (parent->tag)
22320       {
22321       case DW_TAG_namespace:
22322         parent_type = read_type_die (parent, cu);
22323         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22324            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22325            Work around this problem here.  */
22326         if (cu->language == language_cplus
22327             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22328           return "";
22329         /* We give a name to even anonymous namespaces.  */
22330         return TYPE_TAG_NAME (parent_type);
22331       case DW_TAG_class_type:
22332       case DW_TAG_interface_type:
22333       case DW_TAG_structure_type:
22334       case DW_TAG_union_type:
22335       case DW_TAG_module:
22336         parent_type = read_type_die (parent, cu);
22337         if (TYPE_TAG_NAME (parent_type) != NULL)
22338           return TYPE_TAG_NAME (parent_type);
22339         else
22340           /* An anonymous structure is only allowed non-static data
22341              members; no typedefs, no member functions, et cetera.
22342              So it does not need a prefix.  */
22343           return "";
22344       case DW_TAG_compile_unit:
22345       case DW_TAG_partial_unit:
22346         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22347         if (cu->language == language_cplus
22348             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22349             && die->child != NULL
22350             && (die->tag == DW_TAG_class_type
22351                 || die->tag == DW_TAG_structure_type
22352                 || die->tag == DW_TAG_union_type))
22353           {
22354             char *name = guess_full_die_structure_name (die, cu);
22355             if (name != NULL)
22356               return name;
22357           }
22358         return "";
22359       case DW_TAG_enumeration_type:
22360         parent_type = read_type_die (parent, cu);
22361         if (TYPE_DECLARED_CLASS (parent_type))
22362           {
22363             if (TYPE_TAG_NAME (parent_type) != NULL)
22364               return TYPE_TAG_NAME (parent_type);
22365             return "";
22366           }
22367         /* Fall through.  */
22368       default:
22369         return determine_prefix (parent, cu);
22370       }
22371 }
22372
22373 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22374    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22375    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22376    an obconcat, otherwise allocate storage for the result.  The CU argument is
22377    used to determine the language and hence, the appropriate separator.  */
22378
22379 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22380
22381 static char *
22382 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22383                  int physname, struct dwarf2_cu *cu)
22384 {
22385   const char *lead = "";
22386   const char *sep;
22387
22388   if (suffix == NULL || suffix[0] == '\0'
22389       || prefix == NULL || prefix[0] == '\0')
22390     sep = "";
22391   else if (cu->language == language_d)
22392     {
22393       /* For D, the 'main' function could be defined in any module, but it
22394          should never be prefixed.  */
22395       if (strcmp (suffix, "D main") == 0)
22396         {
22397           prefix = "";
22398           sep = "";
22399         }
22400       else
22401         sep = ".";
22402     }
22403   else if (cu->language == language_fortran && physname)
22404     {
22405       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22406          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22407
22408       lead = "__";
22409       sep = "_MOD_";
22410     }
22411   else
22412     sep = "::";
22413
22414   if (prefix == NULL)
22415     prefix = "";
22416   if (suffix == NULL)
22417     suffix = "";
22418
22419   if (obs == NULL)
22420     {
22421       char *retval
22422         = ((char *)
22423            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22424
22425       strcpy (retval, lead);
22426       strcat (retval, prefix);
22427       strcat (retval, sep);
22428       strcat (retval, suffix);
22429       return retval;
22430     }
22431   else
22432     {
22433       /* We have an obstack.  */
22434       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22435     }
22436 }
22437
22438 /* Return sibling of die, NULL if no sibling.  */
22439
22440 static struct die_info *
22441 sibling_die (struct die_info *die)
22442 {
22443   return die->sibling;
22444 }
22445
22446 /* Get name of a die, return NULL if not found.  */
22447
22448 static const char *
22449 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22450                           struct obstack *obstack)
22451 {
22452   if (name && cu->language == language_cplus)
22453     {
22454       std::string canon_name = cp_canonicalize_string (name);
22455
22456       if (!canon_name.empty ())
22457         {
22458           if (canon_name != name)
22459             name = (const char *) obstack_copy0 (obstack,
22460                                                  canon_name.c_str (),
22461                                                  canon_name.length ());
22462         }
22463     }
22464
22465   return name;
22466 }
22467
22468 /* Get name of a die, return NULL if not found.
22469    Anonymous namespaces are converted to their magic string.  */
22470
22471 static const char *
22472 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22473 {
22474   struct attribute *attr;
22475   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22476
22477   attr = dwarf2_attr (die, DW_AT_name, cu);
22478   if ((!attr || !DW_STRING (attr))
22479       && die->tag != DW_TAG_namespace
22480       && die->tag != DW_TAG_class_type
22481       && die->tag != DW_TAG_interface_type
22482       && die->tag != DW_TAG_structure_type
22483       && die->tag != DW_TAG_union_type)
22484     return NULL;
22485
22486   switch (die->tag)
22487     {
22488     case DW_TAG_compile_unit:
22489     case DW_TAG_partial_unit:
22490       /* Compilation units have a DW_AT_name that is a filename, not
22491          a source language identifier.  */
22492     case DW_TAG_enumeration_type:
22493     case DW_TAG_enumerator:
22494       /* These tags always have simple identifiers already; no need
22495          to canonicalize them.  */
22496       return DW_STRING (attr);
22497
22498     case DW_TAG_namespace:
22499       if (attr != NULL && DW_STRING (attr) != NULL)
22500         return DW_STRING (attr);
22501       return CP_ANONYMOUS_NAMESPACE_STR;
22502
22503     case DW_TAG_class_type:
22504     case DW_TAG_interface_type:
22505     case DW_TAG_structure_type:
22506     case DW_TAG_union_type:
22507       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22508          structures or unions.  These were of the form "._%d" in GCC 4.1,
22509          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22510          and GCC 4.4.  We work around this problem by ignoring these.  */
22511       if (attr && DW_STRING (attr)
22512           && (startswith (DW_STRING (attr), "._")
22513               || startswith (DW_STRING (attr), "<anonymous")))
22514         return NULL;
22515
22516       /* GCC might emit a nameless typedef that has a linkage name.  See
22517          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22518       if (!attr || DW_STRING (attr) == NULL)
22519         {
22520           char *demangled = NULL;
22521
22522           attr = dw2_linkage_name_attr (die, cu);
22523           if (attr == NULL || DW_STRING (attr) == NULL)
22524             return NULL;
22525
22526           /* Avoid demangling DW_STRING (attr) the second time on a second
22527              call for the same DIE.  */
22528           if (!DW_STRING_IS_CANONICAL (attr))
22529             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22530
22531           if (demangled)
22532             {
22533               const char *base;
22534
22535               /* FIXME: we already did this for the partial symbol... */
22536               DW_STRING (attr)
22537                 = ((const char *)
22538                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22539                                   demangled, strlen (demangled)));
22540               DW_STRING_IS_CANONICAL (attr) = 1;
22541               xfree (demangled);
22542
22543               /* Strip any leading namespaces/classes, keep only the base name.
22544                  DW_AT_name for named DIEs does not contain the prefixes.  */
22545               base = strrchr (DW_STRING (attr), ':');
22546               if (base && base > DW_STRING (attr) && base[-1] == ':')
22547                 return &base[1];
22548               else
22549                 return DW_STRING (attr);
22550             }
22551         }
22552       break;
22553
22554     default:
22555       break;
22556     }
22557
22558   if (!DW_STRING_IS_CANONICAL (attr))
22559     {
22560       DW_STRING (attr)
22561         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22562                                     &objfile->per_bfd->storage_obstack);
22563       DW_STRING_IS_CANONICAL (attr) = 1;
22564     }
22565   return DW_STRING (attr);
22566 }
22567
22568 /* Return the die that this die in an extension of, or NULL if there
22569    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22570    containing the return value on output.  */
22571
22572 static struct die_info *
22573 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22574 {
22575   struct attribute *attr;
22576
22577   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22578   if (attr == NULL)
22579     return NULL;
22580
22581   return follow_die_ref (die, attr, ext_cu);
22582 }
22583
22584 /* Convert a DIE tag into its string name.  */
22585
22586 static const char *
22587 dwarf_tag_name (unsigned tag)
22588 {
22589   const char *name = get_DW_TAG_name (tag);
22590
22591   if (name == NULL)
22592     return "DW_TAG_<unknown>";
22593
22594   return name;
22595 }
22596
22597 /* Convert a DWARF attribute code into its string name.  */
22598
22599 static const char *
22600 dwarf_attr_name (unsigned attr)
22601 {
22602   const char *name;
22603
22604 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22605   if (attr == DW_AT_MIPS_fde)
22606     return "DW_AT_MIPS_fde";
22607 #else
22608   if (attr == DW_AT_HP_block_index)
22609     return "DW_AT_HP_block_index";
22610 #endif
22611
22612   name = get_DW_AT_name (attr);
22613
22614   if (name == NULL)
22615     return "DW_AT_<unknown>";
22616
22617   return name;
22618 }
22619
22620 /* Convert a DWARF value form code into its string name.  */
22621
22622 static const char *
22623 dwarf_form_name (unsigned form)
22624 {
22625   const char *name = get_DW_FORM_name (form);
22626
22627   if (name == NULL)
22628     return "DW_FORM_<unknown>";
22629
22630   return name;
22631 }
22632
22633 static const char *
22634 dwarf_bool_name (unsigned mybool)
22635 {
22636   if (mybool)
22637     return "TRUE";
22638   else
22639     return "FALSE";
22640 }
22641
22642 /* Convert a DWARF type code into its string name.  */
22643
22644 static const char *
22645 dwarf_type_encoding_name (unsigned enc)
22646 {
22647   const char *name = get_DW_ATE_name (enc);
22648
22649   if (name == NULL)
22650     return "DW_ATE_<unknown>";
22651
22652   return name;
22653 }
22654
22655 static void
22656 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22657 {
22658   unsigned int i;
22659
22660   print_spaces (indent, f);
22661   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22662                       dwarf_tag_name (die->tag), die->abbrev,
22663                       sect_offset_str (die->sect_off));
22664
22665   if (die->parent != NULL)
22666     {
22667       print_spaces (indent, f);
22668       fprintf_unfiltered (f, "  parent at offset: %s\n",
22669                           sect_offset_str (die->parent->sect_off));
22670     }
22671
22672   print_spaces (indent, f);
22673   fprintf_unfiltered (f, "  has children: %s\n",
22674            dwarf_bool_name (die->child != NULL));
22675
22676   print_spaces (indent, f);
22677   fprintf_unfiltered (f, "  attributes:\n");
22678
22679   for (i = 0; i < die->num_attrs; ++i)
22680     {
22681       print_spaces (indent, f);
22682       fprintf_unfiltered (f, "    %s (%s) ",
22683                dwarf_attr_name (die->attrs[i].name),
22684                dwarf_form_name (die->attrs[i].form));
22685
22686       switch (die->attrs[i].form)
22687         {
22688         case DW_FORM_addr:
22689         case DW_FORM_GNU_addr_index:
22690           fprintf_unfiltered (f, "address: ");
22691           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22692           break;
22693         case DW_FORM_block2:
22694         case DW_FORM_block4:
22695         case DW_FORM_block:
22696         case DW_FORM_block1:
22697           fprintf_unfiltered (f, "block: size %s",
22698                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22699           break;
22700         case DW_FORM_exprloc:
22701           fprintf_unfiltered (f, "expression: size %s",
22702                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22703           break;
22704         case DW_FORM_data16:
22705           fprintf_unfiltered (f, "constant of 16 bytes");
22706           break;
22707         case DW_FORM_ref_addr:
22708           fprintf_unfiltered (f, "ref address: ");
22709           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22710           break;
22711         case DW_FORM_GNU_ref_alt:
22712           fprintf_unfiltered (f, "alt ref address: ");
22713           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22714           break;
22715         case DW_FORM_ref1:
22716         case DW_FORM_ref2:
22717         case DW_FORM_ref4:
22718         case DW_FORM_ref8:
22719         case DW_FORM_ref_udata:
22720           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22721                               (long) (DW_UNSND (&die->attrs[i])));
22722           break;
22723         case DW_FORM_data1:
22724         case DW_FORM_data2:
22725         case DW_FORM_data4:
22726         case DW_FORM_data8:
22727         case DW_FORM_udata:
22728         case DW_FORM_sdata:
22729           fprintf_unfiltered (f, "constant: %s",
22730                               pulongest (DW_UNSND (&die->attrs[i])));
22731           break;
22732         case DW_FORM_sec_offset:
22733           fprintf_unfiltered (f, "section offset: %s",
22734                               pulongest (DW_UNSND (&die->attrs[i])));
22735           break;
22736         case DW_FORM_ref_sig8:
22737           fprintf_unfiltered (f, "signature: %s",
22738                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22739           break;
22740         case DW_FORM_string:
22741         case DW_FORM_strp:
22742         case DW_FORM_line_strp:
22743         case DW_FORM_GNU_str_index:
22744         case DW_FORM_GNU_strp_alt:
22745           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22746                    DW_STRING (&die->attrs[i])
22747                    ? DW_STRING (&die->attrs[i]) : "",
22748                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22749           break;
22750         case DW_FORM_flag:
22751           if (DW_UNSND (&die->attrs[i]))
22752             fprintf_unfiltered (f, "flag: TRUE");
22753           else
22754             fprintf_unfiltered (f, "flag: FALSE");
22755           break;
22756         case DW_FORM_flag_present:
22757           fprintf_unfiltered (f, "flag: TRUE");
22758           break;
22759         case DW_FORM_indirect:
22760           /* The reader will have reduced the indirect form to
22761              the "base form" so this form should not occur.  */
22762           fprintf_unfiltered (f, 
22763                               "unexpected attribute form: DW_FORM_indirect");
22764           break;
22765         case DW_FORM_implicit_const:
22766           fprintf_unfiltered (f, "constant: %s",
22767                               plongest (DW_SND (&die->attrs[i])));
22768           break;
22769         default:
22770           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22771                    die->attrs[i].form);
22772           break;
22773         }
22774       fprintf_unfiltered (f, "\n");
22775     }
22776 }
22777
22778 static void
22779 dump_die_for_error (struct die_info *die)
22780 {
22781   dump_die_shallow (gdb_stderr, 0, die);
22782 }
22783
22784 static void
22785 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22786 {
22787   int indent = level * 4;
22788
22789   gdb_assert (die != NULL);
22790
22791   if (level >= max_level)
22792     return;
22793
22794   dump_die_shallow (f, indent, die);
22795
22796   if (die->child != NULL)
22797     {
22798       print_spaces (indent, f);
22799       fprintf_unfiltered (f, "  Children:");
22800       if (level + 1 < max_level)
22801         {
22802           fprintf_unfiltered (f, "\n");
22803           dump_die_1 (f, level + 1, max_level, die->child);
22804         }
22805       else
22806         {
22807           fprintf_unfiltered (f,
22808                               " [not printed, max nesting level reached]\n");
22809         }
22810     }
22811
22812   if (die->sibling != NULL && level > 0)
22813     {
22814       dump_die_1 (f, level, max_level, die->sibling);
22815     }
22816 }
22817
22818 /* This is called from the pdie macro in gdbinit.in.
22819    It's not static so gcc will keep a copy callable from gdb.  */
22820
22821 void
22822 dump_die (struct die_info *die, int max_level)
22823 {
22824   dump_die_1 (gdb_stdlog, 0, max_level, die);
22825 }
22826
22827 static void
22828 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22829 {
22830   void **slot;
22831
22832   slot = htab_find_slot_with_hash (cu->die_hash, die,
22833                                    to_underlying (die->sect_off),
22834                                    INSERT);
22835
22836   *slot = die;
22837 }
22838
22839 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22840    required kind.  */
22841
22842 static sect_offset
22843 dwarf2_get_ref_die_offset (const struct attribute *attr)
22844 {
22845   if (attr_form_is_ref (attr))
22846     return (sect_offset) DW_UNSND (attr);
22847
22848   complaint (&symfile_complaints,
22849              _("unsupported die ref attribute form: '%s'"),
22850              dwarf_form_name (attr->form));
22851   return {};
22852 }
22853
22854 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22855  * the value held by the attribute is not constant.  */
22856
22857 static LONGEST
22858 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22859 {
22860   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22861     return DW_SND (attr);
22862   else if (attr->form == DW_FORM_udata
22863            || attr->form == DW_FORM_data1
22864            || attr->form == DW_FORM_data2
22865            || attr->form == DW_FORM_data4
22866            || attr->form == DW_FORM_data8)
22867     return DW_UNSND (attr);
22868   else
22869     {
22870       /* For DW_FORM_data16 see attr_form_is_constant.  */
22871       complaint (&symfile_complaints,
22872                  _("Attribute value is not a constant (%s)"),
22873                  dwarf_form_name (attr->form));
22874       return default_value;
22875     }
22876 }
22877
22878 /* Follow reference or signature attribute ATTR of SRC_DIE.
22879    On entry *REF_CU is the CU of SRC_DIE.
22880    On exit *REF_CU is the CU of the result.  */
22881
22882 static struct die_info *
22883 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22884                        struct dwarf2_cu **ref_cu)
22885 {
22886   struct die_info *die;
22887
22888   if (attr_form_is_ref (attr))
22889     die = follow_die_ref (src_die, attr, ref_cu);
22890   else if (attr->form == DW_FORM_ref_sig8)
22891     die = follow_die_sig (src_die, attr, ref_cu);
22892   else
22893     {
22894       dump_die_for_error (src_die);
22895       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22896              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22897     }
22898
22899   return die;
22900 }
22901
22902 /* Follow reference OFFSET.
22903    On entry *REF_CU is the CU of the source die referencing OFFSET.
22904    On exit *REF_CU is the CU of the result.
22905    Returns NULL if OFFSET is invalid.  */
22906
22907 static struct die_info *
22908 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22909                    struct dwarf2_cu **ref_cu)
22910 {
22911   struct die_info temp_die;
22912   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22913   struct dwarf2_per_objfile *dwarf2_per_objfile
22914     = cu->per_cu->dwarf2_per_objfile;
22915   struct objfile *objfile = dwarf2_per_objfile->objfile;
22916
22917   gdb_assert (cu->per_cu != NULL);
22918
22919   target_cu = cu;
22920
22921   if (cu->per_cu->is_debug_types)
22922     {
22923       /* .debug_types CUs cannot reference anything outside their CU.
22924          If they need to, they have to reference a signatured type via
22925          DW_FORM_ref_sig8.  */
22926       if (!offset_in_cu_p (&cu->header, sect_off))
22927         return NULL;
22928     }
22929   else if (offset_in_dwz != cu->per_cu->is_dwz
22930            || !offset_in_cu_p (&cu->header, sect_off))
22931     {
22932       struct dwarf2_per_cu_data *per_cu;
22933
22934       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22935                                                  dwarf2_per_objfile);
22936
22937       /* If necessary, add it to the queue and load its DIEs.  */
22938       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22939         load_full_comp_unit (per_cu, cu->language);
22940
22941       target_cu = per_cu->cu;
22942     }
22943   else if (cu->dies == NULL)
22944     {
22945       /* We're loading full DIEs during partial symbol reading.  */
22946       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22947       load_full_comp_unit (cu->per_cu, language_minimal);
22948     }
22949
22950   *ref_cu = target_cu;
22951   temp_die.sect_off = sect_off;
22952   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22953                                                   &temp_die,
22954                                                   to_underlying (sect_off));
22955 }
22956
22957 /* Follow reference attribute ATTR of SRC_DIE.
22958    On entry *REF_CU is the CU of SRC_DIE.
22959    On exit *REF_CU is the CU of the result.  */
22960
22961 static struct die_info *
22962 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22963                 struct dwarf2_cu **ref_cu)
22964 {
22965   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22966   struct dwarf2_cu *cu = *ref_cu;
22967   struct die_info *die;
22968
22969   die = follow_die_offset (sect_off,
22970                            (attr->form == DW_FORM_GNU_ref_alt
22971                             || cu->per_cu->is_dwz),
22972                            ref_cu);
22973   if (!die)
22974     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22975            "at %s [in module %s]"),
22976            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22977            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22978
22979   return die;
22980 }
22981
22982 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22983    Returned value is intended for DW_OP_call*.  Returned
22984    dwarf2_locexpr_baton->data has lifetime of
22985    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22986
22987 struct dwarf2_locexpr_baton
22988 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22989                                struct dwarf2_per_cu_data *per_cu,
22990                                CORE_ADDR (*get_frame_pc) (void *baton),
22991                                void *baton)
22992 {
22993   struct dwarf2_cu *cu;
22994   struct die_info *die;
22995   struct attribute *attr;
22996   struct dwarf2_locexpr_baton retval;
22997   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22998   struct dwarf2_per_objfile *dwarf2_per_objfile
22999     = get_dwarf2_per_objfile (objfile);
23000
23001   if (per_cu->cu == NULL)
23002     load_cu (per_cu);
23003   cu = per_cu->cu;
23004   if (cu == NULL)
23005     {
23006       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23007          Instead just throw an error, not much else we can do.  */
23008       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23009              sect_offset_str (sect_off), objfile_name (objfile));
23010     }
23011
23012   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23013   if (!die)
23014     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23015            sect_offset_str (sect_off), objfile_name (objfile));
23016
23017   attr = dwarf2_attr (die, DW_AT_location, cu);
23018   if (!attr)
23019     {
23020       /* DWARF: "If there is no such attribute, then there is no effect.".
23021          DATA is ignored if SIZE is 0.  */
23022
23023       retval.data = NULL;
23024       retval.size = 0;
23025     }
23026   else if (attr_form_is_section_offset (attr))
23027     {
23028       struct dwarf2_loclist_baton loclist_baton;
23029       CORE_ADDR pc = (*get_frame_pc) (baton);
23030       size_t size;
23031
23032       fill_in_loclist_baton (cu, &loclist_baton, attr);
23033
23034       retval.data = dwarf2_find_location_expression (&loclist_baton,
23035                                                      &size, pc);
23036       retval.size = size;
23037     }
23038   else
23039     {
23040       if (!attr_form_is_block (attr))
23041         error (_("Dwarf Error: DIE at %s referenced in module %s "
23042                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23043                sect_offset_str (sect_off), objfile_name (objfile));
23044
23045       retval.data = DW_BLOCK (attr)->data;
23046       retval.size = DW_BLOCK (attr)->size;
23047     }
23048   retval.per_cu = cu->per_cu;
23049
23050   age_cached_comp_units (dwarf2_per_objfile);
23051
23052   return retval;
23053 }
23054
23055 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23056    offset.  */
23057
23058 struct dwarf2_locexpr_baton
23059 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23060                              struct dwarf2_per_cu_data *per_cu,
23061                              CORE_ADDR (*get_frame_pc) (void *baton),
23062                              void *baton)
23063 {
23064   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23065
23066   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23067 }
23068
23069 /* Write a constant of a given type as target-ordered bytes into
23070    OBSTACK.  */
23071
23072 static const gdb_byte *
23073 write_constant_as_bytes (struct obstack *obstack,
23074                          enum bfd_endian byte_order,
23075                          struct type *type,
23076                          ULONGEST value,
23077                          LONGEST *len)
23078 {
23079   gdb_byte *result;
23080
23081   *len = TYPE_LENGTH (type);
23082   result = (gdb_byte *) obstack_alloc (obstack, *len);
23083   store_unsigned_integer (result, *len, byte_order, value);
23084
23085   return result;
23086 }
23087
23088 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23089    pointer to the constant bytes and set LEN to the length of the
23090    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23091    does not have a DW_AT_const_value, return NULL.  */
23092
23093 const gdb_byte *
23094 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23095                              struct dwarf2_per_cu_data *per_cu,
23096                              struct obstack *obstack,
23097                              LONGEST *len)
23098 {
23099   struct dwarf2_cu *cu;
23100   struct die_info *die;
23101   struct attribute *attr;
23102   const gdb_byte *result = NULL;
23103   struct type *type;
23104   LONGEST value;
23105   enum bfd_endian byte_order;
23106   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23107
23108   if (per_cu->cu == NULL)
23109     load_cu (per_cu);
23110   cu = per_cu->cu;
23111   if (cu == NULL)
23112     {
23113       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23114          Instead just throw an error, not much else we can do.  */
23115       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23116              sect_offset_str (sect_off), objfile_name (objfile));
23117     }
23118
23119   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23120   if (!die)
23121     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23122            sect_offset_str (sect_off), objfile_name (objfile));
23123
23124   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23125   if (attr == NULL)
23126     return NULL;
23127
23128   byte_order = (bfd_big_endian (objfile->obfd)
23129                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23130
23131   switch (attr->form)
23132     {
23133     case DW_FORM_addr:
23134     case DW_FORM_GNU_addr_index:
23135       {
23136         gdb_byte *tem;
23137
23138         *len = cu->header.addr_size;
23139         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23140         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23141         result = tem;
23142       }
23143       break;
23144     case DW_FORM_string:
23145     case DW_FORM_strp:
23146     case DW_FORM_GNU_str_index:
23147     case DW_FORM_GNU_strp_alt:
23148       /* DW_STRING is already allocated on the objfile obstack, point
23149          directly to it.  */
23150       result = (const gdb_byte *) DW_STRING (attr);
23151       *len = strlen (DW_STRING (attr));
23152       break;
23153     case DW_FORM_block1:
23154     case DW_FORM_block2:
23155     case DW_FORM_block4:
23156     case DW_FORM_block:
23157     case DW_FORM_exprloc:
23158     case DW_FORM_data16:
23159       result = DW_BLOCK (attr)->data;
23160       *len = DW_BLOCK (attr)->size;
23161       break;
23162
23163       /* The DW_AT_const_value attributes are supposed to carry the
23164          symbol's value "represented as it would be on the target
23165          architecture."  By the time we get here, it's already been
23166          converted to host endianness, so we just need to sign- or
23167          zero-extend it as appropriate.  */
23168     case DW_FORM_data1:
23169       type = die_type (die, cu);
23170       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23171       if (result == NULL)
23172         result = write_constant_as_bytes (obstack, byte_order,
23173                                           type, value, len);
23174       break;
23175     case DW_FORM_data2:
23176       type = die_type (die, cu);
23177       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23178       if (result == NULL)
23179         result = write_constant_as_bytes (obstack, byte_order,
23180                                           type, value, len);
23181       break;
23182     case DW_FORM_data4:
23183       type = die_type (die, cu);
23184       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23185       if (result == NULL)
23186         result = write_constant_as_bytes (obstack, byte_order,
23187                                           type, value, len);
23188       break;
23189     case DW_FORM_data8:
23190       type = die_type (die, cu);
23191       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23192       if (result == NULL)
23193         result = write_constant_as_bytes (obstack, byte_order,
23194                                           type, value, len);
23195       break;
23196
23197     case DW_FORM_sdata:
23198     case DW_FORM_implicit_const:
23199       type = die_type (die, cu);
23200       result = write_constant_as_bytes (obstack, byte_order,
23201                                         type, DW_SND (attr), len);
23202       break;
23203
23204     case DW_FORM_udata:
23205       type = die_type (die, cu);
23206       result = write_constant_as_bytes (obstack, byte_order,
23207                                         type, DW_UNSND (attr), len);
23208       break;
23209
23210     default:
23211       complaint (&symfile_complaints,
23212                  _("unsupported const value attribute form: '%s'"),
23213                  dwarf_form_name (attr->form));
23214       break;
23215     }
23216
23217   return result;
23218 }
23219
23220 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23221    valid type for this die is found.  */
23222
23223 struct type *
23224 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23225                                 struct dwarf2_per_cu_data *per_cu)
23226 {
23227   struct dwarf2_cu *cu;
23228   struct die_info *die;
23229
23230   if (per_cu->cu == NULL)
23231     load_cu (per_cu);
23232   cu = per_cu->cu;
23233   if (!cu)
23234     return NULL;
23235
23236   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23237   if (!die)
23238     return NULL;
23239
23240   return die_type (die, cu);
23241 }
23242
23243 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23244    PER_CU.  */
23245
23246 struct type *
23247 dwarf2_get_die_type (cu_offset die_offset,
23248                      struct dwarf2_per_cu_data *per_cu)
23249 {
23250   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23251   return get_die_type_at_offset (die_offset_sect, per_cu);
23252 }
23253
23254 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23255    On entry *REF_CU is the CU of SRC_DIE.
23256    On exit *REF_CU is the CU of the result.
23257    Returns NULL if the referenced DIE isn't found.  */
23258
23259 static struct die_info *
23260 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23261                   struct dwarf2_cu **ref_cu)
23262 {
23263   struct die_info temp_die;
23264   struct dwarf2_cu *sig_cu;
23265   struct die_info *die;
23266
23267   /* While it might be nice to assert sig_type->type == NULL here,
23268      we can get here for DW_AT_imported_declaration where we need
23269      the DIE not the type.  */
23270
23271   /* If necessary, add it to the queue and load its DIEs.  */
23272
23273   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23274     read_signatured_type (sig_type);
23275
23276   sig_cu = sig_type->per_cu.cu;
23277   gdb_assert (sig_cu != NULL);
23278   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23279   temp_die.sect_off = sig_type->type_offset_in_section;
23280   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23281                                                  to_underlying (temp_die.sect_off));
23282   if (die)
23283     {
23284       struct dwarf2_per_objfile *dwarf2_per_objfile
23285         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23286
23287       /* For .gdb_index version 7 keep track of included TUs.
23288          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23289       if (dwarf2_per_objfile->index_table != NULL
23290           && dwarf2_per_objfile->index_table->version <= 7)
23291         {
23292           VEC_safe_push (dwarf2_per_cu_ptr,
23293                          (*ref_cu)->per_cu->imported_symtabs,
23294                          sig_cu->per_cu);
23295         }
23296
23297       *ref_cu = sig_cu;
23298       return die;
23299     }
23300
23301   return NULL;
23302 }
23303
23304 /* Follow signatured type referenced by ATTR in SRC_DIE.
23305    On entry *REF_CU is the CU of SRC_DIE.
23306    On exit *REF_CU is the CU of the result.
23307    The result is the DIE of the type.
23308    If the referenced type cannot be found an error is thrown.  */
23309
23310 static struct die_info *
23311 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23312                 struct dwarf2_cu **ref_cu)
23313 {
23314   ULONGEST signature = DW_SIGNATURE (attr);
23315   struct signatured_type *sig_type;
23316   struct die_info *die;
23317
23318   gdb_assert (attr->form == DW_FORM_ref_sig8);
23319
23320   sig_type = lookup_signatured_type (*ref_cu, signature);
23321   /* sig_type will be NULL if the signatured type is missing from
23322      the debug info.  */
23323   if (sig_type == NULL)
23324     {
23325       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23326                " from DIE at %s [in module %s]"),
23327              hex_string (signature), sect_offset_str (src_die->sect_off),
23328              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23329     }
23330
23331   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23332   if (die == NULL)
23333     {
23334       dump_die_for_error (src_die);
23335       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23336                " from DIE at %s [in module %s]"),
23337              hex_string (signature), sect_offset_str (src_die->sect_off),
23338              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23339     }
23340
23341   return die;
23342 }
23343
23344 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23345    reading in and processing the type unit if necessary.  */
23346
23347 static struct type *
23348 get_signatured_type (struct die_info *die, ULONGEST signature,
23349                      struct dwarf2_cu *cu)
23350 {
23351   struct dwarf2_per_objfile *dwarf2_per_objfile
23352     = cu->per_cu->dwarf2_per_objfile;
23353   struct signatured_type *sig_type;
23354   struct dwarf2_cu *type_cu;
23355   struct die_info *type_die;
23356   struct type *type;
23357
23358   sig_type = lookup_signatured_type (cu, signature);
23359   /* sig_type will be NULL if the signatured type is missing from
23360      the debug info.  */
23361   if (sig_type == NULL)
23362     {
23363       complaint (&symfile_complaints,
23364                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23365                    " from DIE at %s [in module %s]"),
23366                  hex_string (signature), sect_offset_str (die->sect_off),
23367                  objfile_name (dwarf2_per_objfile->objfile));
23368       return build_error_marker_type (cu, die);
23369     }
23370
23371   /* If we already know the type we're done.  */
23372   if (sig_type->type != NULL)
23373     return sig_type->type;
23374
23375   type_cu = cu;
23376   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23377   if (type_die != NULL)
23378     {
23379       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23380          is created.  This is important, for example, because for c++ classes
23381          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23382       type = read_type_die (type_die, type_cu);
23383       if (type == NULL)
23384         {
23385           complaint (&symfile_complaints,
23386                      _("Dwarf Error: Cannot build signatured type %s"
23387                        " referenced from DIE at %s [in module %s]"),
23388                      hex_string (signature), sect_offset_str (die->sect_off),
23389                      objfile_name (dwarf2_per_objfile->objfile));
23390           type = build_error_marker_type (cu, die);
23391         }
23392     }
23393   else
23394     {
23395       complaint (&symfile_complaints,
23396                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23397                    " from DIE at %s [in module %s]"),
23398                  hex_string (signature), sect_offset_str (die->sect_off),
23399                  objfile_name (dwarf2_per_objfile->objfile));
23400       type = build_error_marker_type (cu, die);
23401     }
23402   sig_type->type = type;
23403
23404   return type;
23405 }
23406
23407 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23408    reading in and processing the type unit if necessary.  */
23409
23410 static struct type *
23411 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23412                           struct dwarf2_cu *cu) /* ARI: editCase function */
23413 {
23414   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23415   if (attr_form_is_ref (attr))
23416     {
23417       struct dwarf2_cu *type_cu = cu;
23418       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23419
23420       return read_type_die (type_die, type_cu);
23421     }
23422   else if (attr->form == DW_FORM_ref_sig8)
23423     {
23424       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23425     }
23426   else
23427     {
23428       struct dwarf2_per_objfile *dwarf2_per_objfile
23429         = cu->per_cu->dwarf2_per_objfile;
23430
23431       complaint (&symfile_complaints,
23432                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23433                    " at %s [in module %s]"),
23434                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23435                  objfile_name (dwarf2_per_objfile->objfile));
23436       return build_error_marker_type (cu, die);
23437     }
23438 }
23439
23440 /* Load the DIEs associated with type unit PER_CU into memory.  */
23441
23442 static void
23443 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23444 {
23445   struct signatured_type *sig_type;
23446
23447   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23448   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23449
23450   /* We have the per_cu, but we need the signatured_type.
23451      Fortunately this is an easy translation.  */
23452   gdb_assert (per_cu->is_debug_types);
23453   sig_type = (struct signatured_type *) per_cu;
23454
23455   gdb_assert (per_cu->cu == NULL);
23456
23457   read_signatured_type (sig_type);
23458
23459   gdb_assert (per_cu->cu != NULL);
23460 }
23461
23462 /* die_reader_func for read_signatured_type.
23463    This is identical to load_full_comp_unit_reader,
23464    but is kept separate for now.  */
23465
23466 static void
23467 read_signatured_type_reader (const struct die_reader_specs *reader,
23468                              const gdb_byte *info_ptr,
23469                              struct die_info *comp_unit_die,
23470                              int has_children,
23471                              void *data)
23472 {
23473   struct dwarf2_cu *cu = reader->cu;
23474
23475   gdb_assert (cu->die_hash == NULL);
23476   cu->die_hash =
23477     htab_create_alloc_ex (cu->header.length / 12,
23478                           die_hash,
23479                           die_eq,
23480                           NULL,
23481                           &cu->comp_unit_obstack,
23482                           hashtab_obstack_allocate,
23483                           dummy_obstack_deallocate);
23484
23485   if (has_children)
23486     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23487                                                   &info_ptr, comp_unit_die);
23488   cu->dies = comp_unit_die;
23489   /* comp_unit_die is not stored in die_hash, no need.  */
23490
23491   /* We try not to read any attributes in this function, because not
23492      all CUs needed for references have been loaded yet, and symbol
23493      table processing isn't initialized.  But we have to set the CU language,
23494      or we won't be able to build types correctly.
23495      Similarly, if we do not read the producer, we can not apply
23496      producer-specific interpretation.  */
23497   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23498 }
23499
23500 /* Read in a signatured type and build its CU and DIEs.
23501    If the type is a stub for the real type in a DWO file,
23502    read in the real type from the DWO file as well.  */
23503
23504 static void
23505 read_signatured_type (struct signatured_type *sig_type)
23506 {
23507   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23508
23509   gdb_assert (per_cu->is_debug_types);
23510   gdb_assert (per_cu->cu == NULL);
23511
23512   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23513                            read_signatured_type_reader, NULL);
23514   sig_type->per_cu.tu_read = 1;
23515 }
23516
23517 /* Decode simple location descriptions.
23518    Given a pointer to a dwarf block that defines a location, compute
23519    the location and return the value.
23520
23521    NOTE drow/2003-11-18: This function is called in two situations
23522    now: for the address of static or global variables (partial symbols
23523    only) and for offsets into structures which are expected to be
23524    (more or less) constant.  The partial symbol case should go away,
23525    and only the constant case should remain.  That will let this
23526    function complain more accurately.  A few special modes are allowed
23527    without complaint for global variables (for instance, global
23528    register values and thread-local values).
23529
23530    A location description containing no operations indicates that the
23531    object is optimized out.  The return value is 0 for that case.
23532    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23533    callers will only want a very basic result and this can become a
23534    complaint.
23535
23536    Note that stack[0] is unused except as a default error return.  */
23537
23538 static CORE_ADDR
23539 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23540 {
23541   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23542   size_t i;
23543   size_t size = blk->size;
23544   const gdb_byte *data = blk->data;
23545   CORE_ADDR stack[64];
23546   int stacki;
23547   unsigned int bytes_read, unsnd;
23548   gdb_byte op;
23549
23550   i = 0;
23551   stacki = 0;
23552   stack[stacki] = 0;
23553   stack[++stacki] = 0;
23554
23555   while (i < size)
23556     {
23557       op = data[i++];
23558       switch (op)
23559         {
23560         case DW_OP_lit0:
23561         case DW_OP_lit1:
23562         case DW_OP_lit2:
23563         case DW_OP_lit3:
23564         case DW_OP_lit4:
23565         case DW_OP_lit5:
23566         case DW_OP_lit6:
23567         case DW_OP_lit7:
23568         case DW_OP_lit8:
23569         case DW_OP_lit9:
23570         case DW_OP_lit10:
23571         case DW_OP_lit11:
23572         case DW_OP_lit12:
23573         case DW_OP_lit13:
23574         case DW_OP_lit14:
23575         case DW_OP_lit15:
23576         case DW_OP_lit16:
23577         case DW_OP_lit17:
23578         case DW_OP_lit18:
23579         case DW_OP_lit19:
23580         case DW_OP_lit20:
23581         case DW_OP_lit21:
23582         case DW_OP_lit22:
23583         case DW_OP_lit23:
23584         case DW_OP_lit24:
23585         case DW_OP_lit25:
23586         case DW_OP_lit26:
23587         case DW_OP_lit27:
23588         case DW_OP_lit28:
23589         case DW_OP_lit29:
23590         case DW_OP_lit30:
23591         case DW_OP_lit31:
23592           stack[++stacki] = op - DW_OP_lit0;
23593           break;
23594
23595         case DW_OP_reg0:
23596         case DW_OP_reg1:
23597         case DW_OP_reg2:
23598         case DW_OP_reg3:
23599         case DW_OP_reg4:
23600         case DW_OP_reg5:
23601         case DW_OP_reg6:
23602         case DW_OP_reg7:
23603         case DW_OP_reg8:
23604         case DW_OP_reg9:
23605         case DW_OP_reg10:
23606         case DW_OP_reg11:
23607         case DW_OP_reg12:
23608         case DW_OP_reg13:
23609         case DW_OP_reg14:
23610         case DW_OP_reg15:
23611         case DW_OP_reg16:
23612         case DW_OP_reg17:
23613         case DW_OP_reg18:
23614         case DW_OP_reg19:
23615         case DW_OP_reg20:
23616         case DW_OP_reg21:
23617         case DW_OP_reg22:
23618         case DW_OP_reg23:
23619         case DW_OP_reg24:
23620         case DW_OP_reg25:
23621         case DW_OP_reg26:
23622         case DW_OP_reg27:
23623         case DW_OP_reg28:
23624         case DW_OP_reg29:
23625         case DW_OP_reg30:
23626         case DW_OP_reg31:
23627           stack[++stacki] = op - DW_OP_reg0;
23628           if (i < size)
23629             dwarf2_complex_location_expr_complaint ();
23630           break;
23631
23632         case DW_OP_regx:
23633           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23634           i += bytes_read;
23635           stack[++stacki] = unsnd;
23636           if (i < size)
23637             dwarf2_complex_location_expr_complaint ();
23638           break;
23639
23640         case DW_OP_addr:
23641           stack[++stacki] = read_address (objfile->obfd, &data[i],
23642                                           cu, &bytes_read);
23643           i += bytes_read;
23644           break;
23645
23646         case DW_OP_const1u:
23647           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23648           i += 1;
23649           break;
23650
23651         case DW_OP_const1s:
23652           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23653           i += 1;
23654           break;
23655
23656         case DW_OP_const2u:
23657           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23658           i += 2;
23659           break;
23660
23661         case DW_OP_const2s:
23662           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23663           i += 2;
23664           break;
23665
23666         case DW_OP_const4u:
23667           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23668           i += 4;
23669           break;
23670
23671         case DW_OP_const4s:
23672           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23673           i += 4;
23674           break;
23675
23676         case DW_OP_const8u:
23677           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23678           i += 8;
23679           break;
23680
23681         case DW_OP_constu:
23682           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23683                                                   &bytes_read);
23684           i += bytes_read;
23685           break;
23686
23687         case DW_OP_consts:
23688           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23689           i += bytes_read;
23690           break;
23691
23692         case DW_OP_dup:
23693           stack[stacki + 1] = stack[stacki];
23694           stacki++;
23695           break;
23696
23697         case DW_OP_plus:
23698           stack[stacki - 1] += stack[stacki];
23699           stacki--;
23700           break;
23701
23702         case DW_OP_plus_uconst:
23703           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23704                                                  &bytes_read);
23705           i += bytes_read;
23706           break;
23707
23708         case DW_OP_minus:
23709           stack[stacki - 1] -= stack[stacki];
23710           stacki--;
23711           break;
23712
23713         case DW_OP_deref:
23714           /* If we're not the last op, then we definitely can't encode
23715              this using GDB's address_class enum.  This is valid for partial
23716              global symbols, although the variable's address will be bogus
23717              in the psymtab.  */
23718           if (i < size)
23719             dwarf2_complex_location_expr_complaint ();
23720           break;
23721
23722         case DW_OP_GNU_push_tls_address:
23723         case DW_OP_form_tls_address:
23724           /* The top of the stack has the offset from the beginning
23725              of the thread control block at which the variable is located.  */
23726           /* Nothing should follow this operator, so the top of stack would
23727              be returned.  */
23728           /* This is valid for partial global symbols, but the variable's
23729              address will be bogus in the psymtab.  Make it always at least
23730              non-zero to not look as a variable garbage collected by linker
23731              which have DW_OP_addr 0.  */
23732           if (i < size)
23733             dwarf2_complex_location_expr_complaint ();
23734           stack[stacki]++;
23735           break;
23736
23737         case DW_OP_GNU_uninit:
23738           break;
23739
23740         case DW_OP_GNU_addr_index:
23741         case DW_OP_GNU_const_index:
23742           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23743                                                          &bytes_read);
23744           i += bytes_read;
23745           break;
23746
23747         default:
23748           {
23749             const char *name = get_DW_OP_name (op);
23750
23751             if (name)
23752               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23753                          name);
23754             else
23755               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23756                          op);
23757           }
23758
23759           return (stack[stacki]);
23760         }
23761
23762       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23763          outside of the allocated space.  Also enforce minimum>0.  */
23764       if (stacki >= ARRAY_SIZE (stack) - 1)
23765         {
23766           complaint (&symfile_complaints,
23767                      _("location description stack overflow"));
23768           return 0;
23769         }
23770
23771       if (stacki <= 0)
23772         {
23773           complaint (&symfile_complaints,
23774                      _("location description stack underflow"));
23775           return 0;
23776         }
23777     }
23778   return (stack[stacki]);
23779 }
23780
23781 /* memory allocation interface */
23782
23783 static struct dwarf_block *
23784 dwarf_alloc_block (struct dwarf2_cu *cu)
23785 {
23786   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23787 }
23788
23789 static struct die_info *
23790 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23791 {
23792   struct die_info *die;
23793   size_t size = sizeof (struct die_info);
23794
23795   if (num_attrs > 1)
23796     size += (num_attrs - 1) * sizeof (struct attribute);
23797
23798   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23799   memset (die, 0, sizeof (struct die_info));
23800   return (die);
23801 }
23802
23803 \f
23804 /* Macro support.  */
23805
23806 /* Return file name relative to the compilation directory of file number I in
23807    *LH's file name table.  The result is allocated using xmalloc; the caller is
23808    responsible for freeing it.  */
23809
23810 static char *
23811 file_file_name (int file, struct line_header *lh)
23812 {
23813   /* Is the file number a valid index into the line header's file name
23814      table?  Remember that file numbers start with one, not zero.  */
23815   if (1 <= file && file <= lh->file_names.size ())
23816     {
23817       const file_entry &fe = lh->file_names[file - 1];
23818
23819       if (!IS_ABSOLUTE_PATH (fe.name))
23820         {
23821           const char *dir = fe.include_dir (lh);
23822           if (dir != NULL)
23823             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23824         }
23825       return xstrdup (fe.name);
23826     }
23827   else
23828     {
23829       /* The compiler produced a bogus file number.  We can at least
23830          record the macro definitions made in the file, even if we
23831          won't be able to find the file by name.  */
23832       char fake_name[80];
23833
23834       xsnprintf (fake_name, sizeof (fake_name),
23835                  "<bad macro file number %d>", file);
23836
23837       complaint (&symfile_complaints,
23838                  _("bad file number in macro information (%d)"),
23839                  file);
23840
23841       return xstrdup (fake_name);
23842     }
23843 }
23844
23845 /* Return the full name of file number I in *LH's file name table.
23846    Use COMP_DIR as the name of the current directory of the
23847    compilation.  The result is allocated using xmalloc; the caller is
23848    responsible for freeing it.  */
23849 static char *
23850 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23851 {
23852   /* Is the file number a valid index into the line header's file name
23853      table?  Remember that file numbers start with one, not zero.  */
23854   if (1 <= file && file <= lh->file_names.size ())
23855     {
23856       char *relative = file_file_name (file, lh);
23857
23858       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23859         return relative;
23860       return reconcat (relative, comp_dir, SLASH_STRING,
23861                        relative, (char *) NULL);
23862     }
23863   else
23864     return file_file_name (file, lh);
23865 }
23866
23867
23868 static struct macro_source_file *
23869 macro_start_file (int file, int line,
23870                   struct macro_source_file *current_file,
23871                   struct line_header *lh)
23872 {
23873   /* File name relative to the compilation directory of this source file.  */
23874   char *file_name = file_file_name (file, lh);
23875
23876   if (! current_file)
23877     {
23878       /* Note: We don't create a macro table for this compilation unit
23879          at all until we actually get a filename.  */
23880       struct macro_table *macro_table = get_macro_table ();
23881
23882       /* If we have no current file, then this must be the start_file
23883          directive for the compilation unit's main source file.  */
23884       current_file = macro_set_main (macro_table, file_name);
23885       macro_define_special (macro_table);
23886     }
23887   else
23888     current_file = macro_include (current_file, line, file_name);
23889
23890   xfree (file_name);
23891
23892   return current_file;
23893 }
23894
23895 static const char *
23896 consume_improper_spaces (const char *p, const char *body)
23897 {
23898   if (*p == ' ')
23899     {
23900       complaint (&symfile_complaints,
23901                  _("macro definition contains spaces "
23902                    "in formal argument list:\n`%s'"),
23903                  body);
23904
23905       while (*p == ' ')
23906         p++;
23907     }
23908
23909   return p;
23910 }
23911
23912
23913 static void
23914 parse_macro_definition (struct macro_source_file *file, int line,
23915                         const char *body)
23916 {
23917   const char *p;
23918
23919   /* The body string takes one of two forms.  For object-like macro
23920      definitions, it should be:
23921
23922         <macro name> " " <definition>
23923
23924      For function-like macro definitions, it should be:
23925
23926         <macro name> "() " <definition>
23927      or
23928         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23929
23930      Spaces may appear only where explicitly indicated, and in the
23931      <definition>.
23932
23933      The Dwarf 2 spec says that an object-like macro's name is always
23934      followed by a space, but versions of GCC around March 2002 omit
23935      the space when the macro's definition is the empty string.
23936
23937      The Dwarf 2 spec says that there should be no spaces between the
23938      formal arguments in a function-like macro's formal argument list,
23939      but versions of GCC around March 2002 include spaces after the
23940      commas.  */
23941
23942
23943   /* Find the extent of the macro name.  The macro name is terminated
23944      by either a space or null character (for an object-like macro) or
23945      an opening paren (for a function-like macro).  */
23946   for (p = body; *p; p++)
23947     if (*p == ' ' || *p == '(')
23948       break;
23949
23950   if (*p == ' ' || *p == '\0')
23951     {
23952       /* It's an object-like macro.  */
23953       int name_len = p - body;
23954       char *name = savestring (body, name_len);
23955       const char *replacement;
23956
23957       if (*p == ' ')
23958         replacement = body + name_len + 1;
23959       else
23960         {
23961           dwarf2_macro_malformed_definition_complaint (body);
23962           replacement = body + name_len;
23963         }
23964
23965       macro_define_object (file, line, name, replacement);
23966
23967       xfree (name);
23968     }
23969   else if (*p == '(')
23970     {
23971       /* It's a function-like macro.  */
23972       char *name = savestring (body, p - body);
23973       int argc = 0;
23974       int argv_size = 1;
23975       char **argv = XNEWVEC (char *, argv_size);
23976
23977       p++;
23978
23979       p = consume_improper_spaces (p, body);
23980
23981       /* Parse the formal argument list.  */
23982       while (*p && *p != ')')
23983         {
23984           /* Find the extent of the current argument name.  */
23985           const char *arg_start = p;
23986
23987           while (*p && *p != ',' && *p != ')' && *p != ' ')
23988             p++;
23989
23990           if (! *p || p == arg_start)
23991             dwarf2_macro_malformed_definition_complaint (body);
23992           else
23993             {
23994               /* Make sure argv has room for the new argument.  */
23995               if (argc >= argv_size)
23996                 {
23997                   argv_size *= 2;
23998                   argv = XRESIZEVEC (char *, argv, argv_size);
23999                 }
24000
24001               argv[argc++] = savestring (arg_start, p - arg_start);
24002             }
24003
24004           p = consume_improper_spaces (p, body);
24005
24006           /* Consume the comma, if present.  */
24007           if (*p == ',')
24008             {
24009               p++;
24010
24011               p = consume_improper_spaces (p, body);
24012             }
24013         }
24014
24015       if (*p == ')')
24016         {
24017           p++;
24018
24019           if (*p == ' ')
24020             /* Perfectly formed definition, no complaints.  */
24021             macro_define_function (file, line, name,
24022                                    argc, (const char **) argv,
24023                                    p + 1);
24024           else if (*p == '\0')
24025             {
24026               /* Complain, but do define it.  */
24027               dwarf2_macro_malformed_definition_complaint (body);
24028               macro_define_function (file, line, name,
24029                                      argc, (const char **) argv,
24030                                      p);
24031             }
24032           else
24033             /* Just complain.  */
24034             dwarf2_macro_malformed_definition_complaint (body);
24035         }
24036       else
24037         /* Just complain.  */
24038         dwarf2_macro_malformed_definition_complaint (body);
24039
24040       xfree (name);
24041       {
24042         int i;
24043
24044         for (i = 0; i < argc; i++)
24045           xfree (argv[i]);
24046       }
24047       xfree (argv);
24048     }
24049   else
24050     dwarf2_macro_malformed_definition_complaint (body);
24051 }
24052
24053 /* Skip some bytes from BYTES according to the form given in FORM.
24054    Returns the new pointer.  */
24055
24056 static const gdb_byte *
24057 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24058                  enum dwarf_form form,
24059                  unsigned int offset_size,
24060                  struct dwarf2_section_info *section)
24061 {
24062   unsigned int bytes_read;
24063
24064   switch (form)
24065     {
24066     case DW_FORM_data1:
24067     case DW_FORM_flag:
24068       ++bytes;
24069       break;
24070
24071     case DW_FORM_data2:
24072       bytes += 2;
24073       break;
24074
24075     case DW_FORM_data4:
24076       bytes += 4;
24077       break;
24078
24079     case DW_FORM_data8:
24080       bytes += 8;
24081       break;
24082
24083     case DW_FORM_data16:
24084       bytes += 16;
24085       break;
24086
24087     case DW_FORM_string:
24088       read_direct_string (abfd, bytes, &bytes_read);
24089       bytes += bytes_read;
24090       break;
24091
24092     case DW_FORM_sec_offset:
24093     case DW_FORM_strp:
24094     case DW_FORM_GNU_strp_alt:
24095       bytes += offset_size;
24096       break;
24097
24098     case DW_FORM_block:
24099       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24100       bytes += bytes_read;
24101       break;
24102
24103     case DW_FORM_block1:
24104       bytes += 1 + read_1_byte (abfd, bytes);
24105       break;
24106     case DW_FORM_block2:
24107       bytes += 2 + read_2_bytes (abfd, bytes);
24108       break;
24109     case DW_FORM_block4:
24110       bytes += 4 + read_4_bytes (abfd, bytes);
24111       break;
24112
24113     case DW_FORM_sdata:
24114     case DW_FORM_udata:
24115     case DW_FORM_GNU_addr_index:
24116     case DW_FORM_GNU_str_index:
24117       bytes = gdb_skip_leb128 (bytes, buffer_end);
24118       if (bytes == NULL)
24119         {
24120           dwarf2_section_buffer_overflow_complaint (section);
24121           return NULL;
24122         }
24123       break;
24124
24125     case DW_FORM_implicit_const:
24126       break;
24127
24128     default:
24129       {
24130         complaint (&symfile_complaints,
24131                    _("invalid form 0x%x in `%s'"),
24132                    form, get_section_name (section));
24133         return NULL;
24134       }
24135     }
24136
24137   return bytes;
24138 }
24139
24140 /* A helper for dwarf_decode_macros that handles skipping an unknown
24141    opcode.  Returns an updated pointer to the macro data buffer; or,
24142    on error, issues a complaint and returns NULL.  */
24143
24144 static const gdb_byte *
24145 skip_unknown_opcode (unsigned int opcode,
24146                      const gdb_byte **opcode_definitions,
24147                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24148                      bfd *abfd,
24149                      unsigned int offset_size,
24150                      struct dwarf2_section_info *section)
24151 {
24152   unsigned int bytes_read, i;
24153   unsigned long arg;
24154   const gdb_byte *defn;
24155
24156   if (opcode_definitions[opcode] == NULL)
24157     {
24158       complaint (&symfile_complaints,
24159                  _("unrecognized DW_MACFINO opcode 0x%x"),
24160                  opcode);
24161       return NULL;
24162     }
24163
24164   defn = opcode_definitions[opcode];
24165   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24166   defn += bytes_read;
24167
24168   for (i = 0; i < arg; ++i)
24169     {
24170       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24171                                  (enum dwarf_form) defn[i], offset_size,
24172                                  section);
24173       if (mac_ptr == NULL)
24174         {
24175           /* skip_form_bytes already issued the complaint.  */
24176           return NULL;
24177         }
24178     }
24179
24180   return mac_ptr;
24181 }
24182
24183 /* A helper function which parses the header of a macro section.
24184    If the macro section is the extended (for now called "GNU") type,
24185    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24186    the header, or issues a complaint and returns NULL on error.  */
24187
24188 static const gdb_byte *
24189 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24190                           bfd *abfd,
24191                           const gdb_byte *mac_ptr,
24192                           unsigned int *offset_size,
24193                           int section_is_gnu)
24194 {
24195   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24196
24197   if (section_is_gnu)
24198     {
24199       unsigned int version, flags;
24200
24201       version = read_2_bytes (abfd, mac_ptr);
24202       if (version != 4 && version != 5)
24203         {
24204           complaint (&symfile_complaints,
24205                      _("unrecognized version `%d' in .debug_macro section"),
24206                      version);
24207           return NULL;
24208         }
24209       mac_ptr += 2;
24210
24211       flags = read_1_byte (abfd, mac_ptr);
24212       ++mac_ptr;
24213       *offset_size = (flags & 1) ? 8 : 4;
24214
24215       if ((flags & 2) != 0)
24216         /* We don't need the line table offset.  */
24217         mac_ptr += *offset_size;
24218
24219       /* Vendor opcode descriptions.  */
24220       if ((flags & 4) != 0)
24221         {
24222           unsigned int i, count;
24223
24224           count = read_1_byte (abfd, mac_ptr);
24225           ++mac_ptr;
24226           for (i = 0; i < count; ++i)
24227             {
24228               unsigned int opcode, bytes_read;
24229               unsigned long arg;
24230
24231               opcode = read_1_byte (abfd, mac_ptr);
24232               ++mac_ptr;
24233               opcode_definitions[opcode] = mac_ptr;
24234               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24235               mac_ptr += bytes_read;
24236               mac_ptr += arg;
24237             }
24238         }
24239     }
24240
24241   return mac_ptr;
24242 }
24243
24244 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24245    including DW_MACRO_import.  */
24246
24247 static void
24248 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24249                           bfd *abfd,
24250                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24251                           struct macro_source_file *current_file,
24252                           struct line_header *lh,
24253                           struct dwarf2_section_info *section,
24254                           int section_is_gnu, int section_is_dwz,
24255                           unsigned int offset_size,
24256                           htab_t include_hash)
24257 {
24258   struct objfile *objfile = dwarf2_per_objfile->objfile;
24259   enum dwarf_macro_record_type macinfo_type;
24260   int at_commandline;
24261   const gdb_byte *opcode_definitions[256];
24262
24263   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24264                                       &offset_size, section_is_gnu);
24265   if (mac_ptr == NULL)
24266     {
24267       /* We already issued a complaint.  */
24268       return;
24269     }
24270
24271   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24272      GDB is still reading the definitions from command line.  First
24273      DW_MACINFO_start_file will need to be ignored as it was already executed
24274      to create CURRENT_FILE for the main source holding also the command line
24275      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24276      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24277
24278   at_commandline = 1;
24279
24280   do
24281     {
24282       /* Do we at least have room for a macinfo type byte?  */
24283       if (mac_ptr >= mac_end)
24284         {
24285           dwarf2_section_buffer_overflow_complaint (section);
24286           break;
24287         }
24288
24289       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24290       mac_ptr++;
24291
24292       /* Note that we rely on the fact that the corresponding GNU and
24293          DWARF constants are the same.  */
24294       DIAGNOSTIC_PUSH
24295       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24296       switch (macinfo_type)
24297         {
24298           /* A zero macinfo type indicates the end of the macro
24299              information.  */
24300         case 0:
24301           break;
24302
24303         case DW_MACRO_define:
24304         case DW_MACRO_undef:
24305         case DW_MACRO_define_strp:
24306         case DW_MACRO_undef_strp:
24307         case DW_MACRO_define_sup:
24308         case DW_MACRO_undef_sup:
24309           {
24310             unsigned int bytes_read;
24311             int line;
24312             const char *body;
24313             int is_define;
24314
24315             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24316             mac_ptr += bytes_read;
24317
24318             if (macinfo_type == DW_MACRO_define
24319                 || macinfo_type == DW_MACRO_undef)
24320               {
24321                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24322                 mac_ptr += bytes_read;
24323               }
24324             else
24325               {
24326                 LONGEST str_offset;
24327
24328                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24329                 mac_ptr += offset_size;
24330
24331                 if (macinfo_type == DW_MACRO_define_sup
24332                     || macinfo_type == DW_MACRO_undef_sup
24333                     || section_is_dwz)
24334                   {
24335                     struct dwz_file *dwz
24336                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24337
24338                     body = read_indirect_string_from_dwz (objfile,
24339                                                           dwz, str_offset);
24340                   }
24341                 else
24342                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24343                                                          abfd, str_offset);
24344               }
24345
24346             is_define = (macinfo_type == DW_MACRO_define
24347                          || macinfo_type == DW_MACRO_define_strp
24348                          || macinfo_type == DW_MACRO_define_sup);
24349             if (! current_file)
24350               {
24351                 /* DWARF violation as no main source is present.  */
24352                 complaint (&symfile_complaints,
24353                            _("debug info with no main source gives macro %s "
24354                              "on line %d: %s"),
24355                            is_define ? _("definition") : _("undefinition"),
24356                            line, body);
24357                 break;
24358               }
24359             if ((line == 0 && !at_commandline)
24360                 || (line != 0 && at_commandline))
24361               complaint (&symfile_complaints,
24362                          _("debug info gives %s macro %s with %s line %d: %s"),
24363                          at_commandline ? _("command-line") : _("in-file"),
24364                          is_define ? _("definition") : _("undefinition"),
24365                          line == 0 ? _("zero") : _("non-zero"), line, body);
24366
24367             if (is_define)
24368               parse_macro_definition (current_file, line, body);
24369             else
24370               {
24371                 gdb_assert (macinfo_type == DW_MACRO_undef
24372                             || macinfo_type == DW_MACRO_undef_strp
24373                             || macinfo_type == DW_MACRO_undef_sup);
24374                 macro_undef (current_file, line, body);
24375               }
24376           }
24377           break;
24378
24379         case DW_MACRO_start_file:
24380           {
24381             unsigned int bytes_read;
24382             int line, file;
24383
24384             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24385             mac_ptr += bytes_read;
24386             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24387             mac_ptr += bytes_read;
24388
24389             if ((line == 0 && !at_commandline)
24390                 || (line != 0 && at_commandline))
24391               complaint (&symfile_complaints,
24392                          _("debug info gives source %d included "
24393                            "from %s at %s line %d"),
24394                          file, at_commandline ? _("command-line") : _("file"),
24395                          line == 0 ? _("zero") : _("non-zero"), line);
24396
24397             if (at_commandline)
24398               {
24399                 /* This DW_MACRO_start_file was executed in the
24400                    pass one.  */
24401                 at_commandline = 0;
24402               }
24403             else
24404               current_file = macro_start_file (file, line, current_file, lh);
24405           }
24406           break;
24407
24408         case DW_MACRO_end_file:
24409           if (! current_file)
24410             complaint (&symfile_complaints,
24411                        _("macro debug info has an unmatched "
24412                          "`close_file' directive"));
24413           else
24414             {
24415               current_file = current_file->included_by;
24416               if (! current_file)
24417                 {
24418                   enum dwarf_macro_record_type next_type;
24419
24420                   /* GCC circa March 2002 doesn't produce the zero
24421                      type byte marking the end of the compilation
24422                      unit.  Complain if it's not there, but exit no
24423                      matter what.  */
24424
24425                   /* Do we at least have room for a macinfo type byte?  */
24426                   if (mac_ptr >= mac_end)
24427                     {
24428                       dwarf2_section_buffer_overflow_complaint (section);
24429                       return;
24430                     }
24431
24432                   /* We don't increment mac_ptr here, so this is just
24433                      a look-ahead.  */
24434                   next_type
24435                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24436                                                                   mac_ptr);
24437                   if (next_type != 0)
24438                     complaint (&symfile_complaints,
24439                                _("no terminating 0-type entry for "
24440                                  "macros in `.debug_macinfo' section"));
24441
24442                   return;
24443                 }
24444             }
24445           break;
24446
24447         case DW_MACRO_import:
24448         case DW_MACRO_import_sup:
24449           {
24450             LONGEST offset;
24451             void **slot;
24452             bfd *include_bfd = abfd;
24453             struct dwarf2_section_info *include_section = section;
24454             const gdb_byte *include_mac_end = mac_end;
24455             int is_dwz = section_is_dwz;
24456             const gdb_byte *new_mac_ptr;
24457
24458             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24459             mac_ptr += offset_size;
24460
24461             if (macinfo_type == DW_MACRO_import_sup)
24462               {
24463                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24464
24465                 dwarf2_read_section (objfile, &dwz->macro);
24466
24467                 include_section = &dwz->macro;
24468                 include_bfd = get_section_bfd_owner (include_section);
24469                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24470                 is_dwz = 1;
24471               }
24472
24473             new_mac_ptr = include_section->buffer + offset;
24474             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24475
24476             if (*slot != NULL)
24477               {
24478                 /* This has actually happened; see
24479                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24480                 complaint (&symfile_complaints,
24481                            _("recursive DW_MACRO_import in "
24482                              ".debug_macro section"));
24483               }
24484             else
24485               {
24486                 *slot = (void *) new_mac_ptr;
24487
24488                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24489                                           include_bfd, new_mac_ptr,
24490                                           include_mac_end, current_file, lh,
24491                                           section, section_is_gnu, is_dwz,
24492                                           offset_size, include_hash);
24493
24494                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24495               }
24496           }
24497           break;
24498
24499         case DW_MACINFO_vendor_ext:
24500           if (!section_is_gnu)
24501             {
24502               unsigned int bytes_read;
24503
24504               /* This reads the constant, but since we don't recognize
24505                  any vendor extensions, we ignore it.  */
24506               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24507               mac_ptr += bytes_read;
24508               read_direct_string (abfd, mac_ptr, &bytes_read);
24509               mac_ptr += bytes_read;
24510
24511               /* We don't recognize any vendor extensions.  */
24512               break;
24513             }
24514           /* FALLTHROUGH */
24515
24516         default:
24517           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24518                                          mac_ptr, mac_end, abfd, offset_size,
24519                                          section);
24520           if (mac_ptr == NULL)
24521             return;
24522           break;
24523         }
24524       DIAGNOSTIC_POP
24525     } while (macinfo_type != 0);
24526 }
24527
24528 static void
24529 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24530                      int section_is_gnu)
24531 {
24532   struct dwarf2_per_objfile *dwarf2_per_objfile
24533     = cu->per_cu->dwarf2_per_objfile;
24534   struct objfile *objfile = dwarf2_per_objfile->objfile;
24535   struct line_header *lh = cu->line_header;
24536   bfd *abfd;
24537   const gdb_byte *mac_ptr, *mac_end;
24538   struct macro_source_file *current_file = 0;
24539   enum dwarf_macro_record_type macinfo_type;
24540   unsigned int offset_size = cu->header.offset_size;
24541   const gdb_byte *opcode_definitions[256];
24542   void **slot;
24543   struct dwarf2_section_info *section;
24544   const char *section_name;
24545
24546   if (cu->dwo_unit != NULL)
24547     {
24548       if (section_is_gnu)
24549         {
24550           section = &cu->dwo_unit->dwo_file->sections.macro;
24551           section_name = ".debug_macro.dwo";
24552         }
24553       else
24554         {
24555           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24556           section_name = ".debug_macinfo.dwo";
24557         }
24558     }
24559   else
24560     {
24561       if (section_is_gnu)
24562         {
24563           section = &dwarf2_per_objfile->macro;
24564           section_name = ".debug_macro";
24565         }
24566       else
24567         {
24568           section = &dwarf2_per_objfile->macinfo;
24569           section_name = ".debug_macinfo";
24570         }
24571     }
24572
24573   dwarf2_read_section (objfile, section);
24574   if (section->buffer == NULL)
24575     {
24576       complaint (&symfile_complaints, _("missing %s section"), section_name);
24577       return;
24578     }
24579   abfd = get_section_bfd_owner (section);
24580
24581   /* First pass: Find the name of the base filename.
24582      This filename is needed in order to process all macros whose definition
24583      (or undefinition) comes from the command line.  These macros are defined
24584      before the first DW_MACINFO_start_file entry, and yet still need to be
24585      associated to the base file.
24586
24587      To determine the base file name, we scan the macro definitions until we
24588      reach the first DW_MACINFO_start_file entry.  We then initialize
24589      CURRENT_FILE accordingly so that any macro definition found before the
24590      first DW_MACINFO_start_file can still be associated to the base file.  */
24591
24592   mac_ptr = section->buffer + offset;
24593   mac_end = section->buffer + section->size;
24594
24595   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24596                                       &offset_size, section_is_gnu);
24597   if (mac_ptr == NULL)
24598     {
24599       /* We already issued a complaint.  */
24600       return;
24601     }
24602
24603   do
24604     {
24605       /* Do we at least have room for a macinfo type byte?  */
24606       if (mac_ptr >= mac_end)
24607         {
24608           /* Complaint is printed during the second pass as GDB will probably
24609              stop the first pass earlier upon finding
24610              DW_MACINFO_start_file.  */
24611           break;
24612         }
24613
24614       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24615       mac_ptr++;
24616
24617       /* Note that we rely on the fact that the corresponding GNU and
24618          DWARF constants are the same.  */
24619       DIAGNOSTIC_PUSH
24620       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24621       switch (macinfo_type)
24622         {
24623           /* A zero macinfo type indicates the end of the macro
24624              information.  */
24625         case 0:
24626           break;
24627
24628         case DW_MACRO_define:
24629         case DW_MACRO_undef:
24630           /* Only skip the data by MAC_PTR.  */
24631           {
24632             unsigned int bytes_read;
24633
24634             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24635             mac_ptr += bytes_read;
24636             read_direct_string (abfd, mac_ptr, &bytes_read);
24637             mac_ptr += bytes_read;
24638           }
24639           break;
24640
24641         case DW_MACRO_start_file:
24642           {
24643             unsigned int bytes_read;
24644             int line, file;
24645
24646             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24647             mac_ptr += bytes_read;
24648             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24649             mac_ptr += bytes_read;
24650
24651             current_file = macro_start_file (file, line, current_file, lh);
24652           }
24653           break;
24654
24655         case DW_MACRO_end_file:
24656           /* No data to skip by MAC_PTR.  */
24657           break;
24658
24659         case DW_MACRO_define_strp:
24660         case DW_MACRO_undef_strp:
24661         case DW_MACRO_define_sup:
24662         case DW_MACRO_undef_sup:
24663           {
24664             unsigned int bytes_read;
24665
24666             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24667             mac_ptr += bytes_read;
24668             mac_ptr += offset_size;
24669           }
24670           break;
24671
24672         case DW_MACRO_import:
24673         case DW_MACRO_import_sup:
24674           /* Note that, according to the spec, a transparent include
24675              chain cannot call DW_MACRO_start_file.  So, we can just
24676              skip this opcode.  */
24677           mac_ptr += offset_size;
24678           break;
24679
24680         case DW_MACINFO_vendor_ext:
24681           /* Only skip the data by MAC_PTR.  */
24682           if (!section_is_gnu)
24683             {
24684               unsigned int bytes_read;
24685
24686               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24687               mac_ptr += bytes_read;
24688               read_direct_string (abfd, mac_ptr, &bytes_read);
24689               mac_ptr += bytes_read;
24690             }
24691           /* FALLTHROUGH */
24692
24693         default:
24694           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24695                                          mac_ptr, mac_end, abfd, offset_size,
24696                                          section);
24697           if (mac_ptr == NULL)
24698             return;
24699           break;
24700         }
24701       DIAGNOSTIC_POP
24702     } while (macinfo_type != 0 && current_file == NULL);
24703
24704   /* Second pass: Process all entries.
24705
24706      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24707      command-line macro definitions/undefinitions.  This flag is unset when we
24708      reach the first DW_MACINFO_start_file entry.  */
24709
24710   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24711                                            htab_eq_pointer,
24712                                            NULL, xcalloc, xfree));
24713   mac_ptr = section->buffer + offset;
24714   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24715   *slot = (void *) mac_ptr;
24716   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24717                             abfd, mac_ptr, mac_end,
24718                             current_file, lh, section,
24719                             section_is_gnu, 0, offset_size,
24720                             include_hash.get ());
24721 }
24722
24723 /* Check if the attribute's form is a DW_FORM_block*
24724    if so return true else false.  */
24725
24726 static int
24727 attr_form_is_block (const struct attribute *attr)
24728 {
24729   return (attr == NULL ? 0 :
24730       attr->form == DW_FORM_block1
24731       || attr->form == DW_FORM_block2
24732       || attr->form == DW_FORM_block4
24733       || attr->form == DW_FORM_block
24734       || attr->form == DW_FORM_exprloc);
24735 }
24736
24737 /* Return non-zero if ATTR's value is a section offset --- classes
24738    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24739    You may use DW_UNSND (attr) to retrieve such offsets.
24740
24741    Section 7.5.4, "Attribute Encodings", explains that no attribute
24742    may have a value that belongs to more than one of these classes; it
24743    would be ambiguous if we did, because we use the same forms for all
24744    of them.  */
24745
24746 static int
24747 attr_form_is_section_offset (const struct attribute *attr)
24748 {
24749   return (attr->form == DW_FORM_data4
24750           || attr->form == DW_FORM_data8
24751           || attr->form == DW_FORM_sec_offset);
24752 }
24753
24754 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24755    zero otherwise.  When this function returns true, you can apply
24756    dwarf2_get_attr_constant_value to it.
24757
24758    However, note that for some attributes you must check
24759    attr_form_is_section_offset before using this test.  DW_FORM_data4
24760    and DW_FORM_data8 are members of both the constant class, and of
24761    the classes that contain offsets into other debug sections
24762    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24763    that, if an attribute's can be either a constant or one of the
24764    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24765    taken as section offsets, not constants.
24766
24767    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24768    cannot handle that.  */
24769
24770 static int
24771 attr_form_is_constant (const struct attribute *attr)
24772 {
24773   switch (attr->form)
24774     {
24775     case DW_FORM_sdata:
24776     case DW_FORM_udata:
24777     case DW_FORM_data1:
24778     case DW_FORM_data2:
24779     case DW_FORM_data4:
24780     case DW_FORM_data8:
24781     case DW_FORM_implicit_const:
24782       return 1;
24783     default:
24784       return 0;
24785     }
24786 }
24787
24788
24789 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24790    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24791
24792 static int
24793 attr_form_is_ref (const struct attribute *attr)
24794 {
24795   switch (attr->form)
24796     {
24797     case DW_FORM_ref_addr:
24798     case DW_FORM_ref1:
24799     case DW_FORM_ref2:
24800     case DW_FORM_ref4:
24801     case DW_FORM_ref8:
24802     case DW_FORM_ref_udata:
24803     case DW_FORM_GNU_ref_alt:
24804       return 1;
24805     default:
24806       return 0;
24807     }
24808 }
24809
24810 /* Return the .debug_loc section to use for CU.
24811    For DWO files use .debug_loc.dwo.  */
24812
24813 static struct dwarf2_section_info *
24814 cu_debug_loc_section (struct dwarf2_cu *cu)
24815 {
24816   struct dwarf2_per_objfile *dwarf2_per_objfile
24817     = cu->per_cu->dwarf2_per_objfile;
24818
24819   if (cu->dwo_unit)
24820     {
24821       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24822       
24823       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24824     }
24825   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24826                                   : &dwarf2_per_objfile->loc);
24827 }
24828
24829 /* A helper function that fills in a dwarf2_loclist_baton.  */
24830
24831 static void
24832 fill_in_loclist_baton (struct dwarf2_cu *cu,
24833                        struct dwarf2_loclist_baton *baton,
24834                        const struct attribute *attr)
24835 {
24836   struct dwarf2_per_objfile *dwarf2_per_objfile
24837     = cu->per_cu->dwarf2_per_objfile;
24838   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24839
24840   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24841
24842   baton->per_cu = cu->per_cu;
24843   gdb_assert (baton->per_cu);
24844   /* We don't know how long the location list is, but make sure we
24845      don't run off the edge of the section.  */
24846   baton->size = section->size - DW_UNSND (attr);
24847   baton->data = section->buffer + DW_UNSND (attr);
24848   baton->base_address = cu->base_address;
24849   baton->from_dwo = cu->dwo_unit != NULL;
24850 }
24851
24852 static void
24853 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24854                              struct dwarf2_cu *cu, int is_block)
24855 {
24856   struct dwarf2_per_objfile *dwarf2_per_objfile
24857     = cu->per_cu->dwarf2_per_objfile;
24858   struct objfile *objfile = dwarf2_per_objfile->objfile;
24859   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24860
24861   if (attr_form_is_section_offset (attr)
24862       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24863          the section.  If so, fall through to the complaint in the
24864          other branch.  */
24865       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24866     {
24867       struct dwarf2_loclist_baton *baton;
24868
24869       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24870
24871       fill_in_loclist_baton (cu, baton, attr);
24872
24873       if (cu->base_known == 0)
24874         complaint (&symfile_complaints,
24875                    _("Location list used without "
24876                      "specifying the CU base address."));
24877
24878       SYMBOL_ACLASS_INDEX (sym) = (is_block
24879                                    ? dwarf2_loclist_block_index
24880                                    : dwarf2_loclist_index);
24881       SYMBOL_LOCATION_BATON (sym) = baton;
24882     }
24883   else
24884     {
24885       struct dwarf2_locexpr_baton *baton;
24886
24887       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24888       baton->per_cu = cu->per_cu;
24889       gdb_assert (baton->per_cu);
24890
24891       if (attr_form_is_block (attr))
24892         {
24893           /* Note that we're just copying the block's data pointer
24894              here, not the actual data.  We're still pointing into the
24895              info_buffer for SYM's objfile; right now we never release
24896              that buffer, but when we do clean up properly this may
24897              need to change.  */
24898           baton->size = DW_BLOCK (attr)->size;
24899           baton->data = DW_BLOCK (attr)->data;
24900         }
24901       else
24902         {
24903           dwarf2_invalid_attrib_class_complaint ("location description",
24904                                                  SYMBOL_NATURAL_NAME (sym));
24905           baton->size = 0;
24906         }
24907
24908       SYMBOL_ACLASS_INDEX (sym) = (is_block
24909                                    ? dwarf2_locexpr_block_index
24910                                    : dwarf2_locexpr_index);
24911       SYMBOL_LOCATION_BATON (sym) = baton;
24912     }
24913 }
24914
24915 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24916    came from a separate debuginfo file, then the master objfile is
24917    returned.  */
24918
24919 struct objfile *
24920 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24921 {
24922   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24923
24924   /* Return the master objfile, so that we can report and look up the
24925      correct file containing this variable.  */
24926   if (objfile->separate_debug_objfile_backlink)
24927     objfile = objfile->separate_debug_objfile_backlink;
24928
24929   return objfile;
24930 }
24931
24932 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24933    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24934    CU_HEADERP first.  */
24935
24936 static const struct comp_unit_head *
24937 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24938                        struct dwarf2_per_cu_data *per_cu)
24939 {
24940   const gdb_byte *info_ptr;
24941
24942   if (per_cu->cu)
24943     return &per_cu->cu->header;
24944
24945   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24946
24947   memset (cu_headerp, 0, sizeof (*cu_headerp));
24948   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24949                        rcuh_kind::COMPILE);
24950
24951   return cu_headerp;
24952 }
24953
24954 /* Return the address size given in the compilation unit header for CU.  */
24955
24956 int
24957 dwarf2_per_cu_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   return cu_headerp->addr_size;
24965 }
24966
24967 /* Return the offset size given in the compilation unit header for CU.  */
24968
24969 int
24970 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24971 {
24972   struct comp_unit_head cu_header_local;
24973   const struct comp_unit_head *cu_headerp;
24974
24975   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24976
24977   return cu_headerp->offset_size;
24978 }
24979
24980 /* See its dwarf2loc.h declaration.  */
24981
24982 int
24983 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24984 {
24985   struct comp_unit_head cu_header_local;
24986   const struct comp_unit_head *cu_headerp;
24987
24988   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24989
24990   if (cu_headerp->version == 2)
24991     return cu_headerp->addr_size;
24992   else
24993     return cu_headerp->offset_size;
24994 }
24995
24996 /* Return the text offset of the CU.  The returned offset comes from
24997    this CU's objfile.  If this objfile came from a separate debuginfo
24998    file, then the offset may be different from the corresponding
24999    offset in the parent objfile.  */
25000
25001 CORE_ADDR
25002 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25003 {
25004   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25005
25006   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25007 }
25008
25009 /* Return DWARF version number of PER_CU.  */
25010
25011 short
25012 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25013 {
25014   return per_cu->dwarf_version;
25015 }
25016
25017 /* Locate the .debug_info compilation unit from CU's objfile which contains
25018    the DIE at OFFSET.  Raises an error on failure.  */
25019
25020 static struct dwarf2_per_cu_data *
25021 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25022                                   unsigned int offset_in_dwz,
25023                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25024 {
25025   struct dwarf2_per_cu_data *this_cu;
25026   int low, high;
25027   const sect_offset *cu_off;
25028
25029   low = 0;
25030   high = dwarf2_per_objfile->n_comp_units - 1;
25031   while (high > low)
25032     {
25033       struct dwarf2_per_cu_data *mid_cu;
25034       int mid = low + (high - low) / 2;
25035
25036       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25037       cu_off = &mid_cu->sect_off;
25038       if (mid_cu->is_dwz > offset_in_dwz
25039           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25040         high = mid;
25041       else
25042         low = mid + 1;
25043     }
25044   gdb_assert (low == high);
25045   this_cu = dwarf2_per_objfile->all_comp_units[low];
25046   cu_off = &this_cu->sect_off;
25047   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25048     {
25049       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25050         error (_("Dwarf Error: could not find partial DIE containing "
25051                "offset %s [in module %s]"),
25052                sect_offset_str (sect_off),
25053                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25054
25055       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25056                   <= sect_off);
25057       return dwarf2_per_objfile->all_comp_units[low-1];
25058     }
25059   else
25060     {
25061       this_cu = dwarf2_per_objfile->all_comp_units[low];
25062       if (low == dwarf2_per_objfile->n_comp_units - 1
25063           && sect_off >= this_cu->sect_off + this_cu->length)
25064         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25065       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25066       return this_cu;
25067     }
25068 }
25069
25070 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25071
25072 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25073   : per_cu (per_cu_),
25074     mark (0),
25075     has_loclist (0),
25076     checked_producer (0),
25077     producer_is_gxx_lt_4_6 (0),
25078     producer_is_gcc_lt_4_3 (0),
25079     producer_is_icc_lt_14 (0),
25080     processing_has_namespace_info (0)
25081 {
25082   per_cu->cu = this;
25083 }
25084
25085 /* Destroy a dwarf2_cu.  */
25086
25087 dwarf2_cu::~dwarf2_cu ()
25088 {
25089   per_cu->cu = NULL;
25090 }
25091
25092 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25093
25094 static void
25095 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25096                        enum language pretend_language)
25097 {
25098   struct attribute *attr;
25099
25100   /* Set the language we're debugging.  */
25101   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25102   if (attr)
25103     set_cu_language (DW_UNSND (attr), cu);
25104   else
25105     {
25106       cu->language = pretend_language;
25107       cu->language_defn = language_def (cu->language);
25108     }
25109
25110   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25111 }
25112
25113 /* Free all cached compilation units.  */
25114
25115 static void
25116 free_cached_comp_units (void *data)
25117 {
25118   struct dwarf2_per_objfile *dwarf2_per_objfile
25119     = (struct dwarf2_per_objfile *) data;
25120
25121   dwarf2_per_objfile->free_cached_comp_units ();
25122 }
25123
25124 /* Increase the age counter on each cached compilation unit, and free
25125    any that are too old.  */
25126
25127 static void
25128 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25129 {
25130   struct dwarf2_per_cu_data *per_cu, **last_chain;
25131
25132   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25133   per_cu = dwarf2_per_objfile->read_in_chain;
25134   while (per_cu != NULL)
25135     {
25136       per_cu->cu->last_used ++;
25137       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25138         dwarf2_mark (per_cu->cu);
25139       per_cu = per_cu->cu->read_in_chain;
25140     }
25141
25142   per_cu = dwarf2_per_objfile->read_in_chain;
25143   last_chain = &dwarf2_per_objfile->read_in_chain;
25144   while (per_cu != NULL)
25145     {
25146       struct dwarf2_per_cu_data *next_cu;
25147
25148       next_cu = per_cu->cu->read_in_chain;
25149
25150       if (!per_cu->cu->mark)
25151         {
25152           delete per_cu->cu;
25153           *last_chain = next_cu;
25154         }
25155       else
25156         last_chain = &per_cu->cu->read_in_chain;
25157
25158       per_cu = next_cu;
25159     }
25160 }
25161
25162 /* Remove a single compilation unit from the cache.  */
25163
25164 static void
25165 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25166 {
25167   struct dwarf2_per_cu_data *per_cu, **last_chain;
25168   struct dwarf2_per_objfile *dwarf2_per_objfile
25169     = target_per_cu->dwarf2_per_objfile;
25170
25171   per_cu = dwarf2_per_objfile->read_in_chain;
25172   last_chain = &dwarf2_per_objfile->read_in_chain;
25173   while (per_cu != NULL)
25174     {
25175       struct dwarf2_per_cu_data *next_cu;
25176
25177       next_cu = per_cu->cu->read_in_chain;
25178
25179       if (per_cu == target_per_cu)
25180         {
25181           delete per_cu->cu;
25182           per_cu->cu = NULL;
25183           *last_chain = next_cu;
25184           break;
25185         }
25186       else
25187         last_chain = &per_cu->cu->read_in_chain;
25188
25189       per_cu = next_cu;
25190     }
25191 }
25192
25193 /* Release all extra memory associated with OBJFILE.  */
25194
25195 void
25196 dwarf2_free_objfile (struct objfile *objfile)
25197 {
25198   struct dwarf2_per_objfile *dwarf2_per_objfile
25199     = get_dwarf2_per_objfile (objfile);
25200
25201   delete dwarf2_per_objfile;
25202 }
25203
25204 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25205    We store these in a hash table separate from the DIEs, and preserve them
25206    when the DIEs are flushed out of cache.
25207
25208    The CU "per_cu" pointer is needed because offset alone is not enough to
25209    uniquely identify the type.  A file may have multiple .debug_types sections,
25210    or the type may come from a DWO file.  Furthermore, while it's more logical
25211    to use per_cu->section+offset, with Fission the section with the data is in
25212    the DWO file but we don't know that section at the point we need it.
25213    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25214    because we can enter the lookup routine, get_die_type_at_offset, from
25215    outside this file, and thus won't necessarily have PER_CU->cu.
25216    Fortunately, PER_CU is stable for the life of the objfile.  */
25217
25218 struct dwarf2_per_cu_offset_and_type
25219 {
25220   const struct dwarf2_per_cu_data *per_cu;
25221   sect_offset sect_off;
25222   struct type *type;
25223 };
25224
25225 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25226
25227 static hashval_t
25228 per_cu_offset_and_type_hash (const void *item)
25229 {
25230   const struct dwarf2_per_cu_offset_and_type *ofs
25231     = (const struct dwarf2_per_cu_offset_and_type *) item;
25232
25233   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25234 }
25235
25236 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25237
25238 static int
25239 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25240 {
25241   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25242     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25243   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25244     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25245
25246   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25247           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25248 }
25249
25250 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25251    table if necessary.  For convenience, return TYPE.
25252
25253    The DIEs reading must have careful ordering to:
25254     * Not cause infite loops trying to read in DIEs as a prerequisite for
25255       reading current DIE.
25256     * Not trying to dereference contents of still incompletely read in types
25257       while reading in other DIEs.
25258     * Enable referencing still incompletely read in types just by a pointer to
25259       the type without accessing its fields.
25260
25261    Therefore caller should follow these rules:
25262      * Try to fetch any prerequisite types we may need to build this DIE type
25263        before building the type and calling set_die_type.
25264      * After building type call set_die_type for current DIE as soon as
25265        possible before fetching more types to complete the current type.
25266      * Make the type as complete as possible before fetching more types.  */
25267
25268 static struct type *
25269 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25270 {
25271   struct dwarf2_per_objfile *dwarf2_per_objfile
25272     = cu->per_cu->dwarf2_per_objfile;
25273   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25274   struct objfile *objfile = dwarf2_per_objfile->objfile;
25275   struct attribute *attr;
25276   struct dynamic_prop prop;
25277
25278   /* For Ada types, make sure that the gnat-specific data is always
25279      initialized (if not already set).  There are a few types where
25280      we should not be doing so, because the type-specific area is
25281      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25282      where the type-specific area is used to store the floatformat).
25283      But this is not a problem, because the gnat-specific information
25284      is actually not needed for these types.  */
25285   if (need_gnat_info (cu)
25286       && TYPE_CODE (type) != TYPE_CODE_FUNC
25287       && TYPE_CODE (type) != TYPE_CODE_FLT
25288       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25289       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25290       && TYPE_CODE (type) != TYPE_CODE_METHOD
25291       && !HAVE_GNAT_AUX_INFO (type))
25292     INIT_GNAT_SPECIFIC (type);
25293
25294   /* Read DW_AT_allocated and set in type.  */
25295   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25296   if (attr_form_is_block (attr))
25297     {
25298       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25299         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25300     }
25301   else if (attr != NULL)
25302     {
25303       complaint (&symfile_complaints,
25304                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25305                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25306                  sect_offset_str (die->sect_off));
25307     }
25308
25309   /* Read DW_AT_associated and set in type.  */
25310   attr = dwarf2_attr (die, DW_AT_associated, cu);
25311   if (attr_form_is_block (attr))
25312     {
25313       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25314         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25315     }
25316   else if (attr != NULL)
25317     {
25318       complaint (&symfile_complaints,
25319                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25320                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25321                  sect_offset_str (die->sect_off));
25322     }
25323
25324   /* Read DW_AT_data_location and set in type.  */
25325   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25326   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25327     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25328
25329   if (dwarf2_per_objfile->die_type_hash == NULL)
25330     {
25331       dwarf2_per_objfile->die_type_hash =
25332         htab_create_alloc_ex (127,
25333                               per_cu_offset_and_type_hash,
25334                               per_cu_offset_and_type_eq,
25335                               NULL,
25336                               &objfile->objfile_obstack,
25337                               hashtab_obstack_allocate,
25338                               dummy_obstack_deallocate);
25339     }
25340
25341   ofs.per_cu = cu->per_cu;
25342   ofs.sect_off = die->sect_off;
25343   ofs.type = type;
25344   slot = (struct dwarf2_per_cu_offset_and_type **)
25345     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25346   if (*slot)
25347     complaint (&symfile_complaints,
25348                _("A problem internal to GDB: DIE %s has type already set"),
25349                sect_offset_str (die->sect_off));
25350   *slot = XOBNEW (&objfile->objfile_obstack,
25351                   struct dwarf2_per_cu_offset_and_type);
25352   **slot = ofs;
25353   return type;
25354 }
25355
25356 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25357    or return NULL if the die does not have a saved type.  */
25358
25359 static struct type *
25360 get_die_type_at_offset (sect_offset sect_off,
25361                         struct dwarf2_per_cu_data *per_cu)
25362 {
25363   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25364   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25365
25366   if (dwarf2_per_objfile->die_type_hash == NULL)
25367     return NULL;
25368
25369   ofs.per_cu = per_cu;
25370   ofs.sect_off = sect_off;
25371   slot = ((struct dwarf2_per_cu_offset_and_type *)
25372           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25373   if (slot)
25374     return slot->type;
25375   else
25376     return NULL;
25377 }
25378
25379 /* Look up the type for DIE in CU in die_type_hash,
25380    or return NULL if DIE does not have a saved type.  */
25381
25382 static struct type *
25383 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25384 {
25385   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25386 }
25387
25388 /* Add a dependence relationship from CU to REF_PER_CU.  */
25389
25390 static void
25391 dwarf2_add_dependence (struct dwarf2_cu *cu,
25392                        struct dwarf2_per_cu_data *ref_per_cu)
25393 {
25394   void **slot;
25395
25396   if (cu->dependencies == NULL)
25397     cu->dependencies
25398       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25399                               NULL, &cu->comp_unit_obstack,
25400                               hashtab_obstack_allocate,
25401                               dummy_obstack_deallocate);
25402
25403   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25404   if (*slot == NULL)
25405     *slot = ref_per_cu;
25406 }
25407
25408 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25409    Set the mark field in every compilation unit in the
25410    cache that we must keep because we are keeping CU.  */
25411
25412 static int
25413 dwarf2_mark_helper (void **slot, void *data)
25414 {
25415   struct dwarf2_per_cu_data *per_cu;
25416
25417   per_cu = (struct dwarf2_per_cu_data *) *slot;
25418
25419   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25420      reading of the chain.  As such dependencies remain valid it is not much
25421      useful to track and undo them during QUIT cleanups.  */
25422   if (per_cu->cu == NULL)
25423     return 1;
25424
25425   if (per_cu->cu->mark)
25426     return 1;
25427   per_cu->cu->mark = 1;
25428
25429   if (per_cu->cu->dependencies != NULL)
25430     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25431
25432   return 1;
25433 }
25434
25435 /* Set the mark field in CU and in every other compilation unit in the
25436    cache that we must keep because we are keeping CU.  */
25437
25438 static void
25439 dwarf2_mark (struct dwarf2_cu *cu)
25440 {
25441   if (cu->mark)
25442     return;
25443   cu->mark = 1;
25444   if (cu->dependencies != NULL)
25445     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25446 }
25447
25448 static void
25449 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25450 {
25451   while (per_cu)
25452     {
25453       per_cu->cu->mark = 0;
25454       per_cu = per_cu->cu->read_in_chain;
25455     }
25456 }
25457
25458 /* Trivial hash function for partial_die_info: the hash value of a DIE
25459    is its offset in .debug_info for this objfile.  */
25460
25461 static hashval_t
25462 partial_die_hash (const void *item)
25463 {
25464   const struct partial_die_info *part_die
25465     = (const struct partial_die_info *) item;
25466
25467   return to_underlying (part_die->sect_off);
25468 }
25469
25470 /* Trivial comparison function for partial_die_info structures: two DIEs
25471    are equal if they have the same offset.  */
25472
25473 static int
25474 partial_die_eq (const void *item_lhs, const void *item_rhs)
25475 {
25476   const struct partial_die_info *part_die_lhs
25477     = (const struct partial_die_info *) item_lhs;
25478   const struct partial_die_info *part_die_rhs
25479     = (const struct partial_die_info *) item_rhs;
25480
25481   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25482 }
25483
25484 static struct cmd_list_element *set_dwarf_cmdlist;
25485 static struct cmd_list_element *show_dwarf_cmdlist;
25486
25487 static void
25488 set_dwarf_cmd (const char *args, int from_tty)
25489 {
25490   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25491              gdb_stdout);
25492 }
25493
25494 static void
25495 show_dwarf_cmd (const char *args, int from_tty)
25496 {
25497   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25498 }
25499
25500 /* The "save gdb-index" command.  */
25501
25502 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25503    error checking.  */
25504
25505 static void
25506 file_write (FILE *file, const void *data, size_t size)
25507 {
25508   if (fwrite (data, 1, size, file) != size)
25509     error (_("couldn't data write to file"));
25510 }
25511
25512 /* Write the contents of VEC to FILE, with error checking.  */
25513
25514 template<typename Elem, typename Alloc>
25515 static void
25516 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25517 {
25518   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25519 }
25520
25521 /* In-memory buffer to prepare data to be written later to a file.  */
25522 class data_buf
25523 {
25524 public:
25525   /* Copy DATA to the end of the buffer.  */
25526   template<typename T>
25527   void append_data (const T &data)
25528   {
25529     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25530                reinterpret_cast<const gdb_byte *> (&data + 1),
25531                grow (sizeof (data)));
25532   }
25533
25534   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25535      terminating zero is appended too.  */
25536   void append_cstr0 (const char *cstr)
25537   {
25538     const size_t size = strlen (cstr) + 1;
25539     std::copy (cstr, cstr + size, grow (size));
25540   }
25541
25542   /* Store INPUT as ULEB128 to the end of buffer.  */
25543   void append_unsigned_leb128 (ULONGEST input)
25544   {
25545     for (;;)
25546       {
25547         gdb_byte output = input & 0x7f;
25548         input >>= 7;
25549         if (input)
25550           output |= 0x80;
25551         append_data (output);
25552         if (input == 0)
25553           break;
25554       }
25555   }
25556
25557   /* Accept a host-format integer in VAL and append it to the buffer
25558      as a target-format integer which is LEN bytes long.  */
25559   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25560   {
25561     ::store_unsigned_integer (grow (len), len, byte_order, val);
25562   }
25563
25564   /* Return the size of the buffer.  */
25565   size_t size () const
25566   {
25567     return m_vec.size ();
25568   }
25569
25570   /* Return true iff the buffer is empty.  */
25571   bool empty () const
25572   {
25573     return m_vec.empty ();
25574   }
25575
25576   /* Write the buffer to FILE.  */
25577   void file_write (FILE *file) const
25578   {
25579     ::file_write (file, m_vec);
25580   }
25581
25582 private:
25583   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25584      the start of the new block.  */
25585   gdb_byte *grow (size_t size)
25586   {
25587     m_vec.resize (m_vec.size () + size);
25588     return &*m_vec.end () - size;
25589   }
25590
25591   gdb::byte_vector m_vec;
25592 };
25593
25594 /* An entry in the symbol table.  */
25595 struct symtab_index_entry
25596 {
25597   /* The name of the symbol.  */
25598   const char *name;
25599   /* The offset of the name in the constant pool.  */
25600   offset_type index_offset;
25601   /* A sorted vector of the indices of all the CUs that hold an object
25602      of this name.  */
25603   std::vector<offset_type> cu_indices;
25604 };
25605
25606 /* The symbol table.  This is a power-of-2-sized hash table.  */
25607 struct mapped_symtab
25608 {
25609   mapped_symtab ()
25610   {
25611     data.resize (1024);
25612   }
25613
25614   offset_type n_elements = 0;
25615   std::vector<symtab_index_entry> data;
25616 };
25617
25618 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25619    the slot.
25620    
25621    Function is used only during write_hash_table so no index format backward
25622    compatibility is needed.  */
25623
25624 static symtab_index_entry &
25625 find_slot (struct mapped_symtab *symtab, const char *name)
25626 {
25627   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25628
25629   index = hash & (symtab->data.size () - 1);
25630   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25631
25632   for (;;)
25633     {
25634       if (symtab->data[index].name == NULL
25635           || strcmp (name, symtab->data[index].name) == 0)
25636         return symtab->data[index];
25637       index = (index + step) & (symtab->data.size () - 1);
25638     }
25639 }
25640
25641 /* Expand SYMTAB's hash table.  */
25642
25643 static void
25644 hash_expand (struct mapped_symtab *symtab)
25645 {
25646   auto old_entries = std::move (symtab->data);
25647
25648   symtab->data.clear ();
25649   symtab->data.resize (old_entries.size () * 2);
25650
25651   for (auto &it : old_entries)
25652     if (it.name != NULL)
25653       {
25654         auto &ref = find_slot (symtab, it.name);
25655         ref = std::move (it);
25656       }
25657 }
25658
25659 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25660    CU_INDEX is the index of the CU in which the symbol appears.
25661    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25662
25663 static void
25664 add_index_entry (struct mapped_symtab *symtab, const char *name,
25665                  int is_static, gdb_index_symbol_kind kind,
25666                  offset_type cu_index)
25667 {
25668   offset_type cu_index_and_attrs;
25669
25670   ++symtab->n_elements;
25671   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25672     hash_expand (symtab);
25673
25674   symtab_index_entry &slot = find_slot (symtab, name);
25675   if (slot.name == NULL)
25676     {
25677       slot.name = name;
25678       /* index_offset is set later.  */
25679     }
25680
25681   cu_index_and_attrs = 0;
25682   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25683   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25684   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25685
25686   /* We don't want to record an index value twice as we want to avoid the
25687      duplication.
25688      We process all global symbols and then all static symbols
25689      (which would allow us to avoid the duplication by only having to check
25690      the last entry pushed), but a symbol could have multiple kinds in one CU.
25691      To keep things simple we don't worry about the duplication here and
25692      sort and uniqufy the list after we've processed all symbols.  */
25693   slot.cu_indices.push_back (cu_index_and_attrs);
25694 }
25695
25696 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25697
25698 static void
25699 uniquify_cu_indices (struct mapped_symtab *symtab)
25700 {
25701   for (auto &entry : symtab->data)
25702     {
25703       if (entry.name != NULL && !entry.cu_indices.empty ())
25704         {
25705           auto &cu_indices = entry.cu_indices;
25706           std::sort (cu_indices.begin (), cu_indices.end ());
25707           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25708           cu_indices.erase (from, cu_indices.end ());
25709         }
25710     }
25711 }
25712
25713 /* A form of 'const char *' suitable for container keys.  Only the
25714    pointer is stored.  The strings themselves are compared, not the
25715    pointers.  */
25716 class c_str_view
25717 {
25718 public:
25719   c_str_view (const char *cstr)
25720     : m_cstr (cstr)
25721   {}
25722
25723   bool operator== (const c_str_view &other) const
25724   {
25725     return strcmp (m_cstr, other.m_cstr) == 0;
25726   }
25727
25728   /* Return the underlying C string.  Note, the returned string is
25729      only a reference with lifetime of this object.  */
25730   const char *c_str () const
25731   {
25732     return m_cstr;
25733   }
25734
25735 private:
25736   friend class c_str_view_hasher;
25737   const char *const m_cstr;
25738 };
25739
25740 /* A std::unordered_map::hasher for c_str_view that uses the right
25741    hash function for strings in a mapped index.  */
25742 class c_str_view_hasher
25743 {
25744 public:
25745   size_t operator () (const c_str_view &x) const
25746   {
25747     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25748   }
25749 };
25750
25751 /* A std::unordered_map::hasher for std::vector<>.  */
25752 template<typename T>
25753 class vector_hasher
25754 {
25755 public:
25756   size_t operator () (const std::vector<T> &key) const
25757   {
25758     return iterative_hash (key.data (),
25759                            sizeof (key.front ()) * key.size (), 0);
25760   }
25761 };
25762
25763 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25764    constant pool entries going into the data buffer CPOOL.  */
25765
25766 static void
25767 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25768 {
25769   {
25770     /* Elements are sorted vectors of the indices of all the CUs that
25771        hold an object of this name.  */
25772     std::unordered_map<std::vector<offset_type>, offset_type,
25773                        vector_hasher<offset_type>>
25774       symbol_hash_table;
25775
25776     /* We add all the index vectors to the constant pool first, to
25777        ensure alignment is ok.  */
25778     for (symtab_index_entry &entry : symtab->data)
25779       {
25780         if (entry.name == NULL)
25781           continue;
25782         gdb_assert (entry.index_offset == 0);
25783
25784         /* Finding before inserting is faster than always trying to
25785            insert, because inserting always allocates a node, does the
25786            lookup, and then destroys the new node if another node
25787            already had the same key.  C++17 try_emplace will avoid
25788            this.  */
25789         const auto found
25790           = symbol_hash_table.find (entry.cu_indices);
25791         if (found != symbol_hash_table.end ())
25792           {
25793             entry.index_offset = found->second;
25794             continue;
25795           }
25796
25797         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25798         entry.index_offset = cpool.size ();
25799         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25800         for (const auto index : entry.cu_indices)
25801           cpool.append_data (MAYBE_SWAP (index));
25802       }
25803   }
25804
25805   /* Now write out the hash table.  */
25806   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25807   for (const auto &entry : symtab->data)
25808     {
25809       offset_type str_off, vec_off;
25810
25811       if (entry.name != NULL)
25812         {
25813           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25814           if (insertpair.second)
25815             cpool.append_cstr0 (entry.name);
25816           str_off = insertpair.first->second;
25817           vec_off = entry.index_offset;
25818         }
25819       else
25820         {
25821           /* While 0 is a valid constant pool index, it is not valid
25822              to have 0 for both offsets.  */
25823           str_off = 0;
25824           vec_off = 0;
25825         }
25826
25827       output.append_data (MAYBE_SWAP (str_off));
25828       output.append_data (MAYBE_SWAP (vec_off));
25829     }
25830 }
25831
25832 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25833
25834 /* Helper struct for building the address table.  */
25835 struct addrmap_index_data
25836 {
25837   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25838     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25839   {}
25840
25841   struct objfile *objfile;
25842   data_buf &addr_vec;
25843   psym_index_map &cu_index_htab;
25844
25845   /* Non-zero if the previous_* fields are valid.
25846      We can't write an entry until we see the next entry (since it is only then
25847      that we know the end of the entry).  */
25848   int previous_valid;
25849   /* Index of the CU in the table of all CUs in the index file.  */
25850   unsigned int previous_cu_index;
25851   /* Start address of the CU.  */
25852   CORE_ADDR previous_cu_start;
25853 };
25854
25855 /* Write an address entry to ADDR_VEC.  */
25856
25857 static void
25858 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25859                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25860 {
25861   CORE_ADDR baseaddr;
25862
25863   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25864
25865   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25866   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25867   addr_vec.append_data (MAYBE_SWAP (cu_index));
25868 }
25869
25870 /* Worker function for traversing an addrmap to build the address table.  */
25871
25872 static int
25873 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25874 {
25875   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25876   struct partial_symtab *pst = (struct partial_symtab *) obj;
25877
25878   if (data->previous_valid)
25879     add_address_entry (data->objfile, data->addr_vec,
25880                        data->previous_cu_start, start_addr,
25881                        data->previous_cu_index);
25882
25883   data->previous_cu_start = start_addr;
25884   if (pst != NULL)
25885     {
25886       const auto it = data->cu_index_htab.find (pst);
25887       gdb_assert (it != data->cu_index_htab.cend ());
25888       data->previous_cu_index = it->second;
25889       data->previous_valid = 1;
25890     }
25891   else
25892     data->previous_valid = 0;
25893
25894   return 0;
25895 }
25896
25897 /* Write OBJFILE's address map to ADDR_VEC.
25898    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25899    in the index file.  */
25900
25901 static void
25902 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25903                    psym_index_map &cu_index_htab)
25904 {
25905   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25906
25907   /* When writing the address table, we have to cope with the fact that
25908      the addrmap iterator only provides the start of a region; we have to
25909      wait until the next invocation to get the start of the next region.  */
25910
25911   addrmap_index_data.objfile = objfile;
25912   addrmap_index_data.previous_valid = 0;
25913
25914   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25915                    &addrmap_index_data);
25916
25917   /* It's highly unlikely the last entry (end address = 0xff...ff)
25918      is valid, but we should still handle it.
25919      The end address is recorded as the start of the next region, but that
25920      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25921      anyway.  */
25922   if (addrmap_index_data.previous_valid)
25923     add_address_entry (objfile, addr_vec,
25924                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25925                        addrmap_index_data.previous_cu_index);
25926 }
25927
25928 /* Return the symbol kind of PSYM.  */
25929
25930 static gdb_index_symbol_kind
25931 symbol_kind (struct partial_symbol *psym)
25932 {
25933   domain_enum domain = PSYMBOL_DOMAIN (psym);
25934   enum address_class aclass = PSYMBOL_CLASS (psym);
25935
25936   switch (domain)
25937     {
25938     case VAR_DOMAIN:
25939       switch (aclass)
25940         {
25941         case LOC_BLOCK:
25942           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25943         case LOC_TYPEDEF:
25944           return GDB_INDEX_SYMBOL_KIND_TYPE;
25945         case LOC_COMPUTED:
25946         case LOC_CONST_BYTES:
25947         case LOC_OPTIMIZED_OUT:
25948         case LOC_STATIC:
25949           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25950         case LOC_CONST:
25951           /* Note: It's currently impossible to recognize psyms as enum values
25952              short of reading the type info.  For now punt.  */
25953           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25954         default:
25955           /* There are other LOC_FOO values that one might want to classify
25956              as variables, but dwarf2read.c doesn't currently use them.  */
25957           return GDB_INDEX_SYMBOL_KIND_OTHER;
25958         }
25959     case STRUCT_DOMAIN:
25960       return GDB_INDEX_SYMBOL_KIND_TYPE;
25961     default:
25962       return GDB_INDEX_SYMBOL_KIND_OTHER;
25963     }
25964 }
25965
25966 /* Add a list of partial symbols to SYMTAB.  */
25967
25968 static void
25969 write_psymbols (struct mapped_symtab *symtab,
25970                 std::unordered_set<partial_symbol *> &psyms_seen,
25971                 struct partial_symbol **psymp,
25972                 int count,
25973                 offset_type cu_index,
25974                 int is_static)
25975 {
25976   for (; count-- > 0; ++psymp)
25977     {
25978       struct partial_symbol *psym = *psymp;
25979
25980       if (SYMBOL_LANGUAGE (psym) == language_ada)
25981         error (_("Ada is not currently supported by the index"));
25982
25983       /* Only add a given psymbol once.  */
25984       if (psyms_seen.insert (psym).second)
25985         {
25986           gdb_index_symbol_kind kind = symbol_kind (psym);
25987
25988           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25989                            is_static, kind, cu_index);
25990         }
25991     }
25992 }
25993
25994 /* A helper struct used when iterating over debug_types.  */
25995 struct signatured_type_index_data
25996 {
25997   signatured_type_index_data (data_buf &types_list_,
25998                               std::unordered_set<partial_symbol *> &psyms_seen_)
25999     : types_list (types_list_), psyms_seen (psyms_seen_)
26000   {}
26001
26002   struct objfile *objfile;
26003   struct mapped_symtab *symtab;
26004   data_buf &types_list;
26005   std::unordered_set<partial_symbol *> &psyms_seen;
26006   int cu_index;
26007 };
26008
26009 /* A helper function that writes a single signatured_type to an
26010    obstack.  */
26011
26012 static int
26013 write_one_signatured_type (void **slot, void *d)
26014 {
26015   struct signatured_type_index_data *info
26016     = (struct signatured_type_index_data *) d;
26017   struct signatured_type *entry = (struct signatured_type *) *slot;
26018   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26019
26020   write_psymbols (info->symtab,
26021                   info->psyms_seen,
26022                   &info->objfile->global_psymbols[psymtab->globals_offset],
26023                   psymtab->n_global_syms, info->cu_index,
26024                   0);
26025   write_psymbols (info->symtab,
26026                   info->psyms_seen,
26027                   &info->objfile->static_psymbols[psymtab->statics_offset],
26028                   psymtab->n_static_syms, info->cu_index,
26029                   1);
26030
26031   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26032                                 to_underlying (entry->per_cu.sect_off));
26033   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26034                                 to_underlying (entry->type_offset_in_tu));
26035   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26036
26037   ++info->cu_index;
26038
26039   return 1;
26040 }
26041
26042 /* Recurse into all "included" dependencies and count their symbols as
26043    if they appeared in this psymtab.  */
26044
26045 static void
26046 recursively_count_psymbols (struct partial_symtab *psymtab,
26047                             size_t &psyms_seen)
26048 {
26049   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26050     if (psymtab->dependencies[i]->user != NULL)
26051       recursively_count_psymbols (psymtab->dependencies[i],
26052                                   psyms_seen);
26053
26054   psyms_seen += psymtab->n_global_syms;
26055   psyms_seen += psymtab->n_static_syms;
26056 }
26057
26058 /* Recurse into all "included" dependencies and write their symbols as
26059    if they appeared in this psymtab.  */
26060
26061 static void
26062 recursively_write_psymbols (struct objfile *objfile,
26063                             struct partial_symtab *psymtab,
26064                             struct mapped_symtab *symtab,
26065                             std::unordered_set<partial_symbol *> &psyms_seen,
26066                             offset_type cu_index)
26067 {
26068   int i;
26069
26070   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26071     if (psymtab->dependencies[i]->user != NULL)
26072       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26073                                   symtab, psyms_seen, cu_index);
26074
26075   write_psymbols (symtab,
26076                   psyms_seen,
26077                   &objfile->global_psymbols[psymtab->globals_offset],
26078                   psymtab->n_global_syms, cu_index,
26079                   0);
26080   write_psymbols (symtab,
26081                   psyms_seen,
26082                   &objfile->static_psymbols[psymtab->statics_offset],
26083                   psymtab->n_static_syms, cu_index,
26084                   1);
26085 }
26086
26087 /* DWARF-5 .debug_names builder.  */
26088 class debug_names
26089 {
26090 public:
26091   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26092                bfd_endian dwarf5_byte_order)
26093     : m_dwarf5_byte_order (dwarf5_byte_order),
26094       m_dwarf32 (dwarf5_byte_order),
26095       m_dwarf64 (dwarf5_byte_order),
26096       m_dwarf (is_dwarf64
26097                ? static_cast<dwarf &> (m_dwarf64)
26098                : static_cast<dwarf &> (m_dwarf32)),
26099       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26100       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26101       m_debugstrlookup (dwarf2_per_objfile)
26102   {}
26103
26104   int dwarf5_offset_size () const
26105   {
26106     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26107     return dwarf5_is_dwarf64 ? 8 : 4;
26108   }
26109
26110   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26111   enum class unit_kind { cu, tu };
26112
26113   /* Insert one symbol.  */
26114   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26115                unit_kind kind)
26116   {
26117     const int dwarf_tag = psymbol_tag (psym);
26118     if (dwarf_tag == 0)
26119       return;
26120     const char *const name = SYMBOL_SEARCH_NAME (psym);
26121     const auto insertpair
26122       = m_name_to_value_set.emplace (c_str_view (name),
26123                                      std::set<symbol_value> ());
26124     std::set<symbol_value> &value_set = insertpair.first->second;
26125     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26126   }
26127
26128   /* Build all the tables.  All symbols must be already inserted.
26129      This function does not call file_write, caller has to do it
26130      afterwards.  */
26131   void build ()
26132   {
26133     /* Verify the build method has not be called twice.  */
26134     gdb_assert (m_abbrev_table.empty ());
26135     const size_t name_count = m_name_to_value_set.size ();
26136     m_bucket_table.resize
26137       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26138     m_hash_table.reserve (name_count);
26139     m_name_table_string_offs.reserve (name_count);
26140     m_name_table_entry_offs.reserve (name_count);
26141
26142     /* Map each hash of symbol to its name and value.  */
26143     struct hash_it_pair
26144     {
26145       uint32_t hash;
26146       decltype (m_name_to_value_set)::const_iterator it;
26147     };
26148     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26149     bucket_hash.resize (m_bucket_table.size ());
26150     for (decltype (m_name_to_value_set)::const_iterator it
26151            = m_name_to_value_set.cbegin ();
26152          it != m_name_to_value_set.cend ();
26153          ++it)
26154       {
26155         const char *const name = it->first.c_str ();
26156         const uint32_t hash = dwarf5_djb_hash (name);
26157         hash_it_pair hashitpair;
26158         hashitpair.hash = hash;
26159         hashitpair.it = it;
26160         auto &slot = bucket_hash[hash % bucket_hash.size()];
26161         slot.push_front (std::move (hashitpair));
26162       }
26163     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26164       {
26165         const std::forward_list<hash_it_pair> &hashitlist
26166           = bucket_hash[bucket_ix];
26167         if (hashitlist.empty ())
26168           continue;
26169         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26170         /* The hashes array is indexed starting at 1.  */
26171         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26172                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26173                                 m_hash_table.size () + 1);
26174         for (const hash_it_pair &hashitpair : hashitlist)
26175           {
26176             m_hash_table.push_back (0);
26177             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26178                                                         (&m_hash_table.back ()),
26179                                     sizeof (m_hash_table.back ()),
26180                                     m_dwarf5_byte_order, hashitpair.hash);
26181             const c_str_view &name = hashitpair.it->first;
26182             const std::set<symbol_value> &value_set = hashitpair.it->second;
26183             m_name_table_string_offs.push_back_reorder
26184               (m_debugstrlookup.lookup (name.c_str ()));
26185             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26186             gdb_assert (!value_set.empty ());
26187             for (const symbol_value &value : value_set)
26188               {
26189                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26190                                                         value.is_static,
26191                                                         value.kind)];
26192                 if (idx == 0)
26193                   {
26194                     idx = m_idx_next++;
26195                     m_abbrev_table.append_unsigned_leb128 (idx);
26196                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26197                     m_abbrev_table.append_unsigned_leb128
26198                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26199                                                            : DW_IDX_type_unit);
26200                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26201                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26202                                                            ? DW_IDX_GNU_internal
26203                                                            : DW_IDX_GNU_external);
26204                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26205
26206                     /* Terminate attributes list.  */
26207                     m_abbrev_table.append_unsigned_leb128 (0);
26208                     m_abbrev_table.append_unsigned_leb128 (0);
26209                   }
26210
26211                 m_entry_pool.append_unsigned_leb128 (idx);
26212                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26213               }
26214
26215             /* Terminate the list of CUs.  */
26216             m_entry_pool.append_unsigned_leb128 (0);
26217           }
26218       }
26219     gdb_assert (m_hash_table.size () == name_count);
26220
26221     /* Terminate tags list.  */
26222     m_abbrev_table.append_unsigned_leb128 (0);
26223   }
26224
26225   /* Return .debug_names bucket count.  This must be called only after
26226      calling the build method.  */
26227   uint32_t bucket_count () const
26228   {
26229     /* Verify the build method has been already called.  */
26230     gdb_assert (!m_abbrev_table.empty ());
26231     const uint32_t retval = m_bucket_table.size ();
26232
26233     /* Check for overflow.  */
26234     gdb_assert (retval == m_bucket_table.size ());
26235     return retval;
26236   }
26237
26238   /* Return .debug_names names count.  This must be called only after
26239      calling the build method.  */
26240   uint32_t name_count () const
26241   {
26242     /* Verify the build method has been already called.  */
26243     gdb_assert (!m_abbrev_table.empty ());
26244     const uint32_t retval = m_hash_table.size ();
26245
26246     /* Check for overflow.  */
26247     gdb_assert (retval == m_hash_table.size ());
26248     return retval;
26249   }
26250
26251   /* Return number of bytes of .debug_names abbreviation table.  This
26252      must be called only after calling the build method.  */
26253   uint32_t abbrev_table_bytes () const
26254   {
26255     gdb_assert (!m_abbrev_table.empty ());
26256     return m_abbrev_table.size ();
26257   }
26258
26259   /* Recurse into all "included" dependencies and store their symbols
26260      as if they appeared in this psymtab.  */
26261   void recursively_write_psymbols
26262     (struct objfile *objfile,
26263      struct partial_symtab *psymtab,
26264      std::unordered_set<partial_symbol *> &psyms_seen,
26265      int cu_index)
26266   {
26267     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26268       if (psymtab->dependencies[i]->user != NULL)
26269         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26270                                     psyms_seen, cu_index);
26271
26272     write_psymbols (psyms_seen,
26273                     &objfile->global_psymbols[psymtab->globals_offset],
26274                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26275     write_psymbols (psyms_seen,
26276                     &objfile->static_psymbols[psymtab->statics_offset],
26277                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26278   }
26279
26280   /* Return number of bytes the .debug_names section will have.  This
26281      must be called only after calling the build method.  */
26282   size_t bytes () const
26283   {
26284     /* Verify the build method has been already called.  */
26285     gdb_assert (!m_abbrev_table.empty ());
26286     size_t expected_bytes = 0;
26287     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26288     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26289     expected_bytes += m_name_table_string_offs.bytes ();
26290     expected_bytes += m_name_table_entry_offs.bytes ();
26291     expected_bytes += m_abbrev_table.size ();
26292     expected_bytes += m_entry_pool.size ();
26293     return expected_bytes;
26294   }
26295
26296   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26297      FILE_STR.  This must be called only after calling the build
26298      method.  */
26299   void file_write (FILE *file_names, FILE *file_str) const
26300   {
26301     /* Verify the build method has been already called.  */
26302     gdb_assert (!m_abbrev_table.empty ());
26303     ::file_write (file_names, m_bucket_table);
26304     ::file_write (file_names, m_hash_table);
26305     m_name_table_string_offs.file_write (file_names);
26306     m_name_table_entry_offs.file_write (file_names);
26307     m_abbrev_table.file_write (file_names);
26308     m_entry_pool.file_write (file_names);
26309     m_debugstrlookup.file_write (file_str);
26310   }
26311
26312   /* A helper user data for write_one_signatured_type.  */
26313   class write_one_signatured_type_data
26314   {
26315   public:
26316     write_one_signatured_type_data (debug_names &nametable_,
26317                                     signatured_type_index_data &&info_)
26318     : nametable (nametable_), info (std::move (info_))
26319     {}
26320     debug_names &nametable;
26321     struct signatured_type_index_data info;
26322   };
26323
26324   /* A helper function to pass write_one_signatured_type to
26325      htab_traverse_noresize.  */
26326   static int
26327   write_one_signatured_type (void **slot, void *d)
26328   {
26329     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26330     struct signatured_type_index_data *info = &data->info;
26331     struct signatured_type *entry = (struct signatured_type *) *slot;
26332
26333     data->nametable.write_one_signatured_type (entry, info);
26334
26335     return 1;
26336   }
26337
26338 private:
26339
26340   /* Storage for symbol names mapping them to their .debug_str section
26341      offsets.  */
26342   class debug_str_lookup
26343   {
26344   public:
26345
26346     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26347        All .debug_str section strings are automatically stored.  */
26348     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26349       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26350         m_dwarf2_per_objfile (dwarf2_per_objfile)
26351     {
26352       dwarf2_read_section (dwarf2_per_objfile->objfile,
26353                            &dwarf2_per_objfile->str);
26354       if (dwarf2_per_objfile->str.buffer == NULL)
26355         return;
26356       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26357            data < (dwarf2_per_objfile->str.buffer
26358                    + dwarf2_per_objfile->str.size);)
26359         {
26360           const char *const s = reinterpret_cast<const char *> (data);
26361           const auto insertpair
26362             = m_str_table.emplace (c_str_view (s),
26363                                    data - dwarf2_per_objfile->str.buffer);
26364           if (!insertpair.second)
26365             complaint (&symfile_complaints,
26366                        _("Duplicate string \"%s\" in "
26367                          ".debug_str section [in module %s]"),
26368                        s, bfd_get_filename (m_abfd));
26369           data += strlen (s) + 1;
26370         }
26371     }
26372
26373     /* Return offset of symbol name S in the .debug_str section.  Add
26374        such symbol to the section's end if it does not exist there
26375        yet.  */
26376     size_t lookup (const char *s)
26377     {
26378       const auto it = m_str_table.find (c_str_view (s));
26379       if (it != m_str_table.end ())
26380         return it->second;
26381       const size_t offset = (m_dwarf2_per_objfile->str.size
26382                              + m_str_add_buf.size ());
26383       m_str_table.emplace (c_str_view (s), offset);
26384       m_str_add_buf.append_cstr0 (s);
26385       return offset;
26386     }
26387
26388     /* Append the end of the .debug_str section to FILE.  */
26389     void file_write (FILE *file) const
26390     {
26391       m_str_add_buf.file_write (file);
26392     }
26393
26394   private:
26395     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26396     bfd *const m_abfd;
26397     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26398
26399     /* Data to add at the end of .debug_str for new needed symbol names.  */
26400     data_buf m_str_add_buf;
26401   };
26402
26403   /* Container to map used DWARF tags to their .debug_names abbreviation
26404      tags.  */
26405   class index_key
26406   {
26407   public:
26408     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26409       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26410     {
26411     }
26412
26413     bool
26414     operator== (const index_key &other) const
26415     {
26416       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26417               && kind == other.kind);
26418     }
26419
26420     const int dwarf_tag;
26421     const bool is_static;
26422     const unit_kind kind;
26423   };
26424
26425   /* Provide std::unordered_map::hasher for index_key.  */
26426   class index_key_hasher
26427   {
26428   public:
26429     size_t
26430     operator () (const index_key &key) const
26431     {
26432       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26433     }
26434   };
26435
26436   /* Parameters of one symbol entry.  */
26437   class symbol_value
26438   {
26439   public:
26440     const int dwarf_tag, cu_index;
26441     const bool is_static;
26442     const unit_kind kind;
26443
26444     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26445                   unit_kind kind_)
26446       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26447         kind (kind_)
26448     {}
26449
26450     bool
26451     operator< (const symbol_value &other) const
26452     {
26453 #define X(n) \
26454   do \
26455     { \
26456       if (n < other.n) \
26457         return true; \
26458       if (n > other.n) \
26459         return false; \
26460     } \
26461   while (0)
26462       X (dwarf_tag);
26463       X (is_static);
26464       X (kind);
26465       X (cu_index);
26466 #undef X
26467       return false;
26468     }
26469   };
26470
26471   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26472      output.  */
26473   class offset_vec
26474   {
26475   protected:
26476     const bfd_endian dwarf5_byte_order;
26477   public:
26478     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26479       : dwarf5_byte_order (dwarf5_byte_order_)
26480     {}
26481
26482     /* Call std::vector::reserve for NELEM elements.  */
26483     virtual void reserve (size_t nelem) = 0;
26484
26485     /* Call std::vector::push_back with store_unsigned_integer byte
26486        reordering for ELEM.  */
26487     virtual void push_back_reorder (size_t elem) = 0;
26488
26489     /* Return expected output size in bytes.  */
26490     virtual size_t bytes () const = 0;
26491
26492     /* Write name table to FILE.  */
26493     virtual void file_write (FILE *file) const = 0;
26494   };
26495
26496   /* Template to unify DWARF-32 and DWARF-64 output.  */
26497   template<typename OffsetSize>
26498   class offset_vec_tmpl : public offset_vec
26499   {
26500   public:
26501     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26502       : offset_vec (dwarf5_byte_order_)
26503     {}
26504
26505     /* Implement offset_vec::reserve.  */
26506     void reserve (size_t nelem) override
26507     {
26508       m_vec.reserve (nelem);
26509     }
26510
26511     /* Implement offset_vec::push_back_reorder.  */
26512     void push_back_reorder (size_t elem) override
26513     {
26514       m_vec.push_back (elem);
26515       /* Check for overflow.  */
26516       gdb_assert (m_vec.back () == elem);
26517       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26518                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26519     }
26520
26521     /* Implement offset_vec::bytes.  */
26522     size_t bytes () const override
26523     {
26524       return m_vec.size () * sizeof (m_vec[0]);
26525     }
26526
26527     /* Implement offset_vec::file_write.  */
26528     void file_write (FILE *file) const override
26529     {
26530       ::file_write (file, m_vec);
26531     }
26532
26533   private:
26534     std::vector<OffsetSize> m_vec;
26535   };
26536
26537   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26538      respecting name table width.  */
26539   class dwarf
26540   {
26541   public:
26542     offset_vec &name_table_string_offs, &name_table_entry_offs;
26543
26544     dwarf (offset_vec &name_table_string_offs_,
26545            offset_vec &name_table_entry_offs_)
26546       : name_table_string_offs (name_table_string_offs_),
26547         name_table_entry_offs (name_table_entry_offs_)
26548     {
26549     }
26550   };
26551
26552   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26553      respecting name table width.  */
26554   template<typename OffsetSize>
26555   class dwarf_tmpl : public dwarf
26556   {
26557   public:
26558     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26559       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26560         m_name_table_string_offs (dwarf5_byte_order_),
26561         m_name_table_entry_offs (dwarf5_byte_order_)
26562     {}
26563
26564   private:
26565     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26566     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26567   };
26568
26569   /* Try to reconstruct original DWARF tag for given partial_symbol.
26570      This function is not DWARF-5 compliant but it is sufficient for
26571      GDB as a DWARF-5 index consumer.  */
26572   static int psymbol_tag (const struct partial_symbol *psym)
26573   {
26574     domain_enum domain = PSYMBOL_DOMAIN (psym);
26575     enum address_class aclass = PSYMBOL_CLASS (psym);
26576
26577     switch (domain)
26578       {
26579       case VAR_DOMAIN:
26580         switch (aclass)
26581           {
26582           case LOC_BLOCK:
26583             return DW_TAG_subprogram;
26584           case LOC_TYPEDEF:
26585             return DW_TAG_typedef;
26586           case LOC_COMPUTED:
26587           case LOC_CONST_BYTES:
26588           case LOC_OPTIMIZED_OUT:
26589           case LOC_STATIC:
26590             return DW_TAG_variable;
26591           case LOC_CONST:
26592             /* Note: It's currently impossible to recognize psyms as enum values
26593                short of reading the type info.  For now punt.  */
26594             return DW_TAG_variable;
26595           default:
26596             /* There are other LOC_FOO values that one might want to classify
26597                as variables, but dwarf2read.c doesn't currently use them.  */
26598             return DW_TAG_variable;
26599           }
26600       case STRUCT_DOMAIN:
26601         return DW_TAG_structure_type;
26602       default:
26603         return 0;
26604       }
26605   }
26606
26607   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26608   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26609                        struct partial_symbol **psymp, int count, int cu_index,
26610                        bool is_static, unit_kind kind)
26611   {
26612     for (; count-- > 0; ++psymp)
26613       {
26614         struct partial_symbol *psym = *psymp;
26615
26616         if (SYMBOL_LANGUAGE (psym) == language_ada)
26617           error (_("Ada is not currently supported by the index"));
26618
26619         /* Only add a given psymbol once.  */
26620         if (psyms_seen.insert (psym).second)
26621           insert (psym, cu_index, is_static, kind);
26622       }
26623   }
26624
26625   /* A helper function that writes a single signatured_type
26626      to a debug_names.  */
26627   void
26628   write_one_signatured_type (struct signatured_type *entry,
26629                              struct signatured_type_index_data *info)
26630   {
26631     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26632
26633     write_psymbols (info->psyms_seen,
26634                     &info->objfile->global_psymbols[psymtab->globals_offset],
26635                     psymtab->n_global_syms, info->cu_index, false,
26636                     unit_kind::tu);
26637     write_psymbols (info->psyms_seen,
26638                     &info->objfile->static_psymbols[psymtab->statics_offset],
26639                     psymtab->n_static_syms, info->cu_index, true,
26640                     unit_kind::tu);
26641
26642     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26643                                   to_underlying (entry->per_cu.sect_off));
26644
26645     ++info->cu_index;
26646   }
26647
26648   /* Store value of each symbol.  */
26649   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26650     m_name_to_value_set;
26651
26652   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26653      order.  */
26654   std::vector<uint32_t> m_bucket_table;
26655   std::vector<uint32_t> m_hash_table;
26656
26657   const bfd_endian m_dwarf5_byte_order;
26658   dwarf_tmpl<uint32_t> m_dwarf32;
26659   dwarf_tmpl<uint64_t> m_dwarf64;
26660   dwarf &m_dwarf;
26661   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26662   debug_str_lookup m_debugstrlookup;
26663
26664   /* Map each used .debug_names abbreviation tag parameter to its
26665      index value.  */
26666   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26667
26668   /* Next unused .debug_names abbreviation tag for
26669      m_indexkey_to_idx.  */
26670   int m_idx_next = 1;
26671
26672   /* .debug_names abbreviation table.  */
26673   data_buf m_abbrev_table;
26674
26675   /* .debug_names entry pool.  */
26676   data_buf m_entry_pool;
26677 };
26678
26679 /* Return iff any of the needed offsets does not fit into 32-bit
26680    .debug_names section.  */
26681
26682 static bool
26683 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26684 {
26685   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26686     {
26687       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26688
26689       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26690         return true;
26691     }
26692   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26693     {
26694       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26695       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26696
26697       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26698         return true;
26699     }
26700   return false;
26701 }
26702
26703 /* The psyms_seen set is potentially going to be largish (~40k
26704    elements when indexing a -g3 build of GDB itself).  Estimate the
26705    number of elements in order to avoid too many rehashes, which
26706    require rebuilding buckets and thus many trips to
26707    malloc/free.  */
26708
26709 static size_t
26710 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26711 {
26712   size_t psyms_count = 0;
26713   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26714     {
26715       struct dwarf2_per_cu_data *per_cu
26716         = dwarf2_per_objfile->all_comp_units[i];
26717       struct partial_symtab *psymtab = per_cu->v.psymtab;
26718
26719       if (psymtab != NULL && psymtab->user == NULL)
26720         recursively_count_psymbols (psymtab, psyms_count);
26721     }
26722   /* Generating an index for gdb itself shows a ratio of
26723      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26724   return psyms_count / 4;
26725 }
26726
26727 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26728    Return how many bytes were expected to be written into OUT_FILE.  */
26729
26730 static size_t
26731 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26732 {
26733   struct objfile *objfile = dwarf2_per_objfile->objfile;
26734   mapped_symtab symtab;
26735   data_buf cu_list;
26736
26737   /* While we're scanning CU's create a table that maps a psymtab pointer
26738      (which is what addrmap records) to its index (which is what is recorded
26739      in the index file).  This will later be needed to write the address
26740      table.  */
26741   psym_index_map cu_index_htab;
26742   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26743
26744   /* The CU list is already sorted, so we don't need to do additional
26745      work here.  Also, the debug_types entries do not appear in
26746      all_comp_units, but only in their own hash table.  */
26747
26748   std::unordered_set<partial_symbol *> psyms_seen
26749     (psyms_seen_size (dwarf2_per_objfile));
26750   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26751     {
26752       struct dwarf2_per_cu_data *per_cu
26753         = dwarf2_per_objfile->all_comp_units[i];
26754       struct partial_symtab *psymtab = per_cu->v.psymtab;
26755
26756       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26757          It may be referenced from a local scope but in such case it does not
26758          need to be present in .gdb_index.  */
26759       if (psymtab == NULL)
26760         continue;
26761
26762       if (psymtab->user == NULL)
26763         recursively_write_psymbols (objfile, psymtab, &symtab,
26764                                     psyms_seen, i);
26765
26766       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26767       gdb_assert (insertpair.second);
26768
26769       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26770                            to_underlying (per_cu->sect_off));
26771       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26772     }
26773
26774   /* Dump the address map.  */
26775   data_buf addr_vec;
26776   write_address_map (objfile, addr_vec, cu_index_htab);
26777
26778   /* Write out the .debug_type entries, if any.  */
26779   data_buf types_cu_list;
26780   if (dwarf2_per_objfile->signatured_types)
26781     {
26782       signatured_type_index_data sig_data (types_cu_list,
26783                                            psyms_seen);
26784
26785       sig_data.objfile = objfile;
26786       sig_data.symtab = &symtab;
26787       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26788       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26789                               write_one_signatured_type, &sig_data);
26790     }
26791
26792   /* Now that we've processed all symbols we can shrink their cu_indices
26793      lists.  */
26794   uniquify_cu_indices (&symtab);
26795
26796   data_buf symtab_vec, constant_pool;
26797   write_hash_table (&symtab, symtab_vec, constant_pool);
26798
26799   data_buf contents;
26800   const offset_type size_of_contents = 6 * sizeof (offset_type);
26801   offset_type total_len = size_of_contents;
26802
26803   /* The version number.  */
26804   contents.append_data (MAYBE_SWAP (8));
26805
26806   /* The offset of the CU list from the start of the file.  */
26807   contents.append_data (MAYBE_SWAP (total_len));
26808   total_len += cu_list.size ();
26809
26810   /* The offset of the types CU list from the start of the file.  */
26811   contents.append_data (MAYBE_SWAP (total_len));
26812   total_len += types_cu_list.size ();
26813
26814   /* The offset of the address table from the start of the file.  */
26815   contents.append_data (MAYBE_SWAP (total_len));
26816   total_len += addr_vec.size ();
26817
26818   /* The offset of the symbol table from the start of the file.  */
26819   contents.append_data (MAYBE_SWAP (total_len));
26820   total_len += symtab_vec.size ();
26821
26822   /* The offset of the constant pool from the start of the file.  */
26823   contents.append_data (MAYBE_SWAP (total_len));
26824   total_len += constant_pool.size ();
26825
26826   gdb_assert (contents.size () == size_of_contents);
26827
26828   contents.file_write (out_file);
26829   cu_list.file_write (out_file);
26830   types_cu_list.file_write (out_file);
26831   addr_vec.file_write (out_file);
26832   symtab_vec.file_write (out_file);
26833   constant_pool.file_write (out_file);
26834
26835   return total_len;
26836 }
26837
26838 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26839 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26840
26841 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26842    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26843    many bytes were expected to be written into OUT_FILE.  */
26844
26845 static size_t
26846 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26847                    FILE *out_file, FILE *out_file_str)
26848 {
26849   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26850   struct objfile *objfile = dwarf2_per_objfile->objfile;
26851   const enum bfd_endian dwarf5_byte_order
26852     = gdbarch_byte_order (get_objfile_arch (objfile));
26853
26854   /* The CU list is already sorted, so we don't need to do additional
26855      work here.  Also, the debug_types entries do not appear in
26856      all_comp_units, but only in their own hash table.  */
26857   data_buf cu_list;
26858   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26859                          dwarf5_byte_order);
26860   std::unordered_set<partial_symbol *>
26861     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26862   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26863     {
26864       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26865       partial_symtab *psymtab = per_cu->v.psymtab;
26866
26867       /* CU of a shared file from 'dwz -m' may be unused by this main
26868          file.  It may be referenced from a local scope but in such
26869          case it does not need to be present in .debug_names.  */
26870       if (psymtab == NULL)
26871         continue;
26872
26873       if (psymtab->user == NULL)
26874         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26875
26876       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26877                            to_underlying (per_cu->sect_off));
26878     }
26879
26880   /* Write out the .debug_type entries, if any.  */
26881   data_buf types_cu_list;
26882   if (dwarf2_per_objfile->signatured_types)
26883     {
26884       debug_names::write_one_signatured_type_data sig_data (nametable,
26885                         signatured_type_index_data (types_cu_list, psyms_seen));
26886
26887       sig_data.info.objfile = objfile;
26888       /* It is used only for gdb_index.  */
26889       sig_data.info.symtab = nullptr;
26890       sig_data.info.cu_index = 0;
26891       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26892                               debug_names::write_one_signatured_type,
26893                               &sig_data);
26894     }
26895
26896   nametable.build ();
26897
26898   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26899
26900   const offset_type bytes_of_header
26901     = ((dwarf5_is_dwarf64 ? 12 : 4)
26902        + 2 + 2 + 7 * 4
26903        + sizeof (dwarf5_gdb_augmentation));
26904   size_t expected_bytes = 0;
26905   expected_bytes += bytes_of_header;
26906   expected_bytes += cu_list.size ();
26907   expected_bytes += types_cu_list.size ();
26908   expected_bytes += nametable.bytes ();
26909   data_buf header;
26910
26911   if (!dwarf5_is_dwarf64)
26912     {
26913       const uint64_t size64 = expected_bytes - 4;
26914       gdb_assert (size64 < 0xfffffff0);
26915       header.append_uint (4, dwarf5_byte_order, size64);
26916     }
26917   else
26918     {
26919       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26920       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26921     }
26922
26923   /* The version number.  */
26924   header.append_uint (2, dwarf5_byte_order, 5);
26925
26926   /* Padding.  */
26927   header.append_uint (2, dwarf5_byte_order, 0);
26928
26929   /* comp_unit_count - The number of CUs in the CU list.  */
26930   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26931
26932   /* local_type_unit_count - The number of TUs in the local TU
26933      list.  */
26934   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26935
26936   /* foreign_type_unit_count - The number of TUs in the foreign TU
26937      list.  */
26938   header.append_uint (4, dwarf5_byte_order, 0);
26939
26940   /* bucket_count - The number of hash buckets in the hash lookup
26941      table.  */
26942   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26943
26944   /* name_count - The number of unique names in the index.  */
26945   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26946
26947   /* abbrev_table_size - The size in bytes of the abbreviations
26948      table.  */
26949   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26950
26951   /* augmentation_string_size - The size in bytes of the augmentation
26952      string.  This value is rounded up to a multiple of 4.  */
26953   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26954   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26955   header.append_data (dwarf5_gdb_augmentation);
26956
26957   gdb_assert (header.size () == bytes_of_header);
26958
26959   header.file_write (out_file);
26960   cu_list.file_write (out_file);
26961   types_cu_list.file_write (out_file);
26962   nametable.file_write (out_file, out_file_str);
26963
26964   return expected_bytes;
26965 }
26966
26967 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26968    position is at the end of the file.  */
26969
26970 static void
26971 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26972 {
26973   const auto file_size = ftell (file);
26974   if (file_size == -1)
26975     error (_("Can't get `%s' size"), filename);
26976   gdb_assert (file_size == expected_size);
26977 }
26978
26979 /* Create an index file for OBJFILE in the directory DIR.  */
26980
26981 static void
26982 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
26983                          const char *dir,
26984                          dw_index_kind index_kind)
26985 {
26986   struct objfile *objfile = dwarf2_per_objfile->objfile;
26987
26988   if (dwarf2_per_objfile->using_index)
26989     error (_("Cannot use an index to create the index"));
26990
26991   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26992     error (_("Cannot make an index when the file has multiple .debug_types sections"));
26993
26994   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
26995     return;
26996
26997   struct stat st;
26998   if (stat (objfile_name (objfile), &st) < 0)
26999     perror_with_name (objfile_name (objfile));
27000
27001   std::string filename (std::string (dir) + SLASH_STRING
27002                         + lbasename (objfile_name (objfile))
27003                         + (index_kind == dw_index_kind::DEBUG_NAMES
27004                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27005
27006   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27007   if (!out_file)
27008     error (_("Can't open `%s' for writing"), filename.c_str ());
27009
27010   /* Order matters here; we want FILE to be closed before FILENAME is
27011      unlinked, because on MS-Windows one cannot delete a file that is
27012      still open.  (Don't call anything here that might throw until
27013      file_closer is created.)  */
27014   gdb::unlinker unlink_file (filename.c_str ());
27015   gdb_file_up close_out_file (out_file);
27016
27017   if (index_kind == dw_index_kind::DEBUG_NAMES)
27018     {
27019       std::string filename_str (std::string (dir) + SLASH_STRING
27020                                 + lbasename (objfile_name (objfile))
27021                                 + DEBUG_STR_SUFFIX);
27022       FILE *out_file_str
27023         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27024       if (!out_file_str)
27025         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27026       gdb::unlinker unlink_file_str (filename_str.c_str ());
27027       gdb_file_up close_out_file_str (out_file_str);
27028
27029       const size_t total_len
27030         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27031       assert_file_size (out_file, filename.c_str (), total_len);
27032
27033       /* We want to keep the file .debug_str file too.  */
27034       unlink_file_str.keep ();
27035     }
27036   else
27037     {
27038       const size_t total_len
27039         = write_gdbindex (dwarf2_per_objfile, out_file);
27040       assert_file_size (out_file, filename.c_str (), total_len);
27041     }
27042
27043   /* We want to keep the file.  */
27044   unlink_file.keep ();
27045 }
27046
27047 /* Implementation of the `save gdb-index' command.
27048    
27049    Note that the .gdb_index file format used by this command is
27050    documented in the GDB manual.  Any changes here must be documented
27051    there.  */
27052
27053 static void
27054 save_gdb_index_command (const char *arg, int from_tty)
27055 {
27056   struct objfile *objfile;
27057   const char dwarf5space[] = "-dwarf-5 ";
27058   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27059
27060   if (!arg)
27061     arg = "";
27062
27063   arg = skip_spaces (arg);
27064   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27065     {
27066       index_kind = dw_index_kind::DEBUG_NAMES;
27067       arg += strlen (dwarf5space);
27068       arg = skip_spaces (arg);
27069     }
27070
27071   if (!*arg)
27072     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27073
27074   ALL_OBJFILES (objfile)
27075   {
27076     struct stat st;
27077
27078     /* If the objfile does not correspond to an actual file, skip it.  */
27079     if (stat (objfile_name (objfile), &st) < 0)
27080       continue;
27081
27082     struct dwarf2_per_objfile *dwarf2_per_objfile
27083       = get_dwarf2_per_objfile (objfile);
27084
27085     if (dwarf2_per_objfile != NULL)
27086       {
27087         TRY
27088           {
27089             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27090           }
27091         CATCH (except, RETURN_MASK_ERROR)
27092           {
27093             exception_fprintf (gdb_stderr, except,
27094                                _("Error while writing index for `%s': "),
27095                                objfile_name (objfile));
27096           }
27097         END_CATCH
27098       }
27099
27100   }
27101 }
27102
27103 \f
27104
27105 int dwarf_always_disassemble;
27106
27107 static void
27108 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27109                                struct cmd_list_element *c, const char *value)
27110 {
27111   fprintf_filtered (file,
27112                     _("Whether to always disassemble "
27113                       "DWARF expressions is %s.\n"),
27114                     value);
27115 }
27116
27117 static void
27118 show_check_physname (struct ui_file *file, int from_tty,
27119                      struct cmd_list_element *c, const char *value)
27120 {
27121   fprintf_filtered (file,
27122                     _("Whether to check \"physname\" is %s.\n"),
27123                     value);
27124 }
27125
27126 void
27127 _initialize_dwarf2_read (void)
27128 {
27129   struct cmd_list_element *c;
27130
27131   dwarf2_objfile_data_key = register_objfile_data ();
27132
27133   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27134 Set DWARF specific variables.\n\
27135 Configure DWARF variables such as the cache size"),
27136                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27137                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27138
27139   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27140 Show DWARF specific variables\n\
27141 Show DWARF variables such as the cache size"),
27142                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27143                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27144
27145   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27146                             &dwarf_max_cache_age, _("\
27147 Set the upper bound on the age of cached DWARF compilation units."), _("\
27148 Show the upper bound on the age of cached DWARF compilation units."), _("\
27149 A higher limit means that cached compilation units will be stored\n\
27150 in memory longer, and more total memory will be used.  Zero disables\n\
27151 caching, which can slow down startup."),
27152                             NULL,
27153                             show_dwarf_max_cache_age,
27154                             &set_dwarf_cmdlist,
27155                             &show_dwarf_cmdlist);
27156
27157   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27158                            &dwarf_always_disassemble, _("\
27159 Set whether `info address' always disassembles DWARF expressions."), _("\
27160 Show whether `info address' always disassembles DWARF expressions."), _("\
27161 When enabled, DWARF expressions are always printed in an assembly-like\n\
27162 syntax.  When disabled, expressions will be printed in a more\n\
27163 conversational style, when possible."),
27164                            NULL,
27165                            show_dwarf_always_disassemble,
27166                            &set_dwarf_cmdlist,
27167                            &show_dwarf_cmdlist);
27168
27169   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27170 Set debugging of the DWARF reader."), _("\
27171 Show debugging of the DWARF reader."), _("\
27172 When enabled (non-zero), debugging messages are printed during DWARF\n\
27173 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27174 information.  A value greater than 1 provides more verbose information."),
27175                             NULL,
27176                             NULL,
27177                             &setdebuglist, &showdebuglist);
27178
27179   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27180 Set debugging of the DWARF DIE reader."), _("\
27181 Show debugging of the DWARF DIE reader."), _("\
27182 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27183 The value is the maximum depth to print."),
27184                              NULL,
27185                              NULL,
27186                              &setdebuglist, &showdebuglist);
27187
27188   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27189 Set debugging of the dwarf line reader."), _("\
27190 Show debugging of the dwarf line reader."), _("\
27191 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27192 A value of 1 (one) provides basic information.\n\
27193 A value greater than 1 provides more verbose information."),
27194                              NULL,
27195                              NULL,
27196                              &setdebuglist, &showdebuglist);
27197
27198   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27199 Set cross-checking of \"physname\" code against demangler."), _("\
27200 Show cross-checking of \"physname\" code against demangler."), _("\
27201 When enabled, GDB's internal \"physname\" code is checked against\n\
27202 the demangler."),
27203                            NULL, show_check_physname,
27204                            &setdebuglist, &showdebuglist);
27205
27206   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27207                            no_class, &use_deprecated_index_sections, _("\
27208 Set whether to use deprecated gdb_index sections."), _("\
27209 Show whether to use deprecated gdb_index sections."), _("\
27210 When enabled, deprecated .gdb_index sections are used anyway.\n\
27211 Normally they are ignored either because of a missing feature or\n\
27212 performance issue.\n\
27213 Warning: This option must be enabled before gdb reads the file."),
27214                            NULL,
27215                            NULL,
27216                            &setlist, &showlist);
27217
27218   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27219                _("\
27220 Save a gdb-index file.\n\
27221 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27222 \n\
27223 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27224 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27225 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27226                &save_cmdlist);
27227   set_cmd_completer (c, filename_completer);
27228
27229   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27230                                                         &dwarf2_locexpr_funcs);
27231   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27232                                                         &dwarf2_loclist_funcs);
27233
27234   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27235                                         &dwarf2_block_frame_base_locexpr_funcs);
27236   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27237                                         &dwarf2_block_frame_base_loclist_funcs);
27238
27239 #if GDB_SELF_TEST
27240   selftests::register_test ("dw2_expand_symtabs_matching",
27241                             selftests::dw2_expand_symtabs_matching::run_test);
27242 #endif
27243 }