Change openp et al to use a unique_xmalloc_ptr
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 /* When == 1, print basic high level tracing messages.
91    When > 1, be more verbose.
92    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
93 static unsigned int dwarf_read_debug = 0;
94
95 /* When non-zero, dump DIEs after they are read in.  */
96 static unsigned int dwarf_die_debug = 0;
97
98 /* When non-zero, dump line number entries as they are read in.  */
99 static unsigned int dwarf_line_debug = 0;
100
101 /* When non-zero, cross-check physname against demangler.  */
102 static int check_physname = 0;
103
104 /* When non-zero, do not reject deprecated .gdb_index sections.  */
105 static int use_deprecated_index_sections = 0;
106
107 static const struct objfile_data *dwarf2_objfile_data_key;
108
109 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
110
111 static int dwarf2_locexpr_index;
112 static int dwarf2_loclist_index;
113 static int dwarf2_locexpr_block_index;
114 static int dwarf2_loclist_block_index;
115
116 /* A descriptor for dwarf sections.
117
118    S.ASECTION, SIZE are typically initialized when the objfile is first
119    scanned.  BUFFER, READIN are filled in later when the section is read.
120    If the section contained compressed data then SIZE is updated to record
121    the uncompressed size of the section.
122
123    DWP file format V2 introduces a wrinkle that is easiest to handle by
124    creating the concept of virtual sections contained within a real section.
125    In DWP V2 the sections of the input DWO files are concatenated together
126    into one section, but section offsets are kept relative to the original
127    input section.
128    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
129    the real section this "virtual" section is contained in, and BUFFER,SIZE
130    describe the virtual section.  */
131
132 struct dwarf2_section_info
133 {
134   union
135   {
136     /* If this is a real section, the bfd section.  */
137     asection *section;
138     /* If this is a virtual section, pointer to the containing ("real")
139        section.  */
140     struct dwarf2_section_info *containing_section;
141   } s;
142   /* Pointer to section data, only valid if readin.  */
143   const gdb_byte *buffer;
144   /* The size of the section, real or virtual.  */
145   bfd_size_type size;
146   /* If this is a virtual section, the offset in the real section.
147      Only valid if is_virtual.  */
148   bfd_size_type virtual_offset;
149   /* True if we have tried to read this section.  */
150   char readin;
151   /* True if this is a virtual section, False otherwise.
152      This specifies which of s.section and s.containing_section to use.  */
153   char is_virtual;
154 };
155
156 typedef struct dwarf2_section_info dwarf2_section_info_def;
157 DEF_VEC_O (dwarf2_section_info_def);
158
159 /* All offsets in the index are of this type.  It must be
160    architecture-independent.  */
161 typedef uint32_t offset_type;
162
163 DEF_VEC_I (offset_type);
164
165 /* Ensure only legit values are used.  */
166 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
167   do { \
168     gdb_assert ((unsigned int) (value) <= 1); \
169     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
170   } while (0)
171
172 /* Ensure only legit values are used.  */
173 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
174   do { \
175     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
176                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
177     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
178   } while (0)
179
180 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
181 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
182   do { \
183     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
184     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
185   } while (0)
186
187 #if WORDS_BIGENDIAN
188
189 /* Convert VALUE between big- and little-endian.  */
190
191 static offset_type
192 byte_swap (offset_type value)
193 {
194   offset_type result;
195
196   result = (value & 0xff) << 24;
197   result |= (value & 0xff00) << 8;
198   result |= (value & 0xff0000) >> 8;
199   result |= (value & 0xff000000) >> 24;
200   return result;
201 }
202
203 #define MAYBE_SWAP(V)  byte_swap (V)
204
205 #else
206 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
207 #endif /* WORDS_BIGENDIAN */
208
209 /* An index into a (C++) symbol name component in a symbol name as
210    recorded in the mapped_index's symbol table.  For each C++ symbol
211    in the symbol table, we record one entry for the start of each
212    component in the symbol in a table of name components, and then
213    sort the table, in order to be able to binary search symbol names,
214    ignoring leading namespaces, both completion and regular look up.
215    For example, for symbol "A::B::C", we'll have an entry that points
216    to "A::B::C", another that points to "B::C", and another for "C".
217    Note that function symbols in GDB index have no parameter
218    information, just the function/method names.  You can convert a
219    name_component to a "const char *" using the
220    'mapped_index::symbol_name_at(offset_type)' method.  */
221
222 struct name_component
223 {
224   /* Offset in the symbol name where the component starts.  Stored as
225      a (32-bit) offset instead of a pointer to save memory and improve
226      locality on 64-bit architectures.  */
227   offset_type name_offset;
228
229   /* The symbol's index in the symbol and constant pool tables of a
230      mapped_index.  */
231   offset_type idx;
232 };
233
234 /* Base class containing bits shared by both .gdb_index and
235    .debug_name indexes.  */
236
237 struct mapped_index_base
238 {
239   /* The name_component table (a sorted vector).  See name_component's
240      description above.  */
241   std::vector<name_component> name_components;
242
243   /* How NAME_COMPONENTS is sorted.  */
244   enum case_sensitivity name_components_casing;
245
246   /* Return the number of names in the symbol table.  */
247   virtual size_t symbol_name_count () const = 0;
248
249   /* Get the name of the symbol at IDX in the symbol table.  */
250   virtual const char *symbol_name_at (offset_type idx) const = 0;
251
252   /* Return whether the name at IDX in the symbol table should be
253      ignored.  */
254   virtual bool symbol_name_slot_invalid (offset_type idx) const
255   {
256     return false;
257   }
258
259   /* Build the symbol name component sorted vector, if we haven't
260      yet.  */
261   void build_name_components ();
262
263   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
264      possible matches for LN_NO_PARAMS in the name component
265      vector.  */
266   std::pair<std::vector<name_component>::const_iterator,
267             std::vector<name_component>::const_iterator>
268     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
269
270   /* Prevent deleting/destroying via a base class pointer.  */
271 protected:
272   ~mapped_index_base() = default;
273 };
274
275 /* A description of the mapped index.  The file format is described in
276    a comment by the code that writes the index.  */
277 struct mapped_index final : public mapped_index_base
278 {
279   /* A slot/bucket in the symbol table hash.  */
280   struct symbol_table_slot
281   {
282     const offset_type name;
283     const offset_type vec;
284   };
285
286   /* Index data format version.  */
287   int version;
288
289   /* The total length of the buffer.  */
290   off_t total_size;
291
292   /* The address table data.  */
293   gdb::array_view<const gdb_byte> address_table;
294
295   /* The symbol table, implemented as a hash table.  */
296   gdb::array_view<symbol_table_slot> symbol_table;
297
298   /* A pointer to the constant pool.  */
299   const char *constant_pool;
300
301   bool symbol_name_slot_invalid (offset_type idx) const override
302   {
303     const auto &bucket = this->symbol_table[idx];
304     return bucket.name == 0 && bucket.vec;
305   }
306
307   /* Convenience method to get at the name of the symbol at IDX in the
308      symbol table.  */
309   const char *symbol_name_at (offset_type idx) const override
310   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
311
312   size_t symbol_name_count () const override
313   { return this->symbol_table.size (); }
314 };
315
316 /* A description of the mapped .debug_names.
317    Uninitialized map has CU_COUNT 0.  */
318 struct mapped_debug_names final : public mapped_index_base
319 {
320   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
321   : dwarf2_per_objfile (dwarf2_per_objfile_)
322   {}
323
324   struct dwarf2_per_objfile *dwarf2_per_objfile;
325   bfd_endian dwarf5_byte_order;
326   bool dwarf5_is_dwarf64;
327   bool augmentation_is_gdb;
328   uint8_t offset_size;
329   uint32_t cu_count = 0;
330   uint32_t tu_count, bucket_count, name_count;
331   const gdb_byte *cu_table_reordered, *tu_table_reordered;
332   const uint32_t *bucket_table_reordered, *hash_table_reordered;
333   const gdb_byte *name_table_string_offs_reordered;
334   const gdb_byte *name_table_entry_offs_reordered;
335   const gdb_byte *entry_pool;
336
337   struct index_val
338   {
339     ULONGEST dwarf_tag;
340     struct attr
341     {
342       /* Attribute name DW_IDX_*.  */
343       ULONGEST dw_idx;
344
345       /* Attribute form DW_FORM_*.  */
346       ULONGEST form;
347
348       /* Value if FORM is DW_FORM_implicit_const.  */
349       LONGEST implicit_const;
350     };
351     std::vector<attr> attr_vec;
352   };
353
354   std::unordered_map<ULONGEST, index_val> abbrev_map;
355
356   const char *namei_to_name (uint32_t namei) const;
357
358   /* Implementation of the mapped_index_base virtual interface, for
359      the name_components cache.  */
360
361   const char *symbol_name_at (offset_type idx) const override
362   { return namei_to_name (idx); }
363
364   size_t symbol_name_count () const override
365   { return this->name_count; }
366 };
367
368 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
369 DEF_VEC_P (dwarf2_per_cu_ptr);
370
371 struct tu_stats
372 {
373   int nr_uniq_abbrev_tables;
374   int nr_symtabs;
375   int nr_symtab_sharers;
376   int nr_stmt_less_type_units;
377   int nr_all_type_units_reallocs;
378 };
379
380 /* Collection of data recorded per objfile.
381    This hangs off of dwarf2_objfile_data_key.  */
382
383 struct dwarf2_per_objfile
384 {
385   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
386      dwarf2 section names, or is NULL if the standard ELF names are
387      used.  */
388   dwarf2_per_objfile (struct objfile *objfile,
389                       const dwarf2_debug_sections *names);
390
391   ~dwarf2_per_objfile ();
392
393   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
394
395   /* Free all cached compilation units.  */
396   void free_cached_comp_units ();
397 private:
398   /* This function is mapped across the sections and remembers the
399      offset and size of each of the debugging sections we are
400      interested in.  */
401   void locate_sections (bfd *abfd, asection *sectp,
402                         const dwarf2_debug_sections &names);
403
404 public:
405   dwarf2_section_info info {};
406   dwarf2_section_info abbrev {};
407   dwarf2_section_info line {};
408   dwarf2_section_info loc {};
409   dwarf2_section_info loclists {};
410   dwarf2_section_info macinfo {};
411   dwarf2_section_info macro {};
412   dwarf2_section_info str {};
413   dwarf2_section_info line_str {};
414   dwarf2_section_info ranges {};
415   dwarf2_section_info rnglists {};
416   dwarf2_section_info addr {};
417   dwarf2_section_info frame {};
418   dwarf2_section_info eh_frame {};
419   dwarf2_section_info gdb_index {};
420   dwarf2_section_info debug_names {};
421   dwarf2_section_info debug_aranges {};
422
423   VEC (dwarf2_section_info_def) *types = NULL;
424
425   /* Back link.  */
426   struct objfile *objfile = NULL;
427
428   /* Table of all the compilation units.  This is used to locate
429      the target compilation unit of a particular reference.  */
430   struct dwarf2_per_cu_data **all_comp_units = NULL;
431
432   /* The number of compilation units in ALL_COMP_UNITS.  */
433   int n_comp_units = 0;
434
435   /* The number of .debug_types-related CUs.  */
436   int n_type_units = 0;
437
438   /* The number of elements allocated in all_type_units.
439      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
440   int n_allocated_type_units = 0;
441
442   /* The .debug_types-related CUs (TUs).
443      This is stored in malloc space because we may realloc it.  */
444   struct signatured_type **all_type_units = NULL;
445
446   /* Table of struct type_unit_group objects.
447      The hash key is the DW_AT_stmt_list value.  */
448   htab_t type_unit_groups {};
449
450   /* A table mapping .debug_types signatures to its signatured_type entry.
451      This is NULL if the .debug_types section hasn't been read in yet.  */
452   htab_t signatured_types {};
453
454   /* Type unit statistics, to see how well the scaling improvements
455      are doing.  */
456   struct tu_stats tu_stats {};
457
458   /* A chain of compilation units that are currently read in, so that
459      they can be freed later.  */
460   dwarf2_per_cu_data *read_in_chain = NULL;
461
462   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
463      This is NULL if the table hasn't been allocated yet.  */
464   htab_t dwo_files {};
465
466   /* True if we've checked for whether there is a DWP file.  */
467   bool dwp_checked = false;
468
469   /* The DWP file if there is one, or NULL.  */
470   struct dwp_file *dwp_file = NULL;
471
472   /* The shared '.dwz' file, if one exists.  This is used when the
473      original data was compressed using 'dwz -m'.  */
474   struct dwz_file *dwz_file = NULL;
475
476   /* A flag indicating whether this objfile has a section loaded at a
477      VMA of 0.  */
478   bool has_section_at_zero = false;
479
480   /* True if we are using the mapped index,
481      or we are faking it for OBJF_READNOW's sake.  */
482   bool using_index = false;
483
484   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
485   mapped_index *index_table = NULL;
486
487   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
488   std::unique_ptr<mapped_debug_names> debug_names_table;
489
490   /* When using index_table, this keeps track of all quick_file_names entries.
491      TUs typically share line table entries with a CU, so we maintain a
492      separate table of all line table entries to support the sharing.
493      Note that while there can be way more TUs than CUs, we've already
494      sorted all the TUs into "type unit groups", grouped by their
495      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
496      CU and its associated TU group if there is one.  */
497   htab_t quick_file_names_table {};
498
499   /* Set during partial symbol reading, to prevent queueing of full
500      symbols.  */
501   bool reading_partial_symbols = false;
502
503   /* Table mapping type DIEs to their struct type *.
504      This is NULL if not allocated yet.
505      The mapping is done via (CU/TU + DIE offset) -> type.  */
506   htab_t die_type_hash {};
507
508   /* The CUs we recently read.  */
509   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
510
511   /* Table containing line_header indexed by offset and offset_in_dwz.  */
512   htab_t line_header_hash {};
513
514   /* Table containing all filenames.  This is an optional because the
515      table is lazily constructed on first access.  */
516   gdb::optional<filename_seen_cache> filenames_cache;
517 };
518
519 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
520
521 struct dwarf2_per_objfile *
522 get_dwarf2_per_objfile (struct objfile *objfile)
523 {
524   return ((struct dwarf2_per_objfile *)
525           objfile_data (objfile, dwarf2_objfile_data_key));
526 }
527
528 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
529
530 void
531 set_dwarf2_per_objfile (struct objfile *objfile,
532                         struct dwarf2_per_objfile *dwarf2_per_objfile)
533 {
534   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
535   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
536 }
537
538 /* Default names of the debugging sections.  */
539
540 /* Note that if the debugging section has been compressed, it might
541    have a name like .zdebug_info.  */
542
543 static const struct dwarf2_debug_sections dwarf2_elf_names =
544 {
545   { ".debug_info", ".zdebug_info" },
546   { ".debug_abbrev", ".zdebug_abbrev" },
547   { ".debug_line", ".zdebug_line" },
548   { ".debug_loc", ".zdebug_loc" },
549   { ".debug_loclists", ".zdebug_loclists" },
550   { ".debug_macinfo", ".zdebug_macinfo" },
551   { ".debug_macro", ".zdebug_macro" },
552   { ".debug_str", ".zdebug_str" },
553   { ".debug_line_str", ".zdebug_line_str" },
554   { ".debug_ranges", ".zdebug_ranges" },
555   { ".debug_rnglists", ".zdebug_rnglists" },
556   { ".debug_types", ".zdebug_types" },
557   { ".debug_addr", ".zdebug_addr" },
558   { ".debug_frame", ".zdebug_frame" },
559   { ".eh_frame", NULL },
560   { ".gdb_index", ".zgdb_index" },
561   { ".debug_names", ".zdebug_names" },
562   { ".debug_aranges", ".zdebug_aranges" },
563   23
564 };
565
566 /* List of DWO/DWP sections.  */
567
568 static const struct dwop_section_names
569 {
570   struct dwarf2_section_names abbrev_dwo;
571   struct dwarf2_section_names info_dwo;
572   struct dwarf2_section_names line_dwo;
573   struct dwarf2_section_names loc_dwo;
574   struct dwarf2_section_names loclists_dwo;
575   struct dwarf2_section_names macinfo_dwo;
576   struct dwarf2_section_names macro_dwo;
577   struct dwarf2_section_names str_dwo;
578   struct dwarf2_section_names str_offsets_dwo;
579   struct dwarf2_section_names types_dwo;
580   struct dwarf2_section_names cu_index;
581   struct dwarf2_section_names tu_index;
582 }
583 dwop_section_names =
584 {
585   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
586   { ".debug_info.dwo", ".zdebug_info.dwo" },
587   { ".debug_line.dwo", ".zdebug_line.dwo" },
588   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
589   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
590   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
591   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
592   { ".debug_str.dwo", ".zdebug_str.dwo" },
593   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
594   { ".debug_types.dwo", ".zdebug_types.dwo" },
595   { ".debug_cu_index", ".zdebug_cu_index" },
596   { ".debug_tu_index", ".zdebug_tu_index" },
597 };
598
599 /* local data types */
600
601 /* The data in a compilation unit header, after target2host
602    translation, looks like this.  */
603 struct comp_unit_head
604 {
605   unsigned int length;
606   short version;
607   unsigned char addr_size;
608   unsigned char signed_addr_p;
609   sect_offset abbrev_sect_off;
610
611   /* Size of file offsets; either 4 or 8.  */
612   unsigned int offset_size;
613
614   /* Size of the length field; either 4 or 12.  */
615   unsigned int initial_length_size;
616
617   enum dwarf_unit_type unit_type;
618
619   /* Offset to the first byte of this compilation unit header in the
620      .debug_info section, for resolving relative reference dies.  */
621   sect_offset sect_off;
622
623   /* Offset to first die in this cu from the start of the cu.
624      This will be the first byte following the compilation unit header.  */
625   cu_offset first_die_cu_offset;
626
627   /* 64-bit signature of this type unit - it is valid only for
628      UNIT_TYPE DW_UT_type.  */
629   ULONGEST signature;
630
631   /* For types, offset in the type's DIE of the type defined by this TU.  */
632   cu_offset type_cu_offset_in_tu;
633 };
634
635 /* Type used for delaying computation of method physnames.
636    See comments for compute_delayed_physnames.  */
637 struct delayed_method_info
638 {
639   /* The type to which the method is attached, i.e., its parent class.  */
640   struct type *type;
641
642   /* The index of the method in the type's function fieldlists.  */
643   int fnfield_index;
644
645   /* The index of the method in the fieldlist.  */
646   int index;
647
648   /* The name of the DIE.  */
649   const char *name;
650
651   /*  The DIE associated with this method.  */
652   struct die_info *die;
653 };
654
655 /* Internal state when decoding a particular compilation unit.  */
656 struct dwarf2_cu
657 {
658   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
659   ~dwarf2_cu ();
660
661   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
662
663   /* The header of the compilation unit.  */
664   struct comp_unit_head header {};
665
666   /* Base address of this compilation unit.  */
667   CORE_ADDR base_address = 0;
668
669   /* Non-zero if base_address has been set.  */
670   int base_known = 0;
671
672   /* The language we are debugging.  */
673   enum language language = language_unknown;
674   const struct language_defn *language_defn = nullptr;
675
676   const char *producer = nullptr;
677
678   /* The generic symbol table building routines have separate lists for
679      file scope symbols and all all other scopes (local scopes).  So
680      we need to select the right one to pass to add_symbol_to_list().
681      We do it by keeping a pointer to the correct list in list_in_scope.
682
683      FIXME: The original dwarf code just treated the file scope as the
684      first local scope, and all other local scopes as nested local
685      scopes, and worked fine.  Check to see if we really need to
686      distinguish these in buildsym.c.  */
687   struct pending **list_in_scope = nullptr;
688
689   /* Hash table holding all the loaded partial DIEs
690      with partial_die->offset.SECT_OFF as hash.  */
691   htab_t partial_dies = nullptr;
692
693   /* Storage for things with the same lifetime as this read-in compilation
694      unit, including partial DIEs.  */
695   auto_obstack comp_unit_obstack;
696
697   /* When multiple dwarf2_cu structures are living in memory, this field
698      chains them all together, so that they can be released efficiently.
699      We will probably also want a generation counter so that most-recently-used
700      compilation units are cached...  */
701   struct dwarf2_per_cu_data *read_in_chain = nullptr;
702
703   /* Backlink to our per_cu entry.  */
704   struct dwarf2_per_cu_data *per_cu;
705
706   /* How many compilation units ago was this CU last referenced?  */
707   int last_used = 0;
708
709   /* A hash table of DIE cu_offset for following references with
710      die_info->offset.sect_off as hash.  */
711   htab_t die_hash = nullptr;
712
713   /* Full DIEs if read in.  */
714   struct die_info *dies = nullptr;
715
716   /* A set of pointers to dwarf2_per_cu_data objects for compilation
717      units referenced by this one.  Only set during full symbol processing;
718      partial symbol tables do not have dependencies.  */
719   htab_t dependencies = nullptr;
720
721   /* Header data from the line table, during full symbol processing.  */
722   struct line_header *line_header = nullptr;
723   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
724      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
725      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
726      to the line header as long as this DIE is being processed.  See
727      process_die_scope.  */
728   die_info *line_header_die_owner = nullptr;
729
730   /* A list of methods which need to have physnames computed
731      after all type information has been read.  */
732   std::vector<delayed_method_info> method_list;
733
734   /* To be copied to symtab->call_site_htab.  */
735   htab_t call_site_htab = nullptr;
736
737   /* Non-NULL if this CU came from a DWO file.
738      There is an invariant here that is important to remember:
739      Except for attributes copied from the top level DIE in the "main"
740      (or "stub") file in preparation for reading the DWO file
741      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
742      Either there isn't a DWO file (in which case this is NULL and the point
743      is moot), or there is and either we're not going to read it (in which
744      case this is NULL) or there is and we are reading it (in which case this
745      is non-NULL).  */
746   struct dwo_unit *dwo_unit = nullptr;
747
748   /* The DW_AT_addr_base attribute if present, zero otherwise
749      (zero is a valid value though).
750      Note this value comes from the Fission stub CU/TU's DIE.  */
751   ULONGEST addr_base = 0;
752
753   /* The DW_AT_ranges_base attribute if present, zero otherwise
754      (zero is a valid value though).
755      Note this value comes from the Fission stub CU/TU's DIE.
756      Also note that the value is zero in the non-DWO case so this value can
757      be used without needing to know whether DWO files are in use or not.
758      N.B. This does not apply to DW_AT_ranges appearing in
759      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
760      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
761      DW_AT_ranges_base *would* have to be applied, and we'd have to care
762      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
763   ULONGEST ranges_base = 0;
764
765   /* Mark used when releasing cached dies.  */
766   unsigned int mark : 1;
767
768   /* This CU references .debug_loc.  See the symtab->locations_valid field.
769      This test is imperfect as there may exist optimized debug code not using
770      any location list and still facing inlining issues if handled as
771      unoptimized code.  For a future better test see GCC PR other/32998.  */
772   unsigned int has_loclist : 1;
773
774   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
775      if all the producer_is_* fields are valid.  This information is cached
776      because profiling CU expansion showed excessive time spent in
777      producer_is_gxx_lt_4_6.  */
778   unsigned int checked_producer : 1;
779   unsigned int producer_is_gxx_lt_4_6 : 1;
780   unsigned int producer_is_gcc_lt_4_3 : 1;
781   unsigned int producer_is_icc_lt_14 : 1;
782
783   /* When set, the file that we're processing is known to have
784      debugging info for C++ namespaces.  GCC 3.3.x did not produce
785      this information, but later versions do.  */
786
787   unsigned int processing_has_namespace_info : 1;
788 };
789
790 /* Persistent data held for a compilation unit, even when not
791    processing it.  We put a pointer to this structure in the
792    read_symtab_private field of the psymtab.  */
793
794 struct dwarf2_per_cu_data
795 {
796   /* The start offset and length of this compilation unit.
797      NOTE: Unlike comp_unit_head.length, this length includes
798      initial_length_size.
799      If the DIE refers to a DWO file, this is always of the original die,
800      not the DWO file.  */
801   sect_offset sect_off;
802   unsigned int length;
803
804   /* DWARF standard version this data has been read from (such as 4 or 5).  */
805   short dwarf_version;
806
807   /* Flag indicating this compilation unit will be read in before
808      any of the current compilation units are processed.  */
809   unsigned int queued : 1;
810
811   /* This flag will be set when reading partial DIEs if we need to load
812      absolutely all DIEs for this compilation unit, instead of just the ones
813      we think are interesting.  It gets set if we look for a DIE in the
814      hash table and don't find it.  */
815   unsigned int load_all_dies : 1;
816
817   /* Non-zero if this CU is from .debug_types.
818      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
819      this is non-zero.  */
820   unsigned int is_debug_types : 1;
821
822   /* Non-zero if this CU is from the .dwz file.  */
823   unsigned int is_dwz : 1;
824
825   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
826      This flag is only valid if is_debug_types is true.
827      We can't read a CU directly from a DWO file: There are required
828      attributes in the stub.  */
829   unsigned int reading_dwo_directly : 1;
830
831   /* Non-zero if the TU has been read.
832      This is used to assist the "Stay in DWO Optimization" for Fission:
833      When reading a DWO, it's faster to read TUs from the DWO instead of
834      fetching them from random other DWOs (due to comdat folding).
835      If the TU has already been read, the optimization is unnecessary
836      (and unwise - we don't want to change where gdb thinks the TU lives
837      "midflight").
838      This flag is only valid if is_debug_types is true.  */
839   unsigned int tu_read : 1;
840
841   /* The section this CU/TU lives in.
842      If the DIE refers to a DWO file, this is always the original die,
843      not the DWO file.  */
844   struct dwarf2_section_info *section;
845
846   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
847      of the CU cache it gets reset to NULL again.  This is left as NULL for
848      dummy CUs (a CU header, but nothing else).  */
849   struct dwarf2_cu *cu;
850
851   /* The corresponding dwarf2_per_objfile.  */
852   struct dwarf2_per_objfile *dwarf2_per_objfile;
853
854   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
855      is active.  Otherwise, the 'psymtab' field is active.  */
856   union
857   {
858     /* The partial symbol table associated with this compilation unit,
859        or NULL for unread partial units.  */
860     struct partial_symtab *psymtab;
861
862     /* Data needed by the "quick" functions.  */
863     struct dwarf2_per_cu_quick_data *quick;
864   } v;
865
866   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
867      while reading psymtabs, used to compute the psymtab dependencies,
868      and then cleared.  Then it is filled in again while reading full
869      symbols, and only deleted when the objfile is destroyed.
870
871      This is also used to work around a difference between the way gold
872      generates .gdb_index version <=7 and the way gdb does.  Arguably this
873      is a gold bug.  For symbols coming from TUs, gold records in the index
874      the CU that includes the TU instead of the TU itself.  This breaks
875      dw2_lookup_symbol: It assumes that if the index says symbol X lives
876      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
877      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
878      we need to look in TU Z to find X.  Fortunately, this is akin to
879      DW_TAG_imported_unit, so we just use the same mechanism: For
880      .gdb_index version <=7 this also records the TUs that the CU referred
881      to.  Concurrently with this change gdb was modified to emit version 8
882      indices so we only pay a price for gold generated indices.
883      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
884   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
885 };
886
887 /* Entry in the signatured_types hash table.  */
888
889 struct signatured_type
890 {
891   /* The "per_cu" object of this type.
892      This struct is used iff per_cu.is_debug_types.
893      N.B.: This is the first member so that it's easy to convert pointers
894      between them.  */
895   struct dwarf2_per_cu_data per_cu;
896
897   /* The type's signature.  */
898   ULONGEST signature;
899
900   /* Offset in the TU of the type's DIE, as read from the TU header.
901      If this TU is a DWO stub and the definition lives in a DWO file
902      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
903   cu_offset type_offset_in_tu;
904
905   /* Offset in the section of the type's DIE.
906      If the definition lives in a DWO file, this is the offset in the
907      .debug_types.dwo section.
908      The value is zero until the actual value is known.
909      Zero is otherwise not a valid section offset.  */
910   sect_offset type_offset_in_section;
911
912   /* Type units are grouped by their DW_AT_stmt_list entry so that they
913      can share them.  This points to the containing symtab.  */
914   struct type_unit_group *type_unit_group;
915
916   /* The type.
917      The first time we encounter this type we fully read it in and install it
918      in the symbol tables.  Subsequent times we only need the type.  */
919   struct type *type;
920
921   /* Containing DWO unit.
922      This field is valid iff per_cu.reading_dwo_directly.  */
923   struct dwo_unit *dwo_unit;
924 };
925
926 typedef struct signatured_type *sig_type_ptr;
927 DEF_VEC_P (sig_type_ptr);
928
929 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
930    This includes type_unit_group and quick_file_names.  */
931
932 struct stmt_list_hash
933 {
934   /* The DWO unit this table is from or NULL if there is none.  */
935   struct dwo_unit *dwo_unit;
936
937   /* Offset in .debug_line or .debug_line.dwo.  */
938   sect_offset line_sect_off;
939 };
940
941 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
942    an object of this type.  */
943
944 struct type_unit_group
945 {
946   /* dwarf2read.c's main "handle" on a TU symtab.
947      To simplify things we create an artificial CU that "includes" all the
948      type units using this stmt_list so that the rest of the code still has
949      a "per_cu" handle on the symtab.
950      This PER_CU is recognized by having no section.  */
951 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
952   struct dwarf2_per_cu_data per_cu;
953
954   /* The TUs that share this DW_AT_stmt_list entry.
955      This is added to while parsing type units to build partial symtabs,
956      and is deleted afterwards and not used again.  */
957   VEC (sig_type_ptr) *tus;
958
959   /* The compunit symtab.
960      Type units in a group needn't all be defined in the same source file,
961      so we create an essentially anonymous symtab as the compunit symtab.  */
962   struct compunit_symtab *compunit_symtab;
963
964   /* The data used to construct the hash key.  */
965   struct stmt_list_hash hash;
966
967   /* The number of symtabs from the line header.
968      The value here must match line_header.num_file_names.  */
969   unsigned int num_symtabs;
970
971   /* The symbol tables for this TU (obtained from the files listed in
972      DW_AT_stmt_list).
973      WARNING: The order of entries here must match the order of entries
974      in the line header.  After the first TU using this type_unit_group, the
975      line header for the subsequent TUs is recreated from this.  This is done
976      because we need to use the same symtabs for each TU using the same
977      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
978      there's no guarantee the line header doesn't have duplicate entries.  */
979   struct symtab **symtabs;
980 };
981
982 /* These sections are what may appear in a (real or virtual) DWO file.  */
983
984 struct dwo_sections
985 {
986   struct dwarf2_section_info abbrev;
987   struct dwarf2_section_info line;
988   struct dwarf2_section_info loc;
989   struct dwarf2_section_info loclists;
990   struct dwarf2_section_info macinfo;
991   struct dwarf2_section_info macro;
992   struct dwarf2_section_info str;
993   struct dwarf2_section_info str_offsets;
994   /* In the case of a virtual DWO file, these two are unused.  */
995   struct dwarf2_section_info info;
996   VEC (dwarf2_section_info_def) *types;
997 };
998
999 /* CUs/TUs in DWP/DWO files.  */
1000
1001 struct dwo_unit
1002 {
1003   /* Backlink to the containing struct dwo_file.  */
1004   struct dwo_file *dwo_file;
1005
1006   /* The "id" that distinguishes this CU/TU.
1007      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1008      Since signatures came first, we stick with it for consistency.  */
1009   ULONGEST signature;
1010
1011   /* The section this CU/TU lives in, in the DWO file.  */
1012   struct dwarf2_section_info *section;
1013
1014   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1015   sect_offset sect_off;
1016   unsigned int length;
1017
1018   /* For types, offset in the type's DIE of the type defined by this TU.  */
1019   cu_offset type_offset_in_tu;
1020 };
1021
1022 /* include/dwarf2.h defines the DWP section codes.
1023    It defines a max value but it doesn't define a min value, which we
1024    use for error checking, so provide one.  */
1025
1026 enum dwp_v2_section_ids
1027 {
1028   DW_SECT_MIN = 1
1029 };
1030
1031 /* Data for one DWO file.
1032
1033    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1034    appears in a DWP file).  DWP files don't really have DWO files per se -
1035    comdat folding of types "loses" the DWO file they came from, and from
1036    a high level view DWP files appear to contain a mass of random types.
1037    However, to maintain consistency with the non-DWP case we pretend DWP
1038    files contain virtual DWO files, and we assign each TU with one virtual
1039    DWO file (generally based on the line and abbrev section offsets -
1040    a heuristic that seems to work in practice).  */
1041
1042 struct dwo_file
1043 {
1044   /* The DW_AT_GNU_dwo_name attribute.
1045      For virtual DWO files the name is constructed from the section offsets
1046      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1047      from related CU+TUs.  */
1048   const char *dwo_name;
1049
1050   /* The DW_AT_comp_dir attribute.  */
1051   const char *comp_dir;
1052
1053   /* The bfd, when the file is open.  Otherwise this is NULL.
1054      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1055   bfd *dbfd;
1056
1057   /* The sections that make up this DWO file.
1058      Remember that for virtual DWO files in DWP V2, these are virtual
1059      sections (for lack of a better name).  */
1060   struct dwo_sections sections;
1061
1062   /* The CUs in the file.
1063      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1064      an extension to handle LLVM's Link Time Optimization output (where
1065      multiple source files may be compiled into a single object/dwo pair). */
1066   htab_t cus;
1067
1068   /* Table of TUs in the file.
1069      Each element is a struct dwo_unit.  */
1070   htab_t tus;
1071 };
1072
1073 /* These sections are what may appear in a DWP file.  */
1074
1075 struct dwp_sections
1076 {
1077   /* These are used by both DWP version 1 and 2.  */
1078   struct dwarf2_section_info str;
1079   struct dwarf2_section_info cu_index;
1080   struct dwarf2_section_info tu_index;
1081
1082   /* These are only used by DWP version 2 files.
1083      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1084      sections are referenced by section number, and are not recorded here.
1085      In DWP version 2 there is at most one copy of all these sections, each
1086      section being (effectively) comprised of the concatenation of all of the
1087      individual sections that exist in the version 1 format.
1088      To keep the code simple we treat each of these concatenated pieces as a
1089      section itself (a virtual section?).  */
1090   struct dwarf2_section_info abbrev;
1091   struct dwarf2_section_info info;
1092   struct dwarf2_section_info line;
1093   struct dwarf2_section_info loc;
1094   struct dwarf2_section_info macinfo;
1095   struct dwarf2_section_info macro;
1096   struct dwarf2_section_info str_offsets;
1097   struct dwarf2_section_info types;
1098 };
1099
1100 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1101    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1102
1103 struct virtual_v1_dwo_sections
1104 {
1105   struct dwarf2_section_info abbrev;
1106   struct dwarf2_section_info line;
1107   struct dwarf2_section_info loc;
1108   struct dwarf2_section_info macinfo;
1109   struct dwarf2_section_info macro;
1110   struct dwarf2_section_info str_offsets;
1111   /* Each DWP hash table entry records one CU or one TU.
1112      That is recorded here, and copied to dwo_unit.section.  */
1113   struct dwarf2_section_info info_or_types;
1114 };
1115
1116 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1117    In version 2, the sections of the DWO files are concatenated together
1118    and stored in one section of that name.  Thus each ELF section contains
1119    several "virtual" sections.  */
1120
1121 struct virtual_v2_dwo_sections
1122 {
1123   bfd_size_type abbrev_offset;
1124   bfd_size_type abbrev_size;
1125
1126   bfd_size_type line_offset;
1127   bfd_size_type line_size;
1128
1129   bfd_size_type loc_offset;
1130   bfd_size_type loc_size;
1131
1132   bfd_size_type macinfo_offset;
1133   bfd_size_type macinfo_size;
1134
1135   bfd_size_type macro_offset;
1136   bfd_size_type macro_size;
1137
1138   bfd_size_type str_offsets_offset;
1139   bfd_size_type str_offsets_size;
1140
1141   /* Each DWP hash table entry records one CU or one TU.
1142      That is recorded here, and copied to dwo_unit.section.  */
1143   bfd_size_type info_or_types_offset;
1144   bfd_size_type info_or_types_size;
1145 };
1146
1147 /* Contents of DWP hash tables.  */
1148
1149 struct dwp_hash_table
1150 {
1151   uint32_t version, nr_columns;
1152   uint32_t nr_units, nr_slots;
1153   const gdb_byte *hash_table, *unit_table;
1154   union
1155   {
1156     struct
1157     {
1158       const gdb_byte *indices;
1159     } v1;
1160     struct
1161     {
1162       /* This is indexed by column number and gives the id of the section
1163          in that column.  */
1164 #define MAX_NR_V2_DWO_SECTIONS \
1165   (1 /* .debug_info or .debug_types */ \
1166    + 1 /* .debug_abbrev */ \
1167    + 1 /* .debug_line */ \
1168    + 1 /* .debug_loc */ \
1169    + 1 /* .debug_str_offsets */ \
1170    + 1 /* .debug_macro or .debug_macinfo */)
1171       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1172       const gdb_byte *offsets;
1173       const gdb_byte *sizes;
1174     } v2;
1175   } section_pool;
1176 };
1177
1178 /* Data for one DWP file.  */
1179
1180 struct dwp_file
1181 {
1182   /* Name of the file.  */
1183   const char *name;
1184
1185   /* File format version.  */
1186   int version;
1187
1188   /* The bfd.  */
1189   bfd *dbfd;
1190
1191   /* Section info for this file.  */
1192   struct dwp_sections sections;
1193
1194   /* Table of CUs in the file.  */
1195   const struct dwp_hash_table *cus;
1196
1197   /* Table of TUs in the file.  */
1198   const struct dwp_hash_table *tus;
1199
1200   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1201   htab_t loaded_cus;
1202   htab_t loaded_tus;
1203
1204   /* Table to map ELF section numbers to their sections.
1205      This is only needed for the DWP V1 file format.  */
1206   unsigned int num_sections;
1207   asection **elf_sections;
1208 };
1209
1210 /* This represents a '.dwz' file.  */
1211
1212 struct dwz_file
1213 {
1214   /* A dwz file can only contain a few sections.  */
1215   struct dwarf2_section_info abbrev;
1216   struct dwarf2_section_info info;
1217   struct dwarf2_section_info str;
1218   struct dwarf2_section_info line;
1219   struct dwarf2_section_info macro;
1220   struct dwarf2_section_info gdb_index;
1221   struct dwarf2_section_info debug_names;
1222
1223   /* The dwz's BFD.  */
1224   bfd *dwz_bfd;
1225 };
1226
1227 /* Struct used to pass misc. parameters to read_die_and_children, et
1228    al.  which are used for both .debug_info and .debug_types dies.
1229    All parameters here are unchanging for the life of the call.  This
1230    struct exists to abstract away the constant parameters of die reading.  */
1231
1232 struct die_reader_specs
1233 {
1234   /* The bfd of die_section.  */
1235   bfd* abfd;
1236
1237   /* The CU of the DIE we are parsing.  */
1238   struct dwarf2_cu *cu;
1239
1240   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1241   struct dwo_file *dwo_file;
1242
1243   /* The section the die comes from.
1244      This is either .debug_info or .debug_types, or the .dwo variants.  */
1245   struct dwarf2_section_info *die_section;
1246
1247   /* die_section->buffer.  */
1248   const gdb_byte *buffer;
1249
1250   /* The end of the buffer.  */
1251   const gdb_byte *buffer_end;
1252
1253   /* The value of the DW_AT_comp_dir attribute.  */
1254   const char *comp_dir;
1255
1256   /* The abbreviation table to use when reading the DIEs.  */
1257   struct abbrev_table *abbrev_table;
1258 };
1259
1260 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1261 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1262                                       const gdb_byte *info_ptr,
1263                                       struct die_info *comp_unit_die,
1264                                       int has_children,
1265                                       void *data);
1266
1267 /* A 1-based directory index.  This is a strong typedef to prevent
1268    accidentally using a directory index as a 0-based index into an
1269    array/vector.  */
1270 enum class dir_index : unsigned int {};
1271
1272 /* Likewise, a 1-based file name index.  */
1273 enum class file_name_index : unsigned int {};
1274
1275 struct file_entry
1276 {
1277   file_entry () = default;
1278
1279   file_entry (const char *name_, dir_index d_index_,
1280               unsigned int mod_time_, unsigned int length_)
1281     : name (name_),
1282       d_index (d_index_),
1283       mod_time (mod_time_),
1284       length (length_)
1285   {}
1286
1287   /* Return the include directory at D_INDEX stored in LH.  Returns
1288      NULL if D_INDEX is out of bounds.  */
1289   const char *include_dir (const line_header *lh) const;
1290
1291   /* The file name.  Note this is an observing pointer.  The memory is
1292      owned by debug_line_buffer.  */
1293   const char *name {};
1294
1295   /* The directory index (1-based).  */
1296   dir_index d_index {};
1297
1298   unsigned int mod_time {};
1299
1300   unsigned int length {};
1301
1302   /* True if referenced by the Line Number Program.  */
1303   bool included_p {};
1304
1305   /* The associated symbol table, if any.  */
1306   struct symtab *symtab {};
1307 };
1308
1309 /* The line number information for a compilation unit (found in the
1310    .debug_line section) begins with a "statement program header",
1311    which contains the following information.  */
1312 struct line_header
1313 {
1314   line_header ()
1315     : offset_in_dwz {}
1316   {}
1317
1318   /* Add an entry to the include directory table.  */
1319   void add_include_dir (const char *include_dir);
1320
1321   /* Add an entry to the file name table.  */
1322   void add_file_name (const char *name, dir_index d_index,
1323                       unsigned int mod_time, unsigned int length);
1324
1325   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1326      is out of bounds.  */
1327   const char *include_dir_at (dir_index index) const
1328   {
1329     /* Convert directory index number (1-based) to vector index
1330        (0-based).  */
1331     size_t vec_index = to_underlying (index) - 1;
1332
1333     if (vec_index >= include_dirs.size ())
1334       return NULL;
1335     return include_dirs[vec_index];
1336   }
1337
1338   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1339      is out of bounds.  */
1340   file_entry *file_name_at (file_name_index index)
1341   {
1342     /* Convert file name index number (1-based) to vector index
1343        (0-based).  */
1344     size_t vec_index = to_underlying (index) - 1;
1345
1346     if (vec_index >= file_names.size ())
1347       return NULL;
1348     return &file_names[vec_index];
1349   }
1350
1351   /* Const version of the above.  */
1352   const file_entry *file_name_at (unsigned int index) const
1353   {
1354     if (index >= file_names.size ())
1355       return NULL;
1356     return &file_names[index];
1357   }
1358
1359   /* Offset of line number information in .debug_line section.  */
1360   sect_offset sect_off {};
1361
1362   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1363   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1364
1365   unsigned int total_length {};
1366   unsigned short version {};
1367   unsigned int header_length {};
1368   unsigned char minimum_instruction_length {};
1369   unsigned char maximum_ops_per_instruction {};
1370   unsigned char default_is_stmt {};
1371   int line_base {};
1372   unsigned char line_range {};
1373   unsigned char opcode_base {};
1374
1375   /* standard_opcode_lengths[i] is the number of operands for the
1376      standard opcode whose value is i.  This means that
1377      standard_opcode_lengths[0] is unused, and the last meaningful
1378      element is standard_opcode_lengths[opcode_base - 1].  */
1379   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1380
1381   /* The include_directories table.  Note these are observing
1382      pointers.  The memory is owned by debug_line_buffer.  */
1383   std::vector<const char *> include_dirs;
1384
1385   /* The file_names table.  */
1386   std::vector<file_entry> file_names;
1387
1388   /* The start and end of the statement program following this
1389      header.  These point into dwarf2_per_objfile->line_buffer.  */
1390   const gdb_byte *statement_program_start {}, *statement_program_end {};
1391 };
1392
1393 typedef std::unique_ptr<line_header> line_header_up;
1394
1395 const char *
1396 file_entry::include_dir (const line_header *lh) const
1397 {
1398   return lh->include_dir_at (d_index);
1399 }
1400
1401 /* When we construct a partial symbol table entry we only
1402    need this much information.  */
1403 struct partial_die_info
1404   {
1405     /* Offset of this DIE.  */
1406     sect_offset sect_off;
1407
1408     /* DWARF-2 tag for this DIE.  */
1409     ENUM_BITFIELD(dwarf_tag) tag : 16;
1410
1411     /* Assorted flags describing the data found in this DIE.  */
1412     unsigned int has_children : 1;
1413     unsigned int is_external : 1;
1414     unsigned int is_declaration : 1;
1415     unsigned int has_type : 1;
1416     unsigned int has_specification : 1;
1417     unsigned int has_pc_info : 1;
1418     unsigned int may_be_inlined : 1;
1419
1420     /* This DIE has been marked DW_AT_main_subprogram.  */
1421     unsigned int main_subprogram : 1;
1422
1423     /* Flag set if the SCOPE field of this structure has been
1424        computed.  */
1425     unsigned int scope_set : 1;
1426
1427     /* Flag set if the DIE has a byte_size attribute.  */
1428     unsigned int has_byte_size : 1;
1429
1430     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1431     unsigned int has_const_value : 1;
1432
1433     /* Flag set if any of the DIE's children are template arguments.  */
1434     unsigned int has_template_arguments : 1;
1435
1436     /* Flag set if fixup_partial_die has been called on this die.  */
1437     unsigned int fixup_called : 1;
1438
1439     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1440     unsigned int is_dwz : 1;
1441
1442     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1443     unsigned int spec_is_dwz : 1;
1444
1445     /* The name of this DIE.  Normally the value of DW_AT_name, but
1446        sometimes a default name for unnamed DIEs.  */
1447     const char *name;
1448
1449     /* The linkage name, if present.  */
1450     const char *linkage_name;
1451
1452     /* The scope to prepend to our children.  This is generally
1453        allocated on the comp_unit_obstack, so will disappear
1454        when this compilation unit leaves the cache.  */
1455     const char *scope;
1456
1457     /* Some data associated with the partial DIE.  The tag determines
1458        which field is live.  */
1459     union
1460     {
1461       /* The location description associated with this DIE, if any.  */
1462       struct dwarf_block *locdesc;
1463       /* The offset of an import, for DW_TAG_imported_unit.  */
1464       sect_offset sect_off;
1465     } d;
1466
1467     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1468     CORE_ADDR lowpc;
1469     CORE_ADDR highpc;
1470
1471     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1472        DW_AT_sibling, if any.  */
1473     /* NOTE: This member isn't strictly necessary, read_partial_die could
1474        return DW_AT_sibling values to its caller load_partial_dies.  */
1475     const gdb_byte *sibling;
1476
1477     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1478        DW_AT_specification (or DW_AT_abstract_origin or
1479        DW_AT_extension).  */
1480     sect_offset spec_offset;
1481
1482     /* Pointers to this DIE's parent, first child, and next sibling,
1483        if any.  */
1484     struct partial_die_info *die_parent, *die_child, *die_sibling;
1485   };
1486
1487 /* This data structure holds the information of an abbrev.  */
1488 struct abbrev_info
1489   {
1490     unsigned int number;        /* number identifying abbrev */
1491     enum dwarf_tag tag;         /* dwarf tag */
1492     unsigned short has_children;                /* boolean */
1493     unsigned short num_attrs;   /* number of attributes */
1494     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1495     struct abbrev_info *next;   /* next in chain */
1496   };
1497
1498 struct attr_abbrev
1499   {
1500     ENUM_BITFIELD(dwarf_attribute) name : 16;
1501     ENUM_BITFIELD(dwarf_form) form : 16;
1502
1503     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1504     LONGEST implicit_const;
1505   };
1506
1507 /* Size of abbrev_table.abbrev_hash_table.  */
1508 #define ABBREV_HASH_SIZE 121
1509
1510 /* Top level data structure to contain an abbreviation table.  */
1511
1512 struct abbrev_table
1513 {
1514   explicit abbrev_table (sect_offset off)
1515     : sect_off (off)
1516   {
1517     m_abbrevs =
1518       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1519     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1520   }
1521
1522   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1523
1524   /* Allocate space for a struct abbrev_info object in
1525      ABBREV_TABLE.  */
1526   struct abbrev_info *alloc_abbrev ();
1527
1528   /* Add an abbreviation to the table.  */
1529   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1530
1531   /* Look up an abbrev in the table.
1532      Returns NULL if the abbrev is not found.  */
1533
1534   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1535
1536
1537   /* Where the abbrev table came from.
1538      This is used as a sanity check when the table is used.  */
1539   const sect_offset sect_off;
1540
1541   /* Storage for the abbrev table.  */
1542   auto_obstack abbrev_obstack;
1543
1544 private:
1545
1546   /* Hash table of abbrevs.
1547      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1548      It could be statically allocated, but the previous code didn't so we
1549      don't either.  */
1550   struct abbrev_info **m_abbrevs;
1551 };
1552
1553 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1554
1555 /* Attributes have a name and a value.  */
1556 struct attribute
1557   {
1558     ENUM_BITFIELD(dwarf_attribute) name : 16;
1559     ENUM_BITFIELD(dwarf_form) form : 15;
1560
1561     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1562        field should be in u.str (existing only for DW_STRING) but it is kept
1563        here for better struct attribute alignment.  */
1564     unsigned int string_is_canonical : 1;
1565
1566     union
1567       {
1568         const char *str;
1569         struct dwarf_block *blk;
1570         ULONGEST unsnd;
1571         LONGEST snd;
1572         CORE_ADDR addr;
1573         ULONGEST signature;
1574       }
1575     u;
1576   };
1577
1578 /* This data structure holds a complete die structure.  */
1579 struct die_info
1580   {
1581     /* DWARF-2 tag for this DIE.  */
1582     ENUM_BITFIELD(dwarf_tag) tag : 16;
1583
1584     /* Number of attributes */
1585     unsigned char num_attrs;
1586
1587     /* True if we're presently building the full type name for the
1588        type derived from this DIE.  */
1589     unsigned char building_fullname : 1;
1590
1591     /* True if this die is in process.  PR 16581.  */
1592     unsigned char in_process : 1;
1593
1594     /* Abbrev number */
1595     unsigned int abbrev;
1596
1597     /* Offset in .debug_info or .debug_types section.  */
1598     sect_offset sect_off;
1599
1600     /* The dies in a compilation unit form an n-ary tree.  PARENT
1601        points to this die's parent; CHILD points to the first child of
1602        this node; and all the children of a given node are chained
1603        together via their SIBLING fields.  */
1604     struct die_info *child;     /* Its first child, if any.  */
1605     struct die_info *sibling;   /* Its next sibling, if any.  */
1606     struct die_info *parent;    /* Its parent, if any.  */
1607
1608     /* An array of attributes, with NUM_ATTRS elements.  There may be
1609        zero, but it's not common and zero-sized arrays are not
1610        sufficiently portable C.  */
1611     struct attribute attrs[1];
1612   };
1613
1614 /* Get at parts of an attribute structure.  */
1615
1616 #define DW_STRING(attr)    ((attr)->u.str)
1617 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1618 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1619 #define DW_BLOCK(attr)     ((attr)->u.blk)
1620 #define DW_SND(attr)       ((attr)->u.snd)
1621 #define DW_ADDR(attr)      ((attr)->u.addr)
1622 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1623
1624 /* Blocks are a bunch of untyped bytes.  */
1625 struct dwarf_block
1626   {
1627     size_t size;
1628
1629     /* Valid only if SIZE is not zero.  */
1630     const gdb_byte *data;
1631   };
1632
1633 #ifndef ATTR_ALLOC_CHUNK
1634 #define ATTR_ALLOC_CHUNK 4
1635 #endif
1636
1637 /* Allocate fields for structs, unions and enums in this size.  */
1638 #ifndef DW_FIELD_ALLOC_CHUNK
1639 #define DW_FIELD_ALLOC_CHUNK 4
1640 #endif
1641
1642 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1643    but this would require a corresponding change in unpack_field_as_long
1644    and friends.  */
1645 static int bits_per_byte = 8;
1646
1647 struct nextfield
1648 {
1649   struct nextfield *next;
1650   int accessibility;
1651   int virtuality;
1652   struct field field;
1653 };
1654
1655 struct nextfnfield
1656 {
1657   struct nextfnfield *next;
1658   struct fn_field fnfield;
1659 };
1660
1661 struct fnfieldlist
1662 {
1663   const char *name;
1664   int length;
1665   struct nextfnfield *head;
1666 };
1667
1668 struct decl_field_list
1669 {
1670   struct decl_field field;
1671   struct decl_field_list *next;
1672 };
1673
1674 /* The routines that read and process dies for a C struct or C++ class
1675    pass lists of data member fields and lists of member function fields
1676    in an instance of a field_info structure, as defined below.  */
1677 struct field_info
1678   {
1679     /* List of data member and baseclasses fields.  */
1680     struct nextfield *fields, *baseclasses;
1681
1682     /* Number of fields (including baseclasses).  */
1683     int nfields;
1684
1685     /* Number of baseclasses.  */
1686     int nbaseclasses;
1687
1688     /* Set if the accesibility of one of the fields is not public.  */
1689     int non_public_fields;
1690
1691     /* Member function fieldlist array, contains name of possibly overloaded
1692        member function, number of overloaded member functions and a pointer
1693        to the head of the member function field chain.  */
1694     struct fnfieldlist *fnfieldlists;
1695
1696     /* Number of entries in the fnfieldlists array.  */
1697     int nfnfields;
1698
1699     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1700        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1701     struct decl_field_list *typedef_field_list;
1702     unsigned typedef_field_list_count;
1703
1704     /* Nested types defined by this class and the number of elements in this
1705        list.  */
1706     struct decl_field_list *nested_types_list;
1707     unsigned nested_types_list_count;
1708   };
1709
1710 /* One item on the queue of compilation units to read in full symbols
1711    for.  */
1712 struct dwarf2_queue_item
1713 {
1714   struct dwarf2_per_cu_data *per_cu;
1715   enum language pretend_language;
1716   struct dwarf2_queue_item *next;
1717 };
1718
1719 /* The current queue.  */
1720 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1721
1722 /* Loaded secondary compilation units are kept in memory until they
1723    have not been referenced for the processing of this many
1724    compilation units.  Set this to zero to disable caching.  Cache
1725    sizes of up to at least twenty will improve startup time for
1726    typical inter-CU-reference binaries, at an obvious memory cost.  */
1727 static int dwarf_max_cache_age = 5;
1728 static void
1729 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1730                           struct cmd_list_element *c, const char *value)
1731 {
1732   fprintf_filtered (file, _("The upper bound on the age of cached "
1733                             "DWARF compilation units is %s.\n"),
1734                     value);
1735 }
1736 \f
1737 /* local function prototypes */
1738
1739 static const char *get_section_name (const struct dwarf2_section_info *);
1740
1741 static const char *get_section_file_name (const struct dwarf2_section_info *);
1742
1743 static void dwarf2_find_base_address (struct die_info *die,
1744                                       struct dwarf2_cu *cu);
1745
1746 static struct partial_symtab *create_partial_symtab
1747   (struct dwarf2_per_cu_data *per_cu, const char *name);
1748
1749 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1750                                         const gdb_byte *info_ptr,
1751                                         struct die_info *type_unit_die,
1752                                         int has_children, void *data);
1753
1754 static void dwarf2_build_psymtabs_hard
1755   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1756
1757 static void scan_partial_symbols (struct partial_die_info *,
1758                                   CORE_ADDR *, CORE_ADDR *,
1759                                   int, struct dwarf2_cu *);
1760
1761 static void add_partial_symbol (struct partial_die_info *,
1762                                 struct dwarf2_cu *);
1763
1764 static void add_partial_namespace (struct partial_die_info *pdi,
1765                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1766                                    int set_addrmap, struct dwarf2_cu *cu);
1767
1768 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1769                                 CORE_ADDR *highpc, int set_addrmap,
1770                                 struct dwarf2_cu *cu);
1771
1772 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1773                                      struct dwarf2_cu *cu);
1774
1775 static void add_partial_subprogram (struct partial_die_info *pdi,
1776                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1777                                     int need_pc, struct dwarf2_cu *cu);
1778
1779 static void dwarf2_read_symtab (struct partial_symtab *,
1780                                 struct objfile *);
1781
1782 static void psymtab_to_symtab_1 (struct partial_symtab *);
1783
1784 static abbrev_table_up abbrev_table_read_table
1785   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1786    sect_offset);
1787
1788 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1789
1790 static struct partial_die_info *load_partial_dies
1791   (const struct die_reader_specs *, const gdb_byte *, int);
1792
1793 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1794                                          struct partial_die_info *,
1795                                          struct abbrev_info *,
1796                                          unsigned int,
1797                                          const gdb_byte *);
1798
1799 static struct partial_die_info *find_partial_die (sect_offset, int,
1800                                                   struct dwarf2_cu *);
1801
1802 static void fixup_partial_die (struct partial_die_info *,
1803                                struct dwarf2_cu *);
1804
1805 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1806                                        struct attribute *, struct attr_abbrev *,
1807                                        const gdb_byte *);
1808
1809 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1810
1811 static int read_1_signed_byte (bfd *, const gdb_byte *);
1812
1813 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1814
1815 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1816
1817 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1818
1819 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1820                                unsigned int *);
1821
1822 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1823
1824 static LONGEST read_checked_initial_length_and_offset
1825   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1826    unsigned int *, unsigned int *);
1827
1828 static LONGEST read_offset (bfd *, const gdb_byte *,
1829                             const struct comp_unit_head *,
1830                             unsigned int *);
1831
1832 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1833
1834 static sect_offset read_abbrev_offset
1835   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1836    struct dwarf2_section_info *, sect_offset);
1837
1838 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1839
1840 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1841
1842 static const char *read_indirect_string
1843   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1844    const struct comp_unit_head *, unsigned int *);
1845
1846 static const char *read_indirect_line_string
1847   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1848    const struct comp_unit_head *, unsigned int *);
1849
1850 static const char *read_indirect_string_at_offset
1851   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1852    LONGEST str_offset);
1853
1854 static const char *read_indirect_string_from_dwz
1855   (struct objfile *objfile, struct dwz_file *, LONGEST);
1856
1857 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1858
1859 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1860                                               const gdb_byte *,
1861                                               unsigned int *);
1862
1863 static const char *read_str_index (const struct die_reader_specs *reader,
1864                                    ULONGEST str_index);
1865
1866 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1867
1868 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1869                                       struct dwarf2_cu *);
1870
1871 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1872                                                 unsigned int);
1873
1874 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1875                                        struct dwarf2_cu *cu);
1876
1877 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1878                                struct dwarf2_cu *cu);
1879
1880 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1881
1882 static struct die_info *die_specification (struct die_info *die,
1883                                            struct dwarf2_cu **);
1884
1885 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1886                                                 struct dwarf2_cu *cu);
1887
1888 static void dwarf_decode_lines (struct line_header *, const char *,
1889                                 struct dwarf2_cu *, struct partial_symtab *,
1890                                 CORE_ADDR, int decode_mapping);
1891
1892 static void dwarf2_start_subfile (const char *, const char *);
1893
1894 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1895                                                     const char *, const char *,
1896                                                     CORE_ADDR);
1897
1898 static struct symbol *new_symbol (struct die_info *, struct type *,
1899                                   struct dwarf2_cu *, struct symbol * = NULL);
1900
1901 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1902                                 struct dwarf2_cu *);
1903
1904 static void dwarf2_const_value_attr (const struct attribute *attr,
1905                                      struct type *type,
1906                                      const char *name,
1907                                      struct obstack *obstack,
1908                                      struct dwarf2_cu *cu, LONGEST *value,
1909                                      const gdb_byte **bytes,
1910                                      struct dwarf2_locexpr_baton **baton);
1911
1912 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1913
1914 static int need_gnat_info (struct dwarf2_cu *);
1915
1916 static struct type *die_descriptive_type (struct die_info *,
1917                                           struct dwarf2_cu *);
1918
1919 static void set_descriptive_type (struct type *, struct die_info *,
1920                                   struct dwarf2_cu *);
1921
1922 static struct type *die_containing_type (struct die_info *,
1923                                          struct dwarf2_cu *);
1924
1925 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1926                                      struct dwarf2_cu *);
1927
1928 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1929
1930 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1931
1932 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1933
1934 static char *typename_concat (struct obstack *obs, const char *prefix,
1935                               const char *suffix, int physname,
1936                               struct dwarf2_cu *cu);
1937
1938 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1939
1940 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1941
1942 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1943
1944 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1945
1946 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1947
1948 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1949
1950 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1951                                struct dwarf2_cu *, struct partial_symtab *);
1952
1953 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1954    values.  Keep the items ordered with increasing constraints compliance.  */
1955 enum pc_bounds_kind
1956 {
1957   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1958   PC_BOUNDS_NOT_PRESENT,
1959
1960   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1961      were present but they do not form a valid range of PC addresses.  */
1962   PC_BOUNDS_INVALID,
1963
1964   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1965   PC_BOUNDS_RANGES,
1966
1967   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1968   PC_BOUNDS_HIGH_LOW,
1969 };
1970
1971 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1972                                                  CORE_ADDR *, CORE_ADDR *,
1973                                                  struct dwarf2_cu *,
1974                                                  struct partial_symtab *);
1975
1976 static void get_scope_pc_bounds (struct die_info *,
1977                                  CORE_ADDR *, CORE_ADDR *,
1978                                  struct dwarf2_cu *);
1979
1980 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1981                                         CORE_ADDR, struct dwarf2_cu *);
1982
1983 static void dwarf2_add_field (struct field_info *, struct die_info *,
1984                               struct dwarf2_cu *);
1985
1986 static void dwarf2_attach_fields_to_type (struct field_info *,
1987                                           struct type *, struct dwarf2_cu *);
1988
1989 static void dwarf2_add_member_fn (struct field_info *,
1990                                   struct die_info *, struct type *,
1991                                   struct dwarf2_cu *);
1992
1993 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1994                                              struct type *,
1995                                              struct dwarf2_cu *);
1996
1997 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1998
1999 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2000
2001 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2002
2003 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2004
2005 static struct using_direct **using_directives (enum language);
2006
2007 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2008
2009 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2010
2011 static struct type *read_module_type (struct die_info *die,
2012                                       struct dwarf2_cu *cu);
2013
2014 static const char *namespace_name (struct die_info *die,
2015                                    int *is_anonymous, struct dwarf2_cu *);
2016
2017 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2018
2019 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2020
2021 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2022                                                        struct dwarf2_cu *);
2023
2024 static struct die_info *read_die_and_siblings_1
2025   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2026    struct die_info *);
2027
2028 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2029                                                const gdb_byte *info_ptr,
2030                                                const gdb_byte **new_info_ptr,
2031                                                struct die_info *parent);
2032
2033 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2034                                         struct die_info **, const gdb_byte *,
2035                                         int *, int);
2036
2037 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2038                                       struct die_info **, const gdb_byte *,
2039                                       int *);
2040
2041 static void process_die (struct die_info *, struct dwarf2_cu *);
2042
2043 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2044                                              struct obstack *);
2045
2046 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2047
2048 static const char *dwarf2_full_name (const char *name,
2049                                      struct die_info *die,
2050                                      struct dwarf2_cu *cu);
2051
2052 static const char *dwarf2_physname (const char *name, struct die_info *die,
2053                                     struct dwarf2_cu *cu);
2054
2055 static struct die_info *dwarf2_extension (struct die_info *die,
2056                                           struct dwarf2_cu **);
2057
2058 static const char *dwarf_tag_name (unsigned int);
2059
2060 static const char *dwarf_attr_name (unsigned int);
2061
2062 static const char *dwarf_form_name (unsigned int);
2063
2064 static const char *dwarf_bool_name (unsigned int);
2065
2066 static const char *dwarf_type_encoding_name (unsigned int);
2067
2068 static struct die_info *sibling_die (struct die_info *);
2069
2070 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2071
2072 static void dump_die_for_error (struct die_info *);
2073
2074 static void dump_die_1 (struct ui_file *, int level, int max_level,
2075                         struct die_info *);
2076
2077 /*static*/ void dump_die (struct die_info *, int max_level);
2078
2079 static void store_in_ref_table (struct die_info *,
2080                                 struct dwarf2_cu *);
2081
2082 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2083
2084 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2085
2086 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2087                                                const struct attribute *,
2088                                                struct dwarf2_cu **);
2089
2090 static struct die_info *follow_die_ref (struct die_info *,
2091                                         const struct attribute *,
2092                                         struct dwarf2_cu **);
2093
2094 static struct die_info *follow_die_sig (struct die_info *,
2095                                         const struct attribute *,
2096                                         struct dwarf2_cu **);
2097
2098 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2099                                          struct dwarf2_cu *);
2100
2101 static struct type *get_DW_AT_signature_type (struct die_info *,
2102                                               const struct attribute *,
2103                                               struct dwarf2_cu *);
2104
2105 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2106
2107 static void read_signatured_type (struct signatured_type *);
2108
2109 static int attr_to_dynamic_prop (const struct attribute *attr,
2110                                  struct die_info *die, struct dwarf2_cu *cu,
2111                                  struct dynamic_prop *prop);
2112
2113 /* memory allocation interface */
2114
2115 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2116
2117 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2118
2119 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2120
2121 static int attr_form_is_block (const struct attribute *);
2122
2123 static int attr_form_is_section_offset (const struct attribute *);
2124
2125 static int attr_form_is_constant (const struct attribute *);
2126
2127 static int attr_form_is_ref (const struct attribute *);
2128
2129 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2130                                    struct dwarf2_loclist_baton *baton,
2131                                    const struct attribute *attr);
2132
2133 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2134                                          struct symbol *sym,
2135                                          struct dwarf2_cu *cu,
2136                                          int is_block);
2137
2138 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2139                                      const gdb_byte *info_ptr,
2140                                      struct abbrev_info *abbrev);
2141
2142 static hashval_t partial_die_hash (const void *item);
2143
2144 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2145
2146 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2147   (sect_offset sect_off, unsigned int offset_in_dwz,
2148    struct dwarf2_per_objfile *dwarf2_per_objfile);
2149
2150 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2151                                    struct die_info *comp_unit_die,
2152                                    enum language pretend_language);
2153
2154 static void free_cached_comp_units (void *);
2155
2156 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2157
2158 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2159
2160 static struct type *set_die_type (struct die_info *, struct type *,
2161                                   struct dwarf2_cu *);
2162
2163 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2164
2165 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2166
2167 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2168                                  enum language);
2169
2170 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2171                                     enum language);
2172
2173 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2174                                     enum language);
2175
2176 static void dwarf2_add_dependence (struct dwarf2_cu *,
2177                                    struct dwarf2_per_cu_data *);
2178
2179 static void dwarf2_mark (struct dwarf2_cu *);
2180
2181 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2182
2183 static struct type *get_die_type_at_offset (sect_offset,
2184                                             struct dwarf2_per_cu_data *);
2185
2186 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2187
2188 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2189                              enum language pretend_language);
2190
2191 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2192
2193 /* Class, the destructor of which frees all allocated queue entries.  This
2194    will only have work to do if an error was thrown while processing the
2195    dwarf.  If no error was thrown then the queue entries should have all
2196    been processed, and freed, as we went along.  */
2197
2198 class dwarf2_queue_guard
2199 {
2200 public:
2201   dwarf2_queue_guard () = default;
2202
2203   /* Free any entries remaining on the queue.  There should only be
2204      entries left if we hit an error while processing the dwarf.  */
2205   ~dwarf2_queue_guard ()
2206   {
2207     struct dwarf2_queue_item *item, *last;
2208
2209     item = dwarf2_queue;
2210     while (item)
2211       {
2212         /* Anything still marked queued is likely to be in an
2213            inconsistent state, so discard it.  */
2214         if (item->per_cu->queued)
2215           {
2216             if (item->per_cu->cu != NULL)
2217               free_one_cached_comp_unit (item->per_cu);
2218             item->per_cu->queued = 0;
2219           }
2220
2221         last = item;
2222         item = item->next;
2223         xfree (last);
2224       }
2225
2226     dwarf2_queue = dwarf2_queue_tail = NULL;
2227   }
2228 };
2229
2230 /* The return type of find_file_and_directory.  Note, the enclosed
2231    string pointers are only valid while this object is valid.  */
2232
2233 struct file_and_directory
2234 {
2235   /* The filename.  This is never NULL.  */
2236   const char *name;
2237
2238   /* The compilation directory.  NULL if not known.  If we needed to
2239      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2240      points directly to the DW_AT_comp_dir string attribute owned by
2241      the obstack that owns the DIE.  */
2242   const char *comp_dir;
2243
2244   /* If we needed to build a new string for comp_dir, this is what
2245      owns the storage.  */
2246   std::string comp_dir_storage;
2247 };
2248
2249 static file_and_directory find_file_and_directory (struct die_info *die,
2250                                                    struct dwarf2_cu *cu);
2251
2252 static char *file_full_name (int file, struct line_header *lh,
2253                              const char *comp_dir);
2254
2255 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2256 enum class rcuh_kind { COMPILE, TYPE };
2257
2258 static const gdb_byte *read_and_check_comp_unit_head
2259   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2260    struct comp_unit_head *header,
2261    struct dwarf2_section_info *section,
2262    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2263    rcuh_kind section_kind);
2264
2265 static void init_cutu_and_read_dies
2266   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2267    int use_existing_cu, int keep,
2268    die_reader_func_ftype *die_reader_func, void *data);
2269
2270 static void init_cutu_and_read_dies_simple
2271   (struct dwarf2_per_cu_data *this_cu,
2272    die_reader_func_ftype *die_reader_func, void *data);
2273
2274 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2275
2276 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2277
2278 static struct dwo_unit *lookup_dwo_unit_in_dwp
2279   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2280    struct dwp_file *dwp_file, const char *comp_dir,
2281    ULONGEST signature, int is_debug_types);
2282
2283 static struct dwp_file *get_dwp_file
2284   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2285
2286 static struct dwo_unit *lookup_dwo_comp_unit
2287   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2288
2289 static struct dwo_unit *lookup_dwo_type_unit
2290   (struct signatured_type *, const char *, const char *);
2291
2292 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2293
2294 static void free_dwo_file_cleanup (void *);
2295
2296 struct free_dwo_file_cleanup_data
2297 {
2298   struct dwo_file *dwo_file;
2299   struct dwarf2_per_objfile *dwarf2_per_objfile;
2300 };
2301
2302 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2303
2304 static void check_producer (struct dwarf2_cu *cu);
2305
2306 static void free_line_header_voidp (void *arg);
2307 \f
2308 /* Various complaints about symbol reading that don't abort the process.  */
2309
2310 static void
2311 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2312 {
2313   complaint (&symfile_complaints,
2314              _("statement list doesn't fit in .debug_line section"));
2315 }
2316
2317 static void
2318 dwarf2_debug_line_missing_file_complaint (void)
2319 {
2320   complaint (&symfile_complaints,
2321              _(".debug_line section has line data without a file"));
2322 }
2323
2324 static void
2325 dwarf2_debug_line_missing_end_sequence_complaint (void)
2326 {
2327   complaint (&symfile_complaints,
2328              _(".debug_line section has line "
2329                "program sequence without an end"));
2330 }
2331
2332 static void
2333 dwarf2_complex_location_expr_complaint (void)
2334 {
2335   complaint (&symfile_complaints, _("location expression too complex"));
2336 }
2337
2338 static void
2339 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2340                                               int arg3)
2341 {
2342   complaint (&symfile_complaints,
2343              _("const value length mismatch for '%s', got %d, expected %d"),
2344              arg1, arg2, arg3);
2345 }
2346
2347 static void
2348 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2349 {
2350   complaint (&symfile_complaints,
2351              _("debug info runs off end of %s section"
2352                " [in module %s]"),
2353              get_section_name (section),
2354              get_section_file_name (section));
2355 }
2356
2357 static void
2358 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2359 {
2360   complaint (&symfile_complaints,
2361              _("macro debug info contains a "
2362                "malformed macro definition:\n`%s'"),
2363              arg1);
2364 }
2365
2366 static void
2367 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2368 {
2369   complaint (&symfile_complaints,
2370              _("invalid attribute class or form for '%s' in '%s'"),
2371              arg1, arg2);
2372 }
2373
2374 /* Hash function for line_header_hash.  */
2375
2376 static hashval_t
2377 line_header_hash (const struct line_header *ofs)
2378 {
2379   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2380 }
2381
2382 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2383
2384 static hashval_t
2385 line_header_hash_voidp (const void *item)
2386 {
2387   const struct line_header *ofs = (const struct line_header *) item;
2388
2389   return line_header_hash (ofs);
2390 }
2391
2392 /* Equality function for line_header_hash.  */
2393
2394 static int
2395 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2396 {
2397   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2398   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2399
2400   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2401           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2402 }
2403
2404 \f
2405
2406 /* Read the given attribute value as an address, taking the attribute's
2407    form into account.  */
2408
2409 static CORE_ADDR
2410 attr_value_as_address (struct attribute *attr)
2411 {
2412   CORE_ADDR addr;
2413
2414   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2415     {
2416       /* Aside from a few clearly defined exceptions, attributes that
2417          contain an address must always be in DW_FORM_addr form.
2418          Unfortunately, some compilers happen to be violating this
2419          requirement by encoding addresses using other forms, such
2420          as DW_FORM_data4 for example.  For those broken compilers,
2421          we try to do our best, without any guarantee of success,
2422          to interpret the address correctly.  It would also be nice
2423          to generate a complaint, but that would require us to maintain
2424          a list of legitimate cases where a non-address form is allowed,
2425          as well as update callers to pass in at least the CU's DWARF
2426          version.  This is more overhead than what we're willing to
2427          expand for a pretty rare case.  */
2428       addr = DW_UNSND (attr);
2429     }
2430   else
2431     addr = DW_ADDR (attr);
2432
2433   return addr;
2434 }
2435
2436 /* The suffix for an index file.  */
2437 #define INDEX4_SUFFIX ".gdb-index"
2438 #define INDEX5_SUFFIX ".debug_names"
2439 #define DEBUG_STR_SUFFIX ".debug_str"
2440
2441 /* See declaration.  */
2442
2443 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2444                                         const dwarf2_debug_sections *names)
2445   : objfile (objfile_)
2446 {
2447   if (names == NULL)
2448     names = &dwarf2_elf_names;
2449
2450   bfd *obfd = objfile->obfd;
2451
2452   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2453     locate_sections (obfd, sec, *names);
2454 }
2455
2456 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2457
2458 dwarf2_per_objfile::~dwarf2_per_objfile ()
2459 {
2460   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2461   free_cached_comp_units ();
2462
2463   if (quick_file_names_table)
2464     htab_delete (quick_file_names_table);
2465
2466   if (line_header_hash)
2467     htab_delete (line_header_hash);
2468
2469   for (int ix = 0; ix < n_comp_units; ++ix)
2470    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2471
2472   for (int ix = 0; ix < n_type_units; ++ix)
2473     VEC_free (dwarf2_per_cu_ptr,
2474               all_type_units[ix]->per_cu.imported_symtabs);
2475   xfree (all_type_units);
2476
2477   VEC_free (dwarf2_section_info_def, types);
2478
2479   if (dwo_files != NULL)
2480     free_dwo_files (dwo_files, objfile);
2481   if (dwp_file != NULL)
2482     gdb_bfd_unref (dwp_file->dbfd);
2483
2484   if (dwz_file != NULL && dwz_file->dwz_bfd)
2485     gdb_bfd_unref (dwz_file->dwz_bfd);
2486
2487   if (index_table != NULL)
2488     index_table->~mapped_index ();
2489
2490   /* Everything else should be on the objfile obstack.  */
2491 }
2492
2493 /* See declaration.  */
2494
2495 void
2496 dwarf2_per_objfile::free_cached_comp_units ()
2497 {
2498   dwarf2_per_cu_data *per_cu = read_in_chain;
2499   dwarf2_per_cu_data **last_chain = &read_in_chain;
2500   while (per_cu != NULL)
2501     {
2502       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2503
2504       delete per_cu->cu;
2505       *last_chain = next_cu;
2506       per_cu = next_cu;
2507     }
2508 }
2509
2510 /* Try to locate the sections we need for DWARF 2 debugging
2511    information and return true if we have enough to do something.
2512    NAMES points to the dwarf2 section names, or is NULL if the standard
2513    ELF names are used.  */
2514
2515 int
2516 dwarf2_has_info (struct objfile *objfile,
2517                  const struct dwarf2_debug_sections *names)
2518 {
2519   if (objfile->flags & OBJF_READNEVER)
2520     return 0;
2521
2522   struct dwarf2_per_objfile *dwarf2_per_objfile
2523     = get_dwarf2_per_objfile (objfile);
2524
2525   if (dwarf2_per_objfile == NULL)
2526     {
2527       /* Initialize per-objfile state.  */
2528       struct dwarf2_per_objfile *data
2529         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2530
2531       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2532       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2533     }
2534   return (!dwarf2_per_objfile->info.is_virtual
2535           && dwarf2_per_objfile->info.s.section != NULL
2536           && !dwarf2_per_objfile->abbrev.is_virtual
2537           && dwarf2_per_objfile->abbrev.s.section != NULL);
2538 }
2539
2540 /* Return the containing section of virtual section SECTION.  */
2541
2542 static struct dwarf2_section_info *
2543 get_containing_section (const struct dwarf2_section_info *section)
2544 {
2545   gdb_assert (section->is_virtual);
2546   return section->s.containing_section;
2547 }
2548
2549 /* Return the bfd owner of SECTION.  */
2550
2551 static struct bfd *
2552 get_section_bfd_owner (const struct dwarf2_section_info *section)
2553 {
2554   if (section->is_virtual)
2555     {
2556       section = get_containing_section (section);
2557       gdb_assert (!section->is_virtual);
2558     }
2559   return section->s.section->owner;
2560 }
2561
2562 /* Return the bfd section of SECTION.
2563    Returns NULL if the section is not present.  */
2564
2565 static asection *
2566 get_section_bfd_section (const struct dwarf2_section_info *section)
2567 {
2568   if (section->is_virtual)
2569     {
2570       section = get_containing_section (section);
2571       gdb_assert (!section->is_virtual);
2572     }
2573   return section->s.section;
2574 }
2575
2576 /* Return the name of SECTION.  */
2577
2578 static const char *
2579 get_section_name (const struct dwarf2_section_info *section)
2580 {
2581   asection *sectp = get_section_bfd_section (section);
2582
2583   gdb_assert (sectp != NULL);
2584   return bfd_section_name (get_section_bfd_owner (section), sectp);
2585 }
2586
2587 /* Return the name of the file SECTION is in.  */
2588
2589 static const char *
2590 get_section_file_name (const struct dwarf2_section_info *section)
2591 {
2592   bfd *abfd = get_section_bfd_owner (section);
2593
2594   return bfd_get_filename (abfd);
2595 }
2596
2597 /* Return the id of SECTION.
2598    Returns 0 if SECTION doesn't exist.  */
2599
2600 static int
2601 get_section_id (const struct dwarf2_section_info *section)
2602 {
2603   asection *sectp = get_section_bfd_section (section);
2604
2605   if (sectp == NULL)
2606     return 0;
2607   return sectp->id;
2608 }
2609
2610 /* Return the flags of SECTION.
2611    SECTION (or containing section if this is a virtual section) must exist.  */
2612
2613 static int
2614 get_section_flags (const struct dwarf2_section_info *section)
2615 {
2616   asection *sectp = get_section_bfd_section (section);
2617
2618   gdb_assert (sectp != NULL);
2619   return bfd_get_section_flags (sectp->owner, sectp);
2620 }
2621
2622 /* When loading sections, we look either for uncompressed section or for
2623    compressed section names.  */
2624
2625 static int
2626 section_is_p (const char *section_name,
2627               const struct dwarf2_section_names *names)
2628 {
2629   if (names->normal != NULL
2630       && strcmp (section_name, names->normal) == 0)
2631     return 1;
2632   if (names->compressed != NULL
2633       && strcmp (section_name, names->compressed) == 0)
2634     return 1;
2635   return 0;
2636 }
2637
2638 /* See declaration.  */
2639
2640 void
2641 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2642                                      const dwarf2_debug_sections &names)
2643 {
2644   flagword aflag = bfd_get_section_flags (abfd, sectp);
2645
2646   if ((aflag & SEC_HAS_CONTENTS) == 0)
2647     {
2648     }
2649   else if (section_is_p (sectp->name, &names.info))
2650     {
2651       this->info.s.section = sectp;
2652       this->info.size = bfd_get_section_size (sectp);
2653     }
2654   else if (section_is_p (sectp->name, &names.abbrev))
2655     {
2656       this->abbrev.s.section = sectp;
2657       this->abbrev.size = bfd_get_section_size (sectp);
2658     }
2659   else if (section_is_p (sectp->name, &names.line))
2660     {
2661       this->line.s.section = sectp;
2662       this->line.size = bfd_get_section_size (sectp);
2663     }
2664   else if (section_is_p (sectp->name, &names.loc))
2665     {
2666       this->loc.s.section = sectp;
2667       this->loc.size = bfd_get_section_size (sectp);
2668     }
2669   else if (section_is_p (sectp->name, &names.loclists))
2670     {
2671       this->loclists.s.section = sectp;
2672       this->loclists.size = bfd_get_section_size (sectp);
2673     }
2674   else if (section_is_p (sectp->name, &names.macinfo))
2675     {
2676       this->macinfo.s.section = sectp;
2677       this->macinfo.size = bfd_get_section_size (sectp);
2678     }
2679   else if (section_is_p (sectp->name, &names.macro))
2680     {
2681       this->macro.s.section = sectp;
2682       this->macro.size = bfd_get_section_size (sectp);
2683     }
2684   else if (section_is_p (sectp->name, &names.str))
2685     {
2686       this->str.s.section = sectp;
2687       this->str.size = bfd_get_section_size (sectp);
2688     }
2689   else if (section_is_p (sectp->name, &names.line_str))
2690     {
2691       this->line_str.s.section = sectp;
2692       this->line_str.size = bfd_get_section_size (sectp);
2693     }
2694   else if (section_is_p (sectp->name, &names.addr))
2695     {
2696       this->addr.s.section = sectp;
2697       this->addr.size = bfd_get_section_size (sectp);
2698     }
2699   else if (section_is_p (sectp->name, &names.frame))
2700     {
2701       this->frame.s.section = sectp;
2702       this->frame.size = bfd_get_section_size (sectp);
2703     }
2704   else if (section_is_p (sectp->name, &names.eh_frame))
2705     {
2706       this->eh_frame.s.section = sectp;
2707       this->eh_frame.size = bfd_get_section_size (sectp);
2708     }
2709   else if (section_is_p (sectp->name, &names.ranges))
2710     {
2711       this->ranges.s.section = sectp;
2712       this->ranges.size = bfd_get_section_size (sectp);
2713     }
2714   else if (section_is_p (sectp->name, &names.rnglists))
2715     {
2716       this->rnglists.s.section = sectp;
2717       this->rnglists.size = bfd_get_section_size (sectp);
2718     }
2719   else if (section_is_p (sectp->name, &names.types))
2720     {
2721       struct dwarf2_section_info type_section;
2722
2723       memset (&type_section, 0, sizeof (type_section));
2724       type_section.s.section = sectp;
2725       type_section.size = bfd_get_section_size (sectp);
2726
2727       VEC_safe_push (dwarf2_section_info_def, this->types,
2728                      &type_section);
2729     }
2730   else if (section_is_p (sectp->name, &names.gdb_index))
2731     {
2732       this->gdb_index.s.section = sectp;
2733       this->gdb_index.size = bfd_get_section_size (sectp);
2734     }
2735   else if (section_is_p (sectp->name, &names.debug_names))
2736     {
2737       this->debug_names.s.section = sectp;
2738       this->debug_names.size = bfd_get_section_size (sectp);
2739     }
2740   else if (section_is_p (sectp->name, &names.debug_aranges))
2741     {
2742       this->debug_aranges.s.section = sectp;
2743       this->debug_aranges.size = bfd_get_section_size (sectp);
2744     }
2745
2746   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2747       && bfd_section_vma (abfd, sectp) == 0)
2748     this->has_section_at_zero = true;
2749 }
2750
2751 /* A helper function that decides whether a section is empty,
2752    or not present.  */
2753
2754 static int
2755 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2756 {
2757   if (section->is_virtual)
2758     return section->size == 0;
2759   return section->s.section == NULL || section->size == 0;
2760 }
2761
2762 /* Read the contents of the section INFO.
2763    OBJFILE is the main object file, but not necessarily the file where
2764    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2765    of the DWO file.
2766    If the section is compressed, uncompress it before returning.  */
2767
2768 static void
2769 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2770 {
2771   asection *sectp;
2772   bfd *abfd;
2773   gdb_byte *buf, *retbuf;
2774
2775   if (info->readin)
2776     return;
2777   info->buffer = NULL;
2778   info->readin = 1;
2779
2780   if (dwarf2_section_empty_p (info))
2781     return;
2782
2783   sectp = get_section_bfd_section (info);
2784
2785   /* If this is a virtual section we need to read in the real one first.  */
2786   if (info->is_virtual)
2787     {
2788       struct dwarf2_section_info *containing_section =
2789         get_containing_section (info);
2790
2791       gdb_assert (sectp != NULL);
2792       if ((sectp->flags & SEC_RELOC) != 0)
2793         {
2794           error (_("Dwarf Error: DWP format V2 with relocations is not"
2795                    " supported in section %s [in module %s]"),
2796                  get_section_name (info), get_section_file_name (info));
2797         }
2798       dwarf2_read_section (objfile, containing_section);
2799       /* Other code should have already caught virtual sections that don't
2800          fit.  */
2801       gdb_assert (info->virtual_offset + info->size
2802                   <= containing_section->size);
2803       /* If the real section is empty or there was a problem reading the
2804          section we shouldn't get here.  */
2805       gdb_assert (containing_section->buffer != NULL);
2806       info->buffer = containing_section->buffer + info->virtual_offset;
2807       return;
2808     }
2809
2810   /* If the section has relocations, we must read it ourselves.
2811      Otherwise we attach it to the BFD.  */
2812   if ((sectp->flags & SEC_RELOC) == 0)
2813     {
2814       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2815       return;
2816     }
2817
2818   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2819   info->buffer = buf;
2820
2821   /* When debugging .o files, we may need to apply relocations; see
2822      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2823      We never compress sections in .o files, so we only need to
2824      try this when the section is not compressed.  */
2825   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2826   if (retbuf != NULL)
2827     {
2828       info->buffer = retbuf;
2829       return;
2830     }
2831
2832   abfd = get_section_bfd_owner (info);
2833   gdb_assert (abfd != NULL);
2834
2835   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2836       || bfd_bread (buf, info->size, abfd) != info->size)
2837     {
2838       error (_("Dwarf Error: Can't read DWARF data"
2839                " in section %s [in module %s]"),
2840              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2841     }
2842 }
2843
2844 /* A helper function that returns the size of a section in a safe way.
2845    If you are positive that the section has been read before using the
2846    size, then it is safe to refer to the dwarf2_section_info object's
2847    "size" field directly.  In other cases, you must call this
2848    function, because for compressed sections the size field is not set
2849    correctly until the section has been read.  */
2850
2851 static bfd_size_type
2852 dwarf2_section_size (struct objfile *objfile,
2853                      struct dwarf2_section_info *info)
2854 {
2855   if (!info->readin)
2856     dwarf2_read_section (objfile, info);
2857   return info->size;
2858 }
2859
2860 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2861    SECTION_NAME.  */
2862
2863 void
2864 dwarf2_get_section_info (struct objfile *objfile,
2865                          enum dwarf2_section_enum sect,
2866                          asection **sectp, const gdb_byte **bufp,
2867                          bfd_size_type *sizep)
2868 {
2869   struct dwarf2_per_objfile *data
2870     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2871                                                   dwarf2_objfile_data_key);
2872   struct dwarf2_section_info *info;
2873
2874   /* We may see an objfile without any DWARF, in which case we just
2875      return nothing.  */
2876   if (data == NULL)
2877     {
2878       *sectp = NULL;
2879       *bufp = NULL;
2880       *sizep = 0;
2881       return;
2882     }
2883   switch (sect)
2884     {
2885     case DWARF2_DEBUG_FRAME:
2886       info = &data->frame;
2887       break;
2888     case DWARF2_EH_FRAME:
2889       info = &data->eh_frame;
2890       break;
2891     default:
2892       gdb_assert_not_reached ("unexpected section");
2893     }
2894
2895   dwarf2_read_section (objfile, info);
2896
2897   *sectp = get_section_bfd_section (info);
2898   *bufp = info->buffer;
2899   *sizep = info->size;
2900 }
2901
2902 /* A helper function to find the sections for a .dwz file.  */
2903
2904 static void
2905 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2906 {
2907   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2908
2909   /* Note that we only support the standard ELF names, because .dwz
2910      is ELF-only (at the time of writing).  */
2911   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2912     {
2913       dwz_file->abbrev.s.section = sectp;
2914       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2915     }
2916   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2917     {
2918       dwz_file->info.s.section = sectp;
2919       dwz_file->info.size = bfd_get_section_size (sectp);
2920     }
2921   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2922     {
2923       dwz_file->str.s.section = sectp;
2924       dwz_file->str.size = bfd_get_section_size (sectp);
2925     }
2926   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2927     {
2928       dwz_file->line.s.section = sectp;
2929       dwz_file->line.size = bfd_get_section_size (sectp);
2930     }
2931   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2932     {
2933       dwz_file->macro.s.section = sectp;
2934       dwz_file->macro.size = bfd_get_section_size (sectp);
2935     }
2936   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2937     {
2938       dwz_file->gdb_index.s.section = sectp;
2939       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2940     }
2941   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2942     {
2943       dwz_file->debug_names.s.section = sectp;
2944       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2945     }
2946 }
2947
2948 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2949    there is no .gnu_debugaltlink section in the file.  Error if there
2950    is such a section but the file cannot be found.  */
2951
2952 static struct dwz_file *
2953 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2954 {
2955   const char *filename;
2956   struct dwz_file *result;
2957   bfd_size_type buildid_len_arg;
2958   size_t buildid_len;
2959   bfd_byte *buildid;
2960
2961   if (dwarf2_per_objfile->dwz_file != NULL)
2962     return dwarf2_per_objfile->dwz_file;
2963
2964   bfd_set_error (bfd_error_no_error);
2965   gdb::unique_xmalloc_ptr<char> data
2966     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2967                                   &buildid_len_arg, &buildid));
2968   if (data == NULL)
2969     {
2970       if (bfd_get_error () == bfd_error_no_error)
2971         return NULL;
2972       error (_("could not read '.gnu_debugaltlink' section: %s"),
2973              bfd_errmsg (bfd_get_error ()));
2974     }
2975
2976   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2977
2978   buildid_len = (size_t) buildid_len_arg;
2979
2980   filename = data.get ();
2981
2982   std::string abs_storage;
2983   if (!IS_ABSOLUTE_PATH (filename))
2984     {
2985       gdb::unique_xmalloc_ptr<char> abs
2986         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2987
2988       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2989       filename = abs_storage.c_str ();
2990     }
2991
2992   /* First try the file name given in the section.  If that doesn't
2993      work, try to use the build-id instead.  */
2994   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2995   if (dwz_bfd != NULL)
2996     {
2997       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2998         dwz_bfd.release ();
2999     }
3000
3001   if (dwz_bfd == NULL)
3002     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
3003
3004   if (dwz_bfd == NULL)
3005     error (_("could not find '.gnu_debugaltlink' file for %s"),
3006            objfile_name (dwarf2_per_objfile->objfile));
3007
3008   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
3009                            struct dwz_file);
3010   result->dwz_bfd = dwz_bfd.release ();
3011
3012   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
3013
3014   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
3015   dwarf2_per_objfile->dwz_file = result;
3016   return result;
3017 }
3018 \f
3019 /* DWARF quick_symbols_functions support.  */
3020
3021 /* TUs can share .debug_line entries, and there can be a lot more TUs than
3022    unique line tables, so we maintain a separate table of all .debug_line
3023    derived entries to support the sharing.
3024    All the quick functions need is the list of file names.  We discard the
3025    line_header when we're done and don't need to record it here.  */
3026 struct quick_file_names
3027 {
3028   /* The data used to construct the hash key.  */
3029   struct stmt_list_hash hash;
3030
3031   /* The number of entries in file_names, real_names.  */
3032   unsigned int num_file_names;
3033
3034   /* The file names from the line table, after being run through
3035      file_full_name.  */
3036   const char **file_names;
3037
3038   /* The file names from the line table after being run through
3039      gdb_realpath.  These are computed lazily.  */
3040   const char **real_names;
3041 };
3042
3043 /* When using the index (and thus not using psymtabs), each CU has an
3044    object of this type.  This is used to hold information needed by
3045    the various "quick" methods.  */
3046 struct dwarf2_per_cu_quick_data
3047 {
3048   /* The file table.  This can be NULL if there was no file table
3049      or it's currently not read in.
3050      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3051   struct quick_file_names *file_names;
3052
3053   /* The corresponding symbol table.  This is NULL if symbols for this
3054      CU have not yet been read.  */
3055   struct compunit_symtab *compunit_symtab;
3056
3057   /* A temporary mark bit used when iterating over all CUs in
3058      expand_symtabs_matching.  */
3059   unsigned int mark : 1;
3060
3061   /* True if we've tried to read the file table and found there isn't one.
3062      There will be no point in trying to read it again next time.  */
3063   unsigned int no_file_data : 1;
3064 };
3065
3066 /* Utility hash function for a stmt_list_hash.  */
3067
3068 static hashval_t
3069 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3070 {
3071   hashval_t v = 0;
3072
3073   if (stmt_list_hash->dwo_unit != NULL)
3074     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3075   v += to_underlying (stmt_list_hash->line_sect_off);
3076   return v;
3077 }
3078
3079 /* Utility equality function for a stmt_list_hash.  */
3080
3081 static int
3082 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3083                     const struct stmt_list_hash *rhs)
3084 {
3085   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3086     return 0;
3087   if (lhs->dwo_unit != NULL
3088       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3089     return 0;
3090
3091   return lhs->line_sect_off == rhs->line_sect_off;
3092 }
3093
3094 /* Hash function for a quick_file_names.  */
3095
3096 static hashval_t
3097 hash_file_name_entry (const void *e)
3098 {
3099   const struct quick_file_names *file_data
3100     = (const struct quick_file_names *) e;
3101
3102   return hash_stmt_list_entry (&file_data->hash);
3103 }
3104
3105 /* Equality function for a quick_file_names.  */
3106
3107 static int
3108 eq_file_name_entry (const void *a, const void *b)
3109 {
3110   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3111   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3112
3113   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3114 }
3115
3116 /* Delete function for a quick_file_names.  */
3117
3118 static void
3119 delete_file_name_entry (void *e)
3120 {
3121   struct quick_file_names *file_data = (struct quick_file_names *) e;
3122   int i;
3123
3124   for (i = 0; i < file_data->num_file_names; ++i)
3125     {
3126       xfree ((void*) file_data->file_names[i]);
3127       if (file_data->real_names)
3128         xfree ((void*) file_data->real_names[i]);
3129     }
3130
3131   /* The space for the struct itself lives on objfile_obstack,
3132      so we don't free it here.  */
3133 }
3134
3135 /* Create a quick_file_names hash table.  */
3136
3137 static htab_t
3138 create_quick_file_names_table (unsigned int nr_initial_entries)
3139 {
3140   return htab_create_alloc (nr_initial_entries,
3141                             hash_file_name_entry, eq_file_name_entry,
3142                             delete_file_name_entry, xcalloc, xfree);
3143 }
3144
3145 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3146    have to be created afterwards.  You should call age_cached_comp_units after
3147    processing PER_CU->CU.  dw2_setup must have been already called.  */
3148
3149 static void
3150 load_cu (struct dwarf2_per_cu_data *per_cu)
3151 {
3152   if (per_cu->is_debug_types)
3153     load_full_type_unit (per_cu);
3154   else
3155     load_full_comp_unit (per_cu, language_minimal);
3156
3157   if (per_cu->cu == NULL)
3158     return;  /* Dummy CU.  */
3159
3160   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3161 }
3162
3163 /* Read in the symbols for PER_CU.  */
3164
3165 static void
3166 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3167 {
3168   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3169
3170   /* Skip type_unit_groups, reading the type units they contain
3171      is handled elsewhere.  */
3172   if (IS_TYPE_UNIT_GROUP (per_cu))
3173     return;
3174
3175   /* The destructor of dwarf2_queue_guard frees any entries left on
3176      the queue.  After this point we're guaranteed to leave this function
3177      with the dwarf queue empty.  */
3178   dwarf2_queue_guard q_guard;
3179
3180   if (dwarf2_per_objfile->using_index
3181       ? per_cu->v.quick->compunit_symtab == NULL
3182       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3183     {
3184       queue_comp_unit (per_cu, language_minimal);
3185       load_cu (per_cu);
3186
3187       /* If we just loaded a CU from a DWO, and we're working with an index
3188          that may badly handle TUs, load all the TUs in that DWO as well.
3189          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3190       if (!per_cu->is_debug_types
3191           && per_cu->cu != NULL
3192           && per_cu->cu->dwo_unit != NULL
3193           && dwarf2_per_objfile->index_table != NULL
3194           && dwarf2_per_objfile->index_table->version <= 7
3195           /* DWP files aren't supported yet.  */
3196           && get_dwp_file (dwarf2_per_objfile) == NULL)
3197         queue_and_load_all_dwo_tus (per_cu);
3198     }
3199
3200   process_queue (dwarf2_per_objfile);
3201
3202   /* Age the cache, releasing compilation units that have not
3203      been used recently.  */
3204   age_cached_comp_units (dwarf2_per_objfile);
3205 }
3206
3207 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3208    the objfile from which this CU came.  Returns the resulting symbol
3209    table.  */
3210
3211 static struct compunit_symtab *
3212 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3213 {
3214   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3215
3216   gdb_assert (dwarf2_per_objfile->using_index);
3217   if (!per_cu->v.quick->compunit_symtab)
3218     {
3219       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3220                                               dwarf2_per_objfile);
3221       scoped_restore decrementer = increment_reading_symtab ();
3222       dw2_do_instantiate_symtab (per_cu);
3223       process_cu_includes (dwarf2_per_objfile);
3224       do_cleanups (back_to);
3225     }
3226
3227   return per_cu->v.quick->compunit_symtab;
3228 }
3229
3230 /* Return the CU/TU given its index.
3231
3232    This is intended for loops like:
3233
3234    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3235                     + dwarf2_per_objfile->n_type_units); ++i)
3236      {
3237        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3238
3239        ...;
3240      }
3241 */
3242
3243 static struct dwarf2_per_cu_data *
3244 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3245               int index)
3246 {
3247   if (index >= dwarf2_per_objfile->n_comp_units)
3248     {
3249       index -= dwarf2_per_objfile->n_comp_units;
3250       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3251       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3252     }
3253
3254   return dwarf2_per_objfile->all_comp_units[index];
3255 }
3256
3257 /* Return the CU given its index.
3258    This differs from dw2_get_cutu in that it's for when you know INDEX
3259    refers to a CU.  */
3260
3261 static struct dwarf2_per_cu_data *
3262 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3263 {
3264   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3265
3266   return dwarf2_per_objfile->all_comp_units[index];
3267 }
3268
3269 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3270    objfile_obstack, and constructed with the specified field
3271    values.  */
3272
3273 static dwarf2_per_cu_data *
3274 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3275                           struct dwarf2_section_info *section,
3276                           int is_dwz,
3277                           sect_offset sect_off, ULONGEST length)
3278 {
3279   struct objfile *objfile = dwarf2_per_objfile->objfile;
3280   dwarf2_per_cu_data *the_cu
3281     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3282                      struct dwarf2_per_cu_data);
3283   the_cu->sect_off = sect_off;
3284   the_cu->length = length;
3285   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3286   the_cu->section = section;
3287   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3288                                    struct dwarf2_per_cu_quick_data);
3289   the_cu->is_dwz = is_dwz;
3290   return the_cu;
3291 }
3292
3293 /* A helper for create_cus_from_index that handles a given list of
3294    CUs.  */
3295
3296 static void
3297 create_cus_from_index_list (struct objfile *objfile,
3298                             const gdb_byte *cu_list, offset_type n_elements,
3299                             struct dwarf2_section_info *section,
3300                             int is_dwz,
3301                             int base_offset)
3302 {
3303   offset_type i;
3304   struct dwarf2_per_objfile *dwarf2_per_objfile
3305     = get_dwarf2_per_objfile (objfile);
3306
3307   for (i = 0; i < n_elements; i += 2)
3308     {
3309       gdb_static_assert (sizeof (ULONGEST) >= 8);
3310
3311       sect_offset sect_off
3312         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3313       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3314       cu_list += 2 * 8;
3315
3316       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3317         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3318                                      sect_off, length);
3319     }
3320 }
3321
3322 /* Read the CU list from the mapped index, and use it to create all
3323    the CU objects for this objfile.  */
3324
3325 static void
3326 create_cus_from_index (struct objfile *objfile,
3327                        const gdb_byte *cu_list, offset_type cu_list_elements,
3328                        const gdb_byte *dwz_list, offset_type dwz_elements)
3329 {
3330   struct dwz_file *dwz;
3331   struct dwarf2_per_objfile *dwarf2_per_objfile
3332     = get_dwarf2_per_objfile (objfile);
3333
3334   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3335   dwarf2_per_objfile->all_comp_units =
3336     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3337                dwarf2_per_objfile->n_comp_units);
3338
3339   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3340                               &dwarf2_per_objfile->info, 0, 0);
3341
3342   if (dwz_elements == 0)
3343     return;
3344
3345   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3346   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3347                               cu_list_elements / 2);
3348 }
3349
3350 /* Create the signatured type hash table from the index.  */
3351
3352 static void
3353 create_signatured_type_table_from_index (struct objfile *objfile,
3354                                          struct dwarf2_section_info *section,
3355                                          const gdb_byte *bytes,
3356                                          offset_type elements)
3357 {
3358   offset_type i;
3359   htab_t sig_types_hash;
3360   struct dwarf2_per_objfile *dwarf2_per_objfile
3361     = get_dwarf2_per_objfile (objfile);
3362
3363   dwarf2_per_objfile->n_type_units
3364     = dwarf2_per_objfile->n_allocated_type_units
3365     = elements / 3;
3366   dwarf2_per_objfile->all_type_units =
3367     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3368
3369   sig_types_hash = allocate_signatured_type_table (objfile);
3370
3371   for (i = 0; i < elements; i += 3)
3372     {
3373       struct signatured_type *sig_type;
3374       ULONGEST signature;
3375       void **slot;
3376       cu_offset type_offset_in_tu;
3377
3378       gdb_static_assert (sizeof (ULONGEST) >= 8);
3379       sect_offset sect_off
3380         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3381       type_offset_in_tu
3382         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3383                                                 BFD_ENDIAN_LITTLE);
3384       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3385       bytes += 3 * 8;
3386
3387       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3388                                  struct signatured_type);
3389       sig_type->signature = signature;
3390       sig_type->type_offset_in_tu = type_offset_in_tu;
3391       sig_type->per_cu.is_debug_types = 1;
3392       sig_type->per_cu.section = section;
3393       sig_type->per_cu.sect_off = sect_off;
3394       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3395       sig_type->per_cu.v.quick
3396         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3397                           struct dwarf2_per_cu_quick_data);
3398
3399       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3400       *slot = sig_type;
3401
3402       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3403     }
3404
3405   dwarf2_per_objfile->signatured_types = sig_types_hash;
3406 }
3407
3408 /* Create the signatured type hash table from .debug_names.  */
3409
3410 static void
3411 create_signatured_type_table_from_debug_names
3412   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3413    const mapped_debug_names &map,
3414    struct dwarf2_section_info *section,
3415    struct dwarf2_section_info *abbrev_section)
3416 {
3417   struct objfile *objfile = dwarf2_per_objfile->objfile;
3418
3419   dwarf2_read_section (objfile, section);
3420   dwarf2_read_section (objfile, abbrev_section);
3421
3422   dwarf2_per_objfile->n_type_units
3423     = dwarf2_per_objfile->n_allocated_type_units
3424     = map.tu_count;
3425   dwarf2_per_objfile->all_type_units
3426     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3427
3428   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3429
3430   for (uint32_t i = 0; i < map.tu_count; ++i)
3431     {
3432       struct signatured_type *sig_type;
3433       ULONGEST signature;
3434       void **slot;
3435       cu_offset type_offset_in_tu;
3436
3437       sect_offset sect_off
3438         = (sect_offset) (extract_unsigned_integer
3439                          (map.tu_table_reordered + i * map.offset_size,
3440                           map.offset_size,
3441                           map.dwarf5_byte_order));
3442
3443       comp_unit_head cu_header;
3444       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3445                                      abbrev_section,
3446                                      section->buffer + to_underlying (sect_off),
3447                                      rcuh_kind::TYPE);
3448
3449       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3450                                  struct signatured_type);
3451       sig_type->signature = cu_header.signature;
3452       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3453       sig_type->per_cu.is_debug_types = 1;
3454       sig_type->per_cu.section = section;
3455       sig_type->per_cu.sect_off = sect_off;
3456       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3457       sig_type->per_cu.v.quick
3458         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3459                           struct dwarf2_per_cu_quick_data);
3460
3461       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3462       *slot = sig_type;
3463
3464       dwarf2_per_objfile->all_type_units[i] = sig_type;
3465     }
3466
3467   dwarf2_per_objfile->signatured_types = sig_types_hash;
3468 }
3469
3470 /* Read the address map data from the mapped index, and use it to
3471    populate the objfile's psymtabs_addrmap.  */
3472
3473 static void
3474 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3475                            struct mapped_index *index)
3476 {
3477   struct objfile *objfile = dwarf2_per_objfile->objfile;
3478   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3479   const gdb_byte *iter, *end;
3480   struct addrmap *mutable_map;
3481   CORE_ADDR baseaddr;
3482
3483   auto_obstack temp_obstack;
3484
3485   mutable_map = addrmap_create_mutable (&temp_obstack);
3486
3487   iter = index->address_table.data ();
3488   end = iter + index->address_table.size ();
3489
3490   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3491
3492   while (iter < end)
3493     {
3494       ULONGEST hi, lo, cu_index;
3495       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3496       iter += 8;
3497       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3498       iter += 8;
3499       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3500       iter += 4;
3501
3502       if (lo > hi)
3503         {
3504           complaint (&symfile_complaints,
3505                      _(".gdb_index address table has invalid range (%s - %s)"),
3506                      hex_string (lo), hex_string (hi));
3507           continue;
3508         }
3509
3510       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3511         {
3512           complaint (&symfile_complaints,
3513                      _(".gdb_index address table has invalid CU number %u"),
3514                      (unsigned) cu_index);
3515           continue;
3516         }
3517
3518       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3519       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3520       addrmap_set_empty (mutable_map, lo, hi - 1,
3521                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3522     }
3523
3524   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3525                                                     &objfile->objfile_obstack);
3526 }
3527
3528 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3529    populate the objfile's psymtabs_addrmap.  */
3530
3531 static void
3532 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3533                              struct dwarf2_section_info *section)
3534 {
3535   struct objfile *objfile = dwarf2_per_objfile->objfile;
3536   bfd *abfd = objfile->obfd;
3537   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3538   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3539                                        SECT_OFF_TEXT (objfile));
3540
3541   auto_obstack temp_obstack;
3542   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3543
3544   std::unordered_map<sect_offset,
3545                      dwarf2_per_cu_data *,
3546                      gdb::hash_enum<sect_offset>>
3547     debug_info_offset_to_per_cu;
3548   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3549     {
3550       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3551       const auto insertpair
3552         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3553       if (!insertpair.second)
3554         {
3555           warning (_("Section .debug_aranges in %s has duplicate "
3556                      "debug_info_offset %u, ignoring .debug_aranges."),
3557                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3558           return;
3559         }
3560     }
3561
3562   dwarf2_read_section (objfile, section);
3563
3564   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3565
3566   const gdb_byte *addr = section->buffer;
3567
3568   while (addr < section->buffer + section->size)
3569     {
3570       const gdb_byte *const entry_addr = addr;
3571       unsigned int bytes_read;
3572
3573       const LONGEST entry_length = read_initial_length (abfd, addr,
3574                                                         &bytes_read);
3575       addr += bytes_read;
3576
3577       const gdb_byte *const entry_end = addr + entry_length;
3578       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3579       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3580       if (addr + entry_length > section->buffer + section->size)
3581         {
3582           warning (_("Section .debug_aranges in %s entry at offset %zu "
3583                      "length %s exceeds section length %s, "
3584                      "ignoring .debug_aranges."),
3585                    objfile_name (objfile), entry_addr - section->buffer,
3586                    plongest (bytes_read + entry_length),
3587                    pulongest (section->size));
3588           return;
3589         }
3590
3591       /* The version number.  */
3592       const uint16_t version = read_2_bytes (abfd, addr);
3593       addr += 2;
3594       if (version != 2)
3595         {
3596           warning (_("Section .debug_aranges in %s entry at offset %zu "
3597                      "has unsupported version %d, ignoring .debug_aranges."),
3598                    objfile_name (objfile), entry_addr - section->buffer,
3599                    version);
3600           return;
3601         }
3602
3603       const uint64_t debug_info_offset
3604         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3605       addr += offset_size;
3606       const auto per_cu_it
3607         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3608       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3609         {
3610           warning (_("Section .debug_aranges in %s entry at offset %zu "
3611                      "debug_info_offset %s does not exists, "
3612                      "ignoring .debug_aranges."),
3613                    objfile_name (objfile), entry_addr - section->buffer,
3614                    pulongest (debug_info_offset));
3615           return;
3616         }
3617       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3618
3619       const uint8_t address_size = *addr++;
3620       if (address_size < 1 || address_size > 8)
3621         {
3622           warning (_("Section .debug_aranges in %s entry at offset %zu "
3623                      "address_size %u is invalid, ignoring .debug_aranges."),
3624                    objfile_name (objfile), entry_addr - section->buffer,
3625                    address_size);
3626           return;
3627         }
3628
3629       const uint8_t segment_selector_size = *addr++;
3630       if (segment_selector_size != 0)
3631         {
3632           warning (_("Section .debug_aranges in %s entry at offset %zu "
3633                      "segment_selector_size %u is not supported, "
3634                      "ignoring .debug_aranges."),
3635                    objfile_name (objfile), entry_addr - section->buffer,
3636                    segment_selector_size);
3637           return;
3638         }
3639
3640       /* Must pad to an alignment boundary that is twice the address
3641          size.  It is undocumented by the DWARF standard but GCC does
3642          use it.  */
3643       for (size_t padding = ((-(addr - section->buffer))
3644                              & (2 * address_size - 1));
3645            padding > 0; padding--)
3646         if (*addr++ != 0)
3647           {
3648             warning (_("Section .debug_aranges in %s entry at offset %zu "
3649                        "padding is not zero, ignoring .debug_aranges."),
3650                      objfile_name (objfile), entry_addr - section->buffer);
3651             return;
3652           }
3653
3654       for (;;)
3655         {
3656           if (addr + 2 * address_size > entry_end)
3657             {
3658               warning (_("Section .debug_aranges in %s entry at offset %zu "
3659                          "address list is not properly terminated, "
3660                          "ignoring .debug_aranges."),
3661                        objfile_name (objfile), entry_addr - section->buffer);
3662               return;
3663             }
3664           ULONGEST start = extract_unsigned_integer (addr, address_size,
3665                                                      dwarf5_byte_order);
3666           addr += address_size;
3667           ULONGEST length = extract_unsigned_integer (addr, address_size,
3668                                                       dwarf5_byte_order);
3669           addr += address_size;
3670           if (start == 0 && length == 0)
3671             break;
3672           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3673             {
3674               /* Symbol was eliminated due to a COMDAT group.  */
3675               continue;
3676             }
3677           ULONGEST end = start + length;
3678           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3679           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3680           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3681         }
3682     }
3683
3684   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3685                                                     &objfile->objfile_obstack);
3686 }
3687
3688 /* The hash function for strings in the mapped index.  This is the same as
3689    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3690    implementation.  This is necessary because the hash function is tied to the
3691    format of the mapped index file.  The hash values do not have to match with
3692    SYMBOL_HASH_NEXT.
3693    
3694    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3695
3696 static hashval_t
3697 mapped_index_string_hash (int index_version, const void *p)
3698 {
3699   const unsigned char *str = (const unsigned char *) p;
3700   hashval_t r = 0;
3701   unsigned char c;
3702
3703   while ((c = *str++) != 0)
3704     {
3705       if (index_version >= 5)
3706         c = tolower (c);
3707       r = r * 67 + c - 113;
3708     }
3709
3710   return r;
3711 }
3712
3713 /* Find a slot in the mapped index INDEX for the object named NAME.
3714    If NAME is found, set *VEC_OUT to point to the CU vector in the
3715    constant pool and return true.  If NAME cannot be found, return
3716    false.  */
3717
3718 static bool
3719 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3720                           offset_type **vec_out)
3721 {
3722   offset_type hash;
3723   offset_type slot, step;
3724   int (*cmp) (const char *, const char *);
3725
3726   gdb::unique_xmalloc_ptr<char> without_params;
3727   if (current_language->la_language == language_cplus
3728       || current_language->la_language == language_fortran
3729       || current_language->la_language == language_d)
3730     {
3731       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3732          not contain any.  */
3733
3734       if (strchr (name, '(') != NULL)
3735         {
3736           without_params = cp_remove_params (name);
3737
3738           if (without_params != NULL)
3739             name = without_params.get ();
3740         }
3741     }
3742
3743   /* Index version 4 did not support case insensitive searches.  But the
3744      indices for case insensitive languages are built in lowercase, therefore
3745      simulate our NAME being searched is also lowercased.  */
3746   hash = mapped_index_string_hash ((index->version == 4
3747                                     && case_sensitivity == case_sensitive_off
3748                                     ? 5 : index->version),
3749                                    name);
3750
3751   slot = hash & (index->symbol_table.size () - 1);
3752   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3753   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3754
3755   for (;;)
3756     {
3757       const char *str;
3758
3759       const auto &bucket = index->symbol_table[slot];
3760       if (bucket.name == 0 && bucket.vec == 0)
3761         return false;
3762
3763       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3764       if (!cmp (name, str))
3765         {
3766           *vec_out = (offset_type *) (index->constant_pool
3767                                       + MAYBE_SWAP (bucket.vec));
3768           return true;
3769         }
3770
3771       slot = (slot + step) & (index->symbol_table.size () - 1);
3772     }
3773 }
3774
3775 /* A helper function that reads the .gdb_index from SECTION and fills
3776    in MAP.  FILENAME is the name of the file containing the section;
3777    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3778    ok to use deprecated sections.
3779
3780    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3781    out parameters that are filled in with information about the CU and
3782    TU lists in the section.
3783
3784    Returns 1 if all went well, 0 otherwise.  */
3785
3786 static int
3787 read_index_from_section (struct objfile *objfile,
3788                          const char *filename,
3789                          int deprecated_ok,
3790                          struct dwarf2_section_info *section,
3791                          struct mapped_index *map,
3792                          const gdb_byte **cu_list,
3793                          offset_type *cu_list_elements,
3794                          const gdb_byte **types_list,
3795                          offset_type *types_list_elements)
3796 {
3797   const gdb_byte *addr;
3798   offset_type version;
3799   offset_type *metadata;
3800   int i;
3801
3802   if (dwarf2_section_empty_p (section))
3803     return 0;
3804
3805   /* Older elfutils strip versions could keep the section in the main
3806      executable while splitting it for the separate debug info file.  */
3807   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3808     return 0;
3809
3810   dwarf2_read_section (objfile, section);
3811
3812   addr = section->buffer;
3813   /* Version check.  */
3814   version = MAYBE_SWAP (*(offset_type *) addr);
3815   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3816      causes the index to behave very poorly for certain requests.  Version 3
3817      contained incomplete addrmap.  So, it seems better to just ignore such
3818      indices.  */
3819   if (version < 4)
3820     {
3821       static int warning_printed = 0;
3822       if (!warning_printed)
3823         {
3824           warning (_("Skipping obsolete .gdb_index section in %s."),
3825                    filename);
3826           warning_printed = 1;
3827         }
3828       return 0;
3829     }
3830   /* Index version 4 uses a different hash function than index version
3831      5 and later.
3832
3833      Versions earlier than 6 did not emit psymbols for inlined
3834      functions.  Using these files will cause GDB not to be able to
3835      set breakpoints on inlined functions by name, so we ignore these
3836      indices unless the user has done
3837      "set use-deprecated-index-sections on".  */
3838   if (version < 6 && !deprecated_ok)
3839     {
3840       static int warning_printed = 0;
3841       if (!warning_printed)
3842         {
3843           warning (_("\
3844 Skipping deprecated .gdb_index section in %s.\n\
3845 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3846 to use the section anyway."),
3847                    filename);
3848           warning_printed = 1;
3849         }
3850       return 0;
3851     }
3852   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3853      of the TU (for symbols coming from TUs),
3854      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3855      Plus gold-generated indices can have duplicate entries for global symbols,
3856      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3857      These are just performance bugs, and we can't distinguish gdb-generated
3858      indices from gold-generated ones, so issue no warning here.  */
3859
3860   /* Indexes with higher version than the one supported by GDB may be no
3861      longer backward compatible.  */
3862   if (version > 8)
3863     return 0;
3864
3865   map->version = version;
3866   map->total_size = section->size;
3867
3868   metadata = (offset_type *) (addr + sizeof (offset_type));
3869
3870   i = 0;
3871   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3872   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3873                        / 8);
3874   ++i;
3875
3876   *types_list = addr + MAYBE_SWAP (metadata[i]);
3877   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3878                            - MAYBE_SWAP (metadata[i]))
3879                           / 8);
3880   ++i;
3881
3882   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3883   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3884   map->address_table
3885     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3886   ++i;
3887
3888   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3889   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3890   map->symbol_table
3891     = gdb::array_view<mapped_index::symbol_table_slot>
3892        ((mapped_index::symbol_table_slot *) symbol_table,
3893         (mapped_index::symbol_table_slot *) symbol_table_end);
3894
3895   ++i;
3896   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3897
3898   return 1;
3899 }
3900
3901 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3902    elements of all the CUs and return 1.  Otherwise, return 0.  */
3903
3904 static int
3905 dwarf2_read_index (struct objfile *objfile)
3906 {
3907   struct mapped_index local_map, *map;
3908   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3909   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3910   struct dwz_file *dwz;
3911   struct dwarf2_per_objfile *dwarf2_per_objfile
3912     = get_dwarf2_per_objfile (objfile);
3913
3914   if (!read_index_from_section (objfile, objfile_name (objfile),
3915                                 use_deprecated_index_sections,
3916                                 &dwarf2_per_objfile->gdb_index, &local_map,
3917                                 &cu_list, &cu_list_elements,
3918                                 &types_list, &types_list_elements))
3919     return 0;
3920
3921   /* Don't use the index if it's empty.  */
3922   if (local_map.symbol_table.empty ())
3923     return 0;
3924
3925   /* If there is a .dwz file, read it so we can get its CU list as
3926      well.  */
3927   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3928   if (dwz != NULL)
3929     {
3930       struct mapped_index dwz_map;
3931       const gdb_byte *dwz_types_ignore;
3932       offset_type dwz_types_elements_ignore;
3933
3934       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3935                                     1,
3936                                     &dwz->gdb_index, &dwz_map,
3937                                     &dwz_list, &dwz_list_elements,
3938                                     &dwz_types_ignore,
3939                                     &dwz_types_elements_ignore))
3940         {
3941           warning (_("could not read '.gdb_index' section from %s; skipping"),
3942                    bfd_get_filename (dwz->dwz_bfd));
3943           return 0;
3944         }
3945     }
3946
3947   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3948                          dwz_list_elements);
3949
3950   if (types_list_elements)
3951     {
3952       struct dwarf2_section_info *section;
3953
3954       /* We can only handle a single .debug_types when we have an
3955          index.  */
3956       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3957         return 0;
3958
3959       section = VEC_index (dwarf2_section_info_def,
3960                            dwarf2_per_objfile->types, 0);
3961
3962       create_signatured_type_table_from_index (objfile, section, types_list,
3963                                                types_list_elements);
3964     }
3965
3966   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3967
3968   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3969   map = new (map) mapped_index ();
3970   *map = local_map;
3971
3972   dwarf2_per_objfile->index_table = map;
3973   dwarf2_per_objfile->using_index = 1;
3974   dwarf2_per_objfile->quick_file_names_table =
3975     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3976
3977   return 1;
3978 }
3979
3980 /* die_reader_func for dw2_get_file_names.  */
3981
3982 static void
3983 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3984                            const gdb_byte *info_ptr,
3985                            struct die_info *comp_unit_die,
3986                            int has_children,
3987                            void *data)
3988 {
3989   struct dwarf2_cu *cu = reader->cu;
3990   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3991   struct dwarf2_per_objfile *dwarf2_per_objfile
3992     = cu->per_cu->dwarf2_per_objfile;
3993   struct objfile *objfile = dwarf2_per_objfile->objfile;
3994   struct dwarf2_per_cu_data *lh_cu;
3995   struct attribute *attr;
3996   int i;
3997   void **slot;
3998   struct quick_file_names *qfn;
3999
4000   gdb_assert (! this_cu->is_debug_types);
4001
4002   /* Our callers never want to match partial units -- instead they
4003      will match the enclosing full CU.  */
4004   if (comp_unit_die->tag == DW_TAG_partial_unit)
4005     {
4006       this_cu->v.quick->no_file_data = 1;
4007       return;
4008     }
4009
4010   lh_cu = this_cu;
4011   slot = NULL;
4012
4013   line_header_up lh;
4014   sect_offset line_offset {};
4015
4016   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4017   if (attr)
4018     {
4019       struct quick_file_names find_entry;
4020
4021       line_offset = (sect_offset) DW_UNSND (attr);
4022
4023       /* We may have already read in this line header (TU line header sharing).
4024          If we have we're done.  */
4025       find_entry.hash.dwo_unit = cu->dwo_unit;
4026       find_entry.hash.line_sect_off = line_offset;
4027       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
4028                              &find_entry, INSERT);
4029       if (*slot != NULL)
4030         {
4031           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
4032           return;
4033         }
4034
4035       lh = dwarf_decode_line_header (line_offset, cu);
4036     }
4037   if (lh == NULL)
4038     {
4039       lh_cu->v.quick->no_file_data = 1;
4040       return;
4041     }
4042
4043   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4044   qfn->hash.dwo_unit = cu->dwo_unit;
4045   qfn->hash.line_sect_off = line_offset;
4046   gdb_assert (slot != NULL);
4047   *slot = qfn;
4048
4049   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4050
4051   qfn->num_file_names = lh->file_names.size ();
4052   qfn->file_names =
4053     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4054   for (i = 0; i < lh->file_names.size (); ++i)
4055     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4056   qfn->real_names = NULL;
4057
4058   lh_cu->v.quick->file_names = qfn;
4059 }
4060
4061 /* A helper for the "quick" functions which attempts to read the line
4062    table for THIS_CU.  */
4063
4064 static struct quick_file_names *
4065 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4066 {
4067   /* This should never be called for TUs.  */
4068   gdb_assert (! this_cu->is_debug_types);
4069   /* Nor type unit groups.  */
4070   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4071
4072   if (this_cu->v.quick->file_names != NULL)
4073     return this_cu->v.quick->file_names;
4074   /* If we know there is no line data, no point in looking again.  */
4075   if (this_cu->v.quick->no_file_data)
4076     return NULL;
4077
4078   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4079
4080   if (this_cu->v.quick->no_file_data)
4081     return NULL;
4082   return this_cu->v.quick->file_names;
4083 }
4084
4085 /* A helper for the "quick" functions which computes and caches the
4086    real path for a given file name from the line table.  */
4087
4088 static const char *
4089 dw2_get_real_path (struct objfile *objfile,
4090                    struct quick_file_names *qfn, int index)
4091 {
4092   if (qfn->real_names == NULL)
4093     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4094                                       qfn->num_file_names, const char *);
4095
4096   if (qfn->real_names[index] == NULL)
4097     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4098
4099   return qfn->real_names[index];
4100 }
4101
4102 static struct symtab *
4103 dw2_find_last_source_symtab (struct objfile *objfile)
4104 {
4105   struct dwarf2_per_objfile *dwarf2_per_objfile
4106     = get_dwarf2_per_objfile (objfile);
4107   int index = dwarf2_per_objfile->n_comp_units - 1;
4108   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4109   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4110
4111   if (cust == NULL)
4112     return NULL;
4113
4114   return compunit_primary_filetab (cust);
4115 }
4116
4117 /* Traversal function for dw2_forget_cached_source_info.  */
4118
4119 static int
4120 dw2_free_cached_file_names (void **slot, void *info)
4121 {
4122   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4123
4124   if (file_data->real_names)
4125     {
4126       int i;
4127
4128       for (i = 0; i < file_data->num_file_names; ++i)
4129         {
4130           xfree ((void*) file_data->real_names[i]);
4131           file_data->real_names[i] = NULL;
4132         }
4133     }
4134
4135   return 1;
4136 }
4137
4138 static void
4139 dw2_forget_cached_source_info (struct objfile *objfile)
4140 {
4141   struct dwarf2_per_objfile *dwarf2_per_objfile
4142     = get_dwarf2_per_objfile (objfile);
4143
4144   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4145                           dw2_free_cached_file_names, NULL);
4146 }
4147
4148 /* Helper function for dw2_map_symtabs_matching_filename that expands
4149    the symtabs and calls the iterator.  */
4150
4151 static int
4152 dw2_map_expand_apply (struct objfile *objfile,
4153                       struct dwarf2_per_cu_data *per_cu,
4154                       const char *name, const char *real_path,
4155                       gdb::function_view<bool (symtab *)> callback)
4156 {
4157   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4158
4159   /* Don't visit already-expanded CUs.  */
4160   if (per_cu->v.quick->compunit_symtab)
4161     return 0;
4162
4163   /* This may expand more than one symtab, and we want to iterate over
4164      all of them.  */
4165   dw2_instantiate_symtab (per_cu);
4166
4167   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4168                                     last_made, callback);
4169 }
4170
4171 /* Implementation of the map_symtabs_matching_filename method.  */
4172
4173 static bool
4174 dw2_map_symtabs_matching_filename
4175   (struct objfile *objfile, const char *name, const char *real_path,
4176    gdb::function_view<bool (symtab *)> callback)
4177 {
4178   int i;
4179   const char *name_basename = lbasename (name);
4180   struct dwarf2_per_objfile *dwarf2_per_objfile
4181     = get_dwarf2_per_objfile (objfile);
4182
4183   /* The rule is CUs specify all the files, including those used by
4184      any TU, so there's no need to scan TUs here.  */
4185
4186   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4187     {
4188       int j;
4189       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4190       struct quick_file_names *file_data;
4191
4192       /* We only need to look at symtabs not already expanded.  */
4193       if (per_cu->v.quick->compunit_symtab)
4194         continue;
4195
4196       file_data = dw2_get_file_names (per_cu);
4197       if (file_data == NULL)
4198         continue;
4199
4200       for (j = 0; j < file_data->num_file_names; ++j)
4201         {
4202           const char *this_name = file_data->file_names[j];
4203           const char *this_real_name;
4204
4205           if (compare_filenames_for_search (this_name, name))
4206             {
4207               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4208                                         callback))
4209                 return true;
4210               continue;
4211             }
4212
4213           /* Before we invoke realpath, which can get expensive when many
4214              files are involved, do a quick comparison of the basenames.  */
4215           if (! basenames_may_differ
4216               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4217             continue;
4218
4219           this_real_name = dw2_get_real_path (objfile, file_data, j);
4220           if (compare_filenames_for_search (this_real_name, name))
4221             {
4222               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4223                                         callback))
4224                 return true;
4225               continue;
4226             }
4227
4228           if (real_path != NULL)
4229             {
4230               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4231               gdb_assert (IS_ABSOLUTE_PATH (name));
4232               if (this_real_name != NULL
4233                   && FILENAME_CMP (real_path, this_real_name) == 0)
4234                 {
4235                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4236                                             callback))
4237                     return true;
4238                   continue;
4239                 }
4240             }
4241         }
4242     }
4243
4244   return false;
4245 }
4246
4247 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4248
4249 struct dw2_symtab_iterator
4250 {
4251   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4252   struct dwarf2_per_objfile *dwarf2_per_objfile;
4253   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4254   int want_specific_block;
4255   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4256      Unused if !WANT_SPECIFIC_BLOCK.  */
4257   int block_index;
4258   /* The kind of symbol we're looking for.  */
4259   domain_enum domain;
4260   /* The list of CUs from the index entry of the symbol,
4261      or NULL if not found.  */
4262   offset_type *vec;
4263   /* The next element in VEC to look at.  */
4264   int next;
4265   /* The number of elements in VEC, or zero if there is no match.  */
4266   int length;
4267   /* Have we seen a global version of the symbol?
4268      If so we can ignore all further global instances.
4269      This is to work around gold/15646, inefficient gold-generated
4270      indices.  */
4271   int global_seen;
4272 };
4273
4274 /* Initialize the index symtab iterator ITER.
4275    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4276    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4277
4278 static void
4279 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4280                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4281                       int want_specific_block,
4282                       int block_index,
4283                       domain_enum domain,
4284                       const char *name)
4285 {
4286   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4287   iter->want_specific_block = want_specific_block;
4288   iter->block_index = block_index;
4289   iter->domain = domain;
4290   iter->next = 0;
4291   iter->global_seen = 0;
4292
4293   mapped_index *index = dwarf2_per_objfile->index_table;
4294
4295   /* index is NULL if OBJF_READNOW.  */
4296   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4297     iter->length = MAYBE_SWAP (*iter->vec);
4298   else
4299     {
4300       iter->vec = NULL;
4301       iter->length = 0;
4302     }
4303 }
4304
4305 /* Return the next matching CU or NULL if there are no more.  */
4306
4307 static struct dwarf2_per_cu_data *
4308 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4309 {
4310   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4311
4312   for ( ; iter->next < iter->length; ++iter->next)
4313     {
4314       offset_type cu_index_and_attrs =
4315         MAYBE_SWAP (iter->vec[iter->next + 1]);
4316       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4317       struct dwarf2_per_cu_data *per_cu;
4318       int want_static = iter->block_index != GLOBAL_BLOCK;
4319       /* This value is only valid for index versions >= 7.  */
4320       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4321       gdb_index_symbol_kind symbol_kind =
4322         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4323       /* Only check the symbol attributes if they're present.
4324          Indices prior to version 7 don't record them,
4325          and indices >= 7 may elide them for certain symbols
4326          (gold does this).  */
4327       int attrs_valid =
4328         (dwarf2_per_objfile->index_table->version >= 7
4329          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4330
4331       /* Don't crash on bad data.  */
4332       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4333                        + dwarf2_per_objfile->n_type_units))
4334         {
4335           complaint (&symfile_complaints,
4336                      _(".gdb_index entry has bad CU index"
4337                        " [in module %s]"),
4338                      objfile_name (dwarf2_per_objfile->objfile));
4339           continue;
4340         }
4341
4342       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4343
4344       /* Skip if already read in.  */
4345       if (per_cu->v.quick->compunit_symtab)
4346         continue;
4347
4348       /* Check static vs global.  */
4349       if (attrs_valid)
4350         {
4351           if (iter->want_specific_block
4352               && want_static != is_static)
4353             continue;
4354           /* Work around gold/15646.  */
4355           if (!is_static && iter->global_seen)
4356             continue;
4357           if (!is_static)
4358             iter->global_seen = 1;
4359         }
4360
4361       /* Only check the symbol's kind if it has one.  */
4362       if (attrs_valid)
4363         {
4364           switch (iter->domain)
4365             {
4366             case VAR_DOMAIN:
4367               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4368                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4369                   /* Some types are also in VAR_DOMAIN.  */
4370                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4371                 continue;
4372               break;
4373             case STRUCT_DOMAIN:
4374               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4375                 continue;
4376               break;
4377             case LABEL_DOMAIN:
4378               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4379                 continue;
4380               break;
4381             default:
4382               break;
4383             }
4384         }
4385
4386       ++iter->next;
4387       return per_cu;
4388     }
4389
4390   return NULL;
4391 }
4392
4393 static struct compunit_symtab *
4394 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4395                    const char *name, domain_enum domain)
4396 {
4397   struct compunit_symtab *stab_best = NULL;
4398   struct dwarf2_per_objfile *dwarf2_per_objfile
4399     = get_dwarf2_per_objfile (objfile);
4400
4401   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4402
4403   struct dw2_symtab_iterator iter;
4404   struct dwarf2_per_cu_data *per_cu;
4405
4406   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4407
4408   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4409     {
4410       struct symbol *sym, *with_opaque = NULL;
4411       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4412       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4413       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4414
4415       sym = block_find_symbol (block, name, domain,
4416                                block_find_non_opaque_type_preferred,
4417                                &with_opaque);
4418
4419       /* Some caution must be observed with overloaded functions
4420          and methods, since the index will not contain any overload
4421          information (but NAME might contain it).  */
4422
4423       if (sym != NULL
4424           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4425         return stab;
4426       if (with_opaque != NULL
4427           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4428         stab_best = stab;
4429
4430       /* Keep looking through other CUs.  */
4431     }
4432
4433   return stab_best;
4434 }
4435
4436 static void
4437 dw2_print_stats (struct objfile *objfile)
4438 {
4439   struct dwarf2_per_objfile *dwarf2_per_objfile
4440     = get_dwarf2_per_objfile (objfile);
4441   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4442   int count = 0;
4443
4444   for (int i = 0; i < total; ++i)
4445     {
4446       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4447
4448       if (!per_cu->v.quick->compunit_symtab)
4449         ++count;
4450     }
4451   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4452   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4453 }
4454
4455 /* This dumps minimal information about the index.
4456    It is called via "mt print objfiles".
4457    One use is to verify .gdb_index has been loaded by the
4458    gdb.dwarf2/gdb-index.exp testcase.  */
4459
4460 static void
4461 dw2_dump (struct objfile *objfile)
4462 {
4463   struct dwarf2_per_objfile *dwarf2_per_objfile
4464     = get_dwarf2_per_objfile (objfile);
4465
4466   gdb_assert (dwarf2_per_objfile->using_index);
4467   printf_filtered (".gdb_index:");
4468   if (dwarf2_per_objfile->index_table != NULL)
4469     {
4470       printf_filtered (" version %d\n",
4471                        dwarf2_per_objfile->index_table->version);
4472     }
4473   else
4474     printf_filtered (" faked for \"readnow\"\n");
4475   printf_filtered ("\n");
4476 }
4477
4478 static void
4479 dw2_relocate (struct objfile *objfile,
4480               const struct section_offsets *new_offsets,
4481               const struct section_offsets *delta)
4482 {
4483   /* There's nothing to relocate here.  */
4484 }
4485
4486 static void
4487 dw2_expand_symtabs_for_function (struct objfile *objfile,
4488                                  const char *func_name)
4489 {
4490   struct dwarf2_per_objfile *dwarf2_per_objfile
4491     = get_dwarf2_per_objfile (objfile);
4492
4493   struct dw2_symtab_iterator iter;
4494   struct dwarf2_per_cu_data *per_cu;
4495
4496   /* Note: It doesn't matter what we pass for block_index here.  */
4497   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4498                         func_name);
4499
4500   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4501     dw2_instantiate_symtab (per_cu);
4502
4503 }
4504
4505 static void
4506 dw2_expand_all_symtabs (struct objfile *objfile)
4507 {
4508   struct dwarf2_per_objfile *dwarf2_per_objfile
4509     = get_dwarf2_per_objfile (objfile);
4510   int total_units = (dwarf2_per_objfile->n_comp_units
4511                      + dwarf2_per_objfile->n_type_units);
4512
4513   for (int i = 0; i < total_units; ++i)
4514     {
4515       struct dwarf2_per_cu_data *per_cu
4516         = dw2_get_cutu (dwarf2_per_objfile, i);
4517
4518       dw2_instantiate_symtab (per_cu);
4519     }
4520 }
4521
4522 static void
4523 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4524                                   const char *fullname)
4525 {
4526   struct dwarf2_per_objfile *dwarf2_per_objfile
4527     = get_dwarf2_per_objfile (objfile);
4528
4529   /* We don't need to consider type units here.
4530      This is only called for examining code, e.g. expand_line_sal.
4531      There can be an order of magnitude (or more) more type units
4532      than comp units, and we avoid them if we can.  */
4533
4534   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4535     {
4536       int j;
4537       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4538       struct quick_file_names *file_data;
4539
4540       /* We only need to look at symtabs not already expanded.  */
4541       if (per_cu->v.quick->compunit_symtab)
4542         continue;
4543
4544       file_data = dw2_get_file_names (per_cu);
4545       if (file_data == NULL)
4546         continue;
4547
4548       for (j = 0; j < file_data->num_file_names; ++j)
4549         {
4550           const char *this_fullname = file_data->file_names[j];
4551
4552           if (filename_cmp (this_fullname, fullname) == 0)
4553             {
4554               dw2_instantiate_symtab (per_cu);
4555               break;
4556             }
4557         }
4558     }
4559 }
4560
4561 static void
4562 dw2_map_matching_symbols (struct objfile *objfile,
4563                           const char * name, domain_enum domain,
4564                           int global,
4565                           int (*callback) (struct block *,
4566                                            struct symbol *, void *),
4567                           void *data, symbol_name_match_type match,
4568                           symbol_compare_ftype *ordered_compare)
4569 {
4570   /* Currently unimplemented; used for Ada.  The function can be called if the
4571      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4572      does not look for non-Ada symbols this function should just return.  */
4573 }
4574
4575 /* Symbol name matcher for .gdb_index names.
4576
4577    Symbol names in .gdb_index have a few particularities:
4578
4579    - There's no indication of which is the language of each symbol.
4580
4581      Since each language has its own symbol name matching algorithm,
4582      and we don't know which language is the right one, we must match
4583      each symbol against all languages.  This would be a potential
4584      performance problem if it were not mitigated by the
4585      mapped_index::name_components lookup table, which significantly
4586      reduces the number of times we need to call into this matcher,
4587      making it a non-issue.
4588
4589    - Symbol names in the index have no overload (parameter)
4590      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4591      appear as "foo" in the index, for example.
4592
4593      This means that the lookup names passed to the symbol name
4594      matcher functions must have no parameter information either
4595      because (e.g.) symbol search name "foo" does not match
4596      lookup-name "foo(int)" [while swapping search name for lookup
4597      name would match].
4598 */
4599 class gdb_index_symbol_name_matcher
4600 {
4601 public:
4602   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4603   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4604
4605   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4606      Returns true if any matcher matches.  */
4607   bool matches (const char *symbol_name);
4608
4609 private:
4610   /* A reference to the lookup name we're matching against.  */
4611   const lookup_name_info &m_lookup_name;
4612
4613   /* A vector holding all the different symbol name matchers, for all
4614      languages.  */
4615   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4616 };
4617
4618 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4619   (const lookup_name_info &lookup_name)
4620     : m_lookup_name (lookup_name)
4621 {
4622   /* Prepare the vector of comparison functions upfront, to avoid
4623      doing the same work for each symbol.  Care is taken to avoid
4624      matching with the same matcher more than once if/when multiple
4625      languages use the same matcher function.  */
4626   auto &matchers = m_symbol_name_matcher_funcs;
4627   matchers.reserve (nr_languages);
4628
4629   matchers.push_back (default_symbol_name_matcher);
4630
4631   for (int i = 0; i < nr_languages; i++)
4632     {
4633       const language_defn *lang = language_def ((enum language) i);
4634       symbol_name_matcher_ftype *name_matcher
4635         = get_symbol_name_matcher (lang, m_lookup_name);
4636
4637       /* Don't insert the same comparison routine more than once.
4638          Note that we do this linear walk instead of a seemingly
4639          cheaper sorted insert, or use a std::set or something like
4640          that, because relative order of function addresses is not
4641          stable.  This is not a problem in practice because the number
4642          of supported languages is low, and the cost here is tiny
4643          compared to the number of searches we'll do afterwards using
4644          this object.  */
4645       if (name_matcher != default_symbol_name_matcher
4646           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4647               == matchers.end ()))
4648         matchers.push_back (name_matcher);
4649     }
4650 }
4651
4652 bool
4653 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4654 {
4655   for (auto matches_name : m_symbol_name_matcher_funcs)
4656     if (matches_name (symbol_name, m_lookup_name, NULL))
4657       return true;
4658
4659   return false;
4660 }
4661
4662 /* Starting from a search name, return the string that finds the upper
4663    bound of all strings that start with SEARCH_NAME in a sorted name
4664    list.  Returns the empty string to indicate that the upper bound is
4665    the end of the list.  */
4666
4667 static std::string
4668 make_sort_after_prefix_name (const char *search_name)
4669 {
4670   /* When looking to complete "func", we find the upper bound of all
4671      symbols that start with "func" by looking for where we'd insert
4672      the closest string that would follow "func" in lexicographical
4673      order.  Usually, that's "func"-with-last-character-incremented,
4674      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4675      will be UTF-8 multi-byte sequences, but we can't be certain.
4676      Especially mind the 0xff character, which is a valid character in
4677      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4678      rule out compilers allowing it in identifiers.  Note that
4679      conveniently, strcmp/strcasecmp are specified to compare
4680      characters interpreted as unsigned char.  So what we do is treat
4681      the whole string as a base 256 number composed of a sequence of
4682      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4683      to 0, and carries 1 to the following more-significant position.
4684      If the very first character in SEARCH_NAME ends up incremented
4685      and carries/overflows, then the upper bound is the end of the
4686      list.  The string after the empty string is also the empty
4687      string.
4688
4689      Some examples of this operation:
4690
4691        SEARCH_NAME  => "+1" RESULT
4692
4693        "abc"              => "abd"
4694        "ab\xff"           => "ac"
4695        "\xff" "a" "\xff"  => "\xff" "b"
4696        "\xff"             => ""
4697        "\xff\xff"         => ""
4698        ""                 => ""
4699
4700      Then, with these symbols for example:
4701
4702       func
4703       func1
4704       fund
4705
4706      completing "func" looks for symbols between "func" and
4707      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4708      which finds "func" and "func1", but not "fund".
4709
4710      And with:
4711
4712       funcÿ     (Latin1 'ÿ' [0xff])
4713       funcÿ1
4714       fund
4715
4716      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4717      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4718
4719      And with:
4720
4721       ÿÿ        (Latin1 'ÿ' [0xff])
4722       ÿÿ1
4723
4724      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4725      the end of the list.
4726   */
4727   std::string after = search_name;
4728   while (!after.empty () && (unsigned char) after.back () == 0xff)
4729     after.pop_back ();
4730   if (!after.empty ())
4731     after.back () = (unsigned char) after.back () + 1;
4732   return after;
4733 }
4734
4735 /* See declaration.  */
4736
4737 std::pair<std::vector<name_component>::const_iterator,
4738           std::vector<name_component>::const_iterator>
4739 mapped_index_base::find_name_components_bounds
4740   (const lookup_name_info &lookup_name_without_params) const
4741 {
4742   auto *name_cmp
4743     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4744
4745   const char *cplus
4746     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4747
4748   /* Comparison function object for lower_bound that matches against a
4749      given symbol name.  */
4750   auto lookup_compare_lower = [&] (const name_component &elem,
4751                                    const char *name)
4752     {
4753       const char *elem_qualified = this->symbol_name_at (elem.idx);
4754       const char *elem_name = elem_qualified + elem.name_offset;
4755       return name_cmp (elem_name, name) < 0;
4756     };
4757
4758   /* Comparison function object for upper_bound that matches against a
4759      given symbol name.  */
4760   auto lookup_compare_upper = [&] (const char *name,
4761                                    const name_component &elem)
4762     {
4763       const char *elem_qualified = this->symbol_name_at (elem.idx);
4764       const char *elem_name = elem_qualified + elem.name_offset;
4765       return name_cmp (name, elem_name) < 0;
4766     };
4767
4768   auto begin = this->name_components.begin ();
4769   auto end = this->name_components.end ();
4770
4771   /* Find the lower bound.  */
4772   auto lower = [&] ()
4773     {
4774       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4775         return begin;
4776       else
4777         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4778     } ();
4779
4780   /* Find the upper bound.  */
4781   auto upper = [&] ()
4782     {
4783       if (lookup_name_without_params.completion_mode ())
4784         {
4785           /* In completion mode, we want UPPER to point past all
4786              symbols names that have the same prefix.  I.e., with
4787              these symbols, and completing "func":
4788
4789               function        << lower bound
4790               function1
4791               other_function  << upper bound
4792
4793              We find the upper bound by looking for the insertion
4794              point of "func"-with-last-character-incremented,
4795              i.e. "fund".  */
4796           std::string after = make_sort_after_prefix_name (cplus);
4797           if (after.empty ())
4798             return end;
4799           return std::lower_bound (lower, end, after.c_str (),
4800                                    lookup_compare_lower);
4801         }
4802       else
4803         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4804     } ();
4805
4806   return {lower, upper};
4807 }
4808
4809 /* See declaration.  */
4810
4811 void
4812 mapped_index_base::build_name_components ()
4813 {
4814   if (!this->name_components.empty ())
4815     return;
4816
4817   this->name_components_casing = case_sensitivity;
4818   auto *name_cmp
4819     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4820
4821   /* The code below only knows how to break apart components of C++
4822      symbol names (and other languages that use '::' as
4823      namespace/module separator).  If we add support for wild matching
4824      to some language that uses some other operator (E.g., Ada, Go and
4825      D use '.'), then we'll need to try splitting the symbol name
4826      according to that language too.  Note that Ada does support wild
4827      matching, but doesn't currently support .gdb_index.  */
4828   auto count = this->symbol_name_count ();
4829   for (offset_type idx = 0; idx < count; idx++)
4830     {
4831       if (this->symbol_name_slot_invalid (idx))
4832         continue;
4833
4834       const char *name = this->symbol_name_at (idx);
4835
4836       /* Add each name component to the name component table.  */
4837       unsigned int previous_len = 0;
4838       for (unsigned int current_len = cp_find_first_component (name);
4839            name[current_len] != '\0';
4840            current_len += cp_find_first_component (name + current_len))
4841         {
4842           gdb_assert (name[current_len] == ':');
4843           this->name_components.push_back ({previous_len, idx});
4844           /* Skip the '::'.  */
4845           current_len += 2;
4846           previous_len = current_len;
4847         }
4848       this->name_components.push_back ({previous_len, idx});
4849     }
4850
4851   /* Sort name_components elements by name.  */
4852   auto name_comp_compare = [&] (const name_component &left,
4853                                 const name_component &right)
4854     {
4855       const char *left_qualified = this->symbol_name_at (left.idx);
4856       const char *right_qualified = this->symbol_name_at (right.idx);
4857
4858       const char *left_name = left_qualified + left.name_offset;
4859       const char *right_name = right_qualified + right.name_offset;
4860
4861       return name_cmp (left_name, right_name) < 0;
4862     };
4863
4864   std::sort (this->name_components.begin (),
4865              this->name_components.end (),
4866              name_comp_compare);
4867 }
4868
4869 /* Helper for dw2_expand_symtabs_matching that works with a
4870    mapped_index_base instead of the containing objfile.  This is split
4871    to a separate function in order to be able to unit test the
4872    name_components matching using a mock mapped_index_base.  For each
4873    symbol name that matches, calls MATCH_CALLBACK, passing it the
4874    symbol's index in the mapped_index_base symbol table.  */
4875
4876 static void
4877 dw2_expand_symtabs_matching_symbol
4878   (mapped_index_base &index,
4879    const lookup_name_info &lookup_name_in,
4880    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4881    enum search_domain kind,
4882    gdb::function_view<void (offset_type)> match_callback)
4883 {
4884   lookup_name_info lookup_name_without_params
4885     = lookup_name_in.make_ignore_params ();
4886   gdb_index_symbol_name_matcher lookup_name_matcher
4887     (lookup_name_without_params);
4888
4889   /* Build the symbol name component sorted vector, if we haven't
4890      yet.  */
4891   index.build_name_components ();
4892
4893   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4894
4895   /* Now for each symbol name in range, check to see if we have a name
4896      match, and if so, call the MATCH_CALLBACK callback.  */
4897
4898   /* The same symbol may appear more than once in the range though.
4899      E.g., if we're looking for symbols that complete "w", and we have
4900      a symbol named "w1::w2", we'll find the two name components for
4901      that same symbol in the range.  To be sure we only call the
4902      callback once per symbol, we first collect the symbol name
4903      indexes that matched in a temporary vector and ignore
4904      duplicates.  */
4905   std::vector<offset_type> matches;
4906   matches.reserve (std::distance (bounds.first, bounds.second));
4907
4908   for (; bounds.first != bounds.second; ++bounds.first)
4909     {
4910       const char *qualified = index.symbol_name_at (bounds.first->idx);
4911
4912       if (!lookup_name_matcher.matches (qualified)
4913           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4914         continue;
4915
4916       matches.push_back (bounds.first->idx);
4917     }
4918
4919   std::sort (matches.begin (), matches.end ());
4920
4921   /* Finally call the callback, once per match.  */
4922   ULONGEST prev = -1;
4923   for (offset_type idx : matches)
4924     {
4925       if (prev != idx)
4926         {
4927           match_callback (idx);
4928           prev = idx;
4929         }
4930     }
4931
4932   /* Above we use a type wider than idx's for 'prev', since 0 and
4933      (offset_type)-1 are both possible values.  */
4934   static_assert (sizeof (prev) > sizeof (offset_type), "");
4935 }
4936
4937 #if GDB_SELF_TEST
4938
4939 namespace selftests { namespace dw2_expand_symtabs_matching {
4940
4941 /* A mock .gdb_index/.debug_names-like name index table, enough to
4942    exercise dw2_expand_symtabs_matching_symbol, which works with the
4943    mapped_index_base interface.  Builds an index from the symbol list
4944    passed as parameter to the constructor.  */
4945 class mock_mapped_index : public mapped_index_base
4946 {
4947 public:
4948   mock_mapped_index (gdb::array_view<const char *> symbols)
4949     : m_symbol_table (symbols)
4950   {}
4951
4952   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4953
4954   /* Return the number of names in the symbol table.  */
4955   virtual size_t symbol_name_count () const
4956   {
4957     return m_symbol_table.size ();
4958   }
4959
4960   /* Get the name of the symbol at IDX in the symbol table.  */
4961   virtual const char *symbol_name_at (offset_type idx) const
4962   {
4963     return m_symbol_table[idx];
4964   }
4965
4966 private:
4967   gdb::array_view<const char *> m_symbol_table;
4968 };
4969
4970 /* Convenience function that converts a NULL pointer to a "<null>"
4971    string, to pass to print routines.  */
4972
4973 static const char *
4974 string_or_null (const char *str)
4975 {
4976   return str != NULL ? str : "<null>";
4977 }
4978
4979 /* Check if a lookup_name_info built from
4980    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4981    index.  EXPECTED_LIST is the list of expected matches, in expected
4982    matching order.  If no match expected, then an empty list is
4983    specified.  Returns true on success.  On failure prints a warning
4984    indicating the file:line that failed, and returns false.  */
4985
4986 static bool
4987 check_match (const char *file, int line,
4988              mock_mapped_index &mock_index,
4989              const char *name, symbol_name_match_type match_type,
4990              bool completion_mode,
4991              std::initializer_list<const char *> expected_list)
4992 {
4993   lookup_name_info lookup_name (name, match_type, completion_mode);
4994
4995   bool matched = true;
4996
4997   auto mismatch = [&] (const char *expected_str,
4998                        const char *got)
4999   {
5000     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
5001                "expected=\"%s\", got=\"%s\"\n"),
5002              file, line,
5003              (match_type == symbol_name_match_type::FULL
5004               ? "FULL" : "WILD"),
5005              name, string_or_null (expected_str), string_or_null (got));
5006     matched = false;
5007   };
5008
5009   auto expected_it = expected_list.begin ();
5010   auto expected_end = expected_list.end ();
5011
5012   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
5013                                       NULL, ALL_DOMAIN,
5014                                       [&] (offset_type idx)
5015   {
5016     const char *matched_name = mock_index.symbol_name_at (idx);
5017     const char *expected_str
5018       = expected_it == expected_end ? NULL : *expected_it++;
5019
5020     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
5021       mismatch (expected_str, matched_name);
5022   });
5023
5024   const char *expected_str
5025   = expected_it == expected_end ? NULL : *expected_it++;
5026   if (expected_str != NULL)
5027     mismatch (expected_str, NULL);
5028
5029   return matched;
5030 }
5031
5032 /* The symbols added to the mock mapped_index for testing (in
5033    canonical form).  */
5034 static const char *test_symbols[] = {
5035   "function",
5036   "std::bar",
5037   "std::zfunction",
5038   "std::zfunction2",
5039   "w1::w2",
5040   "ns::foo<char*>",
5041   "ns::foo<int>",
5042   "ns::foo<long>",
5043   "ns2::tmpl<int>::foo2",
5044   "(anonymous namespace)::A::B::C",
5045
5046   /* These are used to check that the increment-last-char in the
5047      matching algorithm for completion doesn't match "t1_fund" when
5048      completing "t1_func".  */
5049   "t1_func",
5050   "t1_func1",
5051   "t1_fund",
5052   "t1_fund1",
5053
5054   /* A UTF-8 name with multi-byte sequences to make sure that
5055      cp-name-parser understands this as a single identifier ("função"
5056      is "function" in PT).  */
5057   u8"u8função",
5058
5059   /* \377 (0xff) is Latin1 'ÿ'.  */
5060   "yfunc\377",
5061
5062   /* \377 (0xff) is Latin1 'ÿ'.  */
5063   "\377",
5064   "\377\377123",
5065
5066   /* A name with all sorts of complications.  Starts with "z" to make
5067      it easier for the completion tests below.  */
5068 #define Z_SYM_NAME \
5069   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5070     "::tuple<(anonymous namespace)::ui*, " \
5071     "std::default_delete<(anonymous namespace)::ui>, void>"
5072
5073   Z_SYM_NAME
5074 };
5075
5076 /* Returns true if the mapped_index_base::find_name_component_bounds
5077    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5078    in completion mode.  */
5079
5080 static bool
5081 check_find_bounds_finds (mapped_index_base &index,
5082                          const char *search_name,
5083                          gdb::array_view<const char *> expected_syms)
5084 {
5085   lookup_name_info lookup_name (search_name,
5086                                 symbol_name_match_type::FULL, true);
5087
5088   auto bounds = index.find_name_components_bounds (lookup_name);
5089
5090   size_t distance = std::distance (bounds.first, bounds.second);
5091   if (distance != expected_syms.size ())
5092     return false;
5093
5094   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5095     {
5096       auto nc_elem = bounds.first + exp_elem;
5097       const char *qualified = index.symbol_name_at (nc_elem->idx);
5098       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5099         return false;
5100     }
5101
5102   return true;
5103 }
5104
5105 /* Test the lower-level mapped_index::find_name_component_bounds
5106    method.  */
5107
5108 static void
5109 test_mapped_index_find_name_component_bounds ()
5110 {
5111   mock_mapped_index mock_index (test_symbols);
5112
5113   mock_index.build_name_components ();
5114
5115   /* Test the lower-level mapped_index::find_name_component_bounds
5116      method in completion mode.  */
5117   {
5118     static const char *expected_syms[] = {
5119       "t1_func",
5120       "t1_func1",
5121     };
5122
5123     SELF_CHECK (check_find_bounds_finds (mock_index,
5124                                          "t1_func", expected_syms));
5125   }
5126
5127   /* Check that the increment-last-char in the name matching algorithm
5128      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5129   {
5130     static const char *expected_syms1[] = {
5131       "\377",
5132       "\377\377123",
5133     };
5134     SELF_CHECK (check_find_bounds_finds (mock_index,
5135                                          "\377", expected_syms1));
5136
5137     static const char *expected_syms2[] = {
5138       "\377\377123",
5139     };
5140     SELF_CHECK (check_find_bounds_finds (mock_index,
5141                                          "\377\377", expected_syms2));
5142   }
5143 }
5144
5145 /* Test dw2_expand_symtabs_matching_symbol.  */
5146
5147 static void
5148 test_dw2_expand_symtabs_matching_symbol ()
5149 {
5150   mock_mapped_index mock_index (test_symbols);
5151
5152   /* We let all tests run until the end even if some fails, for debug
5153      convenience.  */
5154   bool any_mismatch = false;
5155
5156   /* Create the expected symbols list (an initializer_list).  Needed
5157      because lists have commas, and we need to pass them to CHECK,
5158      which is a macro.  */
5159 #define EXPECT(...) { __VA_ARGS__ }
5160
5161   /* Wrapper for check_match that passes down the current
5162      __FILE__/__LINE__.  */
5163 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5164   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5165                                 mock_index,                             \
5166                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5167                                 EXPECTED_LIST)
5168
5169   /* Identity checks.  */
5170   for (const char *sym : test_symbols)
5171     {
5172       /* Should be able to match all existing symbols.  */
5173       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5174                    EXPECT (sym));
5175
5176       /* Should be able to match all existing symbols with
5177          parameters.  */
5178       std::string with_params = std::string (sym) + "(int)";
5179       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5180                    EXPECT (sym));
5181
5182       /* Should be able to match all existing symbols with
5183          parameters and qualifiers.  */
5184       with_params = std::string (sym) + " ( int ) const";
5185       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5186                    EXPECT (sym));
5187
5188       /* This should really find sym, but cp-name-parser.y doesn't
5189          know about lvalue/rvalue qualifiers yet.  */
5190       with_params = std::string (sym) + " ( int ) &&";
5191       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5192                    {});
5193     }
5194
5195   /* Check that the name matching algorithm for completion doesn't get
5196      confused with Latin1 'ÿ' / 0xff.  */
5197   {
5198     static const char str[] = "\377";
5199     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5200                  EXPECT ("\377", "\377\377123"));
5201   }
5202
5203   /* Check that the increment-last-char in the matching algorithm for
5204      completion doesn't match "t1_fund" when completing "t1_func".  */
5205   {
5206     static const char str[] = "t1_func";
5207     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5208                  EXPECT ("t1_func", "t1_func1"));
5209   }
5210
5211   /* Check that completion mode works at each prefix of the expected
5212      symbol name.  */
5213   {
5214     static const char str[] = "function(int)";
5215     size_t len = strlen (str);
5216     std::string lookup;
5217
5218     for (size_t i = 1; i < len; i++)
5219       {
5220         lookup.assign (str, i);
5221         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5222                      EXPECT ("function"));
5223       }
5224   }
5225
5226   /* While "w" is a prefix of both components, the match function
5227      should still only be called once.  */
5228   {
5229     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5230                  EXPECT ("w1::w2"));
5231     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5232                  EXPECT ("w1::w2"));
5233   }
5234
5235   /* Same, with a "complicated" symbol.  */
5236   {
5237     static const char str[] = Z_SYM_NAME;
5238     size_t len = strlen (str);
5239     std::string lookup;
5240
5241     for (size_t i = 1; i < len; i++)
5242       {
5243         lookup.assign (str, i);
5244         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5245                      EXPECT (Z_SYM_NAME));
5246       }
5247   }
5248
5249   /* In FULL mode, an incomplete symbol doesn't match.  */
5250   {
5251     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5252                  {});
5253   }
5254
5255   /* A complete symbol with parameters matches any overload, since the
5256      index has no overload info.  */
5257   {
5258     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5259                  EXPECT ("std::zfunction", "std::zfunction2"));
5260     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5261                  EXPECT ("std::zfunction", "std::zfunction2"));
5262     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5263                  EXPECT ("std::zfunction", "std::zfunction2"));
5264   }
5265
5266   /* Check that whitespace is ignored appropriately.  A symbol with a
5267      template argument list. */
5268   {
5269     static const char expected[] = "ns::foo<int>";
5270     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5271                  EXPECT (expected));
5272     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5273                  EXPECT (expected));
5274   }
5275
5276   /* Check that whitespace is ignored appropriately.  A symbol with a
5277      template argument list that includes a pointer.  */
5278   {
5279     static const char expected[] = "ns::foo<char*>";
5280     /* Try both completion and non-completion modes.  */
5281     static const bool completion_mode[2] = {false, true};
5282     for (size_t i = 0; i < 2; i++)
5283       {
5284         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5285                      completion_mode[i], EXPECT (expected));
5286         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5287                      completion_mode[i], EXPECT (expected));
5288
5289         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5290                      completion_mode[i], EXPECT (expected));
5291         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5292                      completion_mode[i], EXPECT (expected));
5293       }
5294   }
5295
5296   {
5297     /* Check method qualifiers are ignored.  */
5298     static const char expected[] = "ns::foo<char*>";
5299     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5300                  symbol_name_match_type::FULL, true, EXPECT (expected));
5301     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5302                  symbol_name_match_type::FULL, true, EXPECT (expected));
5303     CHECK_MATCH ("foo < char * >  ( int ) const",
5304                  symbol_name_match_type::WILD, true, EXPECT (expected));
5305     CHECK_MATCH ("foo < char * >  ( int ) &&",
5306                  symbol_name_match_type::WILD, true, EXPECT (expected));
5307   }
5308
5309   /* Test lookup names that don't match anything.  */
5310   {
5311     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5312                  {});
5313
5314     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5315                  {});
5316   }
5317
5318   /* Some wild matching tests, exercising "(anonymous namespace)",
5319      which should not be confused with a parameter list.  */
5320   {
5321     static const char *syms[] = {
5322       "A::B::C",
5323       "B::C",
5324       "C",
5325       "A :: B :: C ( int )",
5326       "B :: C ( int )",
5327       "C ( int )",
5328     };
5329
5330     for (const char *s : syms)
5331       {
5332         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5333                      EXPECT ("(anonymous namespace)::A::B::C"));
5334       }
5335   }
5336
5337   {
5338     static const char expected[] = "ns2::tmpl<int>::foo2";
5339     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5340                  EXPECT (expected));
5341     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5342                  EXPECT (expected));
5343   }
5344
5345   SELF_CHECK (!any_mismatch);
5346
5347 #undef EXPECT
5348 #undef CHECK_MATCH
5349 }
5350
5351 static void
5352 run_test ()
5353 {
5354   test_mapped_index_find_name_component_bounds ();
5355   test_dw2_expand_symtabs_matching_symbol ();
5356 }
5357
5358 }} // namespace selftests::dw2_expand_symtabs_matching
5359
5360 #endif /* GDB_SELF_TEST */
5361
5362 /* If FILE_MATCHER is NULL or if PER_CU has
5363    dwarf2_per_cu_quick_data::MARK set (see
5364    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5365    EXPANSION_NOTIFY on it.  */
5366
5367 static void
5368 dw2_expand_symtabs_matching_one
5369   (struct dwarf2_per_cu_data *per_cu,
5370    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5371    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5372 {
5373   if (file_matcher == NULL || per_cu->v.quick->mark)
5374     {
5375       bool symtab_was_null
5376         = (per_cu->v.quick->compunit_symtab == NULL);
5377
5378       dw2_instantiate_symtab (per_cu);
5379
5380       if (expansion_notify != NULL
5381           && symtab_was_null
5382           && per_cu->v.quick->compunit_symtab != NULL)
5383         expansion_notify (per_cu->v.quick->compunit_symtab);
5384     }
5385 }
5386
5387 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5388    matched, to expand corresponding CUs that were marked.  IDX is the
5389    index of the symbol name that matched.  */
5390
5391 static void
5392 dw2_expand_marked_cus
5393   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5394    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5395    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5396    search_domain kind)
5397 {
5398   offset_type *vec, vec_len, vec_idx;
5399   bool global_seen = false;
5400   mapped_index &index = *dwarf2_per_objfile->index_table;
5401
5402   vec = (offset_type *) (index.constant_pool
5403                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5404   vec_len = MAYBE_SWAP (vec[0]);
5405   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5406     {
5407       struct dwarf2_per_cu_data *per_cu;
5408       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5409       /* This value is only valid for index versions >= 7.  */
5410       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5411       gdb_index_symbol_kind symbol_kind =
5412         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5413       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5414       /* Only check the symbol attributes if they're present.
5415          Indices prior to version 7 don't record them,
5416          and indices >= 7 may elide them for certain symbols
5417          (gold does this).  */
5418       int attrs_valid =
5419         (index.version >= 7
5420          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5421
5422       /* Work around gold/15646.  */
5423       if (attrs_valid)
5424         {
5425           if (!is_static && global_seen)
5426             continue;
5427           if (!is_static)
5428             global_seen = true;
5429         }
5430
5431       /* Only check the symbol's kind if it has one.  */
5432       if (attrs_valid)
5433         {
5434           switch (kind)
5435             {
5436             case VARIABLES_DOMAIN:
5437               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5438                 continue;
5439               break;
5440             case FUNCTIONS_DOMAIN:
5441               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5442                 continue;
5443               break;
5444             case TYPES_DOMAIN:
5445               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5446                 continue;
5447               break;
5448             default:
5449               break;
5450             }
5451         }
5452
5453       /* Don't crash on bad data.  */
5454       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5455                        + dwarf2_per_objfile->n_type_units))
5456         {
5457           complaint (&symfile_complaints,
5458                      _(".gdb_index entry has bad CU index"
5459                        " [in module %s]"),
5460                        objfile_name (dwarf2_per_objfile->objfile));
5461           continue;
5462         }
5463
5464       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5465       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5466                                        expansion_notify);
5467     }
5468 }
5469
5470 /* If FILE_MATCHER is non-NULL, set all the
5471    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5472    that match FILE_MATCHER.  */
5473
5474 static void
5475 dw_expand_symtabs_matching_file_matcher
5476   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5477    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5478 {
5479   if (file_matcher == NULL)
5480     return;
5481
5482   objfile *const objfile = dwarf2_per_objfile->objfile;
5483
5484   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5485                                             htab_eq_pointer,
5486                                             NULL, xcalloc, xfree));
5487   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5488                                                 htab_eq_pointer,
5489                                                 NULL, xcalloc, xfree));
5490
5491   /* The rule is CUs specify all the files, including those used by
5492      any TU, so there's no need to scan TUs here.  */
5493
5494   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5495     {
5496       int j;
5497       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5498       struct quick_file_names *file_data;
5499       void **slot;
5500
5501       QUIT;
5502
5503       per_cu->v.quick->mark = 0;
5504
5505       /* We only need to look at symtabs not already expanded.  */
5506       if (per_cu->v.quick->compunit_symtab)
5507         continue;
5508
5509       file_data = dw2_get_file_names (per_cu);
5510       if (file_data == NULL)
5511         continue;
5512
5513       if (htab_find (visited_not_found.get (), file_data) != NULL)
5514         continue;
5515       else if (htab_find (visited_found.get (), file_data) != NULL)
5516         {
5517           per_cu->v.quick->mark = 1;
5518           continue;
5519         }
5520
5521       for (j = 0; j < file_data->num_file_names; ++j)
5522         {
5523           const char *this_real_name;
5524
5525           if (file_matcher (file_data->file_names[j], false))
5526             {
5527               per_cu->v.quick->mark = 1;
5528               break;
5529             }
5530
5531           /* Before we invoke realpath, which can get expensive when many
5532              files are involved, do a quick comparison of the basenames.  */
5533           if (!basenames_may_differ
5534               && !file_matcher (lbasename (file_data->file_names[j]),
5535                                 true))
5536             continue;
5537
5538           this_real_name = dw2_get_real_path (objfile, file_data, j);
5539           if (file_matcher (this_real_name, false))
5540             {
5541               per_cu->v.quick->mark = 1;
5542               break;
5543             }
5544         }
5545
5546       slot = htab_find_slot (per_cu->v.quick->mark
5547                              ? visited_found.get ()
5548                              : visited_not_found.get (),
5549                              file_data, INSERT);
5550       *slot = file_data;
5551     }
5552 }
5553
5554 static void
5555 dw2_expand_symtabs_matching
5556   (struct objfile *objfile,
5557    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5558    const lookup_name_info &lookup_name,
5559    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5560    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5561    enum search_domain kind)
5562 {
5563   struct dwarf2_per_objfile *dwarf2_per_objfile
5564     = get_dwarf2_per_objfile (objfile);
5565
5566   /* index_table is NULL if OBJF_READNOW.  */
5567   if (!dwarf2_per_objfile->index_table)
5568     return;
5569
5570   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5571
5572   mapped_index &index = *dwarf2_per_objfile->index_table;
5573
5574   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5575                                       symbol_matcher,
5576                                       kind, [&] (offset_type idx)
5577     {
5578       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5579                              expansion_notify, kind);
5580     });
5581 }
5582
5583 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5584    symtab.  */
5585
5586 static struct compunit_symtab *
5587 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5588                                           CORE_ADDR pc)
5589 {
5590   int i;
5591
5592   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5593       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5594     return cust;
5595
5596   if (cust->includes == NULL)
5597     return NULL;
5598
5599   for (i = 0; cust->includes[i]; ++i)
5600     {
5601       struct compunit_symtab *s = cust->includes[i];
5602
5603       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5604       if (s != NULL)
5605         return s;
5606     }
5607
5608   return NULL;
5609 }
5610
5611 static struct compunit_symtab *
5612 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5613                                   struct bound_minimal_symbol msymbol,
5614                                   CORE_ADDR pc,
5615                                   struct obj_section *section,
5616                                   int warn_if_readin)
5617 {
5618   struct dwarf2_per_cu_data *data;
5619   struct compunit_symtab *result;
5620
5621   if (!objfile->psymtabs_addrmap)
5622     return NULL;
5623
5624   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5625                                                      pc);
5626   if (!data)
5627     return NULL;
5628
5629   if (warn_if_readin && data->v.quick->compunit_symtab)
5630     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5631              paddress (get_objfile_arch (objfile), pc));
5632
5633   result
5634     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5635                                                 pc);
5636   gdb_assert (result != NULL);
5637   return result;
5638 }
5639
5640 static void
5641 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5642                           void *data, int need_fullname)
5643 {
5644   struct dwarf2_per_objfile *dwarf2_per_objfile
5645     = get_dwarf2_per_objfile (objfile);
5646
5647   if (!dwarf2_per_objfile->filenames_cache)
5648     {
5649       dwarf2_per_objfile->filenames_cache.emplace ();
5650
5651       htab_up visited (htab_create_alloc (10,
5652                                           htab_hash_pointer, htab_eq_pointer,
5653                                           NULL, xcalloc, xfree));
5654
5655       /* The rule is CUs specify all the files, including those used
5656          by any TU, so there's no need to scan TUs here.  We can
5657          ignore file names coming from already-expanded CUs.  */
5658
5659       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5660         {
5661           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5662
5663           if (per_cu->v.quick->compunit_symtab)
5664             {
5665               void **slot = htab_find_slot (visited.get (),
5666                                             per_cu->v.quick->file_names,
5667                                             INSERT);
5668
5669               *slot = per_cu->v.quick->file_names;
5670             }
5671         }
5672
5673       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5674         {
5675           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5676           struct quick_file_names *file_data;
5677           void **slot;
5678
5679           /* We only need to look at symtabs not already expanded.  */
5680           if (per_cu->v.quick->compunit_symtab)
5681             continue;
5682
5683           file_data = dw2_get_file_names (per_cu);
5684           if (file_data == NULL)
5685             continue;
5686
5687           slot = htab_find_slot (visited.get (), file_data, INSERT);
5688           if (*slot)
5689             {
5690               /* Already visited.  */
5691               continue;
5692             }
5693           *slot = file_data;
5694
5695           for (int j = 0; j < file_data->num_file_names; ++j)
5696             {
5697               const char *filename = file_data->file_names[j];
5698               dwarf2_per_objfile->filenames_cache->seen (filename);
5699             }
5700         }
5701     }
5702
5703   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5704     {
5705       gdb::unique_xmalloc_ptr<char> this_real_name;
5706
5707       if (need_fullname)
5708         this_real_name = gdb_realpath (filename);
5709       (*fun) (filename, this_real_name.get (), data);
5710     });
5711 }
5712
5713 static int
5714 dw2_has_symbols (struct objfile *objfile)
5715 {
5716   return 1;
5717 }
5718
5719 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5720 {
5721   dw2_has_symbols,
5722   dw2_find_last_source_symtab,
5723   dw2_forget_cached_source_info,
5724   dw2_map_symtabs_matching_filename,
5725   dw2_lookup_symbol,
5726   dw2_print_stats,
5727   dw2_dump,
5728   dw2_relocate,
5729   dw2_expand_symtabs_for_function,
5730   dw2_expand_all_symtabs,
5731   dw2_expand_symtabs_with_fullname,
5732   dw2_map_matching_symbols,
5733   dw2_expand_symtabs_matching,
5734   dw2_find_pc_sect_compunit_symtab,
5735   NULL,
5736   dw2_map_symbol_filenames
5737 };
5738
5739 /* DWARF-5 debug_names reader.  */
5740
5741 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5742 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5743
5744 /* A helper function that reads the .debug_names section in SECTION
5745    and fills in MAP.  FILENAME is the name of the file containing the
5746    section; it is used for error reporting.
5747
5748    Returns true if all went well, false otherwise.  */
5749
5750 static bool
5751 read_debug_names_from_section (struct objfile *objfile,
5752                                const char *filename,
5753                                struct dwarf2_section_info *section,
5754                                mapped_debug_names &map)
5755 {
5756   if (dwarf2_section_empty_p (section))
5757     return false;
5758
5759   /* Older elfutils strip versions could keep the section in the main
5760      executable while splitting it for the separate debug info file.  */
5761   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5762     return false;
5763
5764   dwarf2_read_section (objfile, section);
5765
5766   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5767
5768   const gdb_byte *addr = section->buffer;
5769
5770   bfd *const abfd = get_section_bfd_owner (section);
5771
5772   unsigned int bytes_read;
5773   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5774   addr += bytes_read;
5775
5776   map.dwarf5_is_dwarf64 = bytes_read != 4;
5777   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5778   if (bytes_read + length != section->size)
5779     {
5780       /* There may be multiple per-CU indices.  */
5781       warning (_("Section .debug_names in %s length %s does not match "
5782                  "section length %s, ignoring .debug_names."),
5783                filename, plongest (bytes_read + length),
5784                pulongest (section->size));
5785       return false;
5786     }
5787
5788   /* The version number.  */
5789   uint16_t version = read_2_bytes (abfd, addr);
5790   addr += 2;
5791   if (version != 5)
5792     {
5793       warning (_("Section .debug_names in %s has unsupported version %d, "
5794                  "ignoring .debug_names."),
5795                filename, version);
5796       return false;
5797     }
5798
5799   /* Padding.  */
5800   uint16_t padding = read_2_bytes (abfd, addr);
5801   addr += 2;
5802   if (padding != 0)
5803     {
5804       warning (_("Section .debug_names in %s has unsupported padding %d, "
5805                  "ignoring .debug_names."),
5806                filename, padding);
5807       return false;
5808     }
5809
5810   /* comp_unit_count - The number of CUs in the CU list.  */
5811   map.cu_count = read_4_bytes (abfd, addr);
5812   addr += 4;
5813
5814   /* local_type_unit_count - The number of TUs in the local TU
5815      list.  */
5816   map.tu_count = read_4_bytes (abfd, addr);
5817   addr += 4;
5818
5819   /* foreign_type_unit_count - The number of TUs in the foreign TU
5820      list.  */
5821   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5822   addr += 4;
5823   if (foreign_tu_count != 0)
5824     {
5825       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5826                  "ignoring .debug_names."),
5827                filename, static_cast<unsigned long> (foreign_tu_count));
5828       return false;
5829     }
5830
5831   /* bucket_count - The number of hash buckets in the hash lookup
5832      table.  */
5833   map.bucket_count = read_4_bytes (abfd, addr);
5834   addr += 4;
5835
5836   /* name_count - The number of unique names in the index.  */
5837   map.name_count = read_4_bytes (abfd, addr);
5838   addr += 4;
5839
5840   /* abbrev_table_size - The size in bytes of the abbreviations
5841      table.  */
5842   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5843   addr += 4;
5844
5845   /* augmentation_string_size - The size in bytes of the augmentation
5846      string.  This value is rounded up to a multiple of 4.  */
5847   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5848   addr += 4;
5849   map.augmentation_is_gdb = ((augmentation_string_size
5850                               == sizeof (dwarf5_augmentation))
5851                              && memcmp (addr, dwarf5_augmentation,
5852                                         sizeof (dwarf5_augmentation)) == 0);
5853   augmentation_string_size += (-augmentation_string_size) & 3;
5854   addr += augmentation_string_size;
5855
5856   /* List of CUs */
5857   map.cu_table_reordered = addr;
5858   addr += map.cu_count * map.offset_size;
5859
5860   /* List of Local TUs */
5861   map.tu_table_reordered = addr;
5862   addr += map.tu_count * map.offset_size;
5863
5864   /* Hash Lookup Table */
5865   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5866   addr += map.bucket_count * 4;
5867   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5868   addr += map.name_count * 4;
5869
5870   /* Name Table */
5871   map.name_table_string_offs_reordered = addr;
5872   addr += map.name_count * map.offset_size;
5873   map.name_table_entry_offs_reordered = addr;
5874   addr += map.name_count * map.offset_size;
5875
5876   const gdb_byte *abbrev_table_start = addr;
5877   for (;;)
5878     {
5879       unsigned int bytes_read;
5880       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5881       addr += bytes_read;
5882       if (index_num == 0)
5883         break;
5884
5885       const auto insertpair
5886         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5887       if (!insertpair.second)
5888         {
5889           warning (_("Section .debug_names in %s has duplicate index %s, "
5890                      "ignoring .debug_names."),
5891                    filename, pulongest (index_num));
5892           return false;
5893         }
5894       mapped_debug_names::index_val &indexval = insertpair.first->second;
5895       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5896       addr += bytes_read;
5897
5898       for (;;)
5899         {
5900           mapped_debug_names::index_val::attr attr;
5901           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5902           addr += bytes_read;
5903           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5904           addr += bytes_read;
5905           if (attr.form == DW_FORM_implicit_const)
5906             {
5907               attr.implicit_const = read_signed_leb128 (abfd, addr,
5908                                                         &bytes_read);
5909               addr += bytes_read;
5910             }
5911           if (attr.dw_idx == 0 && attr.form == 0)
5912             break;
5913           indexval.attr_vec.push_back (std::move (attr));
5914         }
5915     }
5916   if (addr != abbrev_table_start + abbrev_table_size)
5917     {
5918       warning (_("Section .debug_names in %s has abbreviation_table "
5919                  "of size %zu vs. written as %u, ignoring .debug_names."),
5920                filename, addr - abbrev_table_start, abbrev_table_size);
5921       return false;
5922     }
5923   map.entry_pool = addr;
5924
5925   return true;
5926 }
5927
5928 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5929    list.  */
5930
5931 static void
5932 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5933                                   const mapped_debug_names &map,
5934                                   dwarf2_section_info &section,
5935                                   bool is_dwz, int base_offset)
5936 {
5937   sect_offset sect_off_prev;
5938   for (uint32_t i = 0; i <= map.cu_count; ++i)
5939     {
5940       sect_offset sect_off_next;
5941       if (i < map.cu_count)
5942         {
5943           sect_off_next
5944             = (sect_offset) (extract_unsigned_integer
5945                              (map.cu_table_reordered + i * map.offset_size,
5946                               map.offset_size,
5947                               map.dwarf5_byte_order));
5948         }
5949       else
5950         sect_off_next = (sect_offset) section.size;
5951       if (i >= 1)
5952         {
5953           const ULONGEST length = sect_off_next - sect_off_prev;
5954           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5955             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5956                                          sect_off_prev, length);
5957         }
5958       sect_off_prev = sect_off_next;
5959     }
5960 }
5961
5962 /* Read the CU list from the mapped index, and use it to create all
5963    the CU objects for this dwarf2_per_objfile.  */
5964
5965 static void
5966 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5967                              const mapped_debug_names &map,
5968                              const mapped_debug_names &dwz_map)
5969 {
5970   struct objfile *objfile = dwarf2_per_objfile->objfile;
5971
5972   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5973   dwarf2_per_objfile->all_comp_units
5974     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5975                  dwarf2_per_objfile->n_comp_units);
5976
5977   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5978                                     dwarf2_per_objfile->info,
5979                                     false /* is_dwz */,
5980                                     0 /* base_offset */);
5981
5982   if (dwz_map.cu_count == 0)
5983     return;
5984
5985   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5986   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5987                                     true /* is_dwz */,
5988                                     map.cu_count /* base_offset */);
5989 }
5990
5991 /* Read .debug_names.  If everything went ok, initialize the "quick"
5992    elements of all the CUs and return true.  Otherwise, return false.  */
5993
5994 static bool
5995 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5996 {
5997   mapped_debug_names local_map (dwarf2_per_objfile);
5998   mapped_debug_names dwz_map (dwarf2_per_objfile);
5999   struct objfile *objfile = dwarf2_per_objfile->objfile;
6000
6001   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
6002                                       &dwarf2_per_objfile->debug_names,
6003                                       local_map))
6004     return false;
6005
6006   /* Don't use the index if it's empty.  */
6007   if (local_map.name_count == 0)
6008     return false;
6009
6010   /* If there is a .dwz file, read it so we can get its CU list as
6011      well.  */
6012   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6013   if (dwz != NULL)
6014     {
6015       if (!read_debug_names_from_section (objfile,
6016                                           bfd_get_filename (dwz->dwz_bfd),
6017                                           &dwz->debug_names, dwz_map))
6018         {
6019           warning (_("could not read '.debug_names' section from %s; skipping"),
6020                    bfd_get_filename (dwz->dwz_bfd));
6021           return false;
6022         }
6023     }
6024
6025   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
6026
6027   if (local_map.tu_count != 0)
6028     {
6029       /* We can only handle a single .debug_types when we have an
6030          index.  */
6031       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
6032         return false;
6033
6034       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6035                                                 dwarf2_per_objfile->types, 0);
6036
6037       create_signatured_type_table_from_debug_names
6038         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6039     }
6040
6041   create_addrmap_from_aranges (dwarf2_per_objfile,
6042                                &dwarf2_per_objfile->debug_aranges);
6043
6044   dwarf2_per_objfile->debug_names_table.reset
6045     (new mapped_debug_names (dwarf2_per_objfile));
6046   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6047   dwarf2_per_objfile->using_index = 1;
6048   dwarf2_per_objfile->quick_file_names_table =
6049     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6050
6051   return true;
6052 }
6053
6054 /* Symbol name hashing function as specified by DWARF-5.  */
6055
6056 static uint32_t
6057 dwarf5_djb_hash (const char *str_)
6058 {
6059   const unsigned char *str = (const unsigned char *) str_;
6060
6061   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6062      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6063
6064   uint32_t hash = 5381;
6065   while (int c = *str++)
6066     hash = hash * 33 + tolower (c);
6067   return hash;
6068 }
6069
6070 /* Type used to manage iterating over all CUs looking for a symbol for
6071    .debug_names.  */
6072
6073 class dw2_debug_names_iterator
6074 {
6075 public:
6076   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6077      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6078   dw2_debug_names_iterator (const mapped_debug_names &map,
6079                             bool want_specific_block,
6080                             block_enum block_index, domain_enum domain,
6081                             const char *name)
6082     : m_map (map), m_want_specific_block (want_specific_block),
6083       m_block_index (block_index), m_domain (domain),
6084       m_addr (find_vec_in_debug_names (map, name))
6085   {}
6086
6087   dw2_debug_names_iterator (const mapped_debug_names &map,
6088                             search_domain search, uint32_t namei)
6089     : m_map (map),
6090       m_search (search),
6091       m_addr (find_vec_in_debug_names (map, namei))
6092   {}
6093
6094   /* Return the next matching CU or NULL if there are no more.  */
6095   dwarf2_per_cu_data *next ();
6096
6097 private:
6098   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6099                                                   const char *name);
6100   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6101                                                   uint32_t namei);
6102
6103   /* The internalized form of .debug_names.  */
6104   const mapped_debug_names &m_map;
6105
6106   /* If true, only look for symbols that match BLOCK_INDEX.  */
6107   const bool m_want_specific_block = false;
6108
6109   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6110      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6111      value.  */
6112   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6113
6114   /* The kind of symbol we're looking for.  */
6115   const domain_enum m_domain = UNDEF_DOMAIN;
6116   const search_domain m_search = ALL_DOMAIN;
6117
6118   /* The list of CUs from the index entry of the symbol, or NULL if
6119      not found.  */
6120   const gdb_byte *m_addr;
6121 };
6122
6123 const char *
6124 mapped_debug_names::namei_to_name (uint32_t namei) const
6125 {
6126   const ULONGEST namei_string_offs
6127     = extract_unsigned_integer ((name_table_string_offs_reordered
6128                                  + namei * offset_size),
6129                                 offset_size,
6130                                 dwarf5_byte_order);
6131   return read_indirect_string_at_offset
6132     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6133 }
6134
6135 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6136    found, return pointer to its pool data.  If NAME cannot be found,
6137    return NULL.  */
6138
6139 const gdb_byte *
6140 dw2_debug_names_iterator::find_vec_in_debug_names
6141   (const mapped_debug_names &map, const char *name)
6142 {
6143   int (*cmp) (const char *, const char *);
6144
6145   if (current_language->la_language == language_cplus
6146       || current_language->la_language == language_fortran
6147       || current_language->la_language == language_d)
6148     {
6149       /* NAME is already canonical.  Drop any qualifiers as
6150          .debug_names does not contain any.  */
6151
6152       if (strchr (name, '(') != NULL)
6153         {
6154           gdb::unique_xmalloc_ptr<char> without_params
6155             = cp_remove_params (name);
6156
6157           if (without_params != NULL)
6158             {
6159               name = without_params.get();
6160             }
6161         }
6162     }
6163
6164   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6165
6166   const uint32_t full_hash = dwarf5_djb_hash (name);
6167   uint32_t namei
6168     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6169                                 (map.bucket_table_reordered
6170                                  + (full_hash % map.bucket_count)), 4,
6171                                 map.dwarf5_byte_order);
6172   if (namei == 0)
6173     return NULL;
6174   --namei;
6175   if (namei >= map.name_count)
6176     {
6177       complaint (&symfile_complaints,
6178                  _("Wrong .debug_names with name index %u but name_count=%u "
6179                    "[in module %s]"),
6180                  namei, map.name_count,
6181                  objfile_name (map.dwarf2_per_objfile->objfile));
6182       return NULL;
6183     }
6184
6185   for (;;)
6186     {
6187       const uint32_t namei_full_hash
6188         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6189                                     (map.hash_table_reordered + namei), 4,
6190                                     map.dwarf5_byte_order);
6191       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6192         return NULL;
6193
6194       if (full_hash == namei_full_hash)
6195         {
6196           const char *const namei_string = map.namei_to_name (namei);
6197
6198 #if 0 /* An expensive sanity check.  */
6199           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6200             {
6201               complaint (&symfile_complaints,
6202                          _("Wrong .debug_names hash for string at index %u "
6203                            "[in module %s]"),
6204                          namei, objfile_name (dwarf2_per_objfile->objfile));
6205               return NULL;
6206             }
6207 #endif
6208
6209           if (cmp (namei_string, name) == 0)
6210             {
6211               const ULONGEST namei_entry_offs
6212                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6213                                              + namei * map.offset_size),
6214                                             map.offset_size, map.dwarf5_byte_order);
6215               return map.entry_pool + namei_entry_offs;
6216             }
6217         }
6218
6219       ++namei;
6220       if (namei >= map.name_count)
6221         return NULL;
6222     }
6223 }
6224
6225 const gdb_byte *
6226 dw2_debug_names_iterator::find_vec_in_debug_names
6227   (const mapped_debug_names &map, uint32_t namei)
6228 {
6229   if (namei >= map.name_count)
6230     {
6231       complaint (&symfile_complaints,
6232                  _("Wrong .debug_names with name index %u but name_count=%u "
6233                    "[in module %s]"),
6234                  namei, map.name_count,
6235                  objfile_name (map.dwarf2_per_objfile->objfile));
6236       return NULL;
6237     }
6238
6239   const ULONGEST namei_entry_offs
6240     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6241                                  + namei * map.offset_size),
6242                                 map.offset_size, map.dwarf5_byte_order);
6243   return map.entry_pool + namei_entry_offs;
6244 }
6245
6246 /* See dw2_debug_names_iterator.  */
6247
6248 dwarf2_per_cu_data *
6249 dw2_debug_names_iterator::next ()
6250 {
6251   if (m_addr == NULL)
6252     return NULL;
6253
6254   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6255   struct objfile *objfile = dwarf2_per_objfile->objfile;
6256   bfd *const abfd = objfile->obfd;
6257
6258  again:
6259
6260   unsigned int bytes_read;
6261   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6262   m_addr += bytes_read;
6263   if (abbrev == 0)
6264     return NULL;
6265
6266   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6267   if (indexval_it == m_map.abbrev_map.cend ())
6268     {
6269       complaint (&symfile_complaints,
6270                  _("Wrong .debug_names undefined abbrev code %s "
6271                    "[in module %s]"),
6272                  pulongest (abbrev), objfile_name (objfile));
6273       return NULL;
6274     }
6275   const mapped_debug_names::index_val &indexval = indexval_it->second;
6276   bool have_is_static = false;
6277   bool is_static;
6278   dwarf2_per_cu_data *per_cu = NULL;
6279   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6280     {
6281       ULONGEST ull;
6282       switch (attr.form)
6283         {
6284         case DW_FORM_implicit_const:
6285           ull = attr.implicit_const;
6286           break;
6287         case DW_FORM_flag_present:
6288           ull = 1;
6289           break;
6290         case DW_FORM_udata:
6291           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6292           m_addr += bytes_read;
6293           break;
6294         default:
6295           complaint (&symfile_complaints,
6296                      _("Unsupported .debug_names form %s [in module %s]"),
6297                      dwarf_form_name (attr.form),
6298                      objfile_name (objfile));
6299           return NULL;
6300         }
6301       switch (attr.dw_idx)
6302         {
6303         case DW_IDX_compile_unit:
6304           /* Don't crash on bad data.  */
6305           if (ull >= dwarf2_per_objfile->n_comp_units)
6306             {
6307               complaint (&symfile_complaints,
6308                          _(".debug_names entry has bad CU index %s"
6309                            " [in module %s]"),
6310                          pulongest (ull),
6311                          objfile_name (dwarf2_per_objfile->objfile));
6312               continue;
6313             }
6314           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6315           break;
6316         case DW_IDX_type_unit:
6317           /* Don't crash on bad data.  */
6318           if (ull >= dwarf2_per_objfile->n_type_units)
6319             {
6320               complaint (&symfile_complaints,
6321                          _(".debug_names entry has bad TU index %s"
6322                            " [in module %s]"),
6323                          pulongest (ull),
6324                          objfile_name (dwarf2_per_objfile->objfile));
6325               continue;
6326             }
6327           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6328                                  dwarf2_per_objfile->n_comp_units + ull);
6329           break;
6330         case DW_IDX_GNU_internal:
6331           if (!m_map.augmentation_is_gdb)
6332             break;
6333           have_is_static = true;
6334           is_static = true;
6335           break;
6336         case DW_IDX_GNU_external:
6337           if (!m_map.augmentation_is_gdb)
6338             break;
6339           have_is_static = true;
6340           is_static = false;
6341           break;
6342         }
6343     }
6344
6345   /* Skip if already read in.  */
6346   if (per_cu->v.quick->compunit_symtab)
6347     goto again;
6348
6349   /* Check static vs global.  */
6350   if (have_is_static)
6351     {
6352       const bool want_static = m_block_index != GLOBAL_BLOCK;
6353       if (m_want_specific_block && want_static != is_static)
6354         goto again;
6355     }
6356
6357   /* Match dw2_symtab_iter_next, symbol_kind
6358      and debug_names::psymbol_tag.  */
6359   switch (m_domain)
6360     {
6361     case VAR_DOMAIN:
6362       switch (indexval.dwarf_tag)
6363         {
6364         case DW_TAG_variable:
6365         case DW_TAG_subprogram:
6366         /* Some types are also in VAR_DOMAIN.  */
6367         case DW_TAG_typedef:
6368         case DW_TAG_structure_type:
6369           break;
6370         default:
6371           goto again;
6372         }
6373       break;
6374     case STRUCT_DOMAIN:
6375       switch (indexval.dwarf_tag)
6376         {
6377         case DW_TAG_typedef:
6378         case DW_TAG_structure_type:
6379           break;
6380         default:
6381           goto again;
6382         }
6383       break;
6384     case LABEL_DOMAIN:
6385       switch (indexval.dwarf_tag)
6386         {
6387         case 0:
6388         case DW_TAG_variable:
6389           break;
6390         default:
6391           goto again;
6392         }
6393       break;
6394     default:
6395       break;
6396     }
6397
6398   /* Match dw2_expand_symtabs_matching, symbol_kind and
6399      debug_names::psymbol_tag.  */
6400   switch (m_search)
6401     {
6402     case VARIABLES_DOMAIN:
6403       switch (indexval.dwarf_tag)
6404         {
6405         case DW_TAG_variable:
6406           break;
6407         default:
6408           goto again;
6409         }
6410       break;
6411     case FUNCTIONS_DOMAIN:
6412       switch (indexval.dwarf_tag)
6413         {
6414         case DW_TAG_subprogram:
6415           break;
6416         default:
6417           goto again;
6418         }
6419       break;
6420     case TYPES_DOMAIN:
6421       switch (indexval.dwarf_tag)
6422         {
6423         case DW_TAG_typedef:
6424         case DW_TAG_structure_type:
6425           break;
6426         default:
6427           goto again;
6428         }
6429       break;
6430     default:
6431       break;
6432     }
6433
6434   return per_cu;
6435 }
6436
6437 static struct compunit_symtab *
6438 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6439                                const char *name, domain_enum domain)
6440 {
6441   const block_enum block_index = static_cast<block_enum> (block_index_int);
6442   struct dwarf2_per_objfile *dwarf2_per_objfile
6443     = get_dwarf2_per_objfile (objfile);
6444
6445   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6446   if (!mapp)
6447     {
6448       /* index is NULL if OBJF_READNOW.  */
6449       return NULL;
6450     }
6451   const auto &map = *mapp;
6452
6453   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6454                                  block_index, domain, name);
6455
6456   struct compunit_symtab *stab_best = NULL;
6457   struct dwarf2_per_cu_data *per_cu;
6458   while ((per_cu = iter.next ()) != NULL)
6459     {
6460       struct symbol *sym, *with_opaque = NULL;
6461       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6462       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6463       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6464
6465       sym = block_find_symbol (block, name, domain,
6466                                block_find_non_opaque_type_preferred,
6467                                &with_opaque);
6468
6469       /* Some caution must be observed with overloaded functions and
6470          methods, since the index will not contain any overload
6471          information (but NAME might contain it).  */
6472
6473       if (sym != NULL
6474           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6475         return stab;
6476       if (with_opaque != NULL
6477           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6478         stab_best = stab;
6479
6480       /* Keep looking through other CUs.  */
6481     }
6482
6483   return stab_best;
6484 }
6485
6486 /* This dumps minimal information about .debug_names.  It is called
6487    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6488    uses this to verify that .debug_names has been loaded.  */
6489
6490 static void
6491 dw2_debug_names_dump (struct objfile *objfile)
6492 {
6493   struct dwarf2_per_objfile *dwarf2_per_objfile
6494     = get_dwarf2_per_objfile (objfile);
6495
6496   gdb_assert (dwarf2_per_objfile->using_index);
6497   printf_filtered (".debug_names:");
6498   if (dwarf2_per_objfile->debug_names_table)
6499     printf_filtered (" exists\n");
6500   else
6501     printf_filtered (" faked for \"readnow\"\n");
6502   printf_filtered ("\n");
6503 }
6504
6505 static void
6506 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6507                                              const char *func_name)
6508 {
6509   struct dwarf2_per_objfile *dwarf2_per_objfile
6510     = get_dwarf2_per_objfile (objfile);
6511
6512   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6513   if (dwarf2_per_objfile->debug_names_table)
6514     {
6515       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6516
6517       /* Note: It doesn't matter what we pass for block_index here.  */
6518       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6519                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6520
6521       struct dwarf2_per_cu_data *per_cu;
6522       while ((per_cu = iter.next ()) != NULL)
6523         dw2_instantiate_symtab (per_cu);
6524     }
6525 }
6526
6527 static void
6528 dw2_debug_names_expand_symtabs_matching
6529   (struct objfile *objfile,
6530    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6531    const lookup_name_info &lookup_name,
6532    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6533    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6534    enum search_domain kind)
6535 {
6536   struct dwarf2_per_objfile *dwarf2_per_objfile
6537     = get_dwarf2_per_objfile (objfile);
6538
6539   /* debug_names_table is NULL if OBJF_READNOW.  */
6540   if (!dwarf2_per_objfile->debug_names_table)
6541     return;
6542
6543   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6544
6545   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6546
6547   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6548                                       symbol_matcher,
6549                                       kind, [&] (offset_type namei)
6550     {
6551       /* The name was matched, now expand corresponding CUs that were
6552          marked.  */
6553       dw2_debug_names_iterator iter (map, kind, namei);
6554
6555       struct dwarf2_per_cu_data *per_cu;
6556       while ((per_cu = iter.next ()) != NULL)
6557         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6558                                          expansion_notify);
6559     });
6560 }
6561
6562 const struct quick_symbol_functions dwarf2_debug_names_functions =
6563 {
6564   dw2_has_symbols,
6565   dw2_find_last_source_symtab,
6566   dw2_forget_cached_source_info,
6567   dw2_map_symtabs_matching_filename,
6568   dw2_debug_names_lookup_symbol,
6569   dw2_print_stats,
6570   dw2_debug_names_dump,
6571   dw2_relocate,
6572   dw2_debug_names_expand_symtabs_for_function,
6573   dw2_expand_all_symtabs,
6574   dw2_expand_symtabs_with_fullname,
6575   dw2_map_matching_symbols,
6576   dw2_debug_names_expand_symtabs_matching,
6577   dw2_find_pc_sect_compunit_symtab,
6578   NULL,
6579   dw2_map_symbol_filenames
6580 };
6581
6582 /* See symfile.h.  */
6583
6584 bool
6585 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6586 {
6587   struct dwarf2_per_objfile *dwarf2_per_objfile
6588     = get_dwarf2_per_objfile (objfile);
6589
6590   /* If we're about to read full symbols, don't bother with the
6591      indices.  In this case we also don't care if some other debug
6592      format is making psymtabs, because they are all about to be
6593      expanded anyway.  */
6594   if ((objfile->flags & OBJF_READNOW))
6595     {
6596       int i;
6597
6598       dwarf2_per_objfile->using_index = 1;
6599       create_all_comp_units (dwarf2_per_objfile);
6600       create_all_type_units (dwarf2_per_objfile);
6601       dwarf2_per_objfile->quick_file_names_table =
6602         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6603
6604       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6605                        + dwarf2_per_objfile->n_type_units); ++i)
6606         {
6607           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6608
6609           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6610                                             struct dwarf2_per_cu_quick_data);
6611         }
6612
6613       /* Return 1 so that gdb sees the "quick" functions.  However,
6614          these functions will be no-ops because we will have expanded
6615          all symtabs.  */
6616       *index_kind = dw_index_kind::GDB_INDEX;
6617       return true;
6618     }
6619
6620   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6621     {
6622       *index_kind = dw_index_kind::DEBUG_NAMES;
6623       return true;
6624     }
6625
6626   if (dwarf2_read_index (objfile))
6627     {
6628       *index_kind = dw_index_kind::GDB_INDEX;
6629       return true;
6630     }
6631
6632   return false;
6633 }
6634
6635 \f
6636
6637 /* Build a partial symbol table.  */
6638
6639 void
6640 dwarf2_build_psymtabs (struct objfile *objfile)
6641 {
6642   struct dwarf2_per_objfile *dwarf2_per_objfile
6643     = get_dwarf2_per_objfile (objfile);
6644
6645   if (objfile->global_psymbols.capacity () == 0
6646       && objfile->static_psymbols.capacity () == 0)
6647     init_psymbol_list (objfile, 1024);
6648
6649   TRY
6650     {
6651       /* This isn't really ideal: all the data we allocate on the
6652          objfile's obstack is still uselessly kept around.  However,
6653          freeing it seems unsafe.  */
6654       psymtab_discarder psymtabs (objfile);
6655       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6656       psymtabs.keep ();
6657     }
6658   CATCH (except, RETURN_MASK_ERROR)
6659     {
6660       exception_print (gdb_stderr, except);
6661     }
6662   END_CATCH
6663 }
6664
6665 /* Return the total length of the CU described by HEADER.  */
6666
6667 static unsigned int
6668 get_cu_length (const struct comp_unit_head *header)
6669 {
6670   return header->initial_length_size + header->length;
6671 }
6672
6673 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6674
6675 static inline bool
6676 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6677 {
6678   sect_offset bottom = cu_header->sect_off;
6679   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6680
6681   return sect_off >= bottom && sect_off < top;
6682 }
6683
6684 /* Find the base address of the compilation unit for range lists and
6685    location lists.  It will normally be specified by DW_AT_low_pc.
6686    In DWARF-3 draft 4, the base address could be overridden by
6687    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6688    compilation units with discontinuous ranges.  */
6689
6690 static void
6691 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6692 {
6693   struct attribute *attr;
6694
6695   cu->base_known = 0;
6696   cu->base_address = 0;
6697
6698   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6699   if (attr)
6700     {
6701       cu->base_address = attr_value_as_address (attr);
6702       cu->base_known = 1;
6703     }
6704   else
6705     {
6706       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6707       if (attr)
6708         {
6709           cu->base_address = attr_value_as_address (attr);
6710           cu->base_known = 1;
6711         }
6712     }
6713 }
6714
6715 /* Read in the comp unit header information from the debug_info at info_ptr.
6716    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6717    NOTE: This leaves members offset, first_die_offset to be filled in
6718    by the caller.  */
6719
6720 static const gdb_byte *
6721 read_comp_unit_head (struct comp_unit_head *cu_header,
6722                      const gdb_byte *info_ptr,
6723                      struct dwarf2_section_info *section,
6724                      rcuh_kind section_kind)
6725 {
6726   int signed_addr;
6727   unsigned int bytes_read;
6728   const char *filename = get_section_file_name (section);
6729   bfd *abfd = get_section_bfd_owner (section);
6730
6731   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6732   cu_header->initial_length_size = bytes_read;
6733   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6734   info_ptr += bytes_read;
6735   cu_header->version = read_2_bytes (abfd, info_ptr);
6736   info_ptr += 2;
6737   if (cu_header->version < 5)
6738     switch (section_kind)
6739       {
6740       case rcuh_kind::COMPILE:
6741         cu_header->unit_type = DW_UT_compile;
6742         break;
6743       case rcuh_kind::TYPE:
6744         cu_header->unit_type = DW_UT_type;
6745         break;
6746       default:
6747         internal_error (__FILE__, __LINE__,
6748                         _("read_comp_unit_head: invalid section_kind"));
6749       }
6750   else
6751     {
6752       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6753                                                  (read_1_byte (abfd, info_ptr));
6754       info_ptr += 1;
6755       switch (cu_header->unit_type)
6756         {
6757         case DW_UT_compile:
6758           if (section_kind != rcuh_kind::COMPILE)
6759             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6760                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6761                    filename);
6762           break;
6763         case DW_UT_type:
6764           section_kind = rcuh_kind::TYPE;
6765           break;
6766         default:
6767           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6768                  "(is %d, should be %d or %d) [in module %s]"),
6769                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6770         }
6771
6772       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6773       info_ptr += 1;
6774     }
6775   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6776                                                           cu_header,
6777                                                           &bytes_read);
6778   info_ptr += bytes_read;
6779   if (cu_header->version < 5)
6780     {
6781       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6782       info_ptr += 1;
6783     }
6784   signed_addr = bfd_get_sign_extend_vma (abfd);
6785   if (signed_addr < 0)
6786     internal_error (__FILE__, __LINE__,
6787                     _("read_comp_unit_head: dwarf from non elf file"));
6788   cu_header->signed_addr_p = signed_addr;
6789
6790   if (section_kind == rcuh_kind::TYPE)
6791     {
6792       LONGEST type_offset;
6793
6794       cu_header->signature = read_8_bytes (abfd, info_ptr);
6795       info_ptr += 8;
6796
6797       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6798       info_ptr += bytes_read;
6799       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6800       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6801         error (_("Dwarf Error: Too big type_offset in compilation unit "
6802                "header (is %s) [in module %s]"), plongest (type_offset),
6803                filename);
6804     }
6805
6806   return info_ptr;
6807 }
6808
6809 /* Helper function that returns the proper abbrev section for
6810    THIS_CU.  */
6811
6812 static struct dwarf2_section_info *
6813 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6814 {
6815   struct dwarf2_section_info *abbrev;
6816   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6817
6818   if (this_cu->is_dwz)
6819     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6820   else
6821     abbrev = &dwarf2_per_objfile->abbrev;
6822
6823   return abbrev;
6824 }
6825
6826 /* Subroutine of read_and_check_comp_unit_head and
6827    read_and_check_type_unit_head to simplify them.
6828    Perform various error checking on the header.  */
6829
6830 static void
6831 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6832                             struct comp_unit_head *header,
6833                             struct dwarf2_section_info *section,
6834                             struct dwarf2_section_info *abbrev_section)
6835 {
6836   const char *filename = get_section_file_name (section);
6837
6838   if (header->version < 2 || header->version > 5)
6839     error (_("Dwarf Error: wrong version in compilation unit header "
6840            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6841            filename);
6842
6843   if (to_underlying (header->abbrev_sect_off)
6844       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6845     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6846            "(offset 0x%x + 6) [in module %s]"),
6847            to_underlying (header->abbrev_sect_off),
6848            to_underlying (header->sect_off),
6849            filename);
6850
6851   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6852      avoid potential 32-bit overflow.  */
6853   if (((ULONGEST) header->sect_off + get_cu_length (header))
6854       > section->size)
6855     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6856            "(offset 0x%x + 0) [in module %s]"),
6857            header->length, to_underlying (header->sect_off),
6858            filename);
6859 }
6860
6861 /* Read in a CU/TU header and perform some basic error checking.
6862    The contents of the header are stored in HEADER.
6863    The result is a pointer to the start of the first DIE.  */
6864
6865 static const gdb_byte *
6866 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6867                                struct comp_unit_head *header,
6868                                struct dwarf2_section_info *section,
6869                                struct dwarf2_section_info *abbrev_section,
6870                                const gdb_byte *info_ptr,
6871                                rcuh_kind section_kind)
6872 {
6873   const gdb_byte *beg_of_comp_unit = info_ptr;
6874
6875   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6876
6877   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6878
6879   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6880
6881   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6882                               abbrev_section);
6883
6884   return info_ptr;
6885 }
6886
6887 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6888
6889 static sect_offset
6890 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6891                     struct dwarf2_section_info *section,
6892                     sect_offset sect_off)
6893 {
6894   bfd *abfd = get_section_bfd_owner (section);
6895   const gdb_byte *info_ptr;
6896   unsigned int initial_length_size, offset_size;
6897   uint16_t version;
6898
6899   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6900   info_ptr = section->buffer + to_underlying (sect_off);
6901   read_initial_length (abfd, info_ptr, &initial_length_size);
6902   offset_size = initial_length_size == 4 ? 4 : 8;
6903   info_ptr += initial_length_size;
6904
6905   version = read_2_bytes (abfd, info_ptr);
6906   info_ptr += 2;
6907   if (version >= 5)
6908     {
6909       /* Skip unit type and address size.  */
6910       info_ptr += 2;
6911     }
6912
6913   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6914 }
6915
6916 /* Allocate a new partial symtab for file named NAME and mark this new
6917    partial symtab as being an include of PST.  */
6918
6919 static void
6920 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6921                                struct objfile *objfile)
6922 {
6923   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6924
6925   if (!IS_ABSOLUTE_PATH (subpst->filename))
6926     {
6927       /* It shares objfile->objfile_obstack.  */
6928       subpst->dirname = pst->dirname;
6929     }
6930
6931   subpst->textlow = 0;
6932   subpst->texthigh = 0;
6933
6934   subpst->dependencies
6935     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6936   subpst->dependencies[0] = pst;
6937   subpst->number_of_dependencies = 1;
6938
6939   subpst->globals_offset = 0;
6940   subpst->n_global_syms = 0;
6941   subpst->statics_offset = 0;
6942   subpst->n_static_syms = 0;
6943   subpst->compunit_symtab = NULL;
6944   subpst->read_symtab = pst->read_symtab;
6945   subpst->readin = 0;
6946
6947   /* No private part is necessary for include psymtabs.  This property
6948      can be used to differentiate between such include psymtabs and
6949      the regular ones.  */
6950   subpst->read_symtab_private = NULL;
6951 }
6952
6953 /* Read the Line Number Program data and extract the list of files
6954    included by the source file represented by PST.  Build an include
6955    partial symtab for each of these included files.  */
6956
6957 static void
6958 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6959                                struct die_info *die,
6960                                struct partial_symtab *pst)
6961 {
6962   line_header_up lh;
6963   struct attribute *attr;
6964
6965   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6966   if (attr)
6967     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6968   if (lh == NULL)
6969     return;  /* No linetable, so no includes.  */
6970
6971   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6972   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6973 }
6974
6975 static hashval_t
6976 hash_signatured_type (const void *item)
6977 {
6978   const struct signatured_type *sig_type
6979     = (const struct signatured_type *) item;
6980
6981   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6982   return sig_type->signature;
6983 }
6984
6985 static int
6986 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6987 {
6988   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6989   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6990
6991   return lhs->signature == rhs->signature;
6992 }
6993
6994 /* Allocate a hash table for signatured types.  */
6995
6996 static htab_t
6997 allocate_signatured_type_table (struct objfile *objfile)
6998 {
6999   return htab_create_alloc_ex (41,
7000                                hash_signatured_type,
7001                                eq_signatured_type,
7002                                NULL,
7003                                &objfile->objfile_obstack,
7004                                hashtab_obstack_allocate,
7005                                dummy_obstack_deallocate);
7006 }
7007
7008 /* A helper function to add a signatured type CU to a table.  */
7009
7010 static int
7011 add_signatured_type_cu_to_table (void **slot, void *datum)
7012 {
7013   struct signatured_type *sigt = (struct signatured_type *) *slot;
7014   struct signatured_type ***datap = (struct signatured_type ***) datum;
7015
7016   **datap = sigt;
7017   ++*datap;
7018
7019   return 1;
7020 }
7021
7022 /* A helper for create_debug_types_hash_table.  Read types from SECTION
7023    and fill them into TYPES_HTAB.  It will process only type units,
7024    therefore DW_UT_type.  */
7025
7026 static void
7027 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7028                               struct dwo_file *dwo_file,
7029                               dwarf2_section_info *section, htab_t &types_htab,
7030                               rcuh_kind section_kind)
7031 {
7032   struct objfile *objfile = dwarf2_per_objfile->objfile;
7033   struct dwarf2_section_info *abbrev_section;
7034   bfd *abfd;
7035   const gdb_byte *info_ptr, *end_ptr;
7036
7037   abbrev_section = (dwo_file != NULL
7038                     ? &dwo_file->sections.abbrev
7039                     : &dwarf2_per_objfile->abbrev);
7040
7041   if (dwarf_read_debug)
7042     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7043                         get_section_name (section),
7044                         get_section_file_name (abbrev_section));
7045
7046   dwarf2_read_section (objfile, section);
7047   info_ptr = section->buffer;
7048
7049   if (info_ptr == NULL)
7050     return;
7051
7052   /* We can't set abfd until now because the section may be empty or
7053      not present, in which case the bfd is unknown.  */
7054   abfd = get_section_bfd_owner (section);
7055
7056   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7057      because we don't need to read any dies: the signature is in the
7058      header.  */
7059
7060   end_ptr = info_ptr + section->size;
7061   while (info_ptr < end_ptr)
7062     {
7063       struct signatured_type *sig_type;
7064       struct dwo_unit *dwo_tu;
7065       void **slot;
7066       const gdb_byte *ptr = info_ptr;
7067       struct comp_unit_head header;
7068       unsigned int length;
7069
7070       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7071
7072       /* Initialize it due to a false compiler warning.  */
7073       header.signature = -1;
7074       header.type_cu_offset_in_tu = (cu_offset) -1;
7075
7076       /* We need to read the type's signature in order to build the hash
7077          table, but we don't need anything else just yet.  */
7078
7079       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7080                                            abbrev_section, ptr, section_kind);
7081
7082       length = get_cu_length (&header);
7083
7084       /* Skip dummy type units.  */
7085       if (ptr >= info_ptr + length
7086           || peek_abbrev_code (abfd, ptr) == 0
7087           || header.unit_type != DW_UT_type)
7088         {
7089           info_ptr += length;
7090           continue;
7091         }
7092
7093       if (types_htab == NULL)
7094         {
7095           if (dwo_file)
7096             types_htab = allocate_dwo_unit_table (objfile);
7097           else
7098             types_htab = allocate_signatured_type_table (objfile);
7099         }
7100
7101       if (dwo_file)
7102         {
7103           sig_type = NULL;
7104           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7105                                    struct dwo_unit);
7106           dwo_tu->dwo_file = dwo_file;
7107           dwo_tu->signature = header.signature;
7108           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7109           dwo_tu->section = section;
7110           dwo_tu->sect_off = sect_off;
7111           dwo_tu->length = length;
7112         }
7113       else
7114         {
7115           /* N.B.: type_offset is not usable if this type uses a DWO file.
7116              The real type_offset is in the DWO file.  */
7117           dwo_tu = NULL;
7118           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7119                                      struct signatured_type);
7120           sig_type->signature = header.signature;
7121           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7122           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7123           sig_type->per_cu.is_debug_types = 1;
7124           sig_type->per_cu.section = section;
7125           sig_type->per_cu.sect_off = sect_off;
7126           sig_type->per_cu.length = length;
7127         }
7128
7129       slot = htab_find_slot (types_htab,
7130                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7131                              INSERT);
7132       gdb_assert (slot != NULL);
7133       if (*slot != NULL)
7134         {
7135           sect_offset dup_sect_off;
7136
7137           if (dwo_file)
7138             {
7139               const struct dwo_unit *dup_tu
7140                 = (const struct dwo_unit *) *slot;
7141
7142               dup_sect_off = dup_tu->sect_off;
7143             }
7144           else
7145             {
7146               const struct signatured_type *dup_tu
7147                 = (const struct signatured_type *) *slot;
7148
7149               dup_sect_off = dup_tu->per_cu.sect_off;
7150             }
7151
7152           complaint (&symfile_complaints,
7153                      _("debug type entry at offset 0x%x is duplicate to"
7154                        " the entry at offset 0x%x, signature %s"),
7155                      to_underlying (sect_off), to_underlying (dup_sect_off),
7156                      hex_string (header.signature));
7157         }
7158       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7159
7160       if (dwarf_read_debug > 1)
7161         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7162                             to_underlying (sect_off),
7163                             hex_string (header.signature));
7164
7165       info_ptr += length;
7166     }
7167 }
7168
7169 /* Create the hash table of all entries in the .debug_types
7170    (or .debug_types.dwo) section(s).
7171    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7172    otherwise it is NULL.
7173
7174    The result is a pointer to the hash table or NULL if there are no types.
7175
7176    Note: This function processes DWO files only, not DWP files.  */
7177
7178 static void
7179 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7180                                struct dwo_file *dwo_file,
7181                                VEC (dwarf2_section_info_def) *types,
7182                                htab_t &types_htab)
7183 {
7184   int ix;
7185   struct dwarf2_section_info *section;
7186
7187   if (VEC_empty (dwarf2_section_info_def, types))
7188     return;
7189
7190   for (ix = 0;
7191        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7192        ++ix)
7193     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7194                                   types_htab, rcuh_kind::TYPE);
7195 }
7196
7197 /* Create the hash table of all entries in the .debug_types section,
7198    and initialize all_type_units.
7199    The result is zero if there is an error (e.g. missing .debug_types section),
7200    otherwise non-zero.  */
7201
7202 static int
7203 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7204 {
7205   htab_t types_htab = NULL;
7206   struct signatured_type **iter;
7207
7208   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7209                                 &dwarf2_per_objfile->info, types_htab,
7210                                 rcuh_kind::COMPILE);
7211   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7212                                  dwarf2_per_objfile->types, types_htab);
7213   if (types_htab == NULL)
7214     {
7215       dwarf2_per_objfile->signatured_types = NULL;
7216       return 0;
7217     }
7218
7219   dwarf2_per_objfile->signatured_types = types_htab;
7220
7221   dwarf2_per_objfile->n_type_units
7222     = dwarf2_per_objfile->n_allocated_type_units
7223     = htab_elements (types_htab);
7224   dwarf2_per_objfile->all_type_units =
7225     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7226   iter = &dwarf2_per_objfile->all_type_units[0];
7227   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7228   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7229               == dwarf2_per_objfile->n_type_units);
7230
7231   return 1;
7232 }
7233
7234 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7235    If SLOT is non-NULL, it is the entry to use in the hash table.
7236    Otherwise we find one.  */
7237
7238 static struct signatured_type *
7239 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7240                void **slot)
7241 {
7242   struct objfile *objfile = dwarf2_per_objfile->objfile;
7243   int n_type_units = dwarf2_per_objfile->n_type_units;
7244   struct signatured_type *sig_type;
7245
7246   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7247   ++n_type_units;
7248   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7249     {
7250       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7251         dwarf2_per_objfile->n_allocated_type_units = 1;
7252       dwarf2_per_objfile->n_allocated_type_units *= 2;
7253       dwarf2_per_objfile->all_type_units
7254         = XRESIZEVEC (struct signatured_type *,
7255                       dwarf2_per_objfile->all_type_units,
7256                       dwarf2_per_objfile->n_allocated_type_units);
7257       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7258     }
7259   dwarf2_per_objfile->n_type_units = n_type_units;
7260
7261   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7262                              struct signatured_type);
7263   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7264   sig_type->signature = sig;
7265   sig_type->per_cu.is_debug_types = 1;
7266   if (dwarf2_per_objfile->using_index)
7267     {
7268       sig_type->per_cu.v.quick =
7269         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7270                         struct dwarf2_per_cu_quick_data);
7271     }
7272
7273   if (slot == NULL)
7274     {
7275       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7276                              sig_type, INSERT);
7277     }
7278   gdb_assert (*slot == NULL);
7279   *slot = sig_type;
7280   /* The rest of sig_type must be filled in by the caller.  */
7281   return sig_type;
7282 }
7283
7284 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7285    Fill in SIG_ENTRY with DWO_ENTRY.  */
7286
7287 static void
7288 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7289                                   struct signatured_type *sig_entry,
7290                                   struct dwo_unit *dwo_entry)
7291 {
7292   /* Make sure we're not clobbering something we don't expect to.  */
7293   gdb_assert (! sig_entry->per_cu.queued);
7294   gdb_assert (sig_entry->per_cu.cu == NULL);
7295   if (dwarf2_per_objfile->using_index)
7296     {
7297       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7298       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7299     }
7300   else
7301       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7302   gdb_assert (sig_entry->signature == dwo_entry->signature);
7303   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7304   gdb_assert (sig_entry->type_unit_group == NULL);
7305   gdb_assert (sig_entry->dwo_unit == NULL);
7306
7307   sig_entry->per_cu.section = dwo_entry->section;
7308   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7309   sig_entry->per_cu.length = dwo_entry->length;
7310   sig_entry->per_cu.reading_dwo_directly = 1;
7311   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7312   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7313   sig_entry->dwo_unit = dwo_entry;
7314 }
7315
7316 /* Subroutine of lookup_signatured_type.
7317    If we haven't read the TU yet, create the signatured_type data structure
7318    for a TU to be read in directly from a DWO file, bypassing the stub.
7319    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7320    using .gdb_index, then when reading a CU we want to stay in the DWO file
7321    containing that CU.  Otherwise we could end up reading several other DWO
7322    files (due to comdat folding) to process the transitive closure of all the
7323    mentioned TUs, and that can be slow.  The current DWO file will have every
7324    type signature that it needs.
7325    We only do this for .gdb_index because in the psymtab case we already have
7326    to read all the DWOs to build the type unit groups.  */
7327
7328 static struct signatured_type *
7329 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7330 {
7331   struct dwarf2_per_objfile *dwarf2_per_objfile
7332     = cu->per_cu->dwarf2_per_objfile;
7333   struct objfile *objfile = dwarf2_per_objfile->objfile;
7334   struct dwo_file *dwo_file;
7335   struct dwo_unit find_dwo_entry, *dwo_entry;
7336   struct signatured_type find_sig_entry, *sig_entry;
7337   void **slot;
7338
7339   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7340
7341   /* If TU skeletons have been removed then we may not have read in any
7342      TUs yet.  */
7343   if (dwarf2_per_objfile->signatured_types == NULL)
7344     {
7345       dwarf2_per_objfile->signatured_types
7346         = allocate_signatured_type_table (objfile);
7347     }
7348
7349   /* We only ever need to read in one copy of a signatured type.
7350      Use the global signatured_types array to do our own comdat-folding
7351      of types.  If this is the first time we're reading this TU, and
7352      the TU has an entry in .gdb_index, replace the recorded data from
7353      .gdb_index with this TU.  */
7354
7355   find_sig_entry.signature = sig;
7356   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7357                          &find_sig_entry, INSERT);
7358   sig_entry = (struct signatured_type *) *slot;
7359
7360   /* We can get here with the TU already read, *or* in the process of being
7361      read.  Don't reassign the global entry to point to this DWO if that's
7362      the case.  Also note that if the TU is already being read, it may not
7363      have come from a DWO, the program may be a mix of Fission-compiled
7364      code and non-Fission-compiled code.  */
7365
7366   /* Have we already tried to read this TU?
7367      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7368      needn't exist in the global table yet).  */
7369   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7370     return sig_entry;
7371
7372   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7373      dwo_unit of the TU itself.  */
7374   dwo_file = cu->dwo_unit->dwo_file;
7375
7376   /* Ok, this is the first time we're reading this TU.  */
7377   if (dwo_file->tus == NULL)
7378     return NULL;
7379   find_dwo_entry.signature = sig;
7380   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7381   if (dwo_entry == NULL)
7382     return NULL;
7383
7384   /* If the global table doesn't have an entry for this TU, add one.  */
7385   if (sig_entry == NULL)
7386     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7387
7388   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7389   sig_entry->per_cu.tu_read = 1;
7390   return sig_entry;
7391 }
7392
7393 /* Subroutine of lookup_signatured_type.
7394    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7395    then try the DWP file.  If the TU stub (skeleton) has been removed then
7396    it won't be in .gdb_index.  */
7397
7398 static struct signatured_type *
7399 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7400 {
7401   struct dwarf2_per_objfile *dwarf2_per_objfile
7402     = cu->per_cu->dwarf2_per_objfile;
7403   struct objfile *objfile = dwarf2_per_objfile->objfile;
7404   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7405   struct dwo_unit *dwo_entry;
7406   struct signatured_type find_sig_entry, *sig_entry;
7407   void **slot;
7408
7409   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7410   gdb_assert (dwp_file != NULL);
7411
7412   /* If TU skeletons have been removed then we may not have read in any
7413      TUs yet.  */
7414   if (dwarf2_per_objfile->signatured_types == NULL)
7415     {
7416       dwarf2_per_objfile->signatured_types
7417         = allocate_signatured_type_table (objfile);
7418     }
7419
7420   find_sig_entry.signature = sig;
7421   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7422                          &find_sig_entry, INSERT);
7423   sig_entry = (struct signatured_type *) *slot;
7424
7425   /* Have we already tried to read this TU?
7426      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7427      needn't exist in the global table yet).  */
7428   if (sig_entry != NULL)
7429     return sig_entry;
7430
7431   if (dwp_file->tus == NULL)
7432     return NULL;
7433   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7434                                       sig, 1 /* is_debug_types */);
7435   if (dwo_entry == NULL)
7436     return NULL;
7437
7438   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7439   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7440
7441   return sig_entry;
7442 }
7443
7444 /* Lookup a signature based type for DW_FORM_ref_sig8.
7445    Returns NULL if signature SIG is not present in the table.
7446    It is up to the caller to complain about this.  */
7447
7448 static struct signatured_type *
7449 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7450 {
7451   struct dwarf2_per_objfile *dwarf2_per_objfile
7452     = cu->per_cu->dwarf2_per_objfile;
7453
7454   if (cu->dwo_unit
7455       && dwarf2_per_objfile->using_index)
7456     {
7457       /* We're in a DWO/DWP file, and we're using .gdb_index.
7458          These cases require special processing.  */
7459       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7460         return lookup_dwo_signatured_type (cu, sig);
7461       else
7462         return lookup_dwp_signatured_type (cu, sig);
7463     }
7464   else
7465     {
7466       struct signatured_type find_entry, *entry;
7467
7468       if (dwarf2_per_objfile->signatured_types == NULL)
7469         return NULL;
7470       find_entry.signature = sig;
7471       entry = ((struct signatured_type *)
7472                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7473       return entry;
7474     }
7475 }
7476 \f
7477 /* Low level DIE reading support.  */
7478
7479 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7480
7481 static void
7482 init_cu_die_reader (struct die_reader_specs *reader,
7483                     struct dwarf2_cu *cu,
7484                     struct dwarf2_section_info *section,
7485                     struct dwo_file *dwo_file,
7486                     struct abbrev_table *abbrev_table)
7487 {
7488   gdb_assert (section->readin && section->buffer != NULL);
7489   reader->abfd = get_section_bfd_owner (section);
7490   reader->cu = cu;
7491   reader->dwo_file = dwo_file;
7492   reader->die_section = section;
7493   reader->buffer = section->buffer;
7494   reader->buffer_end = section->buffer + section->size;
7495   reader->comp_dir = NULL;
7496   reader->abbrev_table = abbrev_table;
7497 }
7498
7499 /* Subroutine of init_cutu_and_read_dies to simplify it.
7500    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7501    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7502    already.
7503
7504    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7505    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7506    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7507    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7508    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7509    STUB_COMP_DIR may be non-NULL.
7510    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7511    are filled in with the info of the DIE from the DWO file.
7512    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7513    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7514    kept around for at least as long as *RESULT_READER.
7515
7516    The result is non-zero if a valid (non-dummy) DIE was found.  */
7517
7518 static int
7519 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7520                         struct dwo_unit *dwo_unit,
7521                         struct die_info *stub_comp_unit_die,
7522                         const char *stub_comp_dir,
7523                         struct die_reader_specs *result_reader,
7524                         const gdb_byte **result_info_ptr,
7525                         struct die_info **result_comp_unit_die,
7526                         int *result_has_children,
7527                         abbrev_table_up *result_dwo_abbrev_table)
7528 {
7529   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7530   struct objfile *objfile = dwarf2_per_objfile->objfile;
7531   struct dwarf2_cu *cu = this_cu->cu;
7532   bfd *abfd;
7533   const gdb_byte *begin_info_ptr, *info_ptr;
7534   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7535   int i,num_extra_attrs;
7536   struct dwarf2_section_info *dwo_abbrev_section;
7537   struct attribute *attr;
7538   struct die_info *comp_unit_die;
7539
7540   /* At most one of these may be provided.  */
7541   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7542
7543   /* These attributes aren't processed until later:
7544      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7545      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7546      referenced later.  However, these attributes are found in the stub
7547      which we won't have later.  In order to not impose this complication
7548      on the rest of the code, we read them here and copy them to the
7549      DWO CU/TU die.  */
7550
7551   stmt_list = NULL;
7552   low_pc = NULL;
7553   high_pc = NULL;
7554   ranges = NULL;
7555   comp_dir = NULL;
7556
7557   if (stub_comp_unit_die != NULL)
7558     {
7559       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7560          DWO file.  */
7561       if (! this_cu->is_debug_types)
7562         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7563       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7564       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7565       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7566       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7567
7568       /* There should be a DW_AT_addr_base attribute here (if needed).
7569          We need the value before we can process DW_FORM_GNU_addr_index.  */
7570       cu->addr_base = 0;
7571       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7572       if (attr)
7573         cu->addr_base = DW_UNSND (attr);
7574
7575       /* There should be a DW_AT_ranges_base attribute here (if needed).
7576          We need the value before we can process DW_AT_ranges.  */
7577       cu->ranges_base = 0;
7578       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7579       if (attr)
7580         cu->ranges_base = DW_UNSND (attr);
7581     }
7582   else if (stub_comp_dir != NULL)
7583     {
7584       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7585       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7586       comp_dir->name = DW_AT_comp_dir;
7587       comp_dir->form = DW_FORM_string;
7588       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7589       DW_STRING (comp_dir) = stub_comp_dir;
7590     }
7591
7592   /* Set up for reading the DWO CU/TU.  */
7593   cu->dwo_unit = dwo_unit;
7594   dwarf2_section_info *section = dwo_unit->section;
7595   dwarf2_read_section (objfile, section);
7596   abfd = get_section_bfd_owner (section);
7597   begin_info_ptr = info_ptr = (section->buffer
7598                                + to_underlying (dwo_unit->sect_off));
7599   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7600
7601   if (this_cu->is_debug_types)
7602     {
7603       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7604
7605       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7606                                                 &cu->header, section,
7607                                                 dwo_abbrev_section,
7608                                                 info_ptr, rcuh_kind::TYPE);
7609       /* This is not an assert because it can be caused by bad debug info.  */
7610       if (sig_type->signature != cu->header.signature)
7611         {
7612           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7613                    " TU at offset 0x%x [in module %s]"),
7614                  hex_string (sig_type->signature),
7615                  hex_string (cu->header.signature),
7616                  to_underlying (dwo_unit->sect_off),
7617                  bfd_get_filename (abfd));
7618         }
7619       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7620       /* For DWOs coming from DWP files, we don't know the CU length
7621          nor the type's offset in the TU until now.  */
7622       dwo_unit->length = get_cu_length (&cu->header);
7623       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7624
7625       /* Establish the type offset that can be used to lookup the type.
7626          For DWO files, we don't know it until now.  */
7627       sig_type->type_offset_in_section
7628         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7629     }
7630   else
7631     {
7632       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7633                                                 &cu->header, section,
7634                                                 dwo_abbrev_section,
7635                                                 info_ptr, rcuh_kind::COMPILE);
7636       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7637       /* For DWOs coming from DWP files, we don't know the CU length
7638          until now.  */
7639       dwo_unit->length = get_cu_length (&cu->header);
7640     }
7641
7642   *result_dwo_abbrev_table
7643     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7644                                cu->header.abbrev_sect_off);
7645   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7646                       result_dwo_abbrev_table->get ());
7647
7648   /* Read in the die, but leave space to copy over the attributes
7649      from the stub.  This has the benefit of simplifying the rest of
7650      the code - all the work to maintain the illusion of a single
7651      DW_TAG_{compile,type}_unit DIE is done here.  */
7652   num_extra_attrs = ((stmt_list != NULL)
7653                      + (low_pc != NULL)
7654                      + (high_pc != NULL)
7655                      + (ranges != NULL)
7656                      + (comp_dir != NULL));
7657   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7658                               result_has_children, num_extra_attrs);
7659
7660   /* Copy over the attributes from the stub to the DIE we just read in.  */
7661   comp_unit_die = *result_comp_unit_die;
7662   i = comp_unit_die->num_attrs;
7663   if (stmt_list != NULL)
7664     comp_unit_die->attrs[i++] = *stmt_list;
7665   if (low_pc != NULL)
7666     comp_unit_die->attrs[i++] = *low_pc;
7667   if (high_pc != NULL)
7668     comp_unit_die->attrs[i++] = *high_pc;
7669   if (ranges != NULL)
7670     comp_unit_die->attrs[i++] = *ranges;
7671   if (comp_dir != NULL)
7672     comp_unit_die->attrs[i++] = *comp_dir;
7673   comp_unit_die->num_attrs += num_extra_attrs;
7674
7675   if (dwarf_die_debug)
7676     {
7677       fprintf_unfiltered (gdb_stdlog,
7678                           "Read die from %s@0x%x of %s:\n",
7679                           get_section_name (section),
7680                           (unsigned) (begin_info_ptr - section->buffer),
7681                           bfd_get_filename (abfd));
7682       dump_die (comp_unit_die, dwarf_die_debug);
7683     }
7684
7685   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7686      TUs by skipping the stub and going directly to the entry in the DWO file.
7687      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7688      to get it via circuitous means.  Blech.  */
7689   if (comp_dir != NULL)
7690     result_reader->comp_dir = DW_STRING (comp_dir);
7691
7692   /* Skip dummy compilation units.  */
7693   if (info_ptr >= begin_info_ptr + dwo_unit->length
7694       || peek_abbrev_code (abfd, info_ptr) == 0)
7695     return 0;
7696
7697   *result_info_ptr = info_ptr;
7698   return 1;
7699 }
7700
7701 /* Subroutine of init_cutu_and_read_dies to simplify it.
7702    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7703    Returns NULL if the specified DWO unit cannot be found.  */
7704
7705 static struct dwo_unit *
7706 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7707                  struct die_info *comp_unit_die)
7708 {
7709   struct dwarf2_cu *cu = this_cu->cu;
7710   ULONGEST signature;
7711   struct dwo_unit *dwo_unit;
7712   const char *comp_dir, *dwo_name;
7713
7714   gdb_assert (cu != NULL);
7715
7716   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7717   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7718   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7719
7720   if (this_cu->is_debug_types)
7721     {
7722       struct signatured_type *sig_type;
7723
7724       /* Since this_cu is the first member of struct signatured_type,
7725          we can go from a pointer to one to a pointer to the other.  */
7726       sig_type = (struct signatured_type *) this_cu;
7727       signature = sig_type->signature;
7728       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7729     }
7730   else
7731     {
7732       struct attribute *attr;
7733
7734       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7735       if (! attr)
7736         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7737                  " [in module %s]"),
7738                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7739       signature = DW_UNSND (attr);
7740       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7741                                        signature);
7742     }
7743
7744   return dwo_unit;
7745 }
7746
7747 /* Subroutine of init_cutu_and_read_dies to simplify it.
7748    See it for a description of the parameters.
7749    Read a TU directly from a DWO file, bypassing the stub.  */
7750
7751 static void
7752 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7753                            int use_existing_cu, int keep,
7754                            die_reader_func_ftype *die_reader_func,
7755                            void *data)
7756 {
7757   std::unique_ptr<dwarf2_cu> new_cu;
7758   struct signatured_type *sig_type;
7759   struct die_reader_specs reader;
7760   const gdb_byte *info_ptr;
7761   struct die_info *comp_unit_die;
7762   int has_children;
7763   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7764
7765   /* Verify we can do the following downcast, and that we have the
7766      data we need.  */
7767   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7768   sig_type = (struct signatured_type *) this_cu;
7769   gdb_assert (sig_type->dwo_unit != NULL);
7770
7771   if (use_existing_cu && this_cu->cu != NULL)
7772     {
7773       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7774       /* There's no need to do the rereading_dwo_cu handling that
7775          init_cutu_and_read_dies does since we don't read the stub.  */
7776     }
7777   else
7778     {
7779       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7780       gdb_assert (this_cu->cu == NULL);
7781       new_cu.reset (new dwarf2_cu (this_cu));
7782     }
7783
7784   /* A future optimization, if needed, would be to use an existing
7785      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7786      could share abbrev tables.  */
7787
7788   /* The abbreviation table used by READER, this must live at least as long as
7789      READER.  */
7790   abbrev_table_up dwo_abbrev_table;
7791
7792   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7793                               NULL /* stub_comp_unit_die */,
7794                               sig_type->dwo_unit->dwo_file->comp_dir,
7795                               &reader, &info_ptr,
7796                               &comp_unit_die, &has_children,
7797                               &dwo_abbrev_table) == 0)
7798     {
7799       /* Dummy die.  */
7800       return;
7801     }
7802
7803   /* All the "real" work is done here.  */
7804   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7805
7806   /* This duplicates the code in init_cutu_and_read_dies,
7807      but the alternative is making the latter more complex.
7808      This function is only for the special case of using DWO files directly:
7809      no point in overly complicating the general case just to handle this.  */
7810   if (new_cu != NULL && keep)
7811     {
7812       /* Link this CU into read_in_chain.  */
7813       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7814       dwarf2_per_objfile->read_in_chain = this_cu;
7815       /* The chain owns it now.  */
7816       new_cu.release ();
7817     }
7818 }
7819
7820 /* Initialize a CU (or TU) and read its DIEs.
7821    If the CU defers to a DWO file, read the DWO file as well.
7822
7823    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7824    Otherwise the table specified in the comp unit header is read in and used.
7825    This is an optimization for when we already have the abbrev table.
7826
7827    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7828    Otherwise, a new CU is allocated with xmalloc.
7829
7830    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7831    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7832
7833    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7834    linker) then DIE_READER_FUNC will not get called.  */
7835
7836 static void
7837 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7838                          struct abbrev_table *abbrev_table,
7839                          int use_existing_cu, int keep,
7840                          die_reader_func_ftype *die_reader_func,
7841                          void *data)
7842 {
7843   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7844   struct objfile *objfile = dwarf2_per_objfile->objfile;
7845   struct dwarf2_section_info *section = this_cu->section;
7846   bfd *abfd = get_section_bfd_owner (section);
7847   struct dwarf2_cu *cu;
7848   const gdb_byte *begin_info_ptr, *info_ptr;
7849   struct die_reader_specs reader;
7850   struct die_info *comp_unit_die;
7851   int has_children;
7852   struct attribute *attr;
7853   struct signatured_type *sig_type = NULL;
7854   struct dwarf2_section_info *abbrev_section;
7855   /* Non-zero if CU currently points to a DWO file and we need to
7856      reread it.  When this happens we need to reread the skeleton die
7857      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7858   int rereading_dwo_cu = 0;
7859
7860   if (dwarf_die_debug)
7861     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7862                         this_cu->is_debug_types ? "type" : "comp",
7863                         to_underlying (this_cu->sect_off));
7864
7865   if (use_existing_cu)
7866     gdb_assert (keep);
7867
7868   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7869      file (instead of going through the stub), short-circuit all of this.  */
7870   if (this_cu->reading_dwo_directly)
7871     {
7872       /* Narrow down the scope of possibilities to have to understand.  */
7873       gdb_assert (this_cu->is_debug_types);
7874       gdb_assert (abbrev_table == NULL);
7875       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7876                                  die_reader_func, data);
7877       return;
7878     }
7879
7880   /* This is cheap if the section is already read in.  */
7881   dwarf2_read_section (objfile, section);
7882
7883   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7884
7885   abbrev_section = get_abbrev_section_for_cu (this_cu);
7886
7887   std::unique_ptr<dwarf2_cu> new_cu;
7888   if (use_existing_cu && this_cu->cu != NULL)
7889     {
7890       cu = this_cu->cu;
7891       /* If this CU is from a DWO file we need to start over, we need to
7892          refetch the attributes from the skeleton CU.
7893          This could be optimized by retrieving those attributes from when we
7894          were here the first time: the previous comp_unit_die was stored in
7895          comp_unit_obstack.  But there's no data yet that we need this
7896          optimization.  */
7897       if (cu->dwo_unit != NULL)
7898         rereading_dwo_cu = 1;
7899     }
7900   else
7901     {
7902       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7903       gdb_assert (this_cu->cu == NULL);
7904       new_cu.reset (new dwarf2_cu (this_cu));
7905       cu = new_cu.get ();
7906     }
7907
7908   /* Get the header.  */
7909   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7910     {
7911       /* We already have the header, there's no need to read it in again.  */
7912       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7913     }
7914   else
7915     {
7916       if (this_cu->is_debug_types)
7917         {
7918           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7919                                                     &cu->header, section,
7920                                                     abbrev_section, info_ptr,
7921                                                     rcuh_kind::TYPE);
7922
7923           /* Since per_cu is the first member of struct signatured_type,
7924              we can go from a pointer to one to a pointer to the other.  */
7925           sig_type = (struct signatured_type *) this_cu;
7926           gdb_assert (sig_type->signature == cu->header.signature);
7927           gdb_assert (sig_type->type_offset_in_tu
7928                       == cu->header.type_cu_offset_in_tu);
7929           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7930
7931           /* LENGTH has not been set yet for type units if we're
7932              using .gdb_index.  */
7933           this_cu->length = get_cu_length (&cu->header);
7934
7935           /* Establish the type offset that can be used to lookup the type.  */
7936           sig_type->type_offset_in_section =
7937             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7938
7939           this_cu->dwarf_version = cu->header.version;
7940         }
7941       else
7942         {
7943           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7944                                                     &cu->header, section,
7945                                                     abbrev_section,
7946                                                     info_ptr,
7947                                                     rcuh_kind::COMPILE);
7948
7949           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7950           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7951           this_cu->dwarf_version = cu->header.version;
7952         }
7953     }
7954
7955   /* Skip dummy compilation units.  */
7956   if (info_ptr >= begin_info_ptr + this_cu->length
7957       || peek_abbrev_code (abfd, info_ptr) == 0)
7958     return;
7959
7960   /* If we don't have them yet, read the abbrevs for this compilation unit.
7961      And if we need to read them now, make sure they're freed when we're
7962      done (own the table through ABBREV_TABLE_HOLDER).  */
7963   abbrev_table_up abbrev_table_holder;
7964   if (abbrev_table != NULL)
7965     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7966   else
7967     {
7968       abbrev_table_holder
7969         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7970                                    cu->header.abbrev_sect_off);
7971       abbrev_table = abbrev_table_holder.get ();
7972     }
7973
7974   /* Read the top level CU/TU die.  */
7975   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7976   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7977
7978   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7979      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7980      table from the DWO file and pass the ownership over to us.  It will be
7981      referenced from READER, so we must make sure to free it after we're done
7982      with READER.
7983
7984      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7985      DWO CU, that this test will fail (the attribute will not be present).  */
7986   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7987   abbrev_table_up dwo_abbrev_table;
7988   if (attr)
7989     {
7990       struct dwo_unit *dwo_unit;
7991       struct die_info *dwo_comp_unit_die;
7992
7993       if (has_children)
7994         {
7995           complaint (&symfile_complaints,
7996                      _("compilation unit with DW_AT_GNU_dwo_name"
7997                        " has children (offset 0x%x) [in module %s]"),
7998                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7999         }
8000       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
8001       if (dwo_unit != NULL)
8002         {
8003           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
8004                                       comp_unit_die, NULL,
8005                                       &reader, &info_ptr,
8006                                       &dwo_comp_unit_die, &has_children,
8007                                       &dwo_abbrev_table) == 0)
8008             {
8009               /* Dummy die.  */
8010               return;
8011             }
8012           comp_unit_die = dwo_comp_unit_die;
8013         }
8014       else
8015         {
8016           /* Yikes, we couldn't find the rest of the DIE, we only have
8017              the stub.  A complaint has already been logged.  There's
8018              not much more we can do except pass on the stub DIE to
8019              die_reader_func.  We don't want to throw an error on bad
8020              debug info.  */
8021         }
8022     }
8023
8024   /* All of the above is setup for this call.  Yikes.  */
8025   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8026
8027   /* Done, clean up.  */
8028   if (new_cu != NULL && keep)
8029     {
8030       /* Link this CU into read_in_chain.  */
8031       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8032       dwarf2_per_objfile->read_in_chain = this_cu;
8033       /* The chain owns it now.  */
8034       new_cu.release ();
8035     }
8036 }
8037
8038 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8039    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8040    to have already done the lookup to find the DWO file).
8041
8042    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8043    THIS_CU->is_debug_types, but nothing else.
8044
8045    We fill in THIS_CU->length.
8046
8047    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8048    linker) then DIE_READER_FUNC will not get called.
8049
8050    THIS_CU->cu is always freed when done.
8051    This is done in order to not leave THIS_CU->cu in a state where we have
8052    to care whether it refers to the "main" CU or the DWO CU.  */
8053
8054 static void
8055 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8056                                    struct dwo_file *dwo_file,
8057                                    die_reader_func_ftype *die_reader_func,
8058                                    void *data)
8059 {
8060   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8061   struct objfile *objfile = dwarf2_per_objfile->objfile;
8062   struct dwarf2_section_info *section = this_cu->section;
8063   bfd *abfd = get_section_bfd_owner (section);
8064   struct dwarf2_section_info *abbrev_section;
8065   const gdb_byte *begin_info_ptr, *info_ptr;
8066   struct die_reader_specs reader;
8067   struct die_info *comp_unit_die;
8068   int has_children;
8069
8070   if (dwarf_die_debug)
8071     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
8072                         this_cu->is_debug_types ? "type" : "comp",
8073                         to_underlying (this_cu->sect_off));
8074
8075   gdb_assert (this_cu->cu == NULL);
8076
8077   abbrev_section = (dwo_file != NULL
8078                     ? &dwo_file->sections.abbrev
8079                     : get_abbrev_section_for_cu (this_cu));
8080
8081   /* This is cheap if the section is already read in.  */
8082   dwarf2_read_section (objfile, section);
8083
8084   struct dwarf2_cu cu (this_cu);
8085
8086   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8087   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8088                                             &cu.header, section,
8089                                             abbrev_section, info_ptr,
8090                                             (this_cu->is_debug_types
8091                                              ? rcuh_kind::TYPE
8092                                              : rcuh_kind::COMPILE));
8093
8094   this_cu->length = get_cu_length (&cu.header);
8095
8096   /* Skip dummy compilation units.  */
8097   if (info_ptr >= begin_info_ptr + this_cu->length
8098       || peek_abbrev_code (abfd, info_ptr) == 0)
8099     return;
8100
8101   abbrev_table_up abbrev_table
8102     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8103                                cu.header.abbrev_sect_off);
8104
8105   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8106   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8107
8108   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8109 }
8110
8111 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8112    does not lookup the specified DWO file.
8113    This cannot be used to read DWO files.
8114
8115    THIS_CU->cu is always freed when done.
8116    This is done in order to not leave THIS_CU->cu in a state where we have
8117    to care whether it refers to the "main" CU or the DWO CU.
8118    We can revisit this if the data shows there's a performance issue.  */
8119
8120 static void
8121 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8122                                 die_reader_func_ftype *die_reader_func,
8123                                 void *data)
8124 {
8125   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8126 }
8127 \f
8128 /* Type Unit Groups.
8129
8130    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8131    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8132    so that all types coming from the same compilation (.o file) are grouped
8133    together.  A future step could be to put the types in the same symtab as
8134    the CU the types ultimately came from.  */
8135
8136 static hashval_t
8137 hash_type_unit_group (const void *item)
8138 {
8139   const struct type_unit_group *tu_group
8140     = (const struct type_unit_group *) item;
8141
8142   return hash_stmt_list_entry (&tu_group->hash);
8143 }
8144
8145 static int
8146 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8147 {
8148   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8149   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8150
8151   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8152 }
8153
8154 /* Allocate a hash table for type unit groups.  */
8155
8156 static htab_t
8157 allocate_type_unit_groups_table (struct objfile *objfile)
8158 {
8159   return htab_create_alloc_ex (3,
8160                                hash_type_unit_group,
8161                                eq_type_unit_group,
8162                                NULL,
8163                                &objfile->objfile_obstack,
8164                                hashtab_obstack_allocate,
8165                                dummy_obstack_deallocate);
8166 }
8167
8168 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8169    partial symtabs.  We combine several TUs per psymtab to not let the size
8170    of any one psymtab grow too big.  */
8171 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8172 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8173
8174 /* Helper routine for get_type_unit_group.
8175    Create the type_unit_group object used to hold one or more TUs.  */
8176
8177 static struct type_unit_group *
8178 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8179 {
8180   struct dwarf2_per_objfile *dwarf2_per_objfile
8181     = cu->per_cu->dwarf2_per_objfile;
8182   struct objfile *objfile = dwarf2_per_objfile->objfile;
8183   struct dwarf2_per_cu_data *per_cu;
8184   struct type_unit_group *tu_group;
8185
8186   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8187                              struct type_unit_group);
8188   per_cu = &tu_group->per_cu;
8189   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8190
8191   if (dwarf2_per_objfile->using_index)
8192     {
8193       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8194                                         struct dwarf2_per_cu_quick_data);
8195     }
8196   else
8197     {
8198       unsigned int line_offset = to_underlying (line_offset_struct);
8199       struct partial_symtab *pst;
8200       char *name;
8201
8202       /* Give the symtab a useful name for debug purposes.  */
8203       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8204         name = xstrprintf ("<type_units_%d>",
8205                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8206       else
8207         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8208
8209       pst = create_partial_symtab (per_cu, name);
8210       pst->anonymous = 1;
8211
8212       xfree (name);
8213     }
8214
8215   tu_group->hash.dwo_unit = cu->dwo_unit;
8216   tu_group->hash.line_sect_off = line_offset_struct;
8217
8218   return tu_group;
8219 }
8220
8221 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8222    STMT_LIST is a DW_AT_stmt_list attribute.  */
8223
8224 static struct type_unit_group *
8225 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8226 {
8227   struct dwarf2_per_objfile *dwarf2_per_objfile
8228     = cu->per_cu->dwarf2_per_objfile;
8229   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8230   struct type_unit_group *tu_group;
8231   void **slot;
8232   unsigned int line_offset;
8233   struct type_unit_group type_unit_group_for_lookup;
8234
8235   if (dwarf2_per_objfile->type_unit_groups == NULL)
8236     {
8237       dwarf2_per_objfile->type_unit_groups =
8238         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8239     }
8240
8241   /* Do we need to create a new group, or can we use an existing one?  */
8242
8243   if (stmt_list)
8244     {
8245       line_offset = DW_UNSND (stmt_list);
8246       ++tu_stats->nr_symtab_sharers;
8247     }
8248   else
8249     {
8250       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8251          We can do various things here like create one group per TU or
8252          spread them over multiple groups to split up the expansion work.
8253          To avoid worst case scenarios (too many groups or too large groups)
8254          we, umm, group them in bunches.  */
8255       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8256                      | (tu_stats->nr_stmt_less_type_units
8257                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8258       ++tu_stats->nr_stmt_less_type_units;
8259     }
8260
8261   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8262   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8263   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8264                          &type_unit_group_for_lookup, INSERT);
8265   if (*slot != NULL)
8266     {
8267       tu_group = (struct type_unit_group *) *slot;
8268       gdb_assert (tu_group != NULL);
8269     }
8270   else
8271     {
8272       sect_offset line_offset_struct = (sect_offset) line_offset;
8273       tu_group = create_type_unit_group (cu, line_offset_struct);
8274       *slot = tu_group;
8275       ++tu_stats->nr_symtabs;
8276     }
8277
8278   return tu_group;
8279 }
8280 \f
8281 /* Partial symbol tables.  */
8282
8283 /* Create a psymtab named NAME and assign it to PER_CU.
8284
8285    The caller must fill in the following details:
8286    dirname, textlow, texthigh.  */
8287
8288 static struct partial_symtab *
8289 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8290 {
8291   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8292   struct partial_symtab *pst;
8293
8294   pst = start_psymtab_common (objfile, name, 0,
8295                               objfile->global_psymbols,
8296                               objfile->static_psymbols);
8297
8298   pst->psymtabs_addrmap_supported = 1;
8299
8300   /* This is the glue that links PST into GDB's symbol API.  */
8301   pst->read_symtab_private = per_cu;
8302   pst->read_symtab = dwarf2_read_symtab;
8303   per_cu->v.psymtab = pst;
8304
8305   return pst;
8306 }
8307
8308 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8309    type.  */
8310
8311 struct process_psymtab_comp_unit_data
8312 {
8313   /* True if we are reading a DW_TAG_partial_unit.  */
8314
8315   int want_partial_unit;
8316
8317   /* The "pretend" language that is used if the CU doesn't declare a
8318      language.  */
8319
8320   enum language pretend_language;
8321 };
8322
8323 /* die_reader_func for process_psymtab_comp_unit.  */
8324
8325 static void
8326 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8327                                   const gdb_byte *info_ptr,
8328                                   struct die_info *comp_unit_die,
8329                                   int has_children,
8330                                   void *data)
8331 {
8332   struct dwarf2_cu *cu = reader->cu;
8333   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8334   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8335   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8336   CORE_ADDR baseaddr;
8337   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8338   struct partial_symtab *pst;
8339   enum pc_bounds_kind cu_bounds_kind;
8340   const char *filename;
8341   struct process_psymtab_comp_unit_data *info
8342     = (struct process_psymtab_comp_unit_data *) data;
8343
8344   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8345     return;
8346
8347   gdb_assert (! per_cu->is_debug_types);
8348
8349   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8350
8351   cu->list_in_scope = &file_symbols;
8352
8353   /* Allocate a new partial symbol table structure.  */
8354   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8355   if (filename == NULL)
8356     filename = "";
8357
8358   pst = create_partial_symtab (per_cu, filename);
8359
8360   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8361   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8362
8363   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8364
8365   dwarf2_find_base_address (comp_unit_die, cu);
8366
8367   /* Possibly set the default values of LOWPC and HIGHPC from
8368      `DW_AT_ranges'.  */
8369   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8370                                          &best_highpc, cu, pst);
8371   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8372     /* Store the contiguous range if it is not empty; it can be empty for
8373        CUs with no code.  */
8374     addrmap_set_empty (objfile->psymtabs_addrmap,
8375                        gdbarch_adjust_dwarf2_addr (gdbarch,
8376                                                    best_lowpc + baseaddr),
8377                        gdbarch_adjust_dwarf2_addr (gdbarch,
8378                                                    best_highpc + baseaddr) - 1,
8379                        pst);
8380
8381   /* Check if comp unit has_children.
8382      If so, read the rest of the partial symbols from this comp unit.
8383      If not, there's no more debug_info for this comp unit.  */
8384   if (has_children)
8385     {
8386       struct partial_die_info *first_die;
8387       CORE_ADDR lowpc, highpc;
8388
8389       lowpc = ((CORE_ADDR) -1);
8390       highpc = ((CORE_ADDR) 0);
8391
8392       first_die = load_partial_dies (reader, info_ptr, 1);
8393
8394       scan_partial_symbols (first_die, &lowpc, &highpc,
8395                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8396
8397       /* If we didn't find a lowpc, set it to highpc to avoid
8398          complaints from `maint check'.  */
8399       if (lowpc == ((CORE_ADDR) -1))
8400         lowpc = highpc;
8401
8402       /* If the compilation unit didn't have an explicit address range,
8403          then use the information extracted from its child dies.  */
8404       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8405         {
8406           best_lowpc = lowpc;
8407           best_highpc = highpc;
8408         }
8409     }
8410   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8411   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8412
8413   end_psymtab_common (objfile, pst);
8414
8415   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8416     {
8417       int i;
8418       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8419       struct dwarf2_per_cu_data *iter;
8420
8421       /* Fill in 'dependencies' here; we fill in 'users' in a
8422          post-pass.  */
8423       pst->number_of_dependencies = len;
8424       pst->dependencies =
8425         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8426       for (i = 0;
8427            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8428                         i, iter);
8429            ++i)
8430         pst->dependencies[i] = iter->v.psymtab;
8431
8432       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8433     }
8434
8435   /* Get the list of files included in the current compilation unit,
8436      and build a psymtab for each of them.  */
8437   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8438
8439   if (dwarf_read_debug)
8440     {
8441       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8442
8443       fprintf_unfiltered (gdb_stdlog,
8444                           "Psymtab for %s unit @0x%x: %s - %s"
8445                           ", %d global, %d static syms\n",
8446                           per_cu->is_debug_types ? "type" : "comp",
8447                           to_underlying (per_cu->sect_off),
8448                           paddress (gdbarch, pst->textlow),
8449                           paddress (gdbarch, pst->texthigh),
8450                           pst->n_global_syms, pst->n_static_syms);
8451     }
8452 }
8453
8454 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8455    Process compilation unit THIS_CU for a psymtab.  */
8456
8457 static void
8458 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8459                            int want_partial_unit,
8460                            enum language pretend_language)
8461 {
8462   /* If this compilation unit was already read in, free the
8463      cached copy in order to read it in again.  This is
8464      necessary because we skipped some symbols when we first
8465      read in the compilation unit (see load_partial_dies).
8466      This problem could be avoided, but the benefit is unclear.  */
8467   if (this_cu->cu != NULL)
8468     free_one_cached_comp_unit (this_cu);
8469
8470   if (this_cu->is_debug_types)
8471     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8472                              NULL);
8473   else
8474     {
8475       process_psymtab_comp_unit_data info;
8476       info.want_partial_unit = want_partial_unit;
8477       info.pretend_language = pretend_language;
8478       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8479                                process_psymtab_comp_unit_reader, &info);
8480     }
8481
8482   /* Age out any secondary CUs.  */
8483   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8484 }
8485
8486 /* Reader function for build_type_psymtabs.  */
8487
8488 static void
8489 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8490                             const gdb_byte *info_ptr,
8491                             struct die_info *type_unit_die,
8492                             int has_children,
8493                             void *data)
8494 {
8495   struct dwarf2_per_objfile *dwarf2_per_objfile
8496     = reader->cu->per_cu->dwarf2_per_objfile;
8497   struct objfile *objfile = dwarf2_per_objfile->objfile;
8498   struct dwarf2_cu *cu = reader->cu;
8499   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8500   struct signatured_type *sig_type;
8501   struct type_unit_group *tu_group;
8502   struct attribute *attr;
8503   struct partial_die_info *first_die;
8504   CORE_ADDR lowpc, highpc;
8505   struct partial_symtab *pst;
8506
8507   gdb_assert (data == NULL);
8508   gdb_assert (per_cu->is_debug_types);
8509   sig_type = (struct signatured_type *) per_cu;
8510
8511   if (! has_children)
8512     return;
8513
8514   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8515   tu_group = get_type_unit_group (cu, attr);
8516
8517   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8518
8519   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8520   cu->list_in_scope = &file_symbols;
8521   pst = create_partial_symtab (per_cu, "");
8522   pst->anonymous = 1;
8523
8524   first_die = load_partial_dies (reader, info_ptr, 1);
8525
8526   lowpc = (CORE_ADDR) -1;
8527   highpc = (CORE_ADDR) 0;
8528   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8529
8530   end_psymtab_common (objfile, pst);
8531 }
8532
8533 /* Struct used to sort TUs by their abbreviation table offset.  */
8534
8535 struct tu_abbrev_offset
8536 {
8537   struct signatured_type *sig_type;
8538   sect_offset abbrev_offset;
8539 };
8540
8541 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8542
8543 static int
8544 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8545 {
8546   const struct tu_abbrev_offset * const *a
8547     = (const struct tu_abbrev_offset * const*) ap;
8548   const struct tu_abbrev_offset * const *b
8549     = (const struct tu_abbrev_offset * const*) bp;
8550   sect_offset aoff = (*a)->abbrev_offset;
8551   sect_offset boff = (*b)->abbrev_offset;
8552
8553   return (aoff > boff) - (aoff < boff);
8554 }
8555
8556 /* Efficiently read all the type units.
8557    This does the bulk of the work for build_type_psymtabs.
8558
8559    The efficiency is because we sort TUs by the abbrev table they use and
8560    only read each abbrev table once.  In one program there are 200K TUs
8561    sharing 8K abbrev tables.
8562
8563    The main purpose of this function is to support building the
8564    dwarf2_per_objfile->type_unit_groups table.
8565    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8566    can collapse the search space by grouping them by stmt_list.
8567    The savings can be significant, in the same program from above the 200K TUs
8568    share 8K stmt_list tables.
8569
8570    FUNC is expected to call get_type_unit_group, which will create the
8571    struct type_unit_group if necessary and add it to
8572    dwarf2_per_objfile->type_unit_groups.  */
8573
8574 static void
8575 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8576 {
8577   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8578   struct cleanup *cleanups;
8579   abbrev_table_up abbrev_table;
8580   sect_offset abbrev_offset;
8581   struct tu_abbrev_offset *sorted_by_abbrev;
8582   int i;
8583
8584   /* It's up to the caller to not call us multiple times.  */
8585   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8586
8587   if (dwarf2_per_objfile->n_type_units == 0)
8588     return;
8589
8590   /* TUs typically share abbrev tables, and there can be way more TUs than
8591      abbrev tables.  Sort by abbrev table to reduce the number of times we
8592      read each abbrev table in.
8593      Alternatives are to punt or to maintain a cache of abbrev tables.
8594      This is simpler and efficient enough for now.
8595
8596      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8597      symtab to use).  Typically TUs with the same abbrev offset have the same
8598      stmt_list value too so in practice this should work well.
8599
8600      The basic algorithm here is:
8601
8602       sort TUs by abbrev table
8603       for each TU with same abbrev table:
8604         read abbrev table if first user
8605         read TU top level DIE
8606           [IWBN if DWO skeletons had DW_AT_stmt_list]
8607         call FUNC  */
8608
8609   if (dwarf_read_debug)
8610     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8611
8612   /* Sort in a separate table to maintain the order of all_type_units
8613      for .gdb_index: TU indices directly index all_type_units.  */
8614   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8615                               dwarf2_per_objfile->n_type_units);
8616   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8617     {
8618       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8619
8620       sorted_by_abbrev[i].sig_type = sig_type;
8621       sorted_by_abbrev[i].abbrev_offset =
8622         read_abbrev_offset (dwarf2_per_objfile,
8623                             sig_type->per_cu.section,
8624                             sig_type->per_cu.sect_off);
8625     }
8626   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8627   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8628          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8629
8630   abbrev_offset = (sect_offset) ~(unsigned) 0;
8631
8632   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8633     {
8634       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8635
8636       /* Switch to the next abbrev table if necessary.  */
8637       if (abbrev_table == NULL
8638           || tu->abbrev_offset != abbrev_offset)
8639         {
8640           abbrev_offset = tu->abbrev_offset;
8641           abbrev_table =
8642             abbrev_table_read_table (dwarf2_per_objfile,
8643                                      &dwarf2_per_objfile->abbrev,
8644                                      abbrev_offset);
8645           ++tu_stats->nr_uniq_abbrev_tables;
8646         }
8647
8648       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8649                                0, 0, build_type_psymtabs_reader, NULL);
8650     }
8651
8652   do_cleanups (cleanups);
8653 }
8654
8655 /* Print collected type unit statistics.  */
8656
8657 static void
8658 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8659 {
8660   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8661
8662   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8663   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8664                       dwarf2_per_objfile->n_type_units);
8665   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8666                       tu_stats->nr_uniq_abbrev_tables);
8667   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8668                       tu_stats->nr_symtabs);
8669   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8670                       tu_stats->nr_symtab_sharers);
8671   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8672                       tu_stats->nr_stmt_less_type_units);
8673   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8674                       tu_stats->nr_all_type_units_reallocs);
8675 }
8676
8677 /* Traversal function for build_type_psymtabs.  */
8678
8679 static int
8680 build_type_psymtab_dependencies (void **slot, void *info)
8681 {
8682   struct dwarf2_per_objfile *dwarf2_per_objfile
8683     = (struct dwarf2_per_objfile *) info;
8684   struct objfile *objfile = dwarf2_per_objfile->objfile;
8685   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8686   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8687   struct partial_symtab *pst = per_cu->v.psymtab;
8688   int len = VEC_length (sig_type_ptr, tu_group->tus);
8689   struct signatured_type *iter;
8690   int i;
8691
8692   gdb_assert (len > 0);
8693   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8694
8695   pst->number_of_dependencies = len;
8696   pst->dependencies =
8697     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8698   for (i = 0;
8699        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8700        ++i)
8701     {
8702       gdb_assert (iter->per_cu.is_debug_types);
8703       pst->dependencies[i] = iter->per_cu.v.psymtab;
8704       iter->type_unit_group = tu_group;
8705     }
8706
8707   VEC_free (sig_type_ptr, tu_group->tus);
8708
8709   return 1;
8710 }
8711
8712 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8713    Build partial symbol tables for the .debug_types comp-units.  */
8714
8715 static void
8716 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8717 {
8718   if (! create_all_type_units (dwarf2_per_objfile))
8719     return;
8720
8721   build_type_psymtabs_1 (dwarf2_per_objfile);
8722 }
8723
8724 /* Traversal function for process_skeletonless_type_unit.
8725    Read a TU in a DWO file and build partial symbols for it.  */
8726
8727 static int
8728 process_skeletonless_type_unit (void **slot, void *info)
8729 {
8730   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8731   struct dwarf2_per_objfile *dwarf2_per_objfile
8732     = (struct dwarf2_per_objfile *) info;
8733   struct signatured_type find_entry, *entry;
8734
8735   /* If this TU doesn't exist in the global table, add it and read it in.  */
8736
8737   if (dwarf2_per_objfile->signatured_types == NULL)
8738     {
8739       dwarf2_per_objfile->signatured_types
8740         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8741     }
8742
8743   find_entry.signature = dwo_unit->signature;
8744   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8745                          INSERT);
8746   /* If we've already seen this type there's nothing to do.  What's happening
8747      is we're doing our own version of comdat-folding here.  */
8748   if (*slot != NULL)
8749     return 1;
8750
8751   /* This does the job that create_all_type_units would have done for
8752      this TU.  */
8753   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8754   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8755   *slot = entry;
8756
8757   /* This does the job that build_type_psymtabs_1 would have done.  */
8758   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8759                            build_type_psymtabs_reader, NULL);
8760
8761   return 1;
8762 }
8763
8764 /* Traversal function for process_skeletonless_type_units.  */
8765
8766 static int
8767 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8768 {
8769   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8770
8771   if (dwo_file->tus != NULL)
8772     {
8773       htab_traverse_noresize (dwo_file->tus,
8774                               process_skeletonless_type_unit, info);
8775     }
8776
8777   return 1;
8778 }
8779
8780 /* Scan all TUs of DWO files, verifying we've processed them.
8781    This is needed in case a TU was emitted without its skeleton.
8782    Note: This can't be done until we know what all the DWO files are.  */
8783
8784 static void
8785 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8786 {
8787   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8788   if (get_dwp_file (dwarf2_per_objfile) == NULL
8789       && dwarf2_per_objfile->dwo_files != NULL)
8790     {
8791       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8792                               process_dwo_file_for_skeletonless_type_units,
8793                               dwarf2_per_objfile);
8794     }
8795 }
8796
8797 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8798
8799 static void
8800 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8801 {
8802   int i;
8803
8804   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8805     {
8806       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8807       struct partial_symtab *pst = per_cu->v.psymtab;
8808       int j;
8809
8810       if (pst == NULL)
8811         continue;
8812
8813       for (j = 0; j < pst->number_of_dependencies; ++j)
8814         {
8815           /* Set the 'user' field only if it is not already set.  */
8816           if (pst->dependencies[j]->user == NULL)
8817             pst->dependencies[j]->user = pst;
8818         }
8819     }
8820 }
8821
8822 /* Build the partial symbol table by doing a quick pass through the
8823    .debug_info and .debug_abbrev sections.  */
8824
8825 static void
8826 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8827 {
8828   struct cleanup *back_to;
8829   int i;
8830   struct objfile *objfile = dwarf2_per_objfile->objfile;
8831
8832   if (dwarf_read_debug)
8833     {
8834       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8835                           objfile_name (objfile));
8836     }
8837
8838   dwarf2_per_objfile->reading_partial_symbols = 1;
8839
8840   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8841
8842   /* Any cached compilation units will be linked by the per-objfile
8843      read_in_chain.  Make sure to free them when we're done.  */
8844   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8845
8846   build_type_psymtabs (dwarf2_per_objfile);
8847
8848   create_all_comp_units (dwarf2_per_objfile);
8849
8850   /* Create a temporary address map on a temporary obstack.  We later
8851      copy this to the final obstack.  */
8852   auto_obstack temp_obstack;
8853
8854   scoped_restore save_psymtabs_addrmap
8855     = make_scoped_restore (&objfile->psymtabs_addrmap,
8856                            addrmap_create_mutable (&temp_obstack));
8857
8858   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8859     {
8860       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8861
8862       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8863     }
8864
8865   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8866   process_skeletonless_type_units (dwarf2_per_objfile);
8867
8868   /* Now that all TUs have been processed we can fill in the dependencies.  */
8869   if (dwarf2_per_objfile->type_unit_groups != NULL)
8870     {
8871       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8872                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8873     }
8874
8875   if (dwarf_read_debug)
8876     print_tu_stats (dwarf2_per_objfile);
8877
8878   set_partial_user (dwarf2_per_objfile);
8879
8880   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8881                                                     &objfile->objfile_obstack);
8882   /* At this point we want to keep the address map.  */
8883   save_psymtabs_addrmap.release ();
8884
8885   do_cleanups (back_to);
8886
8887   if (dwarf_read_debug)
8888     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8889                         objfile_name (objfile));
8890 }
8891
8892 /* die_reader_func for load_partial_comp_unit.  */
8893
8894 static void
8895 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8896                                const gdb_byte *info_ptr,
8897                                struct die_info *comp_unit_die,
8898                                int has_children,
8899                                void *data)
8900 {
8901   struct dwarf2_cu *cu = reader->cu;
8902
8903   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8904
8905   /* Check if comp unit has_children.
8906      If so, read the rest of the partial symbols from this comp unit.
8907      If not, there's no more debug_info for this comp unit.  */
8908   if (has_children)
8909     load_partial_dies (reader, info_ptr, 0);
8910 }
8911
8912 /* Load the partial DIEs for a secondary CU into memory.
8913    This is also used when rereading a primary CU with load_all_dies.  */
8914
8915 static void
8916 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8917 {
8918   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8919                            load_partial_comp_unit_reader, NULL);
8920 }
8921
8922 static void
8923 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8924                               struct dwarf2_section_info *section,
8925                               struct dwarf2_section_info *abbrev_section,
8926                               unsigned int is_dwz,
8927                               int *n_allocated,
8928                               int *n_comp_units,
8929                               struct dwarf2_per_cu_data ***all_comp_units)
8930 {
8931   const gdb_byte *info_ptr;
8932   struct objfile *objfile = dwarf2_per_objfile->objfile;
8933
8934   if (dwarf_read_debug)
8935     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8936                         get_section_name (section),
8937                         get_section_file_name (section));
8938
8939   dwarf2_read_section (objfile, section);
8940
8941   info_ptr = section->buffer;
8942
8943   while (info_ptr < section->buffer + section->size)
8944     {
8945       struct dwarf2_per_cu_data *this_cu;
8946
8947       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8948
8949       comp_unit_head cu_header;
8950       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8951                                      abbrev_section, info_ptr,
8952                                      rcuh_kind::COMPILE);
8953
8954       /* Save the compilation unit for later lookup.  */
8955       if (cu_header.unit_type != DW_UT_type)
8956         {
8957           this_cu = XOBNEW (&objfile->objfile_obstack,
8958                             struct dwarf2_per_cu_data);
8959           memset (this_cu, 0, sizeof (*this_cu));
8960         }
8961       else
8962         {
8963           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8964                                   struct signatured_type);
8965           memset (sig_type, 0, sizeof (*sig_type));
8966           sig_type->signature = cu_header.signature;
8967           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8968           this_cu = &sig_type->per_cu;
8969         }
8970       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8971       this_cu->sect_off = sect_off;
8972       this_cu->length = cu_header.length + cu_header.initial_length_size;
8973       this_cu->is_dwz = is_dwz;
8974       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8975       this_cu->section = section;
8976
8977       if (*n_comp_units == *n_allocated)
8978         {
8979           *n_allocated *= 2;
8980           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8981                                         *all_comp_units, *n_allocated);
8982         }
8983       (*all_comp_units)[*n_comp_units] = this_cu;
8984       ++*n_comp_units;
8985
8986       info_ptr = info_ptr + this_cu->length;
8987     }
8988 }
8989
8990 /* Create a list of all compilation units in OBJFILE.
8991    This is only done for -readnow and building partial symtabs.  */
8992
8993 static void
8994 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8995 {
8996   int n_allocated;
8997   int n_comp_units;
8998   struct dwarf2_per_cu_data **all_comp_units;
8999   struct dwz_file *dwz;
9000   struct objfile *objfile = dwarf2_per_objfile->objfile;
9001
9002   n_comp_units = 0;
9003   n_allocated = 10;
9004   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9005
9006   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9007                                 &dwarf2_per_objfile->abbrev, 0,
9008                                 &n_allocated, &n_comp_units, &all_comp_units);
9009
9010   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9011   if (dwz != NULL)
9012     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9013                                   1, &n_allocated, &n_comp_units,
9014                                   &all_comp_units);
9015
9016   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9017                                                   struct dwarf2_per_cu_data *,
9018                                                   n_comp_units);
9019   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9020           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9021   xfree (all_comp_units);
9022   dwarf2_per_objfile->n_comp_units = n_comp_units;
9023 }
9024
9025 /* Process all loaded DIEs for compilation unit CU, starting at
9026    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9027    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9028    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9029    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9030
9031 static void
9032 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9033                       CORE_ADDR *highpc, int set_addrmap,
9034                       struct dwarf2_cu *cu)
9035 {
9036   struct partial_die_info *pdi;
9037
9038   /* Now, march along the PDI's, descending into ones which have
9039      interesting children but skipping the children of the other ones,
9040      until we reach the end of the compilation unit.  */
9041
9042   pdi = first_die;
9043
9044   while (pdi != NULL)
9045     {
9046       fixup_partial_die (pdi, cu);
9047
9048       /* Anonymous namespaces or modules have no name but have interesting
9049          children, so we need to look at them.  Ditto for anonymous
9050          enums.  */
9051
9052       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9053           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9054           || pdi->tag == DW_TAG_imported_unit
9055           || pdi->tag == DW_TAG_inlined_subroutine)
9056         {
9057           switch (pdi->tag)
9058             {
9059             case DW_TAG_subprogram:
9060             case DW_TAG_inlined_subroutine:
9061               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9062               break;
9063             case DW_TAG_constant:
9064             case DW_TAG_variable:
9065             case DW_TAG_typedef:
9066             case DW_TAG_union_type:
9067               if (!pdi->is_declaration)
9068                 {
9069                   add_partial_symbol (pdi, cu);
9070                 }
9071               break;
9072             case DW_TAG_class_type:
9073             case DW_TAG_interface_type:
9074             case DW_TAG_structure_type:
9075               if (!pdi->is_declaration)
9076                 {
9077                   add_partial_symbol (pdi, cu);
9078                 }
9079               if (cu->language == language_rust && pdi->has_children)
9080                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9081                                       set_addrmap, cu);
9082               break;
9083             case DW_TAG_enumeration_type:
9084               if (!pdi->is_declaration)
9085                 add_partial_enumeration (pdi, cu);
9086               break;
9087             case DW_TAG_base_type:
9088             case DW_TAG_subrange_type:
9089               /* File scope base type definitions are added to the partial
9090                  symbol table.  */
9091               add_partial_symbol (pdi, cu);
9092               break;
9093             case DW_TAG_namespace:
9094               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9095               break;
9096             case DW_TAG_module:
9097               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9098               break;
9099             case DW_TAG_imported_unit:
9100               {
9101                 struct dwarf2_per_cu_data *per_cu;
9102
9103                 /* For now we don't handle imported units in type units.  */
9104                 if (cu->per_cu->is_debug_types)
9105                   {
9106                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9107                              " supported in type units [in module %s]"),
9108                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9109                   }
9110
9111                 per_cu = dwarf2_find_containing_comp_unit
9112                            (pdi->d.sect_off, pdi->is_dwz,
9113                             cu->per_cu->dwarf2_per_objfile);
9114
9115                 /* Go read the partial unit, if needed.  */
9116                 if (per_cu->v.psymtab == NULL)
9117                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9118
9119                 VEC_safe_push (dwarf2_per_cu_ptr,
9120                                cu->per_cu->imported_symtabs, per_cu);
9121               }
9122               break;
9123             case DW_TAG_imported_declaration:
9124               add_partial_symbol (pdi, cu);
9125               break;
9126             default:
9127               break;
9128             }
9129         }
9130
9131       /* If the die has a sibling, skip to the sibling.  */
9132
9133       pdi = pdi->die_sibling;
9134     }
9135 }
9136
9137 /* Functions used to compute the fully scoped name of a partial DIE.
9138
9139    Normally, this is simple.  For C++, the parent DIE's fully scoped
9140    name is concatenated with "::" and the partial DIE's name.
9141    Enumerators are an exception; they use the scope of their parent
9142    enumeration type, i.e. the name of the enumeration type is not
9143    prepended to the enumerator.
9144
9145    There are two complexities.  One is DW_AT_specification; in this
9146    case "parent" means the parent of the target of the specification,
9147    instead of the direct parent of the DIE.  The other is compilers
9148    which do not emit DW_TAG_namespace; in this case we try to guess
9149    the fully qualified name of structure types from their members'
9150    linkage names.  This must be done using the DIE's children rather
9151    than the children of any DW_AT_specification target.  We only need
9152    to do this for structures at the top level, i.e. if the target of
9153    any DW_AT_specification (if any; otherwise the DIE itself) does not
9154    have a parent.  */
9155
9156 /* Compute the scope prefix associated with PDI's parent, in
9157    compilation unit CU.  The result will be allocated on CU's
9158    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9159    field.  NULL is returned if no prefix is necessary.  */
9160 static const char *
9161 partial_die_parent_scope (struct partial_die_info *pdi,
9162                           struct dwarf2_cu *cu)
9163 {
9164   const char *grandparent_scope;
9165   struct partial_die_info *parent, *real_pdi;
9166
9167   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9168      then this means the parent of the specification DIE.  */
9169
9170   real_pdi = pdi;
9171   while (real_pdi->has_specification)
9172     real_pdi = find_partial_die (real_pdi->spec_offset,
9173                                  real_pdi->spec_is_dwz, cu);
9174
9175   parent = real_pdi->die_parent;
9176   if (parent == NULL)
9177     return NULL;
9178
9179   if (parent->scope_set)
9180     return parent->scope;
9181
9182   fixup_partial_die (parent, cu);
9183
9184   grandparent_scope = partial_die_parent_scope (parent, cu);
9185
9186   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9187      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9188      Work around this problem here.  */
9189   if (cu->language == language_cplus
9190       && parent->tag == DW_TAG_namespace
9191       && strcmp (parent->name, "::") == 0
9192       && grandparent_scope == NULL)
9193     {
9194       parent->scope = NULL;
9195       parent->scope_set = 1;
9196       return NULL;
9197     }
9198
9199   if (pdi->tag == DW_TAG_enumerator)
9200     /* Enumerators should not get the name of the enumeration as a prefix.  */
9201     parent->scope = grandparent_scope;
9202   else if (parent->tag == DW_TAG_namespace
9203       || parent->tag == DW_TAG_module
9204       || parent->tag == DW_TAG_structure_type
9205       || parent->tag == DW_TAG_class_type
9206       || parent->tag == DW_TAG_interface_type
9207       || parent->tag == DW_TAG_union_type
9208       || parent->tag == DW_TAG_enumeration_type)
9209     {
9210       if (grandparent_scope == NULL)
9211         parent->scope = parent->name;
9212       else
9213         parent->scope = typename_concat (&cu->comp_unit_obstack,
9214                                          grandparent_scope,
9215                                          parent->name, 0, cu);
9216     }
9217   else
9218     {
9219       /* FIXME drow/2004-04-01: What should we be doing with
9220          function-local names?  For partial symbols, we should probably be
9221          ignoring them.  */
9222       complaint (&symfile_complaints,
9223                  _("unhandled containing DIE tag %d for DIE at %d"),
9224                  parent->tag, to_underlying (pdi->sect_off));
9225       parent->scope = grandparent_scope;
9226     }
9227
9228   parent->scope_set = 1;
9229   return parent->scope;
9230 }
9231
9232 /* Return the fully scoped name associated with PDI, from compilation unit
9233    CU.  The result will be allocated with malloc.  */
9234
9235 static char *
9236 partial_die_full_name (struct partial_die_info *pdi,
9237                        struct dwarf2_cu *cu)
9238 {
9239   const char *parent_scope;
9240
9241   /* If this is a template instantiation, we can not work out the
9242      template arguments from partial DIEs.  So, unfortunately, we have
9243      to go through the full DIEs.  At least any work we do building
9244      types here will be reused if full symbols are loaded later.  */
9245   if (pdi->has_template_arguments)
9246     {
9247       fixup_partial_die (pdi, cu);
9248
9249       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9250         {
9251           struct die_info *die;
9252           struct attribute attr;
9253           struct dwarf2_cu *ref_cu = cu;
9254
9255           /* DW_FORM_ref_addr is using section offset.  */
9256           attr.name = (enum dwarf_attribute) 0;
9257           attr.form = DW_FORM_ref_addr;
9258           attr.u.unsnd = to_underlying (pdi->sect_off);
9259           die = follow_die_ref (NULL, &attr, &ref_cu);
9260
9261           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9262         }
9263     }
9264
9265   parent_scope = partial_die_parent_scope (pdi, cu);
9266   if (parent_scope == NULL)
9267     return NULL;
9268   else
9269     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9270 }
9271
9272 static void
9273 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9274 {
9275   struct dwarf2_per_objfile *dwarf2_per_objfile
9276     = cu->per_cu->dwarf2_per_objfile;
9277   struct objfile *objfile = dwarf2_per_objfile->objfile;
9278   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9279   CORE_ADDR addr = 0;
9280   const char *actual_name = NULL;
9281   CORE_ADDR baseaddr;
9282   char *built_actual_name;
9283
9284   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9285
9286   built_actual_name = partial_die_full_name (pdi, cu);
9287   if (built_actual_name != NULL)
9288     actual_name = built_actual_name;
9289
9290   if (actual_name == NULL)
9291     actual_name = pdi->name;
9292
9293   switch (pdi->tag)
9294     {
9295     case DW_TAG_inlined_subroutine:
9296     case DW_TAG_subprogram:
9297       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9298       if (pdi->is_external || cu->language == language_ada)
9299         {
9300           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9301              of the global scope.  But in Ada, we want to be able to access
9302              nested procedures globally.  So all Ada subprograms are stored
9303              in the global scope.  */
9304           add_psymbol_to_list (actual_name, strlen (actual_name),
9305                                built_actual_name != NULL,
9306                                VAR_DOMAIN, LOC_BLOCK,
9307                                &objfile->global_psymbols,
9308                                addr, cu->language, objfile);
9309         }
9310       else
9311         {
9312           add_psymbol_to_list (actual_name, strlen (actual_name),
9313                                built_actual_name != NULL,
9314                                VAR_DOMAIN, LOC_BLOCK,
9315                                &objfile->static_psymbols,
9316                                addr, cu->language, objfile);
9317         }
9318
9319       if (pdi->main_subprogram && actual_name != NULL)
9320         set_objfile_main_name (objfile, actual_name, cu->language);
9321       break;
9322     case DW_TAG_constant:
9323       {
9324         std::vector<partial_symbol *> *list;
9325
9326         if (pdi->is_external)
9327           list = &objfile->global_psymbols;
9328         else
9329           list = &objfile->static_psymbols;
9330         add_psymbol_to_list (actual_name, strlen (actual_name),
9331                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9332                              list, 0, cu->language, objfile);
9333       }
9334       break;
9335     case DW_TAG_variable:
9336       if (pdi->d.locdesc)
9337         addr = decode_locdesc (pdi->d.locdesc, cu);
9338
9339       if (pdi->d.locdesc
9340           && addr == 0
9341           && !dwarf2_per_objfile->has_section_at_zero)
9342         {
9343           /* A global or static variable may also have been stripped
9344              out by the linker if unused, in which case its address
9345              will be nullified; do not add such variables into partial
9346              symbol table then.  */
9347         }
9348       else if (pdi->is_external)
9349         {
9350           /* Global Variable.
9351              Don't enter into the minimal symbol tables as there is
9352              a minimal symbol table entry from the ELF symbols already.
9353              Enter into partial symbol table if it has a location
9354              descriptor or a type.
9355              If the location descriptor is missing, new_symbol will create
9356              a LOC_UNRESOLVED symbol, the address of the variable will then
9357              be determined from the minimal symbol table whenever the variable
9358              is referenced.
9359              The address for the partial symbol table entry is not
9360              used by GDB, but it comes in handy for debugging partial symbol
9361              table building.  */
9362
9363           if (pdi->d.locdesc || pdi->has_type)
9364             add_psymbol_to_list (actual_name, strlen (actual_name),
9365                                  built_actual_name != NULL,
9366                                  VAR_DOMAIN, LOC_STATIC,
9367                                  &objfile->global_psymbols,
9368                                  addr + baseaddr,
9369                                  cu->language, objfile);
9370         }
9371       else
9372         {
9373           int has_loc = pdi->d.locdesc != NULL;
9374
9375           /* Static Variable.  Skip symbols whose value we cannot know (those
9376              without location descriptors or constant values).  */
9377           if (!has_loc && !pdi->has_const_value)
9378             {
9379               xfree (built_actual_name);
9380               return;
9381             }
9382
9383           add_psymbol_to_list (actual_name, strlen (actual_name),
9384                                built_actual_name != NULL,
9385                                VAR_DOMAIN, LOC_STATIC,
9386                                &objfile->static_psymbols,
9387                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9388                                cu->language, objfile);
9389         }
9390       break;
9391     case DW_TAG_typedef:
9392     case DW_TAG_base_type:
9393     case DW_TAG_subrange_type:
9394       add_psymbol_to_list (actual_name, strlen (actual_name),
9395                            built_actual_name != NULL,
9396                            VAR_DOMAIN, LOC_TYPEDEF,
9397                            &objfile->static_psymbols,
9398                            0, cu->language, objfile);
9399       break;
9400     case DW_TAG_imported_declaration:
9401     case DW_TAG_namespace:
9402       add_psymbol_to_list (actual_name, strlen (actual_name),
9403                            built_actual_name != NULL,
9404                            VAR_DOMAIN, LOC_TYPEDEF,
9405                            &objfile->global_psymbols,
9406                            0, cu->language, objfile);
9407       break;
9408     case DW_TAG_module:
9409       add_psymbol_to_list (actual_name, strlen (actual_name),
9410                            built_actual_name != NULL,
9411                            MODULE_DOMAIN, LOC_TYPEDEF,
9412                            &objfile->global_psymbols,
9413                            0, cu->language, objfile);
9414       break;
9415     case DW_TAG_class_type:
9416     case DW_TAG_interface_type:
9417     case DW_TAG_structure_type:
9418     case DW_TAG_union_type:
9419     case DW_TAG_enumeration_type:
9420       /* Skip external references.  The DWARF standard says in the section
9421          about "Structure, Union, and Class Type Entries": "An incomplete
9422          structure, union or class type is represented by a structure,
9423          union or class entry that does not have a byte size attribute
9424          and that has a DW_AT_declaration attribute."  */
9425       if (!pdi->has_byte_size && pdi->is_declaration)
9426         {
9427           xfree (built_actual_name);
9428           return;
9429         }
9430
9431       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9432          static vs. global.  */
9433       add_psymbol_to_list (actual_name, strlen (actual_name),
9434                            built_actual_name != NULL,
9435                            STRUCT_DOMAIN, LOC_TYPEDEF,
9436                            cu->language == language_cplus
9437                            ? &objfile->global_psymbols
9438                            : &objfile->static_psymbols,
9439                            0, cu->language, objfile);
9440
9441       break;
9442     case DW_TAG_enumerator:
9443       add_psymbol_to_list (actual_name, strlen (actual_name),
9444                            built_actual_name != NULL,
9445                            VAR_DOMAIN, LOC_CONST,
9446                            cu->language == language_cplus
9447                            ? &objfile->global_psymbols
9448                            : &objfile->static_psymbols,
9449                            0, cu->language, objfile);
9450       break;
9451     default:
9452       break;
9453     }
9454
9455   xfree (built_actual_name);
9456 }
9457
9458 /* Read a partial die corresponding to a namespace; also, add a symbol
9459    corresponding to that namespace to the symbol table.  NAMESPACE is
9460    the name of the enclosing namespace.  */
9461
9462 static void
9463 add_partial_namespace (struct partial_die_info *pdi,
9464                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9465                        int set_addrmap, struct dwarf2_cu *cu)
9466 {
9467   /* Add a symbol for the namespace.  */
9468
9469   add_partial_symbol (pdi, cu);
9470
9471   /* Now scan partial symbols in that namespace.  */
9472
9473   if (pdi->has_children)
9474     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9475 }
9476
9477 /* Read a partial die corresponding to a Fortran module.  */
9478
9479 static void
9480 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9481                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9482 {
9483   /* Add a symbol for the namespace.  */
9484
9485   add_partial_symbol (pdi, cu);
9486
9487   /* Now scan partial symbols in that module.  */
9488
9489   if (pdi->has_children)
9490     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9491 }
9492
9493 /* Read a partial die corresponding to a subprogram or an inlined
9494    subprogram and create a partial symbol for that subprogram.
9495    When the CU language allows it, this routine also defines a partial
9496    symbol for each nested subprogram that this subprogram contains.
9497    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9498    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9499
9500    PDI may also be a lexical block, in which case we simply search
9501    recursively for subprograms defined inside that lexical block.
9502    Again, this is only performed when the CU language allows this
9503    type of definitions.  */
9504
9505 static void
9506 add_partial_subprogram (struct partial_die_info *pdi,
9507                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9508                         int set_addrmap, struct dwarf2_cu *cu)
9509 {
9510   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9511     {
9512       if (pdi->has_pc_info)
9513         {
9514           if (pdi->lowpc < *lowpc)
9515             *lowpc = pdi->lowpc;
9516           if (pdi->highpc > *highpc)
9517             *highpc = pdi->highpc;
9518           if (set_addrmap)
9519             {
9520               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9521               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9522               CORE_ADDR baseaddr;
9523               CORE_ADDR highpc;
9524               CORE_ADDR lowpc;
9525
9526               baseaddr = ANOFFSET (objfile->section_offsets,
9527                                    SECT_OFF_TEXT (objfile));
9528               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9529                                                   pdi->lowpc + baseaddr);
9530               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9531                                                    pdi->highpc + baseaddr);
9532               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9533                                  cu->per_cu->v.psymtab);
9534             }
9535         }
9536
9537       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9538         {
9539           if (!pdi->is_declaration)
9540             /* Ignore subprogram DIEs that do not have a name, they are
9541                illegal.  Do not emit a complaint at this point, we will
9542                do so when we convert this psymtab into a symtab.  */
9543             if (pdi->name)
9544               add_partial_symbol (pdi, cu);
9545         }
9546     }
9547
9548   if (! pdi->has_children)
9549     return;
9550
9551   if (cu->language == language_ada)
9552     {
9553       pdi = pdi->die_child;
9554       while (pdi != NULL)
9555         {
9556           fixup_partial_die (pdi, cu);
9557           if (pdi->tag == DW_TAG_subprogram
9558               || pdi->tag == DW_TAG_inlined_subroutine
9559               || pdi->tag == DW_TAG_lexical_block)
9560             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9561           pdi = pdi->die_sibling;
9562         }
9563     }
9564 }
9565
9566 /* Read a partial die corresponding to an enumeration type.  */
9567
9568 static void
9569 add_partial_enumeration (struct partial_die_info *enum_pdi,
9570                          struct dwarf2_cu *cu)
9571 {
9572   struct partial_die_info *pdi;
9573
9574   if (enum_pdi->name != NULL)
9575     add_partial_symbol (enum_pdi, cu);
9576
9577   pdi = enum_pdi->die_child;
9578   while (pdi)
9579     {
9580       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9581         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9582       else
9583         add_partial_symbol (pdi, cu);
9584       pdi = pdi->die_sibling;
9585     }
9586 }
9587
9588 /* Return the initial uleb128 in the die at INFO_PTR.  */
9589
9590 static unsigned int
9591 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9592 {
9593   unsigned int bytes_read;
9594
9595   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9596 }
9597
9598 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9599    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9600
9601    Return the corresponding abbrev, or NULL if the number is zero (indicating
9602    an empty DIE).  In either case *BYTES_READ will be set to the length of
9603    the initial number.  */
9604
9605 static struct abbrev_info *
9606 peek_die_abbrev (const die_reader_specs &reader,
9607                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9608 {
9609   dwarf2_cu *cu = reader.cu;
9610   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9611   unsigned int abbrev_number
9612     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9613
9614   if (abbrev_number == 0)
9615     return NULL;
9616
9617   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9618   if (!abbrev)
9619     {
9620       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9621                " at offset 0x%x [in module %s]"),
9622              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9623              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9624     }
9625
9626   return abbrev;
9627 }
9628
9629 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9630    Returns a pointer to the end of a series of DIEs, terminated by an empty
9631    DIE.  Any children of the skipped DIEs will also be skipped.  */
9632
9633 static const gdb_byte *
9634 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9635 {
9636   while (1)
9637     {
9638       unsigned int bytes_read;
9639       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9640
9641       if (abbrev == NULL)
9642         return info_ptr + bytes_read;
9643       else
9644         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9645     }
9646 }
9647
9648 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9649    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9650    abbrev corresponding to that skipped uleb128 should be passed in
9651    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9652    children.  */
9653
9654 static const gdb_byte *
9655 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9656               struct abbrev_info *abbrev)
9657 {
9658   unsigned int bytes_read;
9659   struct attribute attr;
9660   bfd *abfd = reader->abfd;
9661   struct dwarf2_cu *cu = reader->cu;
9662   const gdb_byte *buffer = reader->buffer;
9663   const gdb_byte *buffer_end = reader->buffer_end;
9664   unsigned int form, i;
9665
9666   for (i = 0; i < abbrev->num_attrs; i++)
9667     {
9668       /* The only abbrev we care about is DW_AT_sibling.  */
9669       if (abbrev->attrs[i].name == DW_AT_sibling)
9670         {
9671           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9672           if (attr.form == DW_FORM_ref_addr)
9673             complaint (&symfile_complaints,
9674                        _("ignoring absolute DW_AT_sibling"));
9675           else
9676             {
9677               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9678               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9679
9680               if (sibling_ptr < info_ptr)
9681                 complaint (&symfile_complaints,
9682                            _("DW_AT_sibling points backwards"));
9683               else if (sibling_ptr > reader->buffer_end)
9684                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9685               else
9686                 return sibling_ptr;
9687             }
9688         }
9689
9690       /* If it isn't DW_AT_sibling, skip this attribute.  */
9691       form = abbrev->attrs[i].form;
9692     skip_attribute:
9693       switch (form)
9694         {
9695         case DW_FORM_ref_addr:
9696           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9697              and later it is offset sized.  */
9698           if (cu->header.version == 2)
9699             info_ptr += cu->header.addr_size;
9700           else
9701             info_ptr += cu->header.offset_size;
9702           break;
9703         case DW_FORM_GNU_ref_alt:
9704           info_ptr += cu->header.offset_size;
9705           break;
9706         case DW_FORM_addr:
9707           info_ptr += cu->header.addr_size;
9708           break;
9709         case DW_FORM_data1:
9710         case DW_FORM_ref1:
9711         case DW_FORM_flag:
9712           info_ptr += 1;
9713           break;
9714         case DW_FORM_flag_present:
9715         case DW_FORM_implicit_const:
9716           break;
9717         case DW_FORM_data2:
9718         case DW_FORM_ref2:
9719           info_ptr += 2;
9720           break;
9721         case DW_FORM_data4:
9722         case DW_FORM_ref4:
9723           info_ptr += 4;
9724           break;
9725         case DW_FORM_data8:
9726         case DW_FORM_ref8:
9727         case DW_FORM_ref_sig8:
9728           info_ptr += 8;
9729           break;
9730         case DW_FORM_data16:
9731           info_ptr += 16;
9732           break;
9733         case DW_FORM_string:
9734           read_direct_string (abfd, info_ptr, &bytes_read);
9735           info_ptr += bytes_read;
9736           break;
9737         case DW_FORM_sec_offset:
9738         case DW_FORM_strp:
9739         case DW_FORM_GNU_strp_alt:
9740           info_ptr += cu->header.offset_size;
9741           break;
9742         case DW_FORM_exprloc:
9743         case DW_FORM_block:
9744           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9745           info_ptr += bytes_read;
9746           break;
9747         case DW_FORM_block1:
9748           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9749           break;
9750         case DW_FORM_block2:
9751           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9752           break;
9753         case DW_FORM_block4:
9754           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9755           break;
9756         case DW_FORM_sdata:
9757         case DW_FORM_udata:
9758         case DW_FORM_ref_udata:
9759         case DW_FORM_GNU_addr_index:
9760         case DW_FORM_GNU_str_index:
9761           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9762           break;
9763         case DW_FORM_indirect:
9764           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9765           info_ptr += bytes_read;
9766           /* We need to continue parsing from here, so just go back to
9767              the top.  */
9768           goto skip_attribute;
9769
9770         default:
9771           error (_("Dwarf Error: Cannot handle %s "
9772                    "in DWARF reader [in module %s]"),
9773                  dwarf_form_name (form),
9774                  bfd_get_filename (abfd));
9775         }
9776     }
9777
9778   if (abbrev->has_children)
9779     return skip_children (reader, info_ptr);
9780   else
9781     return info_ptr;
9782 }
9783
9784 /* Locate ORIG_PDI's sibling.
9785    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9786
9787 static const gdb_byte *
9788 locate_pdi_sibling (const struct die_reader_specs *reader,
9789                     struct partial_die_info *orig_pdi,
9790                     const gdb_byte *info_ptr)
9791 {
9792   /* Do we know the sibling already?  */
9793
9794   if (orig_pdi->sibling)
9795     return orig_pdi->sibling;
9796
9797   /* Are there any children to deal with?  */
9798
9799   if (!orig_pdi->has_children)
9800     return info_ptr;
9801
9802   /* Skip the children the long way.  */
9803
9804   return skip_children (reader, info_ptr);
9805 }
9806
9807 /* Expand this partial symbol table into a full symbol table.  SELF is
9808    not NULL.  */
9809
9810 static void
9811 dwarf2_read_symtab (struct partial_symtab *self,
9812                     struct objfile *objfile)
9813 {
9814   struct dwarf2_per_objfile *dwarf2_per_objfile
9815     = get_dwarf2_per_objfile (objfile);
9816
9817   if (self->readin)
9818     {
9819       warning (_("bug: psymtab for %s is already read in."),
9820                self->filename);
9821     }
9822   else
9823     {
9824       if (info_verbose)
9825         {
9826           printf_filtered (_("Reading in symbols for %s..."),
9827                            self->filename);
9828           gdb_flush (gdb_stdout);
9829         }
9830
9831       /* If this psymtab is constructed from a debug-only objfile, the
9832          has_section_at_zero flag will not necessarily be correct.  We
9833          can get the correct value for this flag by looking at the data
9834          associated with the (presumably stripped) associated objfile.  */
9835       if (objfile->separate_debug_objfile_backlink)
9836         {
9837           struct dwarf2_per_objfile *dpo_backlink
9838             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9839
9840           dwarf2_per_objfile->has_section_at_zero
9841             = dpo_backlink->has_section_at_zero;
9842         }
9843
9844       dwarf2_per_objfile->reading_partial_symbols = 0;
9845
9846       psymtab_to_symtab_1 (self);
9847
9848       /* Finish up the debug error message.  */
9849       if (info_verbose)
9850         printf_filtered (_("done.\n"));
9851     }
9852
9853   process_cu_includes (dwarf2_per_objfile);
9854 }
9855 \f
9856 /* Reading in full CUs.  */
9857
9858 /* Add PER_CU to the queue.  */
9859
9860 static void
9861 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9862                  enum language pretend_language)
9863 {
9864   struct dwarf2_queue_item *item;
9865
9866   per_cu->queued = 1;
9867   item = XNEW (struct dwarf2_queue_item);
9868   item->per_cu = per_cu;
9869   item->pretend_language = pretend_language;
9870   item->next = NULL;
9871
9872   if (dwarf2_queue == NULL)
9873     dwarf2_queue = item;
9874   else
9875     dwarf2_queue_tail->next = item;
9876
9877   dwarf2_queue_tail = item;
9878 }
9879
9880 /* If PER_CU is not yet queued, add it to the queue.
9881    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9882    dependency.
9883    The result is non-zero if PER_CU was queued, otherwise the result is zero
9884    meaning either PER_CU is already queued or it is already loaded.
9885
9886    N.B. There is an invariant here that if a CU is queued then it is loaded.
9887    The caller is required to load PER_CU if we return non-zero.  */
9888
9889 static int
9890 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9891                        struct dwarf2_per_cu_data *per_cu,
9892                        enum language pretend_language)
9893 {
9894   /* We may arrive here during partial symbol reading, if we need full
9895      DIEs to process an unusual case (e.g. template arguments).  Do
9896      not queue PER_CU, just tell our caller to load its DIEs.  */
9897   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9898     {
9899       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9900         return 1;
9901       return 0;
9902     }
9903
9904   /* Mark the dependence relation so that we don't flush PER_CU
9905      too early.  */
9906   if (dependent_cu != NULL)
9907     dwarf2_add_dependence (dependent_cu, per_cu);
9908
9909   /* If it's already on the queue, we have nothing to do.  */
9910   if (per_cu->queued)
9911     return 0;
9912
9913   /* If the compilation unit is already loaded, just mark it as
9914      used.  */
9915   if (per_cu->cu != NULL)
9916     {
9917       per_cu->cu->last_used = 0;
9918       return 0;
9919     }
9920
9921   /* Add it to the queue.  */
9922   queue_comp_unit (per_cu, pretend_language);
9923
9924   return 1;
9925 }
9926
9927 /* Process the queue.  */
9928
9929 static void
9930 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9931 {
9932   struct dwarf2_queue_item *item, *next_item;
9933
9934   if (dwarf_read_debug)
9935     {
9936       fprintf_unfiltered (gdb_stdlog,
9937                           "Expanding one or more symtabs of objfile %s ...\n",
9938                           objfile_name (dwarf2_per_objfile->objfile));
9939     }
9940
9941   /* The queue starts out with one item, but following a DIE reference
9942      may load a new CU, adding it to the end of the queue.  */
9943   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9944     {
9945       if ((dwarf2_per_objfile->using_index
9946            ? !item->per_cu->v.quick->compunit_symtab
9947            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9948           /* Skip dummy CUs.  */
9949           && item->per_cu->cu != NULL)
9950         {
9951           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9952           unsigned int debug_print_threshold;
9953           char buf[100];
9954
9955           if (per_cu->is_debug_types)
9956             {
9957               struct signatured_type *sig_type =
9958                 (struct signatured_type *) per_cu;
9959
9960               sprintf (buf, "TU %s at offset 0x%x",
9961                        hex_string (sig_type->signature),
9962                        to_underlying (per_cu->sect_off));
9963               /* There can be 100s of TUs.
9964                  Only print them in verbose mode.  */
9965               debug_print_threshold = 2;
9966             }
9967           else
9968             {
9969               sprintf (buf, "CU at offset 0x%x",
9970                        to_underlying (per_cu->sect_off));
9971               debug_print_threshold = 1;
9972             }
9973
9974           if (dwarf_read_debug >= debug_print_threshold)
9975             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9976
9977           if (per_cu->is_debug_types)
9978             process_full_type_unit (per_cu, item->pretend_language);
9979           else
9980             process_full_comp_unit (per_cu, item->pretend_language);
9981
9982           if (dwarf_read_debug >= debug_print_threshold)
9983             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9984         }
9985
9986       item->per_cu->queued = 0;
9987       next_item = item->next;
9988       xfree (item);
9989     }
9990
9991   dwarf2_queue_tail = NULL;
9992
9993   if (dwarf_read_debug)
9994     {
9995       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9996                           objfile_name (dwarf2_per_objfile->objfile));
9997     }
9998 }
9999
10000 /* Read in full symbols for PST, and anything it depends on.  */
10001
10002 static void
10003 psymtab_to_symtab_1 (struct partial_symtab *pst)
10004 {
10005   struct dwarf2_per_cu_data *per_cu;
10006   int i;
10007
10008   if (pst->readin)
10009     return;
10010
10011   for (i = 0; i < pst->number_of_dependencies; i++)
10012     if (!pst->dependencies[i]->readin
10013         && pst->dependencies[i]->user == NULL)
10014       {
10015         /* Inform about additional files that need to be read in.  */
10016         if (info_verbose)
10017           {
10018             /* FIXME: i18n: Need to make this a single string.  */
10019             fputs_filtered (" ", gdb_stdout);
10020             wrap_here ("");
10021             fputs_filtered ("and ", gdb_stdout);
10022             wrap_here ("");
10023             printf_filtered ("%s...", pst->dependencies[i]->filename);
10024             wrap_here ("");     /* Flush output.  */
10025             gdb_flush (gdb_stdout);
10026           }
10027         psymtab_to_symtab_1 (pst->dependencies[i]);
10028       }
10029
10030   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10031
10032   if (per_cu == NULL)
10033     {
10034       /* It's an include file, no symbols to read for it.
10035          Everything is in the parent symtab.  */
10036       pst->readin = 1;
10037       return;
10038     }
10039
10040   dw2_do_instantiate_symtab (per_cu);
10041 }
10042
10043 /* Trivial hash function for die_info: the hash value of a DIE
10044    is its offset in .debug_info for this objfile.  */
10045
10046 static hashval_t
10047 die_hash (const void *item)
10048 {
10049   const struct die_info *die = (const struct die_info *) item;
10050
10051   return to_underlying (die->sect_off);
10052 }
10053
10054 /* Trivial comparison function for die_info structures: two DIEs
10055    are equal if they have the same offset.  */
10056
10057 static int
10058 die_eq (const void *item_lhs, const void *item_rhs)
10059 {
10060   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10061   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10062
10063   return die_lhs->sect_off == die_rhs->sect_off;
10064 }
10065
10066 /* die_reader_func for load_full_comp_unit.
10067    This is identical to read_signatured_type_reader,
10068    but is kept separate for now.  */
10069
10070 static void
10071 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10072                             const gdb_byte *info_ptr,
10073                             struct die_info *comp_unit_die,
10074                             int has_children,
10075                             void *data)
10076 {
10077   struct dwarf2_cu *cu = reader->cu;
10078   enum language *language_ptr = (enum language *) data;
10079
10080   gdb_assert (cu->die_hash == NULL);
10081   cu->die_hash =
10082     htab_create_alloc_ex (cu->header.length / 12,
10083                           die_hash,
10084                           die_eq,
10085                           NULL,
10086                           &cu->comp_unit_obstack,
10087                           hashtab_obstack_allocate,
10088                           dummy_obstack_deallocate);
10089
10090   if (has_children)
10091     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10092                                                   &info_ptr, comp_unit_die);
10093   cu->dies = comp_unit_die;
10094   /* comp_unit_die is not stored in die_hash, no need.  */
10095
10096   /* We try not to read any attributes in this function, because not
10097      all CUs needed for references have been loaded yet, and symbol
10098      table processing isn't initialized.  But we have to set the CU language,
10099      or we won't be able to build types correctly.
10100      Similarly, if we do not read the producer, we can not apply
10101      producer-specific interpretation.  */
10102   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10103 }
10104
10105 /* Load the DIEs associated with PER_CU into memory.  */
10106
10107 static void
10108 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10109                      enum language pretend_language)
10110 {
10111   gdb_assert (! this_cu->is_debug_types);
10112
10113   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10114                            load_full_comp_unit_reader, &pretend_language);
10115 }
10116
10117 /* Add a DIE to the delayed physname list.  */
10118
10119 static void
10120 add_to_method_list (struct type *type, int fnfield_index, int index,
10121                     const char *name, struct die_info *die,
10122                     struct dwarf2_cu *cu)
10123 {
10124   struct delayed_method_info mi;
10125   mi.type = type;
10126   mi.fnfield_index = fnfield_index;
10127   mi.index = index;
10128   mi.name = name;
10129   mi.die = die;
10130   cu->method_list.push_back (mi);
10131 }
10132
10133 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10134    "const" / "volatile".  If so, decrements LEN by the length of the
10135    modifier and return true.  Otherwise return false.  */
10136
10137 template<size_t N>
10138 static bool
10139 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10140 {
10141   size_t mod_len = sizeof (mod) - 1;
10142   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10143     {
10144       len -= mod_len;
10145       return true;
10146     }
10147   return false;
10148 }
10149
10150 /* Compute the physnames of any methods on the CU's method list.
10151
10152    The computation of method physnames is delayed in order to avoid the
10153    (bad) condition that one of the method's formal parameters is of an as yet
10154    incomplete type.  */
10155
10156 static void
10157 compute_delayed_physnames (struct dwarf2_cu *cu)
10158 {
10159   /* Only C++ delays computing physnames.  */
10160   if (cu->method_list.empty ())
10161     return;
10162   gdb_assert (cu->language == language_cplus);
10163
10164   for (struct delayed_method_info &mi : cu->method_list)
10165     {
10166       const char *physname;
10167       struct fn_fieldlist *fn_flp
10168         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10169       physname = dwarf2_physname (mi.name, mi.die, cu);
10170       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10171         = physname ? physname : "";
10172
10173       /* Since there's no tag to indicate whether a method is a
10174          const/volatile overload, extract that information out of the
10175          demangled name.  */
10176       if (physname != NULL)
10177         {
10178           size_t len = strlen (physname);
10179
10180           while (1)
10181             {
10182               if (physname[len] == ')') /* shortcut */
10183                 break;
10184               else if (check_modifier (physname, len, " const"))
10185                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10186               else if (check_modifier (physname, len, " volatile"))
10187                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10188               else
10189                 break;
10190             }
10191         }
10192     }
10193
10194   /* The list is no longer needed.  */
10195   cu->method_list.clear ();
10196 }
10197
10198 /* Go objects should be embedded in a DW_TAG_module DIE,
10199    and it's not clear if/how imported objects will appear.
10200    To keep Go support simple until that's worked out,
10201    go back through what we've read and create something usable.
10202    We could do this while processing each DIE, and feels kinda cleaner,
10203    but that way is more invasive.
10204    This is to, for example, allow the user to type "p var" or "b main"
10205    without having to specify the package name, and allow lookups
10206    of module.object to work in contexts that use the expression
10207    parser.  */
10208
10209 static void
10210 fixup_go_packaging (struct dwarf2_cu *cu)
10211 {
10212   char *package_name = NULL;
10213   struct pending *list;
10214   int i;
10215
10216   for (list = global_symbols; list != NULL; list = list->next)
10217     {
10218       for (i = 0; i < list->nsyms; ++i)
10219         {
10220           struct symbol *sym = list->symbol[i];
10221
10222           if (SYMBOL_LANGUAGE (sym) == language_go
10223               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10224             {
10225               char *this_package_name = go_symbol_package_name (sym);
10226
10227               if (this_package_name == NULL)
10228                 continue;
10229               if (package_name == NULL)
10230                 package_name = this_package_name;
10231               else
10232                 {
10233                   struct objfile *objfile
10234                     = cu->per_cu->dwarf2_per_objfile->objfile;
10235                   if (strcmp (package_name, this_package_name) != 0)
10236                     complaint (&symfile_complaints,
10237                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10238                                (symbol_symtab (sym) != NULL
10239                                 ? symtab_to_filename_for_display
10240                                     (symbol_symtab (sym))
10241                                 : objfile_name (objfile)),
10242                                this_package_name, package_name);
10243                   xfree (this_package_name);
10244                 }
10245             }
10246         }
10247     }
10248
10249   if (package_name != NULL)
10250     {
10251       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10252       const char *saved_package_name
10253         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10254                                         package_name,
10255                                         strlen (package_name));
10256       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10257                                      saved_package_name);
10258       struct symbol *sym;
10259
10260       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10261
10262       sym = allocate_symbol (objfile);
10263       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10264       SYMBOL_SET_NAMES (sym, saved_package_name,
10265                         strlen (saved_package_name), 0, objfile);
10266       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10267          e.g., "main" finds the "main" module and not C's main().  */
10268       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10269       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10270       SYMBOL_TYPE (sym) = type;
10271
10272       add_symbol_to_list (sym, &global_symbols);
10273
10274       xfree (package_name);
10275     }
10276 }
10277
10278 /* Return the symtab for PER_CU.  This works properly regardless of
10279    whether we're using the index or psymtabs.  */
10280
10281 static struct compunit_symtab *
10282 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10283 {
10284   return (per_cu->dwarf2_per_objfile->using_index
10285           ? per_cu->v.quick->compunit_symtab
10286           : per_cu->v.psymtab->compunit_symtab);
10287 }
10288
10289 /* A helper function for computing the list of all symbol tables
10290    included by PER_CU.  */
10291
10292 static void
10293 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10294                                 htab_t all_children, htab_t all_type_symtabs,
10295                                 struct dwarf2_per_cu_data *per_cu,
10296                                 struct compunit_symtab *immediate_parent)
10297 {
10298   void **slot;
10299   int ix;
10300   struct compunit_symtab *cust;
10301   struct dwarf2_per_cu_data *iter;
10302
10303   slot = htab_find_slot (all_children, per_cu, INSERT);
10304   if (*slot != NULL)
10305     {
10306       /* This inclusion and its children have been processed.  */
10307       return;
10308     }
10309
10310   *slot = per_cu;
10311   /* Only add a CU if it has a symbol table.  */
10312   cust = get_compunit_symtab (per_cu);
10313   if (cust != NULL)
10314     {
10315       /* If this is a type unit only add its symbol table if we haven't
10316          seen it yet (type unit per_cu's can share symtabs).  */
10317       if (per_cu->is_debug_types)
10318         {
10319           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10320           if (*slot == NULL)
10321             {
10322               *slot = cust;
10323               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10324               if (cust->user == NULL)
10325                 cust->user = immediate_parent;
10326             }
10327         }
10328       else
10329         {
10330           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10331           if (cust->user == NULL)
10332             cust->user = immediate_parent;
10333         }
10334     }
10335
10336   for (ix = 0;
10337        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10338        ++ix)
10339     {
10340       recursively_compute_inclusions (result, all_children,
10341                                       all_type_symtabs, iter, cust);
10342     }
10343 }
10344
10345 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10346    PER_CU.  */
10347
10348 static void
10349 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10350 {
10351   gdb_assert (! per_cu->is_debug_types);
10352
10353   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10354     {
10355       int ix, len;
10356       struct dwarf2_per_cu_data *per_cu_iter;
10357       struct compunit_symtab *compunit_symtab_iter;
10358       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10359       htab_t all_children, all_type_symtabs;
10360       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10361
10362       /* If we don't have a symtab, we can just skip this case.  */
10363       if (cust == NULL)
10364         return;
10365
10366       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10367                                         NULL, xcalloc, xfree);
10368       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10369                                             NULL, xcalloc, xfree);
10370
10371       for (ix = 0;
10372            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10373                         ix, per_cu_iter);
10374            ++ix)
10375         {
10376           recursively_compute_inclusions (&result_symtabs, all_children,
10377                                           all_type_symtabs, per_cu_iter,
10378                                           cust);
10379         }
10380
10381       /* Now we have a transitive closure of all the included symtabs.  */
10382       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10383       cust->includes
10384         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10385                      struct compunit_symtab *, len + 1);
10386       for (ix = 0;
10387            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10388                         compunit_symtab_iter);
10389            ++ix)
10390         cust->includes[ix] = compunit_symtab_iter;
10391       cust->includes[len] = NULL;
10392
10393       VEC_free (compunit_symtab_ptr, result_symtabs);
10394       htab_delete (all_children);
10395       htab_delete (all_type_symtabs);
10396     }
10397 }
10398
10399 /* Compute the 'includes' field for the symtabs of all the CUs we just
10400    read.  */
10401
10402 static void
10403 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10404 {
10405   int ix;
10406   struct dwarf2_per_cu_data *iter;
10407
10408   for (ix = 0;
10409        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10410                     ix, iter);
10411        ++ix)
10412     {
10413       if (! iter->is_debug_types)
10414         compute_compunit_symtab_includes (iter);
10415     }
10416
10417   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10418 }
10419
10420 /* Generate full symbol information for PER_CU, whose DIEs have
10421    already been loaded into memory.  */
10422
10423 static void
10424 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10425                         enum language pretend_language)
10426 {
10427   struct dwarf2_cu *cu = per_cu->cu;
10428   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10429   struct objfile *objfile = dwarf2_per_objfile->objfile;
10430   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10431   CORE_ADDR lowpc, highpc;
10432   struct compunit_symtab *cust;
10433   CORE_ADDR baseaddr;
10434   struct block *static_block;
10435   CORE_ADDR addr;
10436
10437   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10438
10439   buildsym_init ();
10440   scoped_free_pendings free_pending;
10441
10442   /* Clear the list here in case something was left over.  */
10443   cu->method_list.clear ();
10444
10445   cu->list_in_scope = &file_symbols;
10446
10447   cu->language = pretend_language;
10448   cu->language_defn = language_def (cu->language);
10449
10450   /* Do line number decoding in read_file_scope () */
10451   process_die (cu->dies, cu);
10452
10453   /* For now fudge the Go package.  */
10454   if (cu->language == language_go)
10455     fixup_go_packaging (cu);
10456
10457   /* Now that we have processed all the DIEs in the CU, all the types 
10458      should be complete, and it should now be safe to compute all of the
10459      physnames.  */
10460   compute_delayed_physnames (cu);
10461
10462   /* Some compilers don't define a DW_AT_high_pc attribute for the
10463      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10464      it, by scanning the DIE's below the compilation unit.  */
10465   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10466
10467   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10468   static_block = end_symtab_get_static_block (addr, 0, 1);
10469
10470   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10471      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10472      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10473      addrmap to help ensure it has an accurate map of pc values belonging to
10474      this comp unit.  */
10475   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10476
10477   cust = end_symtab_from_static_block (static_block,
10478                                        SECT_OFF_TEXT (objfile), 0);
10479
10480   if (cust != NULL)
10481     {
10482       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10483
10484       /* Set symtab language to language from DW_AT_language.  If the
10485          compilation is from a C file generated by language preprocessors, do
10486          not set the language if it was already deduced by start_subfile.  */
10487       if (!(cu->language == language_c
10488             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10489         COMPUNIT_FILETABS (cust)->language = cu->language;
10490
10491       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10492          produce DW_AT_location with location lists but it can be possibly
10493          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10494          there were bugs in prologue debug info, fixed later in GCC-4.5
10495          by "unwind info for epilogues" patch (which is not directly related).
10496
10497          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10498          needed, it would be wrong due to missing DW_AT_producer there.
10499
10500          Still one can confuse GDB by using non-standard GCC compilation
10501          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10502          */ 
10503       if (cu->has_loclist && gcc_4_minor >= 5)
10504         cust->locations_valid = 1;
10505
10506       if (gcc_4_minor >= 5)
10507         cust->epilogue_unwind_valid = 1;
10508
10509       cust->call_site_htab = cu->call_site_htab;
10510     }
10511
10512   if (dwarf2_per_objfile->using_index)
10513     per_cu->v.quick->compunit_symtab = cust;
10514   else
10515     {
10516       struct partial_symtab *pst = per_cu->v.psymtab;
10517       pst->compunit_symtab = cust;
10518       pst->readin = 1;
10519     }
10520
10521   /* Push it for inclusion processing later.  */
10522   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10523 }
10524
10525 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10526    already been loaded into memory.  */
10527
10528 static void
10529 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10530                         enum language pretend_language)
10531 {
10532   struct dwarf2_cu *cu = per_cu->cu;
10533   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10534   struct objfile *objfile = dwarf2_per_objfile->objfile;
10535   struct compunit_symtab *cust;
10536   struct signatured_type *sig_type;
10537
10538   gdb_assert (per_cu->is_debug_types);
10539   sig_type = (struct signatured_type *) per_cu;
10540
10541   buildsym_init ();
10542   scoped_free_pendings free_pending;
10543
10544   /* Clear the list here in case something was left over.  */
10545   cu->method_list.clear ();
10546
10547   cu->list_in_scope = &file_symbols;
10548
10549   cu->language = pretend_language;
10550   cu->language_defn = language_def (cu->language);
10551
10552   /* The symbol tables are set up in read_type_unit_scope.  */
10553   process_die (cu->dies, cu);
10554
10555   /* For now fudge the Go package.  */
10556   if (cu->language == language_go)
10557     fixup_go_packaging (cu);
10558
10559   /* Now that we have processed all the DIEs in the CU, all the types 
10560      should be complete, and it should now be safe to compute all of the
10561      physnames.  */
10562   compute_delayed_physnames (cu);
10563
10564   /* TUs share symbol tables.
10565      If this is the first TU to use this symtab, complete the construction
10566      of it with end_expandable_symtab.  Otherwise, complete the addition of
10567      this TU's symbols to the existing symtab.  */
10568   if (sig_type->type_unit_group->compunit_symtab == NULL)
10569     {
10570       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10571       sig_type->type_unit_group->compunit_symtab = cust;
10572
10573       if (cust != NULL)
10574         {
10575           /* Set symtab language to language from DW_AT_language.  If the
10576              compilation is from a C file generated by language preprocessors,
10577              do not set the language if it was already deduced by
10578              start_subfile.  */
10579           if (!(cu->language == language_c
10580                 && COMPUNIT_FILETABS (cust)->language != language_c))
10581             COMPUNIT_FILETABS (cust)->language = cu->language;
10582         }
10583     }
10584   else
10585     {
10586       augment_type_symtab ();
10587       cust = sig_type->type_unit_group->compunit_symtab;
10588     }
10589
10590   if (dwarf2_per_objfile->using_index)
10591     per_cu->v.quick->compunit_symtab = cust;
10592   else
10593     {
10594       struct partial_symtab *pst = per_cu->v.psymtab;
10595       pst->compunit_symtab = cust;
10596       pst->readin = 1;
10597     }
10598 }
10599
10600 /* Process an imported unit DIE.  */
10601
10602 static void
10603 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10604 {
10605   struct attribute *attr;
10606
10607   /* For now we don't handle imported units in type units.  */
10608   if (cu->per_cu->is_debug_types)
10609     {
10610       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10611                " supported in type units [in module %s]"),
10612              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10613     }
10614
10615   attr = dwarf2_attr (die, DW_AT_import, cu);
10616   if (attr != NULL)
10617     {
10618       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10619       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10620       dwarf2_per_cu_data *per_cu
10621         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10622                                             cu->per_cu->dwarf2_per_objfile);
10623
10624       /* If necessary, add it to the queue and load its DIEs.  */
10625       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10626         load_full_comp_unit (per_cu, cu->language);
10627
10628       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10629                      per_cu);
10630     }
10631 }
10632
10633 /* RAII object that represents a process_die scope: i.e.,
10634    starts/finishes processing a DIE.  */
10635 class process_die_scope
10636 {
10637 public:
10638   process_die_scope (die_info *die, dwarf2_cu *cu)
10639     : m_die (die), m_cu (cu)
10640   {
10641     /* We should only be processing DIEs not already in process.  */
10642     gdb_assert (!m_die->in_process);
10643     m_die->in_process = true;
10644   }
10645
10646   ~process_die_scope ()
10647   {
10648     m_die->in_process = false;
10649
10650     /* If we're done processing the DIE for the CU that owns the line
10651        header, we don't need the line header anymore.  */
10652     if (m_cu->line_header_die_owner == m_die)
10653       {
10654         delete m_cu->line_header;
10655         m_cu->line_header = NULL;
10656         m_cu->line_header_die_owner = NULL;
10657       }
10658   }
10659
10660 private:
10661   die_info *m_die;
10662   dwarf2_cu *m_cu;
10663 };
10664
10665 /* Process a die and its children.  */
10666
10667 static void
10668 process_die (struct die_info *die, struct dwarf2_cu *cu)
10669 {
10670   process_die_scope scope (die, cu);
10671
10672   switch (die->tag)
10673     {
10674     case DW_TAG_padding:
10675       break;
10676     case DW_TAG_compile_unit:
10677     case DW_TAG_partial_unit:
10678       read_file_scope (die, cu);
10679       break;
10680     case DW_TAG_type_unit:
10681       read_type_unit_scope (die, cu);
10682       break;
10683     case DW_TAG_subprogram:
10684     case DW_TAG_inlined_subroutine:
10685       read_func_scope (die, cu);
10686       break;
10687     case DW_TAG_lexical_block:
10688     case DW_TAG_try_block:
10689     case DW_TAG_catch_block:
10690       read_lexical_block_scope (die, cu);
10691       break;
10692     case DW_TAG_call_site:
10693     case DW_TAG_GNU_call_site:
10694       read_call_site_scope (die, cu);
10695       break;
10696     case DW_TAG_class_type:
10697     case DW_TAG_interface_type:
10698     case DW_TAG_structure_type:
10699     case DW_TAG_union_type:
10700       process_structure_scope (die, cu);
10701       break;
10702     case DW_TAG_enumeration_type:
10703       process_enumeration_scope (die, cu);
10704       break;
10705
10706     /* These dies have a type, but processing them does not create
10707        a symbol or recurse to process the children.  Therefore we can
10708        read them on-demand through read_type_die.  */
10709     case DW_TAG_subroutine_type:
10710     case DW_TAG_set_type:
10711     case DW_TAG_array_type:
10712     case DW_TAG_pointer_type:
10713     case DW_TAG_ptr_to_member_type:
10714     case DW_TAG_reference_type:
10715     case DW_TAG_rvalue_reference_type:
10716     case DW_TAG_string_type:
10717       break;
10718
10719     case DW_TAG_base_type:
10720     case DW_TAG_subrange_type:
10721     case DW_TAG_typedef:
10722       /* Add a typedef symbol for the type definition, if it has a
10723          DW_AT_name.  */
10724       new_symbol (die, read_type_die (die, cu), cu);
10725       break;
10726     case DW_TAG_common_block:
10727       read_common_block (die, cu);
10728       break;
10729     case DW_TAG_common_inclusion:
10730       break;
10731     case DW_TAG_namespace:
10732       cu->processing_has_namespace_info = 1;
10733       read_namespace (die, cu);
10734       break;
10735     case DW_TAG_module:
10736       cu->processing_has_namespace_info = 1;
10737       read_module (die, cu);
10738       break;
10739     case DW_TAG_imported_declaration:
10740       cu->processing_has_namespace_info = 1;
10741       if (read_namespace_alias (die, cu))
10742         break;
10743       /* The declaration is not a global namespace alias: fall through.  */
10744     case DW_TAG_imported_module:
10745       cu->processing_has_namespace_info = 1;
10746       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10747                                  || cu->language != language_fortran))
10748         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10749                    dwarf_tag_name (die->tag));
10750       read_import_statement (die, cu);
10751       break;
10752
10753     case DW_TAG_imported_unit:
10754       process_imported_unit_die (die, cu);
10755       break;
10756
10757     case DW_TAG_variable:
10758       read_variable (die, cu);
10759       break;
10760
10761     default:
10762       new_symbol (die, NULL, cu);
10763       break;
10764     }
10765 }
10766 \f
10767 /* DWARF name computation.  */
10768
10769 /* A helper function for dwarf2_compute_name which determines whether DIE
10770    needs to have the name of the scope prepended to the name listed in the
10771    die.  */
10772
10773 static int
10774 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10775 {
10776   struct attribute *attr;
10777
10778   switch (die->tag)
10779     {
10780     case DW_TAG_namespace:
10781     case DW_TAG_typedef:
10782     case DW_TAG_class_type:
10783     case DW_TAG_interface_type:
10784     case DW_TAG_structure_type:
10785     case DW_TAG_union_type:
10786     case DW_TAG_enumeration_type:
10787     case DW_TAG_enumerator:
10788     case DW_TAG_subprogram:
10789     case DW_TAG_inlined_subroutine:
10790     case DW_TAG_member:
10791     case DW_TAG_imported_declaration:
10792       return 1;
10793
10794     case DW_TAG_variable:
10795     case DW_TAG_constant:
10796       /* We only need to prefix "globally" visible variables.  These include
10797          any variable marked with DW_AT_external or any variable that
10798          lives in a namespace.  [Variables in anonymous namespaces
10799          require prefixing, but they are not DW_AT_external.]  */
10800
10801       if (dwarf2_attr (die, DW_AT_specification, cu))
10802         {
10803           struct dwarf2_cu *spec_cu = cu;
10804
10805           return die_needs_namespace (die_specification (die, &spec_cu),
10806                                       spec_cu);
10807         }
10808
10809       attr = dwarf2_attr (die, DW_AT_external, cu);
10810       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10811           && die->parent->tag != DW_TAG_module)
10812         return 0;
10813       /* A variable in a lexical block of some kind does not need a
10814          namespace, even though in C++ such variables may be external
10815          and have a mangled name.  */
10816       if (die->parent->tag ==  DW_TAG_lexical_block
10817           || die->parent->tag ==  DW_TAG_try_block
10818           || die->parent->tag ==  DW_TAG_catch_block
10819           || die->parent->tag == DW_TAG_subprogram)
10820         return 0;
10821       return 1;
10822
10823     default:
10824       return 0;
10825     }
10826 }
10827
10828 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10829    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10830    defined for the given DIE.  */
10831
10832 static struct attribute *
10833 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10834 {
10835   struct attribute *attr;
10836
10837   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10838   if (attr == NULL)
10839     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10840
10841   return attr;
10842 }
10843
10844 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10845    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10846    defined for the given DIE.  */
10847
10848 static const char *
10849 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10850 {
10851   const char *linkage_name;
10852
10853   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10854   if (linkage_name == NULL)
10855     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10856
10857   return linkage_name;
10858 }
10859
10860 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10861    compute the physname for the object, which include a method's:
10862    - formal parameters (C++),
10863    - receiver type (Go),
10864
10865    The term "physname" is a bit confusing.
10866    For C++, for example, it is the demangled name.
10867    For Go, for example, it's the mangled name.
10868
10869    For Ada, return the DIE's linkage name rather than the fully qualified
10870    name.  PHYSNAME is ignored..
10871
10872    The result is allocated on the objfile_obstack and canonicalized.  */
10873
10874 static const char *
10875 dwarf2_compute_name (const char *name,
10876                      struct die_info *die, struct dwarf2_cu *cu,
10877                      int physname)
10878 {
10879   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10880
10881   if (name == NULL)
10882     name = dwarf2_name (die, cu);
10883
10884   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10885      but otherwise compute it by typename_concat inside GDB.
10886      FIXME: Actually this is not really true, or at least not always true.
10887      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10888      Fortran names because there is no mangling standard.  So new_symbol
10889      will set the demangled name to the result of dwarf2_full_name, and it is
10890      the demangled name that GDB uses if it exists.  */
10891   if (cu->language == language_ada
10892       || (cu->language == language_fortran && physname))
10893     {
10894       /* For Ada unit, we prefer the linkage name over the name, as
10895          the former contains the exported name, which the user expects
10896          to be able to reference.  Ideally, we want the user to be able
10897          to reference this entity using either natural or linkage name,
10898          but we haven't started looking at this enhancement yet.  */
10899       const char *linkage_name = dw2_linkage_name (die, cu);
10900
10901       if (linkage_name != NULL)
10902         return linkage_name;
10903     }
10904
10905   /* These are the only languages we know how to qualify names in.  */
10906   if (name != NULL
10907       && (cu->language == language_cplus
10908           || cu->language == language_fortran || cu->language == language_d
10909           || cu->language == language_rust))
10910     {
10911       if (die_needs_namespace (die, cu))
10912         {
10913           const char *prefix;
10914           const char *canonical_name = NULL;
10915
10916           string_file buf;
10917
10918           prefix = determine_prefix (die, cu);
10919           if (*prefix != '\0')
10920             {
10921               char *prefixed_name = typename_concat (NULL, prefix, name,
10922                                                      physname, cu);
10923
10924               buf.puts (prefixed_name);
10925               xfree (prefixed_name);
10926             }
10927           else
10928             buf.puts (name);
10929
10930           /* Template parameters may be specified in the DIE's DW_AT_name, or
10931              as children with DW_TAG_template_type_param or
10932              DW_TAG_value_type_param.  If the latter, add them to the name
10933              here.  If the name already has template parameters, then
10934              skip this step; some versions of GCC emit both, and
10935              it is more efficient to use the pre-computed name.
10936
10937              Something to keep in mind about this process: it is very
10938              unlikely, or in some cases downright impossible, to produce
10939              something that will match the mangled name of a function.
10940              If the definition of the function has the same debug info,
10941              we should be able to match up with it anyway.  But fallbacks
10942              using the minimal symbol, for instance to find a method
10943              implemented in a stripped copy of libstdc++, will not work.
10944              If we do not have debug info for the definition, we will have to
10945              match them up some other way.
10946
10947              When we do name matching there is a related problem with function
10948              templates; two instantiated function templates are allowed to
10949              differ only by their return types, which we do not add here.  */
10950
10951           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10952             {
10953               struct attribute *attr;
10954               struct die_info *child;
10955               int first = 1;
10956
10957               die->building_fullname = 1;
10958
10959               for (child = die->child; child != NULL; child = child->sibling)
10960                 {
10961                   struct type *type;
10962                   LONGEST value;
10963                   const gdb_byte *bytes;
10964                   struct dwarf2_locexpr_baton *baton;
10965                   struct value *v;
10966
10967                   if (child->tag != DW_TAG_template_type_param
10968                       && child->tag != DW_TAG_template_value_param)
10969                     continue;
10970
10971                   if (first)
10972                     {
10973                       buf.puts ("<");
10974                       first = 0;
10975                     }
10976                   else
10977                     buf.puts (", ");
10978
10979                   attr = dwarf2_attr (child, DW_AT_type, cu);
10980                   if (attr == NULL)
10981                     {
10982                       complaint (&symfile_complaints,
10983                                  _("template parameter missing DW_AT_type"));
10984                       buf.puts ("UNKNOWN_TYPE");
10985                       continue;
10986                     }
10987                   type = die_type (child, cu);
10988
10989                   if (child->tag == DW_TAG_template_type_param)
10990                     {
10991                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10992                       continue;
10993                     }
10994
10995                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10996                   if (attr == NULL)
10997                     {
10998                       complaint (&symfile_complaints,
10999                                  _("template parameter missing "
11000                                    "DW_AT_const_value"));
11001                       buf.puts ("UNKNOWN_VALUE");
11002                       continue;
11003                     }
11004
11005                   dwarf2_const_value_attr (attr, type, name,
11006                                            &cu->comp_unit_obstack, cu,
11007                                            &value, &bytes, &baton);
11008
11009                   if (TYPE_NOSIGN (type))
11010                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11011                        changed, this can use value_print instead.  */
11012                     c_printchar (value, type, &buf);
11013                   else
11014                     {
11015                       struct value_print_options opts;
11016
11017                       if (baton != NULL)
11018                         v = dwarf2_evaluate_loc_desc (type, NULL,
11019                                                       baton->data,
11020                                                       baton->size,
11021                                                       baton->per_cu);
11022                       else if (bytes != NULL)
11023                         {
11024                           v = allocate_value (type);
11025                           memcpy (value_contents_writeable (v), bytes,
11026                                   TYPE_LENGTH (type));
11027                         }
11028                       else
11029                         v = value_from_longest (type, value);
11030
11031                       /* Specify decimal so that we do not depend on
11032                          the radix.  */
11033                       get_formatted_print_options (&opts, 'd');
11034                       opts.raw = 1;
11035                       value_print (v, &buf, &opts);
11036                       release_value (v);
11037                       value_free (v);
11038                     }
11039                 }
11040
11041               die->building_fullname = 0;
11042
11043               if (!first)
11044                 {
11045                   /* Close the argument list, with a space if necessary
11046                      (nested templates).  */
11047                   if (!buf.empty () && buf.string ().back () == '>')
11048                     buf.puts (" >");
11049                   else
11050                     buf.puts (">");
11051                 }
11052             }
11053
11054           /* For C++ methods, append formal parameter type
11055              information, if PHYSNAME.  */
11056
11057           if (physname && die->tag == DW_TAG_subprogram
11058               && cu->language == language_cplus)
11059             {
11060               struct type *type = read_type_die (die, cu);
11061
11062               c_type_print_args (type, &buf, 1, cu->language,
11063                                  &type_print_raw_options);
11064
11065               if (cu->language == language_cplus)
11066                 {
11067                   /* Assume that an artificial first parameter is
11068                      "this", but do not crash if it is not.  RealView
11069                      marks unnamed (and thus unused) parameters as
11070                      artificial; there is no way to differentiate
11071                      the two cases.  */
11072                   if (TYPE_NFIELDS (type) > 0
11073                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11074                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11075                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11076                                                                         0))))
11077                     buf.puts (" const");
11078                 }
11079             }
11080
11081           const std::string &intermediate_name = buf.string ();
11082
11083           if (cu->language == language_cplus)
11084             canonical_name
11085               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11086                                           &objfile->per_bfd->storage_obstack);
11087
11088           /* If we only computed INTERMEDIATE_NAME, or if
11089              INTERMEDIATE_NAME is already canonical, then we need to
11090              copy it to the appropriate obstack.  */
11091           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11092             name = ((const char *)
11093                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11094                                    intermediate_name.c_str (),
11095                                    intermediate_name.length ()));
11096           else
11097             name = canonical_name;
11098         }
11099     }
11100
11101   return name;
11102 }
11103
11104 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11105    If scope qualifiers are appropriate they will be added.  The result
11106    will be allocated on the storage_obstack, or NULL if the DIE does
11107    not have a name.  NAME may either be from a previous call to
11108    dwarf2_name or NULL.
11109
11110    The output string will be canonicalized (if C++).  */
11111
11112 static const char *
11113 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11114 {
11115   return dwarf2_compute_name (name, die, cu, 0);
11116 }
11117
11118 /* Construct a physname for the given DIE in CU.  NAME may either be
11119    from a previous call to dwarf2_name or NULL.  The result will be
11120    allocated on the objfile_objstack or NULL if the DIE does not have a
11121    name.
11122
11123    The output string will be canonicalized (if C++).  */
11124
11125 static const char *
11126 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11127 {
11128   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11129   const char *retval, *mangled = NULL, *canon = NULL;
11130   int need_copy = 1;
11131
11132   /* In this case dwarf2_compute_name is just a shortcut not building anything
11133      on its own.  */
11134   if (!die_needs_namespace (die, cu))
11135     return dwarf2_compute_name (name, die, cu, 1);
11136
11137   mangled = dw2_linkage_name (die, cu);
11138
11139   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11140      See https://github.com/rust-lang/rust/issues/32925.  */
11141   if (cu->language == language_rust && mangled != NULL
11142       && strchr (mangled, '{') != NULL)
11143     mangled = NULL;
11144
11145   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11146      has computed.  */
11147   gdb::unique_xmalloc_ptr<char> demangled;
11148   if (mangled != NULL)
11149     {
11150
11151       if (cu->language == language_go)
11152         {
11153           /* This is a lie, but we already lie to the caller new_symbol.
11154              new_symbol assumes we return the mangled name.
11155              This just undoes that lie until things are cleaned up.  */
11156         }
11157       else
11158         {
11159           /* Use DMGL_RET_DROP for C++ template functions to suppress
11160              their return type.  It is easier for GDB users to search
11161              for such functions as `name(params)' than `long name(params)'.
11162              In such case the minimal symbol names do not match the full
11163              symbol names but for template functions there is never a need
11164              to look up their definition from their declaration so
11165              the only disadvantage remains the minimal symbol variant
11166              `long name(params)' does not have the proper inferior type.  */
11167           demangled.reset (gdb_demangle (mangled,
11168                                          (DMGL_PARAMS | DMGL_ANSI
11169                                           | DMGL_RET_DROP)));
11170         }
11171       if (demangled)
11172         canon = demangled.get ();
11173       else
11174         {
11175           canon = mangled;
11176           need_copy = 0;
11177         }
11178     }
11179
11180   if (canon == NULL || check_physname)
11181     {
11182       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11183
11184       if (canon != NULL && strcmp (physname, canon) != 0)
11185         {
11186           /* It may not mean a bug in GDB.  The compiler could also
11187              compute DW_AT_linkage_name incorrectly.  But in such case
11188              GDB would need to be bug-to-bug compatible.  */
11189
11190           complaint (&symfile_complaints,
11191                      _("Computed physname <%s> does not match demangled <%s> "
11192                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11193                      physname, canon, mangled, to_underlying (die->sect_off),
11194                      objfile_name (objfile));
11195
11196           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11197              is available here - over computed PHYSNAME.  It is safer
11198              against both buggy GDB and buggy compilers.  */
11199
11200           retval = canon;
11201         }
11202       else
11203         {
11204           retval = physname;
11205           need_copy = 0;
11206         }
11207     }
11208   else
11209     retval = canon;
11210
11211   if (need_copy)
11212     retval = ((const char *)
11213               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11214                              retval, strlen (retval)));
11215
11216   return retval;
11217 }
11218
11219 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11220    a new symbol for it.
11221
11222    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11223
11224 static int
11225 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11226 {
11227   struct attribute *attr;
11228
11229   /* If the die does not have a name, this is not a namespace
11230      alias.  */
11231   attr = dwarf2_attr (die, DW_AT_name, cu);
11232   if (attr != NULL)
11233     {
11234       int num;
11235       struct die_info *d = die;
11236       struct dwarf2_cu *imported_cu = cu;
11237
11238       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11239          keep inspecting DIEs until we hit the underlying import.  */
11240 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11241       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11242         {
11243           attr = dwarf2_attr (d, DW_AT_import, cu);
11244           if (attr == NULL)
11245             break;
11246
11247           d = follow_die_ref (d, attr, &imported_cu);
11248           if (d->tag != DW_TAG_imported_declaration)
11249             break;
11250         }
11251
11252       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11253         {
11254           complaint (&symfile_complaints,
11255                      _("DIE at 0x%x has too many recursively imported "
11256                        "declarations"), to_underlying (d->sect_off));
11257           return 0;
11258         }
11259
11260       if (attr != NULL)
11261         {
11262           struct type *type;
11263           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11264
11265           type = get_die_type_at_offset (sect_off, cu->per_cu);
11266           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11267             {
11268               /* This declaration is a global namespace alias.  Add
11269                  a symbol for it whose type is the aliased namespace.  */
11270               new_symbol (die, type, cu);
11271               return 1;
11272             }
11273         }
11274     }
11275
11276   return 0;
11277 }
11278
11279 /* Return the using directives repository (global or local?) to use in the
11280    current context for LANGUAGE.
11281
11282    For Ada, imported declarations can materialize renamings, which *may* be
11283    global.  However it is impossible (for now?) in DWARF to distinguish
11284    "external" imported declarations and "static" ones.  As all imported
11285    declarations seem to be static in all other languages, make them all CU-wide
11286    global only in Ada.  */
11287
11288 static struct using_direct **
11289 using_directives (enum language language)
11290 {
11291   if (language == language_ada && context_stack_depth == 0)
11292     return &global_using_directives;
11293   else
11294     return &local_using_directives;
11295 }
11296
11297 /* Read the import statement specified by the given die and record it.  */
11298
11299 static void
11300 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11301 {
11302   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11303   struct attribute *import_attr;
11304   struct die_info *imported_die, *child_die;
11305   struct dwarf2_cu *imported_cu;
11306   const char *imported_name;
11307   const char *imported_name_prefix;
11308   const char *canonical_name;
11309   const char *import_alias;
11310   const char *imported_declaration = NULL;
11311   const char *import_prefix;
11312   std::vector<const char *> excludes;
11313
11314   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11315   if (import_attr == NULL)
11316     {
11317       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11318                  dwarf_tag_name (die->tag));
11319       return;
11320     }
11321
11322   imported_cu = cu;
11323   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11324   imported_name = dwarf2_name (imported_die, imported_cu);
11325   if (imported_name == NULL)
11326     {
11327       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11328
11329         The import in the following code:
11330         namespace A
11331           {
11332             typedef int B;
11333           }
11334
11335         int main ()
11336           {
11337             using A::B;
11338             B b;
11339             return b;
11340           }
11341
11342         ...
11343          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11344             <52>   DW_AT_decl_file   : 1
11345             <53>   DW_AT_decl_line   : 6
11346             <54>   DW_AT_import      : <0x75>
11347          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11348             <59>   DW_AT_name        : B
11349             <5b>   DW_AT_decl_file   : 1
11350             <5c>   DW_AT_decl_line   : 2
11351             <5d>   DW_AT_type        : <0x6e>
11352         ...
11353          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11354             <76>   DW_AT_byte_size   : 4
11355             <77>   DW_AT_encoding    : 5        (signed)
11356
11357         imports the wrong die ( 0x75 instead of 0x58 ).
11358         This case will be ignored until the gcc bug is fixed.  */
11359       return;
11360     }
11361
11362   /* Figure out the local name after import.  */
11363   import_alias = dwarf2_name (die, cu);
11364
11365   /* Figure out where the statement is being imported to.  */
11366   import_prefix = determine_prefix (die, cu);
11367
11368   /* Figure out what the scope of the imported die is and prepend it
11369      to the name of the imported die.  */
11370   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11371
11372   if (imported_die->tag != DW_TAG_namespace
11373       && imported_die->tag != DW_TAG_module)
11374     {
11375       imported_declaration = imported_name;
11376       canonical_name = imported_name_prefix;
11377     }
11378   else if (strlen (imported_name_prefix) > 0)
11379     canonical_name = obconcat (&objfile->objfile_obstack,
11380                                imported_name_prefix,
11381                                (cu->language == language_d ? "." : "::"),
11382                                imported_name, (char *) NULL);
11383   else
11384     canonical_name = imported_name;
11385
11386   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11387     for (child_die = die->child; child_die && child_die->tag;
11388          child_die = sibling_die (child_die))
11389       {
11390         /* DWARF-4: A Fortran use statement with a “rename list” may be
11391            represented by an imported module entry with an import attribute
11392            referring to the module and owned entries corresponding to those
11393            entities that are renamed as part of being imported.  */
11394
11395         if (child_die->tag != DW_TAG_imported_declaration)
11396           {
11397             complaint (&symfile_complaints,
11398                        _("child DW_TAG_imported_declaration expected "
11399                          "- DIE at 0x%x [in module %s]"),
11400                        to_underlying (child_die->sect_off), objfile_name (objfile));
11401             continue;
11402           }
11403
11404         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11405         if (import_attr == NULL)
11406           {
11407             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11408                        dwarf_tag_name (child_die->tag));
11409             continue;
11410           }
11411
11412         imported_cu = cu;
11413         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11414                                               &imported_cu);
11415         imported_name = dwarf2_name (imported_die, imported_cu);
11416         if (imported_name == NULL)
11417           {
11418             complaint (&symfile_complaints,
11419                        _("child DW_TAG_imported_declaration has unknown "
11420                          "imported name - DIE at 0x%x [in module %s]"),
11421                        to_underlying (child_die->sect_off), objfile_name (objfile));
11422             continue;
11423           }
11424
11425         excludes.push_back (imported_name);
11426
11427         process_die (child_die, cu);
11428       }
11429
11430   add_using_directive (using_directives (cu->language),
11431                        import_prefix,
11432                        canonical_name,
11433                        import_alias,
11434                        imported_declaration,
11435                        excludes,
11436                        0,
11437                        &objfile->objfile_obstack);
11438 }
11439
11440 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11441    types, but gives them a size of zero.  Starting with version 14,
11442    ICC is compatible with GCC.  */
11443
11444 static int
11445 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11446 {
11447   if (!cu->checked_producer)
11448     check_producer (cu);
11449
11450   return cu->producer_is_icc_lt_14;
11451 }
11452
11453 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11454    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11455    this, it was first present in GCC release 4.3.0.  */
11456
11457 static int
11458 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11459 {
11460   if (!cu->checked_producer)
11461     check_producer (cu);
11462
11463   return cu->producer_is_gcc_lt_4_3;
11464 }
11465
11466 static file_and_directory
11467 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11468 {
11469   file_and_directory res;
11470
11471   /* Find the filename.  Do not use dwarf2_name here, since the filename
11472      is not a source language identifier.  */
11473   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11474   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11475
11476   if (res.comp_dir == NULL
11477       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11478       && IS_ABSOLUTE_PATH (res.name))
11479     {
11480       res.comp_dir_storage = ldirname (res.name);
11481       if (!res.comp_dir_storage.empty ())
11482         res.comp_dir = res.comp_dir_storage.c_str ();
11483     }
11484   if (res.comp_dir != NULL)
11485     {
11486       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11487          directory, get rid of it.  */
11488       const char *cp = strchr (res.comp_dir, ':');
11489
11490       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11491         res.comp_dir = cp + 1;
11492     }
11493
11494   if (res.name == NULL)
11495     res.name = "<unknown>";
11496
11497   return res;
11498 }
11499
11500 /* Handle DW_AT_stmt_list for a compilation unit.
11501    DIE is the DW_TAG_compile_unit die for CU.
11502    COMP_DIR is the compilation directory.  LOWPC is passed to
11503    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11504
11505 static void
11506 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11507                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11508 {
11509   struct dwarf2_per_objfile *dwarf2_per_objfile
11510     = cu->per_cu->dwarf2_per_objfile;
11511   struct objfile *objfile = dwarf2_per_objfile->objfile;
11512   struct attribute *attr;
11513   struct line_header line_header_local;
11514   hashval_t line_header_local_hash;
11515   void **slot;
11516   int decode_mapping;
11517
11518   gdb_assert (! cu->per_cu->is_debug_types);
11519
11520   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11521   if (attr == NULL)
11522     return;
11523
11524   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11525
11526   /* The line header hash table is only created if needed (it exists to
11527      prevent redundant reading of the line table for partial_units).
11528      If we're given a partial_unit, we'll need it.  If we're given a
11529      compile_unit, then use the line header hash table if it's already
11530      created, but don't create one just yet.  */
11531
11532   if (dwarf2_per_objfile->line_header_hash == NULL
11533       && die->tag == DW_TAG_partial_unit)
11534     {
11535       dwarf2_per_objfile->line_header_hash
11536         = htab_create_alloc_ex (127, line_header_hash_voidp,
11537                                 line_header_eq_voidp,
11538                                 free_line_header_voidp,
11539                                 &objfile->objfile_obstack,
11540                                 hashtab_obstack_allocate,
11541                                 dummy_obstack_deallocate);
11542     }
11543
11544   line_header_local.sect_off = line_offset;
11545   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11546   line_header_local_hash = line_header_hash (&line_header_local);
11547   if (dwarf2_per_objfile->line_header_hash != NULL)
11548     {
11549       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11550                                        &line_header_local,
11551                                        line_header_local_hash, NO_INSERT);
11552
11553       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11554          is not present in *SLOT (since if there is something in *SLOT then
11555          it will be for a partial_unit).  */
11556       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11557         {
11558           gdb_assert (*slot != NULL);
11559           cu->line_header = (struct line_header *) *slot;
11560           return;
11561         }
11562     }
11563
11564   /* dwarf_decode_line_header does not yet provide sufficient information.
11565      We always have to call also dwarf_decode_lines for it.  */
11566   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11567   if (lh == NULL)
11568     return;
11569
11570   cu->line_header = lh.release ();
11571   cu->line_header_die_owner = die;
11572
11573   if (dwarf2_per_objfile->line_header_hash == NULL)
11574     slot = NULL;
11575   else
11576     {
11577       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11578                                        &line_header_local,
11579                                        line_header_local_hash, INSERT);
11580       gdb_assert (slot != NULL);
11581     }
11582   if (slot != NULL && *slot == NULL)
11583     {
11584       /* This newly decoded line number information unit will be owned
11585          by line_header_hash hash table.  */
11586       *slot = cu->line_header;
11587       cu->line_header_die_owner = NULL;
11588     }
11589   else
11590     {
11591       /* We cannot free any current entry in (*slot) as that struct line_header
11592          may be already used by multiple CUs.  Create only temporary decoded
11593          line_header for this CU - it may happen at most once for each line
11594          number information unit.  And if we're not using line_header_hash
11595          then this is what we want as well.  */
11596       gdb_assert (die->tag != DW_TAG_partial_unit);
11597     }
11598   decode_mapping = (die->tag != DW_TAG_partial_unit);
11599   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11600                       decode_mapping);
11601
11602 }
11603
11604 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11605
11606 static void
11607 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11608 {
11609   struct dwarf2_per_objfile *dwarf2_per_objfile
11610     = cu->per_cu->dwarf2_per_objfile;
11611   struct objfile *objfile = dwarf2_per_objfile->objfile;
11612   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11613   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11614   CORE_ADDR highpc = ((CORE_ADDR) 0);
11615   struct attribute *attr;
11616   struct die_info *child_die;
11617   CORE_ADDR baseaddr;
11618
11619   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11620
11621   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11622
11623   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11624      from finish_block.  */
11625   if (lowpc == ((CORE_ADDR) -1))
11626     lowpc = highpc;
11627   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11628
11629   file_and_directory fnd = find_file_and_directory (die, cu);
11630
11631   prepare_one_comp_unit (cu, die, cu->language);
11632
11633   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11634      standardised yet.  As a workaround for the language detection we fall
11635      back to the DW_AT_producer string.  */
11636   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11637     cu->language = language_opencl;
11638
11639   /* Similar hack for Go.  */
11640   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11641     set_cu_language (DW_LANG_Go, cu);
11642
11643   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11644
11645   /* Decode line number information if present.  We do this before
11646      processing child DIEs, so that the line header table is available
11647      for DW_AT_decl_file.  */
11648   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11649
11650   /* Process all dies in compilation unit.  */
11651   if (die->child != NULL)
11652     {
11653       child_die = die->child;
11654       while (child_die && child_die->tag)
11655         {
11656           process_die (child_die, cu);
11657           child_die = sibling_die (child_die);
11658         }
11659     }
11660
11661   /* Decode macro information, if present.  Dwarf 2 macro information
11662      refers to information in the line number info statement program
11663      header, so we can only read it if we've read the header
11664      successfully.  */
11665   attr = dwarf2_attr (die, DW_AT_macros, cu);
11666   if (attr == NULL)
11667     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11668   if (attr && cu->line_header)
11669     {
11670       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11671         complaint (&symfile_complaints,
11672                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11673
11674       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11675     }
11676   else
11677     {
11678       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11679       if (attr && cu->line_header)
11680         {
11681           unsigned int macro_offset = DW_UNSND (attr);
11682
11683           dwarf_decode_macros (cu, macro_offset, 0);
11684         }
11685     }
11686 }
11687
11688 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11689    Create the set of symtabs used by this TU, or if this TU is sharing
11690    symtabs with another TU and the symtabs have already been created
11691    then restore those symtabs in the line header.
11692    We don't need the pc/line-number mapping for type units.  */
11693
11694 static void
11695 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11696 {
11697   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11698   struct type_unit_group *tu_group;
11699   int first_time;
11700   struct attribute *attr;
11701   unsigned int i;
11702   struct signatured_type *sig_type;
11703
11704   gdb_assert (per_cu->is_debug_types);
11705   sig_type = (struct signatured_type *) per_cu;
11706
11707   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11708
11709   /* If we're using .gdb_index (includes -readnow) then
11710      per_cu->type_unit_group may not have been set up yet.  */
11711   if (sig_type->type_unit_group == NULL)
11712     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11713   tu_group = sig_type->type_unit_group;
11714
11715   /* If we've already processed this stmt_list there's no real need to
11716      do it again, we could fake it and just recreate the part we need
11717      (file name,index -> symtab mapping).  If data shows this optimization
11718      is useful we can do it then.  */
11719   first_time = tu_group->compunit_symtab == NULL;
11720
11721   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11722      debug info.  */
11723   line_header_up lh;
11724   if (attr != NULL)
11725     {
11726       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11727       lh = dwarf_decode_line_header (line_offset, cu);
11728     }
11729   if (lh == NULL)
11730     {
11731       if (first_time)
11732         dwarf2_start_symtab (cu, "", NULL, 0);
11733       else
11734         {
11735           gdb_assert (tu_group->symtabs == NULL);
11736           restart_symtab (tu_group->compunit_symtab, "", 0);
11737         }
11738       return;
11739     }
11740
11741   cu->line_header = lh.release ();
11742   cu->line_header_die_owner = die;
11743
11744   if (first_time)
11745     {
11746       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11747
11748       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11749          still initializing it, and our caller (a few levels up)
11750          process_full_type_unit still needs to know if this is the first
11751          time.  */
11752
11753       tu_group->num_symtabs = cu->line_header->file_names.size ();
11754       tu_group->symtabs = XNEWVEC (struct symtab *,
11755                                    cu->line_header->file_names.size ());
11756
11757       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11758         {
11759           file_entry &fe = cu->line_header->file_names[i];
11760
11761           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11762
11763           if (current_subfile->symtab == NULL)
11764             {
11765               /* NOTE: start_subfile will recognize when it's been
11766                  passed a file it has already seen.  So we can't
11767                  assume there's a simple mapping from
11768                  cu->line_header->file_names to subfiles, plus
11769                  cu->line_header->file_names may contain dups.  */
11770               current_subfile->symtab
11771                 = allocate_symtab (cust, current_subfile->name);
11772             }
11773
11774           fe.symtab = current_subfile->symtab;
11775           tu_group->symtabs[i] = fe.symtab;
11776         }
11777     }
11778   else
11779     {
11780       restart_symtab (tu_group->compunit_symtab, "", 0);
11781
11782       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11783         {
11784           file_entry &fe = cu->line_header->file_names[i];
11785
11786           fe.symtab = tu_group->symtabs[i];
11787         }
11788     }
11789
11790   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11791      so they don't have a "real" (so to speak) symtab anyway.
11792      There is later code that will assign the main symtab to all symbols
11793      that don't have one.  We need to handle the case of a symbol with a
11794      missing symtab (DW_AT_decl_file) anyway.  */
11795 }
11796
11797 /* Process DW_TAG_type_unit.
11798    For TUs we want to skip the first top level sibling if it's not the
11799    actual type being defined by this TU.  In this case the first top
11800    level sibling is there to provide context only.  */
11801
11802 static void
11803 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11804 {
11805   struct die_info *child_die;
11806
11807   prepare_one_comp_unit (cu, die, language_minimal);
11808
11809   /* Initialize (or reinitialize) the machinery for building symtabs.
11810      We do this before processing child DIEs, so that the line header table
11811      is available for DW_AT_decl_file.  */
11812   setup_type_unit_groups (die, cu);
11813
11814   if (die->child != NULL)
11815     {
11816       child_die = die->child;
11817       while (child_die && child_die->tag)
11818         {
11819           process_die (child_die, cu);
11820           child_die = sibling_die (child_die);
11821         }
11822     }
11823 }
11824 \f
11825 /* DWO/DWP files.
11826
11827    http://gcc.gnu.org/wiki/DebugFission
11828    http://gcc.gnu.org/wiki/DebugFissionDWP
11829
11830    To simplify handling of both DWO files ("object" files with the DWARF info)
11831    and DWP files (a file with the DWOs packaged up into one file), we treat
11832    DWP files as having a collection of virtual DWO files.  */
11833
11834 static hashval_t
11835 hash_dwo_file (const void *item)
11836 {
11837   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11838   hashval_t hash;
11839
11840   hash = htab_hash_string (dwo_file->dwo_name);
11841   if (dwo_file->comp_dir != NULL)
11842     hash += htab_hash_string (dwo_file->comp_dir);
11843   return hash;
11844 }
11845
11846 static int
11847 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11848 {
11849   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11850   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11851
11852   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11853     return 0;
11854   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11855     return lhs->comp_dir == rhs->comp_dir;
11856   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11857 }
11858
11859 /* Allocate a hash table for DWO files.  */
11860
11861 static htab_t
11862 allocate_dwo_file_hash_table (struct objfile *objfile)
11863 {
11864   return htab_create_alloc_ex (41,
11865                                hash_dwo_file,
11866                                eq_dwo_file,
11867                                NULL,
11868                                &objfile->objfile_obstack,
11869                                hashtab_obstack_allocate,
11870                                dummy_obstack_deallocate);
11871 }
11872
11873 /* Lookup DWO file DWO_NAME.  */
11874
11875 static void **
11876 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11877                       const char *dwo_name,
11878                       const char *comp_dir)
11879 {
11880   struct dwo_file find_entry;
11881   void **slot;
11882
11883   if (dwarf2_per_objfile->dwo_files == NULL)
11884     dwarf2_per_objfile->dwo_files
11885       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11886
11887   memset (&find_entry, 0, sizeof (find_entry));
11888   find_entry.dwo_name = dwo_name;
11889   find_entry.comp_dir = comp_dir;
11890   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11891
11892   return slot;
11893 }
11894
11895 static hashval_t
11896 hash_dwo_unit (const void *item)
11897 {
11898   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11899
11900   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11901   return dwo_unit->signature;
11902 }
11903
11904 static int
11905 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11906 {
11907   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11908   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11909
11910   /* The signature is assumed to be unique within the DWO file.
11911      So while object file CU dwo_id's always have the value zero,
11912      that's OK, assuming each object file DWO file has only one CU,
11913      and that's the rule for now.  */
11914   return lhs->signature == rhs->signature;
11915 }
11916
11917 /* Allocate a hash table for DWO CUs,TUs.
11918    There is one of these tables for each of CUs,TUs for each DWO file.  */
11919
11920 static htab_t
11921 allocate_dwo_unit_table (struct objfile *objfile)
11922 {
11923   /* Start out with a pretty small number.
11924      Generally DWO files contain only one CU and maybe some TUs.  */
11925   return htab_create_alloc_ex (3,
11926                                hash_dwo_unit,
11927                                eq_dwo_unit,
11928                                NULL,
11929                                &objfile->objfile_obstack,
11930                                hashtab_obstack_allocate,
11931                                dummy_obstack_deallocate);
11932 }
11933
11934 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11935
11936 struct create_dwo_cu_data
11937 {
11938   struct dwo_file *dwo_file;
11939   struct dwo_unit dwo_unit;
11940 };
11941
11942 /* die_reader_func for create_dwo_cu.  */
11943
11944 static void
11945 create_dwo_cu_reader (const struct die_reader_specs *reader,
11946                       const gdb_byte *info_ptr,
11947                       struct die_info *comp_unit_die,
11948                       int has_children,
11949                       void *datap)
11950 {
11951   struct dwarf2_cu *cu = reader->cu;
11952   sect_offset sect_off = cu->per_cu->sect_off;
11953   struct dwarf2_section_info *section = cu->per_cu->section;
11954   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11955   struct dwo_file *dwo_file = data->dwo_file;
11956   struct dwo_unit *dwo_unit = &data->dwo_unit;
11957   struct attribute *attr;
11958
11959   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11960   if (attr == NULL)
11961     {
11962       complaint (&symfile_complaints,
11963                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11964                    " its dwo_id [in module %s]"),
11965                  to_underlying (sect_off), dwo_file->dwo_name);
11966       return;
11967     }
11968
11969   dwo_unit->dwo_file = dwo_file;
11970   dwo_unit->signature = DW_UNSND (attr);
11971   dwo_unit->section = section;
11972   dwo_unit->sect_off = sect_off;
11973   dwo_unit->length = cu->per_cu->length;
11974
11975   if (dwarf_read_debug)
11976     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11977                         to_underlying (sect_off),
11978                         hex_string (dwo_unit->signature));
11979 }
11980
11981 /* Create the dwo_units for the CUs in a DWO_FILE.
11982    Note: This function processes DWO files only, not DWP files.  */
11983
11984 static void
11985 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11986                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11987                        htab_t &cus_htab)
11988 {
11989   struct objfile *objfile = dwarf2_per_objfile->objfile;
11990   const gdb_byte *info_ptr, *end_ptr;
11991
11992   dwarf2_read_section (objfile, &section);
11993   info_ptr = section.buffer;
11994
11995   if (info_ptr == NULL)
11996     return;
11997
11998   if (dwarf_read_debug)
11999     {
12000       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12001                           get_section_name (&section),
12002                           get_section_file_name (&section));
12003     }
12004
12005   end_ptr = info_ptr + section.size;
12006   while (info_ptr < end_ptr)
12007     {
12008       struct dwarf2_per_cu_data per_cu;
12009       struct create_dwo_cu_data create_dwo_cu_data;
12010       struct dwo_unit *dwo_unit;
12011       void **slot;
12012       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12013
12014       memset (&create_dwo_cu_data.dwo_unit, 0,
12015               sizeof (create_dwo_cu_data.dwo_unit));
12016       memset (&per_cu, 0, sizeof (per_cu));
12017       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12018       per_cu.is_debug_types = 0;
12019       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12020       per_cu.section = &section;
12021       create_dwo_cu_data.dwo_file = &dwo_file;
12022
12023       init_cutu_and_read_dies_no_follow (
12024           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12025       info_ptr += per_cu.length;
12026
12027       // If the unit could not be parsed, skip it.
12028       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12029         continue;
12030
12031       if (cus_htab == NULL)
12032         cus_htab = allocate_dwo_unit_table (objfile);
12033
12034       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12035       *dwo_unit = create_dwo_cu_data.dwo_unit;
12036       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12037       gdb_assert (slot != NULL);
12038       if (*slot != NULL)
12039         {
12040           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12041           sect_offset dup_sect_off = dup_cu->sect_off;
12042
12043           complaint (&symfile_complaints,
12044                      _("debug cu entry at offset 0x%x is duplicate to"
12045                        " the entry at offset 0x%x, signature %s"),
12046                      to_underlying (sect_off), to_underlying (dup_sect_off),
12047                      hex_string (dwo_unit->signature));
12048         }
12049       *slot = (void *)dwo_unit;
12050     }
12051 }
12052
12053 /* DWP file .debug_{cu,tu}_index section format:
12054    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12055
12056    DWP Version 1:
12057
12058    Both index sections have the same format, and serve to map a 64-bit
12059    signature to a set of section numbers.  Each section begins with a header,
12060    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12061    indexes, and a pool of 32-bit section numbers.  The index sections will be
12062    aligned at 8-byte boundaries in the file.
12063
12064    The index section header consists of:
12065
12066     V, 32 bit version number
12067     -, 32 bits unused
12068     N, 32 bit number of compilation units or type units in the index
12069     M, 32 bit number of slots in the hash table
12070
12071    Numbers are recorded using the byte order of the application binary.
12072
12073    The hash table begins at offset 16 in the section, and consists of an array
12074    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12075    order of the application binary).  Unused slots in the hash table are 0.
12076    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12077
12078    The parallel table begins immediately after the hash table
12079    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12080    array of 32-bit indexes (using the byte order of the application binary),
12081    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12082    table contains a 32-bit index into the pool of section numbers.  For unused
12083    hash table slots, the corresponding entry in the parallel table will be 0.
12084
12085    The pool of section numbers begins immediately following the hash table
12086    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12087    section numbers consists of an array of 32-bit words (using the byte order
12088    of the application binary).  Each item in the array is indexed starting
12089    from 0.  The hash table entry provides the index of the first section
12090    number in the set.  Additional section numbers in the set follow, and the
12091    set is terminated by a 0 entry (section number 0 is not used in ELF).
12092
12093    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12094    section must be the first entry in the set, and the .debug_abbrev.dwo must
12095    be the second entry. Other members of the set may follow in any order.
12096
12097    ---
12098
12099    DWP Version 2:
12100
12101    DWP Version 2 combines all the .debug_info, etc. sections into one,
12102    and the entries in the index tables are now offsets into these sections.
12103    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12104    section.
12105
12106    Index Section Contents:
12107     Header
12108     Hash Table of Signatures   dwp_hash_table.hash_table
12109     Parallel Table of Indices  dwp_hash_table.unit_table
12110     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12111     Table of Section Sizes     dwp_hash_table.v2.sizes
12112
12113    The index section header consists of:
12114
12115     V, 32 bit version number
12116     L, 32 bit number of columns in the table of section offsets
12117     N, 32 bit number of compilation units or type units in the index
12118     M, 32 bit number of slots in the hash table
12119
12120    Numbers are recorded using the byte order of the application binary.
12121
12122    The hash table has the same format as version 1.
12123    The parallel table of indices has the same format as version 1,
12124    except that the entries are origin-1 indices into the table of sections
12125    offsets and the table of section sizes.
12126
12127    The table of offsets begins immediately following the parallel table
12128    (at offset 16 + 12 * M from the beginning of the section).  The table is
12129    a two-dimensional array of 32-bit words (using the byte order of the
12130    application binary), with L columns and N+1 rows, in row-major order.
12131    Each row in the array is indexed starting from 0.  The first row provides
12132    a key to the remaining rows: each column in this row provides an identifier
12133    for a debug section, and the offsets in the same column of subsequent rows
12134    refer to that section.  The section identifiers are:
12135
12136     DW_SECT_INFO         1  .debug_info.dwo
12137     DW_SECT_TYPES        2  .debug_types.dwo
12138     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12139     DW_SECT_LINE         4  .debug_line.dwo
12140     DW_SECT_LOC          5  .debug_loc.dwo
12141     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12142     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12143     DW_SECT_MACRO        8  .debug_macro.dwo
12144
12145    The offsets provided by the CU and TU index sections are the base offsets
12146    for the contributions made by each CU or TU to the corresponding section
12147    in the package file.  Each CU and TU header contains an abbrev_offset
12148    field, used to find the abbreviations table for that CU or TU within the
12149    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12150    be interpreted as relative to the base offset given in the index section.
12151    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12152    should be interpreted as relative to the base offset for .debug_line.dwo,
12153    and offsets into other debug sections obtained from DWARF attributes should
12154    also be interpreted as relative to the corresponding base offset.
12155
12156    The table of sizes begins immediately following the table of offsets.
12157    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12158    with L columns and N rows, in row-major order.  Each row in the array is
12159    indexed starting from 1 (row 0 is shared by the two tables).
12160
12161    ---
12162
12163    Hash table lookup is handled the same in version 1 and 2:
12164
12165    We assume that N and M will not exceed 2^32 - 1.
12166    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12167
12168    Given a 64-bit compilation unit signature or a type signature S, an entry
12169    in the hash table is located as follows:
12170
12171    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12172       the low-order k bits all set to 1.
12173
12174    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12175
12176    3) If the hash table entry at index H matches the signature, use that
12177       entry.  If the hash table entry at index H is unused (all zeroes),
12178       terminate the search: the signature is not present in the table.
12179
12180    4) Let H = (H + H') modulo M. Repeat at Step 3.
12181
12182    Because M > N and H' and M are relatively prime, the search is guaranteed
12183    to stop at an unused slot or find the match.  */
12184
12185 /* Create a hash table to map DWO IDs to their CU/TU entry in
12186    .debug_{info,types}.dwo in DWP_FILE.
12187    Returns NULL if there isn't one.
12188    Note: This function processes DWP files only, not DWO files.  */
12189
12190 static struct dwp_hash_table *
12191 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12192                        struct dwp_file *dwp_file, int is_debug_types)
12193 {
12194   struct objfile *objfile = dwarf2_per_objfile->objfile;
12195   bfd *dbfd = dwp_file->dbfd;
12196   const gdb_byte *index_ptr, *index_end;
12197   struct dwarf2_section_info *index;
12198   uint32_t version, nr_columns, nr_units, nr_slots;
12199   struct dwp_hash_table *htab;
12200
12201   if (is_debug_types)
12202     index = &dwp_file->sections.tu_index;
12203   else
12204     index = &dwp_file->sections.cu_index;
12205
12206   if (dwarf2_section_empty_p (index))
12207     return NULL;
12208   dwarf2_read_section (objfile, index);
12209
12210   index_ptr = index->buffer;
12211   index_end = index_ptr + index->size;
12212
12213   version = read_4_bytes (dbfd, index_ptr);
12214   index_ptr += 4;
12215   if (version == 2)
12216     nr_columns = read_4_bytes (dbfd, index_ptr);
12217   else
12218     nr_columns = 0;
12219   index_ptr += 4;
12220   nr_units = read_4_bytes (dbfd, index_ptr);
12221   index_ptr += 4;
12222   nr_slots = read_4_bytes (dbfd, index_ptr);
12223   index_ptr += 4;
12224
12225   if (version != 1 && version != 2)
12226     {
12227       error (_("Dwarf Error: unsupported DWP file version (%s)"
12228                " [in module %s]"),
12229              pulongest (version), dwp_file->name);
12230     }
12231   if (nr_slots != (nr_slots & -nr_slots))
12232     {
12233       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12234                " is not power of 2 [in module %s]"),
12235              pulongest (nr_slots), dwp_file->name);
12236     }
12237
12238   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12239   htab->version = version;
12240   htab->nr_columns = nr_columns;
12241   htab->nr_units = nr_units;
12242   htab->nr_slots = nr_slots;
12243   htab->hash_table = index_ptr;
12244   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12245
12246   /* Exit early if the table is empty.  */
12247   if (nr_slots == 0 || nr_units == 0
12248       || (version == 2 && nr_columns == 0))
12249     {
12250       /* All must be zero.  */
12251       if (nr_slots != 0 || nr_units != 0
12252           || (version == 2 && nr_columns != 0))
12253         {
12254           complaint (&symfile_complaints,
12255                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12256                        " all zero [in modules %s]"),
12257                      dwp_file->name);
12258         }
12259       return htab;
12260     }
12261
12262   if (version == 1)
12263     {
12264       htab->section_pool.v1.indices =
12265         htab->unit_table + sizeof (uint32_t) * nr_slots;
12266       /* It's harder to decide whether the section is too small in v1.
12267          V1 is deprecated anyway so we punt.  */
12268     }
12269   else
12270     {
12271       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12272       int *ids = htab->section_pool.v2.section_ids;
12273       /* Reverse map for error checking.  */
12274       int ids_seen[DW_SECT_MAX + 1];
12275       int i;
12276
12277       if (nr_columns < 2)
12278         {
12279           error (_("Dwarf Error: bad DWP hash table, too few columns"
12280                    " in section table [in module %s]"),
12281                  dwp_file->name);
12282         }
12283       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12284         {
12285           error (_("Dwarf Error: bad DWP hash table, too many columns"
12286                    " in section table [in module %s]"),
12287                  dwp_file->name);
12288         }
12289       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12290       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12291       for (i = 0; i < nr_columns; ++i)
12292         {
12293           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12294
12295           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12296             {
12297               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12298                        " in section table [in module %s]"),
12299                      id, dwp_file->name);
12300             }
12301           if (ids_seen[id] != -1)
12302             {
12303               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12304                        " id %d in section table [in module %s]"),
12305                      id, dwp_file->name);
12306             }
12307           ids_seen[id] = i;
12308           ids[i] = id;
12309         }
12310       /* Must have exactly one info or types section.  */
12311       if (((ids_seen[DW_SECT_INFO] != -1)
12312            + (ids_seen[DW_SECT_TYPES] != -1))
12313           != 1)
12314         {
12315           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12316                    " DWO info/types section [in module %s]"),
12317                  dwp_file->name);
12318         }
12319       /* Must have an abbrev section.  */
12320       if (ids_seen[DW_SECT_ABBREV] == -1)
12321         {
12322           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12323                    " section [in module %s]"),
12324                  dwp_file->name);
12325         }
12326       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12327       htab->section_pool.v2.sizes =
12328         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12329                                          * nr_units * nr_columns);
12330       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12331                                           * nr_units * nr_columns))
12332           > index_end)
12333         {
12334           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12335                    " [in module %s]"),
12336                  dwp_file->name);
12337         }
12338     }
12339
12340   return htab;
12341 }
12342
12343 /* Update SECTIONS with the data from SECTP.
12344
12345    This function is like the other "locate" section routines that are
12346    passed to bfd_map_over_sections, but in this context the sections to
12347    read comes from the DWP V1 hash table, not the full ELF section table.
12348
12349    The result is non-zero for success, or zero if an error was found.  */
12350
12351 static int
12352 locate_v1_virtual_dwo_sections (asection *sectp,
12353                                 struct virtual_v1_dwo_sections *sections)
12354 {
12355   const struct dwop_section_names *names = &dwop_section_names;
12356
12357   if (section_is_p (sectp->name, &names->abbrev_dwo))
12358     {
12359       /* There can be only one.  */
12360       if (sections->abbrev.s.section != NULL)
12361         return 0;
12362       sections->abbrev.s.section = sectp;
12363       sections->abbrev.size = bfd_get_section_size (sectp);
12364     }
12365   else if (section_is_p (sectp->name, &names->info_dwo)
12366            || section_is_p (sectp->name, &names->types_dwo))
12367     {
12368       /* There can be only one.  */
12369       if (sections->info_or_types.s.section != NULL)
12370         return 0;
12371       sections->info_or_types.s.section = sectp;
12372       sections->info_or_types.size = bfd_get_section_size (sectp);
12373     }
12374   else if (section_is_p (sectp->name, &names->line_dwo))
12375     {
12376       /* There can be only one.  */
12377       if (sections->line.s.section != NULL)
12378         return 0;
12379       sections->line.s.section = sectp;
12380       sections->line.size = bfd_get_section_size (sectp);
12381     }
12382   else if (section_is_p (sectp->name, &names->loc_dwo))
12383     {
12384       /* There can be only one.  */
12385       if (sections->loc.s.section != NULL)
12386         return 0;
12387       sections->loc.s.section = sectp;
12388       sections->loc.size = bfd_get_section_size (sectp);
12389     }
12390   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12391     {
12392       /* There can be only one.  */
12393       if (sections->macinfo.s.section != NULL)
12394         return 0;
12395       sections->macinfo.s.section = sectp;
12396       sections->macinfo.size = bfd_get_section_size (sectp);
12397     }
12398   else if (section_is_p (sectp->name, &names->macro_dwo))
12399     {
12400       /* There can be only one.  */
12401       if (sections->macro.s.section != NULL)
12402         return 0;
12403       sections->macro.s.section = sectp;
12404       sections->macro.size = bfd_get_section_size (sectp);
12405     }
12406   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12407     {
12408       /* There can be only one.  */
12409       if (sections->str_offsets.s.section != NULL)
12410         return 0;
12411       sections->str_offsets.s.section = sectp;
12412       sections->str_offsets.size = bfd_get_section_size (sectp);
12413     }
12414   else
12415     {
12416       /* No other kind of section is valid.  */
12417       return 0;
12418     }
12419
12420   return 1;
12421 }
12422
12423 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12424    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12425    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12426    This is for DWP version 1 files.  */
12427
12428 static struct dwo_unit *
12429 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12430                            struct dwp_file *dwp_file,
12431                            uint32_t unit_index,
12432                            const char *comp_dir,
12433                            ULONGEST signature, int is_debug_types)
12434 {
12435   struct objfile *objfile = dwarf2_per_objfile->objfile;
12436   const struct dwp_hash_table *dwp_htab =
12437     is_debug_types ? dwp_file->tus : dwp_file->cus;
12438   bfd *dbfd = dwp_file->dbfd;
12439   const char *kind = is_debug_types ? "TU" : "CU";
12440   struct dwo_file *dwo_file;
12441   struct dwo_unit *dwo_unit;
12442   struct virtual_v1_dwo_sections sections;
12443   void **dwo_file_slot;
12444   int i;
12445
12446   gdb_assert (dwp_file->version == 1);
12447
12448   if (dwarf_read_debug)
12449     {
12450       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12451                           kind,
12452                           pulongest (unit_index), hex_string (signature),
12453                           dwp_file->name);
12454     }
12455
12456   /* Fetch the sections of this DWO unit.
12457      Put a limit on the number of sections we look for so that bad data
12458      doesn't cause us to loop forever.  */
12459
12460 #define MAX_NR_V1_DWO_SECTIONS \
12461   (1 /* .debug_info or .debug_types */ \
12462    + 1 /* .debug_abbrev */ \
12463    + 1 /* .debug_line */ \
12464    + 1 /* .debug_loc */ \
12465    + 1 /* .debug_str_offsets */ \
12466    + 1 /* .debug_macro or .debug_macinfo */ \
12467    + 1 /* trailing zero */)
12468
12469   memset (&sections, 0, sizeof (sections));
12470
12471   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12472     {
12473       asection *sectp;
12474       uint32_t section_nr =
12475         read_4_bytes (dbfd,
12476                       dwp_htab->section_pool.v1.indices
12477                       + (unit_index + i) * sizeof (uint32_t));
12478
12479       if (section_nr == 0)
12480         break;
12481       if (section_nr >= dwp_file->num_sections)
12482         {
12483           error (_("Dwarf Error: bad DWP hash table, section number too large"
12484                    " [in module %s]"),
12485                  dwp_file->name);
12486         }
12487
12488       sectp = dwp_file->elf_sections[section_nr];
12489       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12490         {
12491           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12492                    " [in module %s]"),
12493                  dwp_file->name);
12494         }
12495     }
12496
12497   if (i < 2
12498       || dwarf2_section_empty_p (&sections.info_or_types)
12499       || dwarf2_section_empty_p (&sections.abbrev))
12500     {
12501       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12502                " [in module %s]"),
12503              dwp_file->name);
12504     }
12505   if (i == MAX_NR_V1_DWO_SECTIONS)
12506     {
12507       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12508                " [in module %s]"),
12509              dwp_file->name);
12510     }
12511
12512   /* It's easier for the rest of the code if we fake a struct dwo_file and
12513      have dwo_unit "live" in that.  At least for now.
12514
12515      The DWP file can be made up of a random collection of CUs and TUs.
12516      However, for each CU + set of TUs that came from the same original DWO
12517      file, we can combine them back into a virtual DWO file to save space
12518      (fewer struct dwo_file objects to allocate).  Remember that for really
12519      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12520
12521   std::string virtual_dwo_name =
12522     string_printf ("virtual-dwo/%d-%d-%d-%d",
12523                    get_section_id (&sections.abbrev),
12524                    get_section_id (&sections.line),
12525                    get_section_id (&sections.loc),
12526                    get_section_id (&sections.str_offsets));
12527   /* Can we use an existing virtual DWO file?  */
12528   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12529                                         virtual_dwo_name.c_str (),
12530                                         comp_dir);
12531   /* Create one if necessary.  */
12532   if (*dwo_file_slot == NULL)
12533     {
12534       if (dwarf_read_debug)
12535         {
12536           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12537                               virtual_dwo_name.c_str ());
12538         }
12539       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12540       dwo_file->dwo_name
12541         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12542                                         virtual_dwo_name.c_str (),
12543                                         virtual_dwo_name.size ());
12544       dwo_file->comp_dir = comp_dir;
12545       dwo_file->sections.abbrev = sections.abbrev;
12546       dwo_file->sections.line = sections.line;
12547       dwo_file->sections.loc = sections.loc;
12548       dwo_file->sections.macinfo = sections.macinfo;
12549       dwo_file->sections.macro = sections.macro;
12550       dwo_file->sections.str_offsets = sections.str_offsets;
12551       /* The "str" section is global to the entire DWP file.  */
12552       dwo_file->sections.str = dwp_file->sections.str;
12553       /* The info or types section is assigned below to dwo_unit,
12554          there's no need to record it in dwo_file.
12555          Also, we can't simply record type sections in dwo_file because
12556          we record a pointer into the vector in dwo_unit.  As we collect more
12557          types we'll grow the vector and eventually have to reallocate space
12558          for it, invalidating all copies of pointers into the previous
12559          contents.  */
12560       *dwo_file_slot = dwo_file;
12561     }
12562   else
12563     {
12564       if (dwarf_read_debug)
12565         {
12566           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12567                               virtual_dwo_name.c_str ());
12568         }
12569       dwo_file = (struct dwo_file *) *dwo_file_slot;
12570     }
12571
12572   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12573   dwo_unit->dwo_file = dwo_file;
12574   dwo_unit->signature = signature;
12575   dwo_unit->section =
12576     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12577   *dwo_unit->section = sections.info_or_types;
12578   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12579
12580   return dwo_unit;
12581 }
12582
12583 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12584    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12585    piece within that section used by a TU/CU, return a virtual section
12586    of just that piece.  */
12587
12588 static struct dwarf2_section_info
12589 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12590                        struct dwarf2_section_info *section,
12591                        bfd_size_type offset, bfd_size_type size)
12592 {
12593   struct dwarf2_section_info result;
12594   asection *sectp;
12595
12596   gdb_assert (section != NULL);
12597   gdb_assert (!section->is_virtual);
12598
12599   memset (&result, 0, sizeof (result));
12600   result.s.containing_section = section;
12601   result.is_virtual = 1;
12602
12603   if (size == 0)
12604     return result;
12605
12606   sectp = get_section_bfd_section (section);
12607
12608   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12609      bounds of the real section.  This is a pretty-rare event, so just
12610      flag an error (easier) instead of a warning and trying to cope.  */
12611   if (sectp == NULL
12612       || offset + size > bfd_get_section_size (sectp))
12613     {
12614       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12615                " in section %s [in module %s]"),
12616              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12617              objfile_name (dwarf2_per_objfile->objfile));
12618     }
12619
12620   result.virtual_offset = offset;
12621   result.size = size;
12622   return result;
12623 }
12624
12625 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12626    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12627    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12628    This is for DWP version 2 files.  */
12629
12630 static struct dwo_unit *
12631 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12632                            struct dwp_file *dwp_file,
12633                            uint32_t unit_index,
12634                            const char *comp_dir,
12635                            ULONGEST signature, int is_debug_types)
12636 {
12637   struct objfile *objfile = dwarf2_per_objfile->objfile;
12638   const struct dwp_hash_table *dwp_htab =
12639     is_debug_types ? dwp_file->tus : dwp_file->cus;
12640   bfd *dbfd = dwp_file->dbfd;
12641   const char *kind = is_debug_types ? "TU" : "CU";
12642   struct dwo_file *dwo_file;
12643   struct dwo_unit *dwo_unit;
12644   struct virtual_v2_dwo_sections sections;
12645   void **dwo_file_slot;
12646   int i;
12647
12648   gdb_assert (dwp_file->version == 2);
12649
12650   if (dwarf_read_debug)
12651     {
12652       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12653                           kind,
12654                           pulongest (unit_index), hex_string (signature),
12655                           dwp_file->name);
12656     }
12657
12658   /* Fetch the section offsets of this DWO unit.  */
12659
12660   memset (&sections, 0, sizeof (sections));
12661
12662   for (i = 0; i < dwp_htab->nr_columns; ++i)
12663     {
12664       uint32_t offset = read_4_bytes (dbfd,
12665                                       dwp_htab->section_pool.v2.offsets
12666                                       + (((unit_index - 1) * dwp_htab->nr_columns
12667                                           + i)
12668                                          * sizeof (uint32_t)));
12669       uint32_t size = read_4_bytes (dbfd,
12670                                     dwp_htab->section_pool.v2.sizes
12671                                     + (((unit_index - 1) * dwp_htab->nr_columns
12672                                         + i)
12673                                        * sizeof (uint32_t)));
12674
12675       switch (dwp_htab->section_pool.v2.section_ids[i])
12676         {
12677         case DW_SECT_INFO:
12678         case DW_SECT_TYPES:
12679           sections.info_or_types_offset = offset;
12680           sections.info_or_types_size = size;
12681           break;
12682         case DW_SECT_ABBREV:
12683           sections.abbrev_offset = offset;
12684           sections.abbrev_size = size;
12685           break;
12686         case DW_SECT_LINE:
12687           sections.line_offset = offset;
12688           sections.line_size = size;
12689           break;
12690         case DW_SECT_LOC:
12691           sections.loc_offset = offset;
12692           sections.loc_size = size;
12693           break;
12694         case DW_SECT_STR_OFFSETS:
12695           sections.str_offsets_offset = offset;
12696           sections.str_offsets_size = size;
12697           break;
12698         case DW_SECT_MACINFO:
12699           sections.macinfo_offset = offset;
12700           sections.macinfo_size = size;
12701           break;
12702         case DW_SECT_MACRO:
12703           sections.macro_offset = offset;
12704           sections.macro_size = size;
12705           break;
12706         }
12707     }
12708
12709   /* It's easier for the rest of the code if we fake a struct dwo_file and
12710      have dwo_unit "live" in that.  At least for now.
12711
12712      The DWP file can be made up of a random collection of CUs and TUs.
12713      However, for each CU + set of TUs that came from the same original DWO
12714      file, we can combine them back into a virtual DWO file to save space
12715      (fewer struct dwo_file objects to allocate).  Remember that for really
12716      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12717
12718   std::string virtual_dwo_name =
12719     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12720                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12721                    (long) (sections.line_size ? sections.line_offset : 0),
12722                    (long) (sections.loc_size ? sections.loc_offset : 0),
12723                    (long) (sections.str_offsets_size
12724                            ? sections.str_offsets_offset : 0));
12725   /* Can we use an existing virtual DWO file?  */
12726   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12727                                         virtual_dwo_name.c_str (),
12728                                         comp_dir);
12729   /* Create one if necessary.  */
12730   if (*dwo_file_slot == NULL)
12731     {
12732       if (dwarf_read_debug)
12733         {
12734           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12735                               virtual_dwo_name.c_str ());
12736         }
12737       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12738       dwo_file->dwo_name
12739         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12740                                         virtual_dwo_name.c_str (),
12741                                         virtual_dwo_name.size ());
12742       dwo_file->comp_dir = comp_dir;
12743       dwo_file->sections.abbrev =
12744         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12745                                sections.abbrev_offset, sections.abbrev_size);
12746       dwo_file->sections.line =
12747         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12748                                sections.line_offset, sections.line_size);
12749       dwo_file->sections.loc =
12750         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12751                                sections.loc_offset, sections.loc_size);
12752       dwo_file->sections.macinfo =
12753         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12754                                sections.macinfo_offset, sections.macinfo_size);
12755       dwo_file->sections.macro =
12756         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12757                                sections.macro_offset, sections.macro_size);
12758       dwo_file->sections.str_offsets =
12759         create_dwp_v2_section (dwarf2_per_objfile,
12760                                &dwp_file->sections.str_offsets,
12761                                sections.str_offsets_offset,
12762                                sections.str_offsets_size);
12763       /* The "str" section is global to the entire DWP file.  */
12764       dwo_file->sections.str = dwp_file->sections.str;
12765       /* The info or types section is assigned below to dwo_unit,
12766          there's no need to record it in dwo_file.
12767          Also, we can't simply record type sections in dwo_file because
12768          we record a pointer into the vector in dwo_unit.  As we collect more
12769          types we'll grow the vector and eventually have to reallocate space
12770          for it, invalidating all copies of pointers into the previous
12771          contents.  */
12772       *dwo_file_slot = dwo_file;
12773     }
12774   else
12775     {
12776       if (dwarf_read_debug)
12777         {
12778           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12779                               virtual_dwo_name.c_str ());
12780         }
12781       dwo_file = (struct dwo_file *) *dwo_file_slot;
12782     }
12783
12784   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12785   dwo_unit->dwo_file = dwo_file;
12786   dwo_unit->signature = signature;
12787   dwo_unit->section =
12788     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12789   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12790                                               is_debug_types
12791                                               ? &dwp_file->sections.types
12792                                               : &dwp_file->sections.info,
12793                                               sections.info_or_types_offset,
12794                                               sections.info_or_types_size);
12795   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12796
12797   return dwo_unit;
12798 }
12799
12800 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12801    Returns NULL if the signature isn't found.  */
12802
12803 static struct dwo_unit *
12804 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12805                         struct dwp_file *dwp_file, const char *comp_dir,
12806                         ULONGEST signature, int is_debug_types)
12807 {
12808   const struct dwp_hash_table *dwp_htab =
12809     is_debug_types ? dwp_file->tus : dwp_file->cus;
12810   bfd *dbfd = dwp_file->dbfd;
12811   uint32_t mask = dwp_htab->nr_slots - 1;
12812   uint32_t hash = signature & mask;
12813   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12814   unsigned int i;
12815   void **slot;
12816   struct dwo_unit find_dwo_cu;
12817
12818   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12819   find_dwo_cu.signature = signature;
12820   slot = htab_find_slot (is_debug_types
12821                          ? dwp_file->loaded_tus
12822                          : dwp_file->loaded_cus,
12823                          &find_dwo_cu, INSERT);
12824
12825   if (*slot != NULL)
12826     return (struct dwo_unit *) *slot;
12827
12828   /* Use a for loop so that we don't loop forever on bad debug info.  */
12829   for (i = 0; i < dwp_htab->nr_slots; ++i)
12830     {
12831       ULONGEST signature_in_table;
12832
12833       signature_in_table =
12834         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12835       if (signature_in_table == signature)
12836         {
12837           uint32_t unit_index =
12838             read_4_bytes (dbfd,
12839                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12840
12841           if (dwp_file->version == 1)
12842             {
12843               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12844                                                  dwp_file, unit_index,
12845                                                  comp_dir, signature,
12846                                                  is_debug_types);
12847             }
12848           else
12849             {
12850               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12851                                                  dwp_file, unit_index,
12852                                                  comp_dir, signature,
12853                                                  is_debug_types);
12854             }
12855           return (struct dwo_unit *) *slot;
12856         }
12857       if (signature_in_table == 0)
12858         return NULL;
12859       hash = (hash + hash2) & mask;
12860     }
12861
12862   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12863            " [in module %s]"),
12864          dwp_file->name);
12865 }
12866
12867 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12868    Open the file specified by FILE_NAME and hand it off to BFD for
12869    preliminary analysis.  Return a newly initialized bfd *, which
12870    includes a canonicalized copy of FILE_NAME.
12871    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12872    SEARCH_CWD is true if the current directory is to be searched.
12873    It will be searched before debug-file-directory.
12874    If successful, the file is added to the bfd include table of the
12875    objfile's bfd (see gdb_bfd_record_inclusion).
12876    If unable to find/open the file, return NULL.
12877    NOTE: This function is derived from symfile_bfd_open.  */
12878
12879 static gdb_bfd_ref_ptr
12880 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12881                     const char *file_name, int is_dwp, int search_cwd)
12882 {
12883   int desc;
12884   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12885      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12886      to debug_file_directory.  */
12887   const char *search_path;
12888   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12889
12890   gdb::unique_xmalloc_ptr<char> search_path_holder;
12891   if (search_cwd)
12892     {
12893       if (*debug_file_directory != '\0')
12894         {
12895           search_path_holder.reset (concat (".", dirname_separator_string,
12896                                             debug_file_directory,
12897                                             (char *) NULL));
12898           search_path = search_path_holder.get ();
12899         }
12900       else
12901         search_path = ".";
12902     }
12903   else
12904     search_path = debug_file_directory;
12905
12906   openp_flags flags = OPF_RETURN_REALPATH;
12907   if (is_dwp)
12908     flags |= OPF_SEARCH_IN_PATH;
12909
12910   gdb::unique_xmalloc_ptr<char> absolute_name;
12911   desc = openp (search_path, flags, file_name,
12912                 O_RDONLY | O_BINARY, &absolute_name);
12913   if (desc < 0)
12914     return NULL;
12915
12916   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12917                                          gnutarget, desc));
12918   if (sym_bfd == NULL)
12919     return NULL;
12920   bfd_set_cacheable (sym_bfd.get (), 1);
12921
12922   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12923     return NULL;
12924
12925   /* Success.  Record the bfd as having been included by the objfile's bfd.
12926      This is important because things like demangled_names_hash lives in the
12927      objfile's per_bfd space and may have references to things like symbol
12928      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12929   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12930
12931   return sym_bfd;
12932 }
12933
12934 /* Try to open DWO file FILE_NAME.
12935    COMP_DIR is the DW_AT_comp_dir attribute.
12936    The result is the bfd handle of the file.
12937    If there is a problem finding or opening the file, return NULL.
12938    Upon success, the canonicalized path of the file is stored in the bfd,
12939    same as symfile_bfd_open.  */
12940
12941 static gdb_bfd_ref_ptr
12942 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12943                const char *file_name, const char *comp_dir)
12944 {
12945   if (IS_ABSOLUTE_PATH (file_name))
12946     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12947                                0 /*is_dwp*/, 0 /*search_cwd*/);
12948
12949   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12950
12951   if (comp_dir != NULL)
12952     {
12953       char *path_to_try = concat (comp_dir, SLASH_STRING,
12954                                   file_name, (char *) NULL);
12955
12956       /* NOTE: If comp_dir is a relative path, this will also try the
12957          search path, which seems useful.  */
12958       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12959                                                 path_to_try,
12960                                                 0 /*is_dwp*/,
12961                                                 1 /*search_cwd*/));
12962       xfree (path_to_try);
12963       if (abfd != NULL)
12964         return abfd;
12965     }
12966
12967   /* That didn't work, try debug-file-directory, which, despite its name,
12968      is a list of paths.  */
12969
12970   if (*debug_file_directory == '\0')
12971     return NULL;
12972
12973   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12974                              0 /*is_dwp*/, 1 /*search_cwd*/);
12975 }
12976
12977 /* This function is mapped across the sections and remembers the offset and
12978    size of each of the DWO debugging sections we are interested in.  */
12979
12980 static void
12981 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12982 {
12983   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12984   const struct dwop_section_names *names = &dwop_section_names;
12985
12986   if (section_is_p (sectp->name, &names->abbrev_dwo))
12987     {
12988       dwo_sections->abbrev.s.section = sectp;
12989       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12990     }
12991   else if (section_is_p (sectp->name, &names->info_dwo))
12992     {
12993       dwo_sections->info.s.section = sectp;
12994       dwo_sections->info.size = bfd_get_section_size (sectp);
12995     }
12996   else if (section_is_p (sectp->name, &names->line_dwo))
12997     {
12998       dwo_sections->line.s.section = sectp;
12999       dwo_sections->line.size = bfd_get_section_size (sectp);
13000     }
13001   else if (section_is_p (sectp->name, &names->loc_dwo))
13002     {
13003       dwo_sections->loc.s.section = sectp;
13004       dwo_sections->loc.size = bfd_get_section_size (sectp);
13005     }
13006   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13007     {
13008       dwo_sections->macinfo.s.section = sectp;
13009       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13010     }
13011   else if (section_is_p (sectp->name, &names->macro_dwo))
13012     {
13013       dwo_sections->macro.s.section = sectp;
13014       dwo_sections->macro.size = bfd_get_section_size (sectp);
13015     }
13016   else if (section_is_p (sectp->name, &names->str_dwo))
13017     {
13018       dwo_sections->str.s.section = sectp;
13019       dwo_sections->str.size = bfd_get_section_size (sectp);
13020     }
13021   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13022     {
13023       dwo_sections->str_offsets.s.section = sectp;
13024       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13025     }
13026   else if (section_is_p (sectp->name, &names->types_dwo))
13027     {
13028       struct dwarf2_section_info type_section;
13029
13030       memset (&type_section, 0, sizeof (type_section));
13031       type_section.s.section = sectp;
13032       type_section.size = bfd_get_section_size (sectp);
13033       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13034                      &type_section);
13035     }
13036 }
13037
13038 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13039    by PER_CU.  This is for the non-DWP case.
13040    The result is NULL if DWO_NAME can't be found.  */
13041
13042 static struct dwo_file *
13043 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13044                         const char *dwo_name, const char *comp_dir)
13045 {
13046   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13047   struct objfile *objfile = dwarf2_per_objfile->objfile;
13048   struct dwo_file *dwo_file;
13049   struct cleanup *cleanups;
13050
13051   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13052   if (dbfd == NULL)
13053     {
13054       if (dwarf_read_debug)
13055         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13056       return NULL;
13057     }
13058   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13059   dwo_file->dwo_name = dwo_name;
13060   dwo_file->comp_dir = comp_dir;
13061   dwo_file->dbfd = dbfd.release ();
13062
13063   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13064   cleanup_data->dwo_file = dwo_file;
13065   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13066
13067   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13068
13069   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13070                          &dwo_file->sections);
13071
13072   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13073                          dwo_file->cus);
13074
13075   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13076                                  dwo_file->sections.types, dwo_file->tus);
13077
13078   discard_cleanups (cleanups);
13079
13080   if (dwarf_read_debug)
13081     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13082
13083   return dwo_file;
13084 }
13085
13086 /* This function is mapped across the sections and remembers the offset and
13087    size of each of the DWP debugging sections common to version 1 and 2 that
13088    we are interested in.  */
13089
13090 static void
13091 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13092                                    void *dwp_file_ptr)
13093 {
13094   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13095   const struct dwop_section_names *names = &dwop_section_names;
13096   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13097
13098   /* Record the ELF section number for later lookup: this is what the
13099      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13100   gdb_assert (elf_section_nr < dwp_file->num_sections);
13101   dwp_file->elf_sections[elf_section_nr] = sectp;
13102
13103   /* Look for specific sections that we need.  */
13104   if (section_is_p (sectp->name, &names->str_dwo))
13105     {
13106       dwp_file->sections.str.s.section = sectp;
13107       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13108     }
13109   else if (section_is_p (sectp->name, &names->cu_index))
13110     {
13111       dwp_file->sections.cu_index.s.section = sectp;
13112       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13113     }
13114   else if (section_is_p (sectp->name, &names->tu_index))
13115     {
13116       dwp_file->sections.tu_index.s.section = sectp;
13117       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13118     }
13119 }
13120
13121 /* This function is mapped across the sections and remembers the offset and
13122    size of each of the DWP version 2 debugging sections that we are interested
13123    in.  This is split into a separate function because we don't know if we
13124    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13125
13126 static void
13127 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13128 {
13129   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13130   const struct dwop_section_names *names = &dwop_section_names;
13131   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13132
13133   /* Record the ELF section number for later lookup: this is what the
13134      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13135   gdb_assert (elf_section_nr < dwp_file->num_sections);
13136   dwp_file->elf_sections[elf_section_nr] = sectp;
13137
13138   /* Look for specific sections that we need.  */
13139   if (section_is_p (sectp->name, &names->abbrev_dwo))
13140     {
13141       dwp_file->sections.abbrev.s.section = sectp;
13142       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13143     }
13144   else if (section_is_p (sectp->name, &names->info_dwo))
13145     {
13146       dwp_file->sections.info.s.section = sectp;
13147       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13148     }
13149   else if (section_is_p (sectp->name, &names->line_dwo))
13150     {
13151       dwp_file->sections.line.s.section = sectp;
13152       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13153     }
13154   else if (section_is_p (sectp->name, &names->loc_dwo))
13155     {
13156       dwp_file->sections.loc.s.section = sectp;
13157       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13158     }
13159   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13160     {
13161       dwp_file->sections.macinfo.s.section = sectp;
13162       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13163     }
13164   else if (section_is_p (sectp->name, &names->macro_dwo))
13165     {
13166       dwp_file->sections.macro.s.section = sectp;
13167       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13168     }
13169   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13170     {
13171       dwp_file->sections.str_offsets.s.section = sectp;
13172       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13173     }
13174   else if (section_is_p (sectp->name, &names->types_dwo))
13175     {
13176       dwp_file->sections.types.s.section = sectp;
13177       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13178     }
13179 }
13180
13181 /* Hash function for dwp_file loaded CUs/TUs.  */
13182
13183 static hashval_t
13184 hash_dwp_loaded_cutus (const void *item)
13185 {
13186   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13187
13188   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13189   return dwo_unit->signature;
13190 }
13191
13192 /* Equality function for dwp_file loaded CUs/TUs.  */
13193
13194 static int
13195 eq_dwp_loaded_cutus (const void *a, const void *b)
13196 {
13197   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13198   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13199
13200   return dua->signature == dub->signature;
13201 }
13202
13203 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13204
13205 static htab_t
13206 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13207 {
13208   return htab_create_alloc_ex (3,
13209                                hash_dwp_loaded_cutus,
13210                                eq_dwp_loaded_cutus,
13211                                NULL,
13212                                &objfile->objfile_obstack,
13213                                hashtab_obstack_allocate,
13214                                dummy_obstack_deallocate);
13215 }
13216
13217 /* Try to open DWP file FILE_NAME.
13218    The result is the bfd handle of the file.
13219    If there is a problem finding or opening the file, return NULL.
13220    Upon success, the canonicalized path of the file is stored in the bfd,
13221    same as symfile_bfd_open.  */
13222
13223 static gdb_bfd_ref_ptr
13224 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13225                const char *file_name)
13226 {
13227   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13228                                             1 /*is_dwp*/,
13229                                             1 /*search_cwd*/));
13230   if (abfd != NULL)
13231     return abfd;
13232
13233   /* Work around upstream bug 15652.
13234      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13235      [Whether that's a "bug" is debatable, but it is getting in our way.]
13236      We have no real idea where the dwp file is, because gdb's realpath-ing
13237      of the executable's path may have discarded the needed info.
13238      [IWBN if the dwp file name was recorded in the executable, akin to
13239      .gnu_debuglink, but that doesn't exist yet.]
13240      Strip the directory from FILE_NAME and search again.  */
13241   if (*debug_file_directory != '\0')
13242     {
13243       /* Don't implicitly search the current directory here.
13244          If the user wants to search "." to handle this case,
13245          it must be added to debug-file-directory.  */
13246       return try_open_dwop_file (dwarf2_per_objfile,
13247                                  lbasename (file_name), 1 /*is_dwp*/,
13248                                  0 /*search_cwd*/);
13249     }
13250
13251   return NULL;
13252 }
13253
13254 /* Initialize the use of the DWP file for the current objfile.
13255    By convention the name of the DWP file is ${objfile}.dwp.
13256    The result is NULL if it can't be found.  */
13257
13258 static struct dwp_file *
13259 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13260 {
13261   struct objfile *objfile = dwarf2_per_objfile->objfile;
13262   struct dwp_file *dwp_file;
13263
13264   /* Try to find first .dwp for the binary file before any symbolic links
13265      resolving.  */
13266
13267   /* If the objfile is a debug file, find the name of the real binary
13268      file and get the name of dwp file from there.  */
13269   std::string dwp_name;
13270   if (objfile->separate_debug_objfile_backlink != NULL)
13271     {
13272       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13273       const char *backlink_basename = lbasename (backlink->original_name);
13274
13275       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13276     }
13277   else
13278     dwp_name = objfile->original_name;
13279
13280   dwp_name += ".dwp";
13281
13282   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13283   if (dbfd == NULL
13284       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13285     {
13286       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13287       dwp_name = objfile_name (objfile);
13288       dwp_name += ".dwp";
13289       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13290     }
13291
13292   if (dbfd == NULL)
13293     {
13294       if (dwarf_read_debug)
13295         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13296       return NULL;
13297     }
13298   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13299   dwp_file->name = bfd_get_filename (dbfd.get ());
13300   dwp_file->dbfd = dbfd.release ();
13301
13302   /* +1: section 0 is unused */
13303   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13304   dwp_file->elf_sections =
13305     OBSTACK_CALLOC (&objfile->objfile_obstack,
13306                     dwp_file->num_sections, asection *);
13307
13308   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13309                          dwp_file);
13310
13311   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13312
13313   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13314
13315   /* The DWP file version is stored in the hash table.  Oh well.  */
13316   if (dwp_file->cus && dwp_file->tus
13317       && dwp_file->cus->version != dwp_file->tus->version)
13318     {
13319       /* Technically speaking, we should try to limp along, but this is
13320          pretty bizarre.  We use pulongest here because that's the established
13321          portability solution (e.g, we cannot use %u for uint32_t).  */
13322       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13323                " TU version %s [in DWP file %s]"),
13324              pulongest (dwp_file->cus->version),
13325              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13326     }
13327
13328   if (dwp_file->cus)
13329     dwp_file->version = dwp_file->cus->version;
13330   else if (dwp_file->tus)
13331     dwp_file->version = dwp_file->tus->version;
13332   else
13333     dwp_file->version = 2;
13334
13335   if (dwp_file->version == 2)
13336     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13337                            dwp_file);
13338
13339   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13340   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13341
13342   if (dwarf_read_debug)
13343     {
13344       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13345       fprintf_unfiltered (gdb_stdlog,
13346                           "    %s CUs, %s TUs\n",
13347                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13348                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13349     }
13350
13351   return dwp_file;
13352 }
13353
13354 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13355
13356 static struct dwp_file *
13357 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13358 {
13359   if (! dwarf2_per_objfile->dwp_checked)
13360     {
13361       dwarf2_per_objfile->dwp_file
13362         = open_and_init_dwp_file (dwarf2_per_objfile);
13363       dwarf2_per_objfile->dwp_checked = 1;
13364     }
13365   return dwarf2_per_objfile->dwp_file;
13366 }
13367
13368 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13369    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13370    or in the DWP file for the objfile, referenced by THIS_UNIT.
13371    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13372    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13373
13374    This is called, for example, when wanting to read a variable with a
13375    complex location.  Therefore we don't want to do file i/o for every call.
13376    Therefore we don't want to look for a DWO file on every call.
13377    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13378    then we check if we've already seen DWO_NAME, and only THEN do we check
13379    for a DWO file.
13380
13381    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13382    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13383
13384 static struct dwo_unit *
13385 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13386                  const char *dwo_name, const char *comp_dir,
13387                  ULONGEST signature, int is_debug_types)
13388 {
13389   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13390   struct objfile *objfile = dwarf2_per_objfile->objfile;
13391   const char *kind = is_debug_types ? "TU" : "CU";
13392   void **dwo_file_slot;
13393   struct dwo_file *dwo_file;
13394   struct dwp_file *dwp_file;
13395
13396   /* First see if there's a DWP file.
13397      If we have a DWP file but didn't find the DWO inside it, don't
13398      look for the original DWO file.  It makes gdb behave differently
13399      depending on whether one is debugging in the build tree.  */
13400
13401   dwp_file = get_dwp_file (dwarf2_per_objfile);
13402   if (dwp_file != NULL)
13403     {
13404       const struct dwp_hash_table *dwp_htab =
13405         is_debug_types ? dwp_file->tus : dwp_file->cus;
13406
13407       if (dwp_htab != NULL)
13408         {
13409           struct dwo_unit *dwo_cutu =
13410             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13411                                     signature, is_debug_types);
13412
13413           if (dwo_cutu != NULL)
13414             {
13415               if (dwarf_read_debug)
13416                 {
13417                   fprintf_unfiltered (gdb_stdlog,
13418                                       "Virtual DWO %s %s found: @%s\n",
13419                                       kind, hex_string (signature),
13420                                       host_address_to_string (dwo_cutu));
13421                 }
13422               return dwo_cutu;
13423             }
13424         }
13425     }
13426   else
13427     {
13428       /* No DWP file, look for the DWO file.  */
13429
13430       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13431                                             dwo_name, comp_dir);
13432       if (*dwo_file_slot == NULL)
13433         {
13434           /* Read in the file and build a table of the CUs/TUs it contains.  */
13435           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13436         }
13437       /* NOTE: This will be NULL if unable to open the file.  */
13438       dwo_file = (struct dwo_file *) *dwo_file_slot;
13439
13440       if (dwo_file != NULL)
13441         {
13442           struct dwo_unit *dwo_cutu = NULL;
13443
13444           if (is_debug_types && dwo_file->tus)
13445             {
13446               struct dwo_unit find_dwo_cutu;
13447
13448               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13449               find_dwo_cutu.signature = signature;
13450               dwo_cutu
13451                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13452             }
13453           else if (!is_debug_types && dwo_file->cus)
13454             {
13455               struct dwo_unit find_dwo_cutu;
13456
13457               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13458               find_dwo_cutu.signature = signature;
13459               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13460                                                        &find_dwo_cutu);
13461             }
13462
13463           if (dwo_cutu != NULL)
13464             {
13465               if (dwarf_read_debug)
13466                 {
13467                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13468                                       kind, dwo_name, hex_string (signature),
13469                                       host_address_to_string (dwo_cutu));
13470                 }
13471               return dwo_cutu;
13472             }
13473         }
13474     }
13475
13476   /* We didn't find it.  This could mean a dwo_id mismatch, or
13477      someone deleted the DWO/DWP file, or the search path isn't set up
13478      correctly to find the file.  */
13479
13480   if (dwarf_read_debug)
13481     {
13482       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13483                           kind, dwo_name, hex_string (signature));
13484     }
13485
13486   /* This is a warning and not a complaint because it can be caused by
13487      pilot error (e.g., user accidentally deleting the DWO).  */
13488   {
13489     /* Print the name of the DWP file if we looked there, helps the user
13490        better diagnose the problem.  */
13491     std::string dwp_text;
13492
13493     if (dwp_file != NULL)
13494       dwp_text = string_printf (" [in DWP file %s]",
13495                                 lbasename (dwp_file->name));
13496
13497     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13498                " [in module %s]"),
13499              kind, dwo_name, hex_string (signature),
13500              dwp_text.c_str (),
13501              this_unit->is_debug_types ? "TU" : "CU",
13502              to_underlying (this_unit->sect_off), objfile_name (objfile));
13503   }
13504   return NULL;
13505 }
13506
13507 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13508    See lookup_dwo_cutu_unit for details.  */
13509
13510 static struct dwo_unit *
13511 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13512                       const char *dwo_name, const char *comp_dir,
13513                       ULONGEST signature)
13514 {
13515   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13516 }
13517
13518 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13519    See lookup_dwo_cutu_unit for details.  */
13520
13521 static struct dwo_unit *
13522 lookup_dwo_type_unit (struct signatured_type *this_tu,
13523                       const char *dwo_name, const char *comp_dir)
13524 {
13525   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13526 }
13527
13528 /* Traversal function for queue_and_load_all_dwo_tus.  */
13529
13530 static int
13531 queue_and_load_dwo_tu (void **slot, void *info)
13532 {
13533   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13534   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13535   ULONGEST signature = dwo_unit->signature;
13536   struct signatured_type *sig_type =
13537     lookup_dwo_signatured_type (per_cu->cu, signature);
13538
13539   if (sig_type != NULL)
13540     {
13541       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13542
13543       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13544          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13545          while processing PER_CU.  */
13546       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13547         load_full_type_unit (sig_cu);
13548       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13549     }
13550
13551   return 1;
13552 }
13553
13554 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13555    The DWO may have the only definition of the type, though it may not be
13556    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13557    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13558
13559 static void
13560 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13561 {
13562   struct dwo_unit *dwo_unit;
13563   struct dwo_file *dwo_file;
13564
13565   gdb_assert (!per_cu->is_debug_types);
13566   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13567   gdb_assert (per_cu->cu != NULL);
13568
13569   dwo_unit = per_cu->cu->dwo_unit;
13570   gdb_assert (dwo_unit != NULL);
13571
13572   dwo_file = dwo_unit->dwo_file;
13573   if (dwo_file->tus != NULL)
13574     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13575 }
13576
13577 /* Free all resources associated with DWO_FILE.
13578    Close the DWO file and munmap the sections.
13579    All memory should be on the objfile obstack.  */
13580
13581 static void
13582 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13583 {
13584
13585   /* Note: dbfd is NULL for virtual DWO files.  */
13586   gdb_bfd_unref (dwo_file->dbfd);
13587
13588   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13589 }
13590
13591 /* Wrapper for free_dwo_file for use in cleanups.  */
13592
13593 static void
13594 free_dwo_file_cleanup (void *arg)
13595 {
13596   struct free_dwo_file_cleanup_data *data
13597     = (struct free_dwo_file_cleanup_data *) arg;
13598   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13599
13600   free_dwo_file (data->dwo_file, objfile);
13601
13602   xfree (data);
13603 }
13604
13605 /* Traversal function for free_dwo_files.  */
13606
13607 static int
13608 free_dwo_file_from_slot (void **slot, void *info)
13609 {
13610   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13611   struct objfile *objfile = (struct objfile *) info;
13612
13613   free_dwo_file (dwo_file, objfile);
13614
13615   return 1;
13616 }
13617
13618 /* Free all resources associated with DWO_FILES.  */
13619
13620 static void
13621 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13622 {
13623   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13624 }
13625 \f
13626 /* Read in various DIEs.  */
13627
13628 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13629    Inherit only the children of the DW_AT_abstract_origin DIE not being
13630    already referenced by DW_AT_abstract_origin from the children of the
13631    current DIE.  */
13632
13633 static void
13634 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13635 {
13636   struct die_info *child_die;
13637   sect_offset *offsetp;
13638   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13639   struct die_info *origin_die;
13640   /* Iterator of the ORIGIN_DIE children.  */
13641   struct die_info *origin_child_die;
13642   struct attribute *attr;
13643   struct dwarf2_cu *origin_cu;
13644   struct pending **origin_previous_list_in_scope;
13645
13646   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13647   if (!attr)
13648     return;
13649
13650   /* Note that following die references may follow to a die in a
13651      different cu.  */
13652
13653   origin_cu = cu;
13654   origin_die = follow_die_ref (die, attr, &origin_cu);
13655
13656   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13657      symbols in.  */
13658   origin_previous_list_in_scope = origin_cu->list_in_scope;
13659   origin_cu->list_in_scope = cu->list_in_scope;
13660
13661   if (die->tag != origin_die->tag
13662       && !(die->tag == DW_TAG_inlined_subroutine
13663            && origin_die->tag == DW_TAG_subprogram))
13664     complaint (&symfile_complaints,
13665                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13666                to_underlying (die->sect_off),
13667                to_underlying (origin_die->sect_off));
13668
13669   std::vector<sect_offset> offsets;
13670
13671   for (child_die = die->child;
13672        child_die && child_die->tag;
13673        child_die = sibling_die (child_die))
13674     {
13675       struct die_info *child_origin_die;
13676       struct dwarf2_cu *child_origin_cu;
13677
13678       /* We are trying to process concrete instance entries:
13679          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13680          it's not relevant to our analysis here. i.e. detecting DIEs that are
13681          present in the abstract instance but not referenced in the concrete
13682          one.  */
13683       if (child_die->tag == DW_TAG_call_site
13684           || child_die->tag == DW_TAG_GNU_call_site)
13685         continue;
13686
13687       /* For each CHILD_DIE, find the corresponding child of
13688          ORIGIN_DIE.  If there is more than one layer of
13689          DW_AT_abstract_origin, follow them all; there shouldn't be,
13690          but GCC versions at least through 4.4 generate this (GCC PR
13691          40573).  */
13692       child_origin_die = child_die;
13693       child_origin_cu = cu;
13694       while (1)
13695         {
13696           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13697                               child_origin_cu);
13698           if (attr == NULL)
13699             break;
13700           child_origin_die = follow_die_ref (child_origin_die, attr,
13701                                              &child_origin_cu);
13702         }
13703
13704       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13705          counterpart may exist.  */
13706       if (child_origin_die != child_die)
13707         {
13708           if (child_die->tag != child_origin_die->tag
13709               && !(child_die->tag == DW_TAG_inlined_subroutine
13710                    && child_origin_die->tag == DW_TAG_subprogram))
13711             complaint (&symfile_complaints,
13712                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13713                          "different tags"),
13714                        to_underlying (child_die->sect_off),
13715                        to_underlying (child_origin_die->sect_off));
13716           if (child_origin_die->parent != origin_die)
13717             complaint (&symfile_complaints,
13718                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13719                          "different parents"),
13720                        to_underlying (child_die->sect_off),
13721                        to_underlying (child_origin_die->sect_off));
13722           else
13723             offsets.push_back (child_origin_die->sect_off);
13724         }
13725     }
13726   std::sort (offsets.begin (), offsets.end ());
13727   sect_offset *offsets_end = offsets.data () + offsets.size ();
13728   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13729     if (offsetp[-1] == *offsetp)
13730       complaint (&symfile_complaints,
13731                  _("Multiple children of DIE 0x%x refer "
13732                    "to DIE 0x%x as their abstract origin"),
13733                  to_underlying (die->sect_off), to_underlying (*offsetp));
13734
13735   offsetp = offsets.data ();
13736   origin_child_die = origin_die->child;
13737   while (origin_child_die && origin_child_die->tag)
13738     {
13739       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13740       while (offsetp < offsets_end
13741              && *offsetp < origin_child_die->sect_off)
13742         offsetp++;
13743       if (offsetp >= offsets_end
13744           || *offsetp > origin_child_die->sect_off)
13745         {
13746           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13747              Check whether we're already processing ORIGIN_CHILD_DIE.
13748              This can happen with mutually referenced abstract_origins.
13749              PR 16581.  */
13750           if (!origin_child_die->in_process)
13751             process_die (origin_child_die, origin_cu);
13752         }
13753       origin_child_die = sibling_die (origin_child_die);
13754     }
13755   origin_cu->list_in_scope = origin_previous_list_in_scope;
13756 }
13757
13758 static void
13759 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13760 {
13761   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13762   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13763   struct context_stack *newobj;
13764   CORE_ADDR lowpc;
13765   CORE_ADDR highpc;
13766   struct die_info *child_die;
13767   struct attribute *attr, *call_line, *call_file;
13768   const char *name;
13769   CORE_ADDR baseaddr;
13770   struct block *block;
13771   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13772   std::vector<struct symbol *> template_args;
13773   struct template_symbol *templ_func = NULL;
13774
13775   if (inlined_func)
13776     {
13777       /* If we do not have call site information, we can't show the
13778          caller of this inlined function.  That's too confusing, so
13779          only use the scope for local variables.  */
13780       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13781       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13782       if (call_line == NULL || call_file == NULL)
13783         {
13784           read_lexical_block_scope (die, cu);
13785           return;
13786         }
13787     }
13788
13789   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13790
13791   name = dwarf2_name (die, cu);
13792
13793   /* Ignore functions with missing or empty names.  These are actually
13794      illegal according to the DWARF standard.  */
13795   if (name == NULL)
13796     {
13797       complaint (&symfile_complaints,
13798                  _("missing name for subprogram DIE at %d"),
13799                  to_underlying (die->sect_off));
13800       return;
13801     }
13802
13803   /* Ignore functions with missing or invalid low and high pc attributes.  */
13804   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13805       <= PC_BOUNDS_INVALID)
13806     {
13807       attr = dwarf2_attr (die, DW_AT_external, cu);
13808       if (!attr || !DW_UNSND (attr))
13809         complaint (&symfile_complaints,
13810                    _("cannot get low and high bounds "
13811                      "for subprogram DIE at %d"),
13812                    to_underlying (die->sect_off));
13813       return;
13814     }
13815
13816   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13817   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13818
13819   /* If we have any template arguments, then we must allocate a
13820      different sort of symbol.  */
13821   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13822     {
13823       if (child_die->tag == DW_TAG_template_type_param
13824           || child_die->tag == DW_TAG_template_value_param)
13825         {
13826           templ_func = allocate_template_symbol (objfile);
13827           templ_func->subclass = SYMBOL_TEMPLATE;
13828           break;
13829         }
13830     }
13831
13832   newobj = push_context (0, lowpc);
13833   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13834                              (struct symbol *) templ_func);
13835
13836   /* If there is a location expression for DW_AT_frame_base, record
13837      it.  */
13838   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13839   if (attr)
13840     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13841
13842   /* If there is a location for the static link, record it.  */
13843   newobj->static_link = NULL;
13844   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13845   if (attr)
13846     {
13847       newobj->static_link
13848         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13849       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13850     }
13851
13852   cu->list_in_scope = &local_symbols;
13853
13854   if (die->child != NULL)
13855     {
13856       child_die = die->child;
13857       while (child_die && child_die->tag)
13858         {
13859           if (child_die->tag == DW_TAG_template_type_param
13860               || child_die->tag == DW_TAG_template_value_param)
13861             {
13862               struct symbol *arg = new_symbol (child_die, NULL, cu);
13863
13864               if (arg != NULL)
13865                 template_args.push_back (arg);
13866             }
13867           else
13868             process_die (child_die, cu);
13869           child_die = sibling_die (child_die);
13870         }
13871     }
13872
13873   inherit_abstract_dies (die, cu);
13874
13875   /* If we have a DW_AT_specification, we might need to import using
13876      directives from the context of the specification DIE.  See the
13877      comment in determine_prefix.  */
13878   if (cu->language == language_cplus
13879       && dwarf2_attr (die, DW_AT_specification, cu))
13880     {
13881       struct dwarf2_cu *spec_cu = cu;
13882       struct die_info *spec_die = die_specification (die, &spec_cu);
13883
13884       while (spec_die)
13885         {
13886           child_die = spec_die->child;
13887           while (child_die && child_die->tag)
13888             {
13889               if (child_die->tag == DW_TAG_imported_module)
13890                 process_die (child_die, spec_cu);
13891               child_die = sibling_die (child_die);
13892             }
13893
13894           /* In some cases, GCC generates specification DIEs that
13895              themselves contain DW_AT_specification attributes.  */
13896           spec_die = die_specification (spec_die, &spec_cu);
13897         }
13898     }
13899
13900   newobj = pop_context ();
13901   /* Make a block for the local symbols within.  */
13902   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13903                         newobj->static_link, lowpc, highpc);
13904
13905   /* For C++, set the block's scope.  */
13906   if ((cu->language == language_cplus
13907        || cu->language == language_fortran
13908        || cu->language == language_d
13909        || cu->language == language_rust)
13910       && cu->processing_has_namespace_info)
13911     block_set_scope (block, determine_prefix (die, cu),
13912                      &objfile->objfile_obstack);
13913
13914   /* If we have address ranges, record them.  */
13915   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13916
13917   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13918
13919   /* Attach template arguments to function.  */
13920   if (!template_args.empty ())
13921     {
13922       gdb_assert (templ_func != NULL);
13923
13924       templ_func->n_template_arguments = template_args.size ();
13925       templ_func->template_arguments
13926         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13927                      templ_func->n_template_arguments);
13928       memcpy (templ_func->template_arguments,
13929               template_args.data (),
13930               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13931     }
13932
13933   /* In C++, we can have functions nested inside functions (e.g., when
13934      a function declares a class that has methods).  This means that
13935      when we finish processing a function scope, we may need to go
13936      back to building a containing block's symbol lists.  */
13937   local_symbols = newobj->locals;
13938   local_using_directives = newobj->local_using_directives;
13939
13940   /* If we've finished processing a top-level function, subsequent
13941      symbols go in the file symbol list.  */
13942   if (outermost_context_p ())
13943     cu->list_in_scope = &file_symbols;
13944 }
13945
13946 /* Process all the DIES contained within a lexical block scope.  Start
13947    a new scope, process the dies, and then close the scope.  */
13948
13949 static void
13950 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13951 {
13952   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13953   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13954   struct context_stack *newobj;
13955   CORE_ADDR lowpc, highpc;
13956   struct die_info *child_die;
13957   CORE_ADDR baseaddr;
13958
13959   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13960
13961   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13962   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13963      as multiple lexical blocks?  Handling children in a sane way would
13964      be nasty.  Might be easier to properly extend generic blocks to
13965      describe ranges.  */
13966   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13967     {
13968     case PC_BOUNDS_NOT_PRESENT:
13969       /* DW_TAG_lexical_block has no attributes, process its children as if
13970          there was no wrapping by that DW_TAG_lexical_block.
13971          GCC does no longer produces such DWARF since GCC r224161.  */
13972       for (child_die = die->child;
13973            child_die != NULL && child_die->tag;
13974            child_die = sibling_die (child_die))
13975         process_die (child_die, cu);
13976       return;
13977     case PC_BOUNDS_INVALID:
13978       return;
13979     }
13980   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13981   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13982
13983   push_context (0, lowpc);
13984   if (die->child != NULL)
13985     {
13986       child_die = die->child;
13987       while (child_die && child_die->tag)
13988         {
13989           process_die (child_die, cu);
13990           child_die = sibling_die (child_die);
13991         }
13992     }
13993   inherit_abstract_dies (die, cu);
13994   newobj = pop_context ();
13995
13996   if (local_symbols != NULL || local_using_directives != NULL)
13997     {
13998       struct block *block
13999         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14000                         newobj->start_addr, highpc);
14001
14002       /* Note that recording ranges after traversing children, as we
14003          do here, means that recording a parent's ranges entails
14004          walking across all its children's ranges as they appear in
14005          the address map, which is quadratic behavior.
14006
14007          It would be nicer to record the parent's ranges before
14008          traversing its children, simply overriding whatever you find
14009          there.  But since we don't even decide whether to create a
14010          block until after we've traversed its children, that's hard
14011          to do.  */
14012       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14013     }
14014   local_symbols = newobj->locals;
14015   local_using_directives = newobj->local_using_directives;
14016 }
14017
14018 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14019
14020 static void
14021 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14022 {
14023   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14024   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14025   CORE_ADDR pc, baseaddr;
14026   struct attribute *attr;
14027   struct call_site *call_site, call_site_local;
14028   void **slot;
14029   int nparams;
14030   struct die_info *child_die;
14031
14032   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14033
14034   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14035   if (attr == NULL)
14036     {
14037       /* This was a pre-DWARF-5 GNU extension alias
14038          for DW_AT_call_return_pc.  */
14039       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14040     }
14041   if (!attr)
14042     {
14043       complaint (&symfile_complaints,
14044                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14045                    "DIE 0x%x [in module %s]"),
14046                  to_underlying (die->sect_off), objfile_name (objfile));
14047       return;
14048     }
14049   pc = attr_value_as_address (attr) + baseaddr;
14050   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14051
14052   if (cu->call_site_htab == NULL)
14053     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14054                                                NULL, &objfile->objfile_obstack,
14055                                                hashtab_obstack_allocate, NULL);
14056   call_site_local.pc = pc;
14057   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14058   if (*slot != NULL)
14059     {
14060       complaint (&symfile_complaints,
14061                  _("Duplicate PC %s for DW_TAG_call_site "
14062                    "DIE 0x%x [in module %s]"),
14063                  paddress (gdbarch, pc), to_underlying (die->sect_off),
14064                  objfile_name (objfile));
14065       return;
14066     }
14067
14068   /* Count parameters at the caller.  */
14069
14070   nparams = 0;
14071   for (child_die = die->child; child_die && child_die->tag;
14072        child_die = sibling_die (child_die))
14073     {
14074       if (child_die->tag != DW_TAG_call_site_parameter
14075           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14076         {
14077           complaint (&symfile_complaints,
14078                      _("Tag %d is not DW_TAG_call_site_parameter in "
14079                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14080                      child_die->tag, to_underlying (child_die->sect_off),
14081                      objfile_name (objfile));
14082           continue;
14083         }
14084
14085       nparams++;
14086     }
14087
14088   call_site
14089     = ((struct call_site *)
14090        obstack_alloc (&objfile->objfile_obstack,
14091                       sizeof (*call_site)
14092                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14093   *slot = call_site;
14094   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14095   call_site->pc = pc;
14096
14097   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14098       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14099     {
14100       struct die_info *func_die;
14101
14102       /* Skip also over DW_TAG_inlined_subroutine.  */
14103       for (func_die = die->parent;
14104            func_die && func_die->tag != DW_TAG_subprogram
14105            && func_die->tag != DW_TAG_subroutine_type;
14106            func_die = func_die->parent);
14107
14108       /* DW_AT_call_all_calls is a superset
14109          of DW_AT_call_all_tail_calls.  */
14110       if (func_die
14111           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14112           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14113           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14114           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14115         {
14116           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14117              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14118              both the initial caller containing the real return address PC and
14119              the final callee containing the current PC of a chain of tail
14120              calls do not need to have the tail call list complete.  But any
14121              function candidate for a virtual tail call frame searched via
14122              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14123              determined unambiguously.  */
14124         }
14125       else
14126         {
14127           struct type *func_type = NULL;
14128
14129           if (func_die)
14130             func_type = get_die_type (func_die, cu);
14131           if (func_type != NULL)
14132             {
14133               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14134
14135               /* Enlist this call site to the function.  */
14136               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14137               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14138             }
14139           else
14140             complaint (&symfile_complaints,
14141                        _("Cannot find function owning DW_TAG_call_site "
14142                          "DIE 0x%x [in module %s]"),
14143                        to_underlying (die->sect_off), objfile_name (objfile));
14144         }
14145     }
14146
14147   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14148   if (attr == NULL)
14149     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14150   if (attr == NULL)
14151     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14152   if (attr == NULL)
14153     {
14154       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14155       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14156     }
14157   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14158   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14159     /* Keep NULL DWARF_BLOCK.  */;
14160   else if (attr_form_is_block (attr))
14161     {
14162       struct dwarf2_locexpr_baton *dlbaton;
14163
14164       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14165       dlbaton->data = DW_BLOCK (attr)->data;
14166       dlbaton->size = DW_BLOCK (attr)->size;
14167       dlbaton->per_cu = cu->per_cu;
14168
14169       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14170     }
14171   else if (attr_form_is_ref (attr))
14172     {
14173       struct dwarf2_cu *target_cu = cu;
14174       struct die_info *target_die;
14175
14176       target_die = follow_die_ref (die, attr, &target_cu);
14177       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14178       if (die_is_declaration (target_die, target_cu))
14179         {
14180           const char *target_physname;
14181
14182           /* Prefer the mangled name; otherwise compute the demangled one.  */
14183           target_physname = dw2_linkage_name (target_die, target_cu);
14184           if (target_physname == NULL)
14185             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14186           if (target_physname == NULL)
14187             complaint (&symfile_complaints,
14188                        _("DW_AT_call_target target DIE has invalid "
14189                          "physname, for referencing DIE 0x%x [in module %s]"),
14190                        to_underlying (die->sect_off), objfile_name (objfile));
14191           else
14192             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14193         }
14194       else
14195         {
14196           CORE_ADDR lowpc;
14197
14198           /* DW_AT_entry_pc should be preferred.  */
14199           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14200               <= PC_BOUNDS_INVALID)
14201             complaint (&symfile_complaints,
14202                        _("DW_AT_call_target target DIE has invalid "
14203                          "low pc, for referencing DIE 0x%x [in module %s]"),
14204                        to_underlying (die->sect_off), objfile_name (objfile));
14205           else
14206             {
14207               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14208               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14209             }
14210         }
14211     }
14212   else
14213     complaint (&symfile_complaints,
14214                _("DW_TAG_call_site DW_AT_call_target is neither "
14215                  "block nor reference, for DIE 0x%x [in module %s]"),
14216                to_underlying (die->sect_off), objfile_name (objfile));
14217
14218   call_site->per_cu = cu->per_cu;
14219
14220   for (child_die = die->child;
14221        child_die && child_die->tag;
14222        child_die = sibling_die (child_die))
14223     {
14224       struct call_site_parameter *parameter;
14225       struct attribute *loc, *origin;
14226
14227       if (child_die->tag != DW_TAG_call_site_parameter
14228           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14229         {
14230           /* Already printed the complaint above.  */
14231           continue;
14232         }
14233
14234       gdb_assert (call_site->parameter_count < nparams);
14235       parameter = &call_site->parameter[call_site->parameter_count];
14236
14237       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14238          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14239          register is contained in DW_AT_call_value.  */
14240
14241       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14242       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14243       if (origin == NULL)
14244         {
14245           /* This was a pre-DWARF-5 GNU extension alias
14246              for DW_AT_call_parameter.  */
14247           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14248         }
14249       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14250         {
14251           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14252
14253           sect_offset sect_off
14254             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14255           if (!offset_in_cu_p (&cu->header, sect_off))
14256             {
14257               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14258                  binding can be done only inside one CU.  Such referenced DIE
14259                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14260               complaint (&symfile_complaints,
14261                          _("DW_AT_call_parameter offset is not in CU for "
14262                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14263                          to_underlying (child_die->sect_off),
14264                          objfile_name (objfile));
14265               continue;
14266             }
14267           parameter->u.param_cu_off
14268             = (cu_offset) (sect_off - cu->header.sect_off);
14269         }
14270       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14271         {
14272           complaint (&symfile_complaints,
14273                      _("No DW_FORM_block* DW_AT_location for "
14274                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14275                      to_underlying (child_die->sect_off), objfile_name (objfile));
14276           continue;
14277         }
14278       else
14279         {
14280           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14281             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14282           if (parameter->u.dwarf_reg != -1)
14283             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14284           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14285                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14286                                              &parameter->u.fb_offset))
14287             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14288           else
14289             {
14290               complaint (&symfile_complaints,
14291                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14292                            "for DW_FORM_block* DW_AT_location is supported for "
14293                            "DW_TAG_call_site child DIE 0x%x "
14294                            "[in module %s]"),
14295                          to_underlying (child_die->sect_off),
14296                          objfile_name (objfile));
14297               continue;
14298             }
14299         }
14300
14301       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14302       if (attr == NULL)
14303         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14304       if (!attr_form_is_block (attr))
14305         {
14306           complaint (&symfile_complaints,
14307                      _("No DW_FORM_block* DW_AT_call_value for "
14308                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14309                      to_underlying (child_die->sect_off),
14310                      objfile_name (objfile));
14311           continue;
14312         }
14313       parameter->value = DW_BLOCK (attr)->data;
14314       parameter->value_size = DW_BLOCK (attr)->size;
14315
14316       /* Parameters are not pre-cleared by memset above.  */
14317       parameter->data_value = NULL;
14318       parameter->data_value_size = 0;
14319       call_site->parameter_count++;
14320
14321       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14322       if (attr == NULL)
14323         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14324       if (attr)
14325         {
14326           if (!attr_form_is_block (attr))
14327             complaint (&symfile_complaints,
14328                        _("No DW_FORM_block* DW_AT_call_data_value for "
14329                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14330                        to_underlying (child_die->sect_off),
14331                        objfile_name (objfile));
14332           else
14333             {
14334               parameter->data_value = DW_BLOCK (attr)->data;
14335               parameter->data_value_size = DW_BLOCK (attr)->size;
14336             }
14337         }
14338     }
14339 }
14340
14341 /* Helper function for read_variable.  If DIE represents a virtual
14342    table, then return the type of the concrete object that is
14343    associated with the virtual table.  Otherwise, return NULL.  */
14344
14345 static struct type *
14346 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14347 {
14348   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14349   if (attr == NULL)
14350     return NULL;
14351
14352   /* Find the type DIE.  */
14353   struct die_info *type_die = NULL;
14354   struct dwarf2_cu *type_cu = cu;
14355
14356   if (attr_form_is_ref (attr))
14357     type_die = follow_die_ref (die, attr, &type_cu);
14358   if (type_die == NULL)
14359     return NULL;
14360
14361   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14362     return NULL;
14363   return die_containing_type (type_die, type_cu);
14364 }
14365
14366 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14367
14368 static void
14369 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14370 {
14371   struct rust_vtable_symbol *storage = NULL;
14372
14373   if (cu->language == language_rust)
14374     {
14375       struct type *containing_type = rust_containing_type (die, cu);
14376
14377       if (containing_type != NULL)
14378         {
14379           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14380
14381           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14382                                     struct rust_vtable_symbol);
14383           initialize_objfile_symbol (storage);
14384           storage->concrete_type = containing_type;
14385           storage->subclass = SYMBOL_RUST_VTABLE;
14386         }
14387     }
14388
14389   new_symbol (die, NULL, cu, storage);
14390 }
14391
14392 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14393    reading .debug_rnglists.
14394    Callback's type should be:
14395     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14396    Return true if the attributes are present and valid, otherwise,
14397    return false.  */
14398
14399 template <typename Callback>
14400 static bool
14401 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14402                          Callback &&callback)
14403 {
14404   struct dwarf2_per_objfile *dwarf2_per_objfile
14405     = cu->per_cu->dwarf2_per_objfile;
14406   struct objfile *objfile = dwarf2_per_objfile->objfile;
14407   bfd *obfd = objfile->obfd;
14408   /* Base address selection entry.  */
14409   CORE_ADDR base;
14410   int found_base;
14411   const gdb_byte *buffer;
14412   CORE_ADDR baseaddr;
14413   bool overflow = false;
14414
14415   found_base = cu->base_known;
14416   base = cu->base_address;
14417
14418   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14419   if (offset >= dwarf2_per_objfile->rnglists.size)
14420     {
14421       complaint (&symfile_complaints,
14422                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14423                  offset);
14424       return false;
14425     }
14426   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14427
14428   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14429
14430   while (1)
14431     {
14432       /* Initialize it due to a false compiler warning.  */
14433       CORE_ADDR range_beginning = 0, range_end = 0;
14434       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14435                                  + dwarf2_per_objfile->rnglists.size);
14436       unsigned int bytes_read;
14437
14438       if (buffer == buf_end)
14439         {
14440           overflow = true;
14441           break;
14442         }
14443       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14444       switch (rlet)
14445         {
14446         case DW_RLE_end_of_list:
14447           break;
14448         case DW_RLE_base_address:
14449           if (buffer + cu->header.addr_size > buf_end)
14450             {
14451               overflow = true;
14452               break;
14453             }
14454           base = read_address (obfd, buffer, cu, &bytes_read);
14455           found_base = 1;
14456           buffer += bytes_read;
14457           break;
14458         case DW_RLE_start_length:
14459           if (buffer + cu->header.addr_size > buf_end)
14460             {
14461               overflow = true;
14462               break;
14463             }
14464           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14465           buffer += bytes_read;
14466           range_end = (range_beginning
14467                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14468           buffer += bytes_read;
14469           if (buffer > buf_end)
14470             {
14471               overflow = true;
14472               break;
14473             }
14474           break;
14475         case DW_RLE_offset_pair:
14476           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14477           buffer += bytes_read;
14478           if (buffer > buf_end)
14479             {
14480               overflow = true;
14481               break;
14482             }
14483           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14484           buffer += bytes_read;
14485           if (buffer > buf_end)
14486             {
14487               overflow = true;
14488               break;
14489             }
14490           break;
14491         case DW_RLE_start_end:
14492           if (buffer + 2 * cu->header.addr_size > buf_end)
14493             {
14494               overflow = true;
14495               break;
14496             }
14497           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14498           buffer += bytes_read;
14499           range_end = read_address (obfd, buffer, cu, &bytes_read);
14500           buffer += bytes_read;
14501           break;
14502         default:
14503           complaint (&symfile_complaints,
14504                      _("Invalid .debug_rnglists data (no base address)"));
14505           return false;
14506         }
14507       if (rlet == DW_RLE_end_of_list || overflow)
14508         break;
14509       if (rlet == DW_RLE_base_address)
14510         continue;
14511
14512       if (!found_base)
14513         {
14514           /* We have no valid base address for the ranges
14515              data.  */
14516           complaint (&symfile_complaints,
14517                      _("Invalid .debug_rnglists data (no base address)"));
14518           return false;
14519         }
14520
14521       if (range_beginning > range_end)
14522         {
14523           /* Inverted range entries are invalid.  */
14524           complaint (&symfile_complaints,
14525                      _("Invalid .debug_rnglists data (inverted range)"));
14526           return false;
14527         }
14528
14529       /* Empty range entries have no effect.  */
14530       if (range_beginning == range_end)
14531         continue;
14532
14533       range_beginning += base;
14534       range_end += base;
14535
14536       /* A not-uncommon case of bad debug info.
14537          Don't pollute the addrmap with bad data.  */
14538       if (range_beginning + baseaddr == 0
14539           && !dwarf2_per_objfile->has_section_at_zero)
14540         {
14541           complaint (&symfile_complaints,
14542                      _(".debug_rnglists entry has start address of zero"
14543                        " [in module %s]"), objfile_name (objfile));
14544           continue;
14545         }
14546
14547       callback (range_beginning, range_end);
14548     }
14549
14550   if (overflow)
14551     {
14552       complaint (&symfile_complaints,
14553                  _("Offset %d is not terminated "
14554                    "for DW_AT_ranges attribute"),
14555                  offset);
14556       return false;
14557     }
14558
14559   return true;
14560 }
14561
14562 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14563    Callback's type should be:
14564     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14565    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14566
14567 template <typename Callback>
14568 static int
14569 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14570                        Callback &&callback)
14571 {
14572   struct dwarf2_per_objfile *dwarf2_per_objfile
14573       = cu->per_cu->dwarf2_per_objfile;
14574   struct objfile *objfile = dwarf2_per_objfile->objfile;
14575   struct comp_unit_head *cu_header = &cu->header;
14576   bfd *obfd = objfile->obfd;
14577   unsigned int addr_size = cu_header->addr_size;
14578   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14579   /* Base address selection entry.  */
14580   CORE_ADDR base;
14581   int found_base;
14582   unsigned int dummy;
14583   const gdb_byte *buffer;
14584   CORE_ADDR baseaddr;
14585
14586   if (cu_header->version >= 5)
14587     return dwarf2_rnglists_process (offset, cu, callback);
14588
14589   found_base = cu->base_known;
14590   base = cu->base_address;
14591
14592   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14593   if (offset >= dwarf2_per_objfile->ranges.size)
14594     {
14595       complaint (&symfile_complaints,
14596                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14597                  offset);
14598       return 0;
14599     }
14600   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14601
14602   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14603
14604   while (1)
14605     {
14606       CORE_ADDR range_beginning, range_end;
14607
14608       range_beginning = read_address (obfd, buffer, cu, &dummy);
14609       buffer += addr_size;
14610       range_end = read_address (obfd, buffer, cu, &dummy);
14611       buffer += addr_size;
14612       offset += 2 * addr_size;
14613
14614       /* An end of list marker is a pair of zero addresses.  */
14615       if (range_beginning == 0 && range_end == 0)
14616         /* Found the end of list entry.  */
14617         break;
14618
14619       /* Each base address selection entry is a pair of 2 values.
14620          The first is the largest possible address, the second is
14621          the base address.  Check for a base address here.  */
14622       if ((range_beginning & mask) == mask)
14623         {
14624           /* If we found the largest possible address, then we already
14625              have the base address in range_end.  */
14626           base = range_end;
14627           found_base = 1;
14628           continue;
14629         }
14630
14631       if (!found_base)
14632         {
14633           /* We have no valid base address for the ranges
14634              data.  */
14635           complaint (&symfile_complaints,
14636                      _("Invalid .debug_ranges data (no base address)"));
14637           return 0;
14638         }
14639
14640       if (range_beginning > range_end)
14641         {
14642           /* Inverted range entries are invalid.  */
14643           complaint (&symfile_complaints,
14644                      _("Invalid .debug_ranges data (inverted range)"));
14645           return 0;
14646         }
14647
14648       /* Empty range entries have no effect.  */
14649       if (range_beginning == range_end)
14650         continue;
14651
14652       range_beginning += base;
14653       range_end += base;
14654
14655       /* A not-uncommon case of bad debug info.
14656          Don't pollute the addrmap with bad data.  */
14657       if (range_beginning + baseaddr == 0
14658           && !dwarf2_per_objfile->has_section_at_zero)
14659         {
14660           complaint (&symfile_complaints,
14661                      _(".debug_ranges entry has start address of zero"
14662                        " [in module %s]"), objfile_name (objfile));
14663           continue;
14664         }
14665
14666       callback (range_beginning, range_end);
14667     }
14668
14669   return 1;
14670 }
14671
14672 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14673    Return 1 if the attributes are present and valid, otherwise, return 0.
14674    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14675
14676 static int
14677 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14678                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14679                     struct partial_symtab *ranges_pst)
14680 {
14681   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14682   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14683   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14684                                        SECT_OFF_TEXT (objfile));
14685   int low_set = 0;
14686   CORE_ADDR low = 0;
14687   CORE_ADDR high = 0;
14688   int retval;
14689
14690   retval = dwarf2_ranges_process (offset, cu,
14691     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14692     {
14693       if (ranges_pst != NULL)
14694         {
14695           CORE_ADDR lowpc;
14696           CORE_ADDR highpc;
14697
14698           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14699                                               range_beginning + baseaddr);
14700           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14701                                                range_end + baseaddr);
14702           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14703                              ranges_pst);
14704         }
14705
14706       /* FIXME: This is recording everything as a low-high
14707          segment of consecutive addresses.  We should have a
14708          data structure for discontiguous block ranges
14709          instead.  */
14710       if (! low_set)
14711         {
14712           low = range_beginning;
14713           high = range_end;
14714           low_set = 1;
14715         }
14716       else
14717         {
14718           if (range_beginning < low)
14719             low = range_beginning;
14720           if (range_end > high)
14721             high = range_end;
14722         }
14723     });
14724   if (!retval)
14725     return 0;
14726
14727   if (! low_set)
14728     /* If the first entry is an end-of-list marker, the range
14729        describes an empty scope, i.e. no instructions.  */
14730     return 0;
14731
14732   if (low_return)
14733     *low_return = low;
14734   if (high_return)
14735     *high_return = high;
14736   return 1;
14737 }
14738
14739 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14740    definition for the return value.  *LOWPC and *HIGHPC are set iff
14741    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14742
14743 static enum pc_bounds_kind
14744 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14745                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14746                       struct partial_symtab *pst)
14747 {
14748   struct dwarf2_per_objfile *dwarf2_per_objfile
14749     = cu->per_cu->dwarf2_per_objfile;
14750   struct attribute *attr;
14751   struct attribute *attr_high;
14752   CORE_ADDR low = 0;
14753   CORE_ADDR high = 0;
14754   enum pc_bounds_kind ret;
14755
14756   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14757   if (attr_high)
14758     {
14759       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14760       if (attr)
14761         {
14762           low = attr_value_as_address (attr);
14763           high = attr_value_as_address (attr_high);
14764           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14765             high += low;
14766         }
14767       else
14768         /* Found high w/o low attribute.  */
14769         return PC_BOUNDS_INVALID;
14770
14771       /* Found consecutive range of addresses.  */
14772       ret = PC_BOUNDS_HIGH_LOW;
14773     }
14774   else
14775     {
14776       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14777       if (attr != NULL)
14778         {
14779           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14780              We take advantage of the fact that DW_AT_ranges does not appear
14781              in DW_TAG_compile_unit of DWO files.  */
14782           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14783           unsigned int ranges_offset = (DW_UNSND (attr)
14784                                         + (need_ranges_base
14785                                            ? cu->ranges_base
14786                                            : 0));
14787
14788           /* Value of the DW_AT_ranges attribute is the offset in the
14789              .debug_ranges section.  */
14790           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14791             return PC_BOUNDS_INVALID;
14792           /* Found discontinuous range of addresses.  */
14793           ret = PC_BOUNDS_RANGES;
14794         }
14795       else
14796         return PC_BOUNDS_NOT_PRESENT;
14797     }
14798
14799   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14800   if (high <= low)
14801     return PC_BOUNDS_INVALID;
14802
14803   /* When using the GNU linker, .gnu.linkonce. sections are used to
14804      eliminate duplicate copies of functions and vtables and such.
14805      The linker will arbitrarily choose one and discard the others.
14806      The AT_*_pc values for such functions refer to local labels in
14807      these sections.  If the section from that file was discarded, the
14808      labels are not in the output, so the relocs get a value of 0.
14809      If this is a discarded function, mark the pc bounds as invalid,
14810      so that GDB will ignore it.  */
14811   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14812     return PC_BOUNDS_INVALID;
14813
14814   *lowpc = low;
14815   if (highpc)
14816     *highpc = high;
14817   return ret;
14818 }
14819
14820 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14821    its low and high PC addresses.  Do nothing if these addresses could not
14822    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14823    and HIGHPC to the high address if greater than HIGHPC.  */
14824
14825 static void
14826 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14827                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14828                                  struct dwarf2_cu *cu)
14829 {
14830   CORE_ADDR low, high;
14831   struct die_info *child = die->child;
14832
14833   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14834     {
14835       *lowpc = std::min (*lowpc, low);
14836       *highpc = std::max (*highpc, high);
14837     }
14838
14839   /* If the language does not allow nested subprograms (either inside
14840      subprograms or lexical blocks), we're done.  */
14841   if (cu->language != language_ada)
14842     return;
14843
14844   /* Check all the children of the given DIE.  If it contains nested
14845      subprograms, then check their pc bounds.  Likewise, we need to
14846      check lexical blocks as well, as they may also contain subprogram
14847      definitions.  */
14848   while (child && child->tag)
14849     {
14850       if (child->tag == DW_TAG_subprogram
14851           || child->tag == DW_TAG_lexical_block)
14852         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14853       child = sibling_die (child);
14854     }
14855 }
14856
14857 /* Get the low and high pc's represented by the scope DIE, and store
14858    them in *LOWPC and *HIGHPC.  If the correct values can't be
14859    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14860
14861 static void
14862 get_scope_pc_bounds (struct die_info *die,
14863                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14864                      struct dwarf2_cu *cu)
14865 {
14866   CORE_ADDR best_low = (CORE_ADDR) -1;
14867   CORE_ADDR best_high = (CORE_ADDR) 0;
14868   CORE_ADDR current_low, current_high;
14869
14870   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14871       >= PC_BOUNDS_RANGES)
14872     {
14873       best_low = current_low;
14874       best_high = current_high;
14875     }
14876   else
14877     {
14878       struct die_info *child = die->child;
14879
14880       while (child && child->tag)
14881         {
14882           switch (child->tag) {
14883           case DW_TAG_subprogram:
14884             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14885             break;
14886           case DW_TAG_namespace:
14887           case DW_TAG_module:
14888             /* FIXME: carlton/2004-01-16: Should we do this for
14889                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14890                that current GCC's always emit the DIEs corresponding
14891                to definitions of methods of classes as children of a
14892                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14893                the DIEs giving the declarations, which could be
14894                anywhere).  But I don't see any reason why the
14895                standards says that they have to be there.  */
14896             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14897
14898             if (current_low != ((CORE_ADDR) -1))
14899               {
14900                 best_low = std::min (best_low, current_low);
14901                 best_high = std::max (best_high, current_high);
14902               }
14903             break;
14904           default:
14905             /* Ignore.  */
14906             break;
14907           }
14908
14909           child = sibling_die (child);
14910         }
14911     }
14912
14913   *lowpc = best_low;
14914   *highpc = best_high;
14915 }
14916
14917 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14918    in DIE.  */
14919
14920 static void
14921 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14922                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14923 {
14924   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14925   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14926   struct attribute *attr;
14927   struct attribute *attr_high;
14928
14929   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14930   if (attr_high)
14931     {
14932       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14933       if (attr)
14934         {
14935           CORE_ADDR low = attr_value_as_address (attr);
14936           CORE_ADDR high = attr_value_as_address (attr_high);
14937
14938           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14939             high += low;
14940
14941           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14942           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14943           record_block_range (block, low, high - 1);
14944         }
14945     }
14946
14947   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14948   if (attr)
14949     {
14950       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14951          We take advantage of the fact that DW_AT_ranges does not appear
14952          in DW_TAG_compile_unit of DWO files.  */
14953       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14954
14955       /* The value of the DW_AT_ranges attribute is the offset of the
14956          address range list in the .debug_ranges section.  */
14957       unsigned long offset = (DW_UNSND (attr)
14958                               + (need_ranges_base ? cu->ranges_base : 0));
14959       const gdb_byte *buffer;
14960
14961       /* For some target architectures, but not others, the
14962          read_address function sign-extends the addresses it returns.
14963          To recognize base address selection entries, we need a
14964          mask.  */
14965       unsigned int addr_size = cu->header.addr_size;
14966       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14967
14968       /* The base address, to which the next pair is relative.  Note
14969          that this 'base' is a DWARF concept: most entries in a range
14970          list are relative, to reduce the number of relocs against the
14971          debugging information.  This is separate from this function's
14972          'baseaddr' argument, which GDB uses to relocate debugging
14973          information from a shared library based on the address at
14974          which the library was loaded.  */
14975       CORE_ADDR base = cu->base_address;
14976       int base_known = cu->base_known;
14977
14978       dwarf2_ranges_process (offset, cu,
14979         [&] (CORE_ADDR start, CORE_ADDR end)
14980         {
14981           start += baseaddr;
14982           end += baseaddr;
14983           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14984           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14985           record_block_range (block, start, end - 1);
14986         });
14987     }
14988 }
14989
14990 /* Check whether the producer field indicates either of GCC < 4.6, or the
14991    Intel C/C++ compiler, and cache the result in CU.  */
14992
14993 static void
14994 check_producer (struct dwarf2_cu *cu)
14995 {
14996   int major, minor;
14997
14998   if (cu->producer == NULL)
14999     {
15000       /* For unknown compilers expect their behavior is DWARF version
15001          compliant.
15002
15003          GCC started to support .debug_types sections by -gdwarf-4 since
15004          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15005          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15006          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15007          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15008     }
15009   else if (producer_is_gcc (cu->producer, &major, &minor))
15010     {
15011       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15012       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15013     }
15014   else if (producer_is_icc (cu->producer, &major, &minor))
15015     cu->producer_is_icc_lt_14 = major < 14;
15016   else
15017     {
15018       /* For other non-GCC compilers, expect their behavior is DWARF version
15019          compliant.  */
15020     }
15021
15022   cu->checked_producer = 1;
15023 }
15024
15025 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15026    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15027    during 4.6.0 experimental.  */
15028
15029 static int
15030 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15031 {
15032   if (!cu->checked_producer)
15033     check_producer (cu);
15034
15035   return cu->producer_is_gxx_lt_4_6;
15036 }
15037
15038 /* Return the default accessibility type if it is not overriden by
15039    DW_AT_accessibility.  */
15040
15041 static enum dwarf_access_attribute
15042 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15043 {
15044   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15045     {
15046       /* The default DWARF 2 accessibility for members is public, the default
15047          accessibility for inheritance is private.  */
15048
15049       if (die->tag != DW_TAG_inheritance)
15050         return DW_ACCESS_public;
15051       else
15052         return DW_ACCESS_private;
15053     }
15054   else
15055     {
15056       /* DWARF 3+ defines the default accessibility a different way.  The same
15057          rules apply now for DW_TAG_inheritance as for the members and it only
15058          depends on the container kind.  */
15059
15060       if (die->parent->tag == DW_TAG_class_type)
15061         return DW_ACCESS_private;
15062       else
15063         return DW_ACCESS_public;
15064     }
15065 }
15066
15067 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15068    offset.  If the attribute was not found return 0, otherwise return
15069    1.  If it was found but could not properly be handled, set *OFFSET
15070    to 0.  */
15071
15072 static int
15073 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15074                              LONGEST *offset)
15075 {
15076   struct attribute *attr;
15077
15078   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15079   if (attr != NULL)
15080     {
15081       *offset = 0;
15082
15083       /* Note that we do not check for a section offset first here.
15084          This is because DW_AT_data_member_location is new in DWARF 4,
15085          so if we see it, we can assume that a constant form is really
15086          a constant and not a section offset.  */
15087       if (attr_form_is_constant (attr))
15088         *offset = dwarf2_get_attr_constant_value (attr, 0);
15089       else if (attr_form_is_section_offset (attr))
15090         dwarf2_complex_location_expr_complaint ();
15091       else if (attr_form_is_block (attr))
15092         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15093       else
15094         dwarf2_complex_location_expr_complaint ();
15095
15096       return 1;
15097     }
15098
15099   return 0;
15100 }
15101
15102 /* Add an aggregate field to the field list.  */
15103
15104 static void
15105 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15106                   struct dwarf2_cu *cu)
15107 {
15108   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15109   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15110   struct nextfield *new_field;
15111   struct attribute *attr;
15112   struct field *fp;
15113   const char *fieldname = "";
15114
15115   /* Allocate a new field list entry and link it in.  */
15116   new_field = XNEW (struct nextfield);
15117   make_cleanup (xfree, new_field);
15118   memset (new_field, 0, sizeof (struct nextfield));
15119
15120   if (die->tag == DW_TAG_inheritance)
15121     {
15122       new_field->next = fip->baseclasses;
15123       fip->baseclasses = new_field;
15124     }
15125   else
15126     {
15127       new_field->next = fip->fields;
15128       fip->fields = new_field;
15129     }
15130   fip->nfields++;
15131
15132   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15133   if (attr)
15134     new_field->accessibility = DW_UNSND (attr);
15135   else
15136     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15137   if (new_field->accessibility != DW_ACCESS_public)
15138     fip->non_public_fields = 1;
15139
15140   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15141   if (attr)
15142     new_field->virtuality = DW_UNSND (attr);
15143   else
15144     new_field->virtuality = DW_VIRTUALITY_none;
15145
15146   fp = &new_field->field;
15147
15148   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15149     {
15150       LONGEST offset;
15151
15152       /* Data member other than a C++ static data member.  */
15153
15154       /* Get type of field.  */
15155       fp->type = die_type (die, cu);
15156
15157       SET_FIELD_BITPOS (*fp, 0);
15158
15159       /* Get bit size of field (zero if none).  */
15160       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15161       if (attr)
15162         {
15163           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15164         }
15165       else
15166         {
15167           FIELD_BITSIZE (*fp) = 0;
15168         }
15169
15170       /* Get bit offset of field.  */
15171       if (handle_data_member_location (die, cu, &offset))
15172         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15173       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15174       if (attr)
15175         {
15176           if (gdbarch_bits_big_endian (gdbarch))
15177             {
15178               /* For big endian bits, the DW_AT_bit_offset gives the
15179                  additional bit offset from the MSB of the containing
15180                  anonymous object to the MSB of the field.  We don't
15181                  have to do anything special since we don't need to
15182                  know the size of the anonymous object.  */
15183               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15184             }
15185           else
15186             {
15187               /* For little endian bits, compute the bit offset to the
15188                  MSB of the anonymous object, subtract off the number of
15189                  bits from the MSB of the field to the MSB of the
15190                  object, and then subtract off the number of bits of
15191                  the field itself.  The result is the bit offset of
15192                  the LSB of the field.  */
15193               int anonymous_size;
15194               int bit_offset = DW_UNSND (attr);
15195
15196               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15197               if (attr)
15198                 {
15199                   /* The size of the anonymous object containing
15200                      the bit field is explicit, so use the
15201                      indicated size (in bytes).  */
15202                   anonymous_size = DW_UNSND (attr);
15203                 }
15204               else
15205                 {
15206                   /* The size of the anonymous object containing
15207                      the bit field must be inferred from the type
15208                      attribute of the data member containing the
15209                      bit field.  */
15210                   anonymous_size = TYPE_LENGTH (fp->type);
15211                 }
15212               SET_FIELD_BITPOS (*fp,
15213                                 (FIELD_BITPOS (*fp)
15214                                  + anonymous_size * bits_per_byte
15215                                  - bit_offset - FIELD_BITSIZE (*fp)));
15216             }
15217         }
15218       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15219       if (attr != NULL)
15220         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15221                                 + dwarf2_get_attr_constant_value (attr, 0)));
15222
15223       /* Get name of field.  */
15224       fieldname = dwarf2_name (die, cu);
15225       if (fieldname == NULL)
15226         fieldname = "";
15227
15228       /* The name is already allocated along with this objfile, so we don't
15229          need to duplicate it for the type.  */
15230       fp->name = fieldname;
15231
15232       /* Change accessibility for artificial fields (e.g. virtual table
15233          pointer or virtual base class pointer) to private.  */
15234       if (dwarf2_attr (die, DW_AT_artificial, cu))
15235         {
15236           FIELD_ARTIFICIAL (*fp) = 1;
15237           new_field->accessibility = DW_ACCESS_private;
15238           fip->non_public_fields = 1;
15239         }
15240     }
15241   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15242     {
15243       /* C++ static member.  */
15244
15245       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15246          is a declaration, but all versions of G++ as of this writing
15247          (so through at least 3.2.1) incorrectly generate
15248          DW_TAG_variable tags.  */
15249
15250       const char *physname;
15251
15252       /* Get name of field.  */
15253       fieldname = dwarf2_name (die, cu);
15254       if (fieldname == NULL)
15255         return;
15256
15257       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15258       if (attr
15259           /* Only create a symbol if this is an external value.
15260              new_symbol checks this and puts the value in the global symbol
15261              table, which we want.  If it is not external, new_symbol
15262              will try to put the value in cu->list_in_scope which is wrong.  */
15263           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15264         {
15265           /* A static const member, not much different than an enum as far as
15266              we're concerned, except that we can support more types.  */
15267           new_symbol (die, NULL, cu);
15268         }
15269
15270       /* Get physical name.  */
15271       physname = dwarf2_physname (fieldname, die, cu);
15272
15273       /* The name is already allocated along with this objfile, so we don't
15274          need to duplicate it for the type.  */
15275       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15276       FIELD_TYPE (*fp) = die_type (die, cu);
15277       FIELD_NAME (*fp) = fieldname;
15278     }
15279   else if (die->tag == DW_TAG_inheritance)
15280     {
15281       LONGEST offset;
15282
15283       /* C++ base class field.  */
15284       if (handle_data_member_location (die, cu, &offset))
15285         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15286       FIELD_BITSIZE (*fp) = 0;
15287       FIELD_TYPE (*fp) = die_type (die, cu);
15288       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15289       fip->nbaseclasses++;
15290     }
15291 }
15292
15293 /* Can the type given by DIE define another type?  */
15294
15295 static bool
15296 type_can_define_types (const struct die_info *die)
15297 {
15298   switch (die->tag)
15299     {
15300     case DW_TAG_typedef:
15301     case DW_TAG_class_type:
15302     case DW_TAG_structure_type:
15303     case DW_TAG_union_type:
15304     case DW_TAG_enumeration_type:
15305       return true;
15306
15307     default:
15308       return false;
15309     }
15310 }
15311
15312 /* Add a type definition defined in the scope of the FIP's class.  */
15313
15314 static void
15315 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15316                       struct dwarf2_cu *cu)
15317 {
15318   struct decl_field_list *new_field;
15319   struct decl_field *fp;
15320
15321   /* Allocate a new field list entry and link it in.  */
15322   new_field = XCNEW (struct decl_field_list);
15323   make_cleanup (xfree, new_field);
15324
15325   gdb_assert (type_can_define_types (die));
15326
15327   fp = &new_field->field;
15328
15329   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15330   fp->name = dwarf2_name (die, cu);
15331   fp->type = read_type_die (die, cu);
15332
15333   /* Save accessibility.  */
15334   enum dwarf_access_attribute accessibility;
15335   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15336   if (attr != NULL)
15337     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15338   else
15339     accessibility = dwarf2_default_access_attribute (die, cu);
15340   switch (accessibility)
15341     {
15342     case DW_ACCESS_public:
15343       /* The assumed value if neither private nor protected.  */
15344       break;
15345     case DW_ACCESS_private:
15346       fp->is_private = 1;
15347       break;
15348     case DW_ACCESS_protected:
15349       fp->is_protected = 1;
15350       break;
15351     default:
15352       complaint (&symfile_complaints,
15353                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15354     }
15355
15356   if (die->tag == DW_TAG_typedef)
15357     {
15358       new_field->next = fip->typedef_field_list;
15359       fip->typedef_field_list = new_field;
15360       fip->typedef_field_list_count++;
15361     }
15362   else
15363     {
15364       new_field->next = fip->nested_types_list;
15365       fip->nested_types_list = new_field;
15366       fip->nested_types_list_count++;
15367     }
15368 }
15369
15370 /* Create the vector of fields, and attach it to the type.  */
15371
15372 static void
15373 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15374                               struct dwarf2_cu *cu)
15375 {
15376   int nfields = fip->nfields;
15377
15378   /* Record the field count, allocate space for the array of fields,
15379      and create blank accessibility bitfields if necessary.  */
15380   TYPE_NFIELDS (type) = nfields;
15381   TYPE_FIELDS (type) = (struct field *)
15382     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15383   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15384
15385   if (fip->non_public_fields && cu->language != language_ada)
15386     {
15387       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15388
15389       TYPE_FIELD_PRIVATE_BITS (type) =
15390         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15391       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15392
15393       TYPE_FIELD_PROTECTED_BITS (type) =
15394         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15395       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15396
15397       TYPE_FIELD_IGNORE_BITS (type) =
15398         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15399       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15400     }
15401
15402   /* If the type has baseclasses, allocate and clear a bit vector for
15403      TYPE_FIELD_VIRTUAL_BITS.  */
15404   if (fip->nbaseclasses && cu->language != language_ada)
15405     {
15406       int num_bytes = B_BYTES (fip->nbaseclasses);
15407       unsigned char *pointer;
15408
15409       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15410       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15411       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15412       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15413       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15414     }
15415
15416   /* Copy the saved-up fields into the field vector.  Start from the head of
15417      the list, adding to the tail of the field array, so that they end up in
15418      the same order in the array in which they were added to the list.  */
15419   while (nfields-- > 0)
15420     {
15421       struct nextfield *fieldp;
15422
15423       if (fip->fields)
15424         {
15425           fieldp = fip->fields;
15426           fip->fields = fieldp->next;
15427         }
15428       else
15429         {
15430           fieldp = fip->baseclasses;
15431           fip->baseclasses = fieldp->next;
15432         }
15433
15434       TYPE_FIELD (type, nfields) = fieldp->field;
15435       switch (fieldp->accessibility)
15436         {
15437         case DW_ACCESS_private:
15438           if (cu->language != language_ada)
15439             SET_TYPE_FIELD_PRIVATE (type, nfields);
15440           break;
15441
15442         case DW_ACCESS_protected:
15443           if (cu->language != language_ada)
15444             SET_TYPE_FIELD_PROTECTED (type, nfields);
15445           break;
15446
15447         case DW_ACCESS_public:
15448           break;
15449
15450         default:
15451           /* Unknown accessibility.  Complain and treat it as public.  */
15452           {
15453             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15454                        fieldp->accessibility);
15455           }
15456           break;
15457         }
15458       if (nfields < fip->nbaseclasses)
15459         {
15460           switch (fieldp->virtuality)
15461             {
15462             case DW_VIRTUALITY_virtual:
15463             case DW_VIRTUALITY_pure_virtual:
15464               if (cu->language == language_ada)
15465                 error (_("unexpected virtuality in component of Ada type"));
15466               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15467               break;
15468             }
15469         }
15470     }
15471 }
15472
15473 /* Return true if this member function is a constructor, false
15474    otherwise.  */
15475
15476 static int
15477 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15478 {
15479   const char *fieldname;
15480   const char *type_name;
15481   int len;
15482
15483   if (die->parent == NULL)
15484     return 0;
15485
15486   if (die->parent->tag != DW_TAG_structure_type
15487       && die->parent->tag != DW_TAG_union_type
15488       && die->parent->tag != DW_TAG_class_type)
15489     return 0;
15490
15491   fieldname = dwarf2_name (die, cu);
15492   type_name = dwarf2_name (die->parent, cu);
15493   if (fieldname == NULL || type_name == NULL)
15494     return 0;
15495
15496   len = strlen (fieldname);
15497   return (strncmp (fieldname, type_name, len) == 0
15498           && (type_name[len] == '\0' || type_name[len] == '<'));
15499 }
15500
15501 /* Add a member function to the proper fieldlist.  */
15502
15503 static void
15504 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15505                       struct type *type, struct dwarf2_cu *cu)
15506 {
15507   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15508   struct attribute *attr;
15509   struct fnfieldlist *flp;
15510   int i;
15511   struct fn_field *fnp;
15512   const char *fieldname;
15513   struct nextfnfield *new_fnfield;
15514   struct type *this_type;
15515   enum dwarf_access_attribute accessibility;
15516
15517   if (cu->language == language_ada)
15518     error (_("unexpected member function in Ada type"));
15519
15520   /* Get name of member function.  */
15521   fieldname = dwarf2_name (die, cu);
15522   if (fieldname == NULL)
15523     return;
15524
15525   /* Look up member function name in fieldlist.  */
15526   for (i = 0; i < fip->nfnfields; i++)
15527     {
15528       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15529         break;
15530     }
15531
15532   /* Create new list element if necessary.  */
15533   if (i < fip->nfnfields)
15534     flp = &fip->fnfieldlists[i];
15535   else
15536     {
15537       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15538         {
15539           fip->fnfieldlists = (struct fnfieldlist *)
15540             xrealloc (fip->fnfieldlists,
15541                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15542                       * sizeof (struct fnfieldlist));
15543           if (fip->nfnfields == 0)
15544             make_cleanup (free_current_contents, &fip->fnfieldlists);
15545         }
15546       flp = &fip->fnfieldlists[fip->nfnfields];
15547       flp->name = fieldname;
15548       flp->length = 0;
15549       flp->head = NULL;
15550       i = fip->nfnfields++;
15551     }
15552
15553   /* Create a new member function field and chain it to the field list
15554      entry.  */
15555   new_fnfield = XNEW (struct nextfnfield);
15556   make_cleanup (xfree, new_fnfield);
15557   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15558   new_fnfield->next = flp->head;
15559   flp->head = new_fnfield;
15560   flp->length++;
15561
15562   /* Fill in the member function field info.  */
15563   fnp = &new_fnfield->fnfield;
15564
15565   /* Delay processing of the physname until later.  */
15566   if (cu->language == language_cplus)
15567     {
15568       add_to_method_list (type, i, flp->length - 1, fieldname,
15569                           die, cu);
15570     }
15571   else
15572     {
15573       const char *physname = dwarf2_physname (fieldname, die, cu);
15574       fnp->physname = physname ? physname : "";
15575     }
15576
15577   fnp->type = alloc_type (objfile);
15578   this_type = read_type_die (die, cu);
15579   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15580     {
15581       int nparams = TYPE_NFIELDS (this_type);
15582
15583       /* TYPE is the domain of this method, and THIS_TYPE is the type
15584            of the method itself (TYPE_CODE_METHOD).  */
15585       smash_to_method_type (fnp->type, type,
15586                             TYPE_TARGET_TYPE (this_type),
15587                             TYPE_FIELDS (this_type),
15588                             TYPE_NFIELDS (this_type),
15589                             TYPE_VARARGS (this_type));
15590
15591       /* Handle static member functions.
15592          Dwarf2 has no clean way to discern C++ static and non-static
15593          member functions.  G++ helps GDB by marking the first
15594          parameter for non-static member functions (which is the this
15595          pointer) as artificial.  We obtain this information from
15596          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15597       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15598         fnp->voffset = VOFFSET_STATIC;
15599     }
15600   else
15601     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15602                dwarf2_full_name (fieldname, die, cu));
15603
15604   /* Get fcontext from DW_AT_containing_type if present.  */
15605   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15606     fnp->fcontext = die_containing_type (die, cu);
15607
15608   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15609      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15610
15611   /* Get accessibility.  */
15612   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15613   if (attr)
15614     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15615   else
15616     accessibility = dwarf2_default_access_attribute (die, cu);
15617   switch (accessibility)
15618     {
15619     case DW_ACCESS_private:
15620       fnp->is_private = 1;
15621       break;
15622     case DW_ACCESS_protected:
15623       fnp->is_protected = 1;
15624       break;
15625     }
15626
15627   /* Check for artificial methods.  */
15628   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15629   if (attr && DW_UNSND (attr) != 0)
15630     fnp->is_artificial = 1;
15631
15632   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15633
15634   /* Get index in virtual function table if it is a virtual member
15635      function.  For older versions of GCC, this is an offset in the
15636      appropriate virtual table, as specified by DW_AT_containing_type.
15637      For everyone else, it is an expression to be evaluated relative
15638      to the object address.  */
15639
15640   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15641   if (attr)
15642     {
15643       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15644         {
15645           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15646             {
15647               /* Old-style GCC.  */
15648               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15649             }
15650           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15651                    || (DW_BLOCK (attr)->size > 1
15652                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15653                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15654             {
15655               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15656               if ((fnp->voffset % cu->header.addr_size) != 0)
15657                 dwarf2_complex_location_expr_complaint ();
15658               else
15659                 fnp->voffset /= cu->header.addr_size;
15660               fnp->voffset += 2;
15661             }
15662           else
15663             dwarf2_complex_location_expr_complaint ();
15664
15665           if (!fnp->fcontext)
15666             {
15667               /* If there is no `this' field and no DW_AT_containing_type,
15668                  we cannot actually find a base class context for the
15669                  vtable!  */
15670               if (TYPE_NFIELDS (this_type) == 0
15671                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15672                 {
15673                   complaint (&symfile_complaints,
15674                              _("cannot determine context for virtual member "
15675                                "function \"%s\" (offset %d)"),
15676                              fieldname, to_underlying (die->sect_off));
15677                 }
15678               else
15679                 {
15680                   fnp->fcontext
15681                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15682                 }
15683             }
15684         }
15685       else if (attr_form_is_section_offset (attr))
15686         {
15687           dwarf2_complex_location_expr_complaint ();
15688         }
15689       else
15690         {
15691           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15692                                                  fieldname);
15693         }
15694     }
15695   else
15696     {
15697       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15698       if (attr && DW_UNSND (attr))
15699         {
15700           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15701           complaint (&symfile_complaints,
15702                      _("Member function \"%s\" (offset %d) is virtual "
15703                        "but the vtable offset is not specified"),
15704                      fieldname, to_underlying (die->sect_off));
15705           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15706           TYPE_CPLUS_DYNAMIC (type) = 1;
15707         }
15708     }
15709 }
15710
15711 /* Create the vector of member function fields, and attach it to the type.  */
15712
15713 static void
15714 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15715                                  struct dwarf2_cu *cu)
15716 {
15717   struct fnfieldlist *flp;
15718   int i;
15719
15720   if (cu->language == language_ada)
15721     error (_("unexpected member functions in Ada type"));
15722
15723   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15724   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15725     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15726
15727   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15728     {
15729       struct nextfnfield *nfp = flp->head;
15730       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15731       int k;
15732
15733       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15734       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15735       fn_flp->fn_fields = (struct fn_field *)
15736         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15737       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15738         fn_flp->fn_fields[k] = nfp->fnfield;
15739     }
15740
15741   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15742 }
15743
15744 /* Returns non-zero if NAME is the name of a vtable member in CU's
15745    language, zero otherwise.  */
15746 static int
15747 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15748 {
15749   static const char vptr[] = "_vptr";
15750
15751   /* Look for the C++ form of the vtable.  */
15752   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15753     return 1;
15754
15755   return 0;
15756 }
15757
15758 /* GCC outputs unnamed structures that are really pointers to member
15759    functions, with the ABI-specified layout.  If TYPE describes
15760    such a structure, smash it into a member function type.
15761
15762    GCC shouldn't do this; it should just output pointer to member DIEs.
15763    This is GCC PR debug/28767.  */
15764
15765 static void
15766 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15767 {
15768   struct type *pfn_type, *self_type, *new_type;
15769
15770   /* Check for a structure with no name and two children.  */
15771   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15772     return;
15773
15774   /* Check for __pfn and __delta members.  */
15775   if (TYPE_FIELD_NAME (type, 0) == NULL
15776       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15777       || TYPE_FIELD_NAME (type, 1) == NULL
15778       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15779     return;
15780
15781   /* Find the type of the method.  */
15782   pfn_type = TYPE_FIELD_TYPE (type, 0);
15783   if (pfn_type == NULL
15784       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15785       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15786     return;
15787
15788   /* Look for the "this" argument.  */
15789   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15790   if (TYPE_NFIELDS (pfn_type) == 0
15791       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15792       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15793     return;
15794
15795   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15796   new_type = alloc_type (objfile);
15797   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15798                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15799                         TYPE_VARARGS (pfn_type));
15800   smash_to_methodptr_type (type, new_type);
15801 }
15802
15803
15804 /* Called when we find the DIE that starts a structure or union scope
15805    (definition) to create a type for the structure or union.  Fill in
15806    the type's name and general properties; the members will not be
15807    processed until process_structure_scope.  A symbol table entry for
15808    the type will also not be done until process_structure_scope (assuming
15809    the type has a name).
15810
15811    NOTE: we need to call these functions regardless of whether or not the
15812    DIE has a DW_AT_name attribute, since it might be an anonymous
15813    structure or union.  This gets the type entered into our set of
15814    user defined types.  */
15815
15816 static struct type *
15817 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15818 {
15819   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15820   struct type *type;
15821   struct attribute *attr;
15822   const char *name;
15823
15824   /* If the definition of this type lives in .debug_types, read that type.
15825      Don't follow DW_AT_specification though, that will take us back up
15826      the chain and we want to go down.  */
15827   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15828   if (attr)
15829     {
15830       type = get_DW_AT_signature_type (die, attr, cu);
15831
15832       /* The type's CU may not be the same as CU.
15833          Ensure TYPE is recorded with CU in die_type_hash.  */
15834       return set_die_type (die, type, cu);
15835     }
15836
15837   type = alloc_type (objfile);
15838   INIT_CPLUS_SPECIFIC (type);
15839
15840   name = dwarf2_name (die, cu);
15841   if (name != NULL)
15842     {
15843       if (cu->language == language_cplus
15844           || cu->language == language_d
15845           || cu->language == language_rust)
15846         {
15847           const char *full_name = dwarf2_full_name (name, die, cu);
15848
15849           /* dwarf2_full_name might have already finished building the DIE's
15850              type.  If so, there is no need to continue.  */
15851           if (get_die_type (die, cu) != NULL)
15852             return get_die_type (die, cu);
15853
15854           TYPE_TAG_NAME (type) = full_name;
15855           if (die->tag == DW_TAG_structure_type
15856               || die->tag == DW_TAG_class_type)
15857             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15858         }
15859       else
15860         {
15861           /* The name is already allocated along with this objfile, so
15862              we don't need to duplicate it for the type.  */
15863           TYPE_TAG_NAME (type) = name;
15864           if (die->tag == DW_TAG_class_type)
15865             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15866         }
15867     }
15868
15869   if (die->tag == DW_TAG_structure_type)
15870     {
15871       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15872     }
15873   else if (die->tag == DW_TAG_union_type)
15874     {
15875       TYPE_CODE (type) = TYPE_CODE_UNION;
15876     }
15877   else
15878     {
15879       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15880     }
15881
15882   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15883     TYPE_DECLARED_CLASS (type) = 1;
15884
15885   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15886   if (attr)
15887     {
15888       if (attr_form_is_constant (attr))
15889         TYPE_LENGTH (type) = DW_UNSND (attr);
15890       else
15891         {
15892           /* For the moment, dynamic type sizes are not supported
15893              by GDB's struct type.  The actual size is determined
15894              on-demand when resolving the type of a given object,
15895              so set the type's length to zero for now.  Otherwise,
15896              we record an expression as the length, and that expression
15897              could lead to a very large value, which could eventually
15898              lead to us trying to allocate that much memory when creating
15899              a value of that type.  */
15900           TYPE_LENGTH (type) = 0;
15901         }
15902     }
15903   else
15904     {
15905       TYPE_LENGTH (type) = 0;
15906     }
15907
15908   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15909     {
15910       /* ICC<14 does not output the required DW_AT_declaration on
15911          incomplete types, but gives them a size of zero.  */
15912       TYPE_STUB (type) = 1;
15913     }
15914   else
15915     TYPE_STUB_SUPPORTED (type) = 1;
15916
15917   if (die_is_declaration (die, cu))
15918     TYPE_STUB (type) = 1;
15919   else if (attr == NULL && die->child == NULL
15920            && producer_is_realview (cu->producer))
15921     /* RealView does not output the required DW_AT_declaration
15922        on incomplete types.  */
15923     TYPE_STUB (type) = 1;
15924
15925   /* We need to add the type field to the die immediately so we don't
15926      infinitely recurse when dealing with pointers to the structure
15927      type within the structure itself.  */
15928   set_die_type (die, type, cu);
15929
15930   /* set_die_type should be already done.  */
15931   set_descriptive_type (type, die, cu);
15932
15933   return type;
15934 }
15935
15936 /* Finish creating a structure or union type, including filling in
15937    its members and creating a symbol for it.  */
15938
15939 static void
15940 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15941 {
15942   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15943   struct die_info *child_die;
15944   struct type *type;
15945
15946   type = get_die_type (die, cu);
15947   if (type == NULL)
15948     type = read_structure_type (die, cu);
15949
15950   if (die->child != NULL && ! die_is_declaration (die, cu))
15951     {
15952       struct field_info fi;
15953       std::vector<struct symbol *> template_args;
15954       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15955
15956       memset (&fi, 0, sizeof (struct field_info));
15957
15958       child_die = die->child;
15959
15960       while (child_die && child_die->tag)
15961         {
15962           if (child_die->tag == DW_TAG_member
15963               || child_die->tag == DW_TAG_variable)
15964             {
15965               /* NOTE: carlton/2002-11-05: A C++ static data member
15966                  should be a DW_TAG_member that is a declaration, but
15967                  all versions of G++ as of this writing (so through at
15968                  least 3.2.1) incorrectly generate DW_TAG_variable
15969                  tags for them instead.  */
15970               dwarf2_add_field (&fi, child_die, cu);
15971             }
15972           else if (child_die->tag == DW_TAG_subprogram)
15973             {
15974               /* Rust doesn't have member functions in the C++ sense.
15975                  However, it does emit ordinary functions as children
15976                  of a struct DIE.  */
15977               if (cu->language == language_rust)
15978                 read_func_scope (child_die, cu);
15979               else
15980                 {
15981                   /* C++ member function.  */
15982                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15983                 }
15984             }
15985           else if (child_die->tag == DW_TAG_inheritance)
15986             {
15987               /* C++ base class field.  */
15988               dwarf2_add_field (&fi, child_die, cu);
15989             }
15990           else if (type_can_define_types (child_die))
15991             dwarf2_add_type_defn (&fi, child_die, cu);
15992           else if (child_die->tag == DW_TAG_template_type_param
15993                    || child_die->tag == DW_TAG_template_value_param)
15994             {
15995               struct symbol *arg = new_symbol (child_die, NULL, cu);
15996
15997               if (arg != NULL)
15998                 template_args.push_back (arg);
15999             }
16000
16001           child_die = sibling_die (child_die);
16002         }
16003
16004       /* Attach template arguments to type.  */
16005       if (!template_args.empty ())
16006         {
16007           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16008           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16009           TYPE_TEMPLATE_ARGUMENTS (type)
16010             = XOBNEWVEC (&objfile->objfile_obstack,
16011                          struct symbol *,
16012                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16013           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16014                   template_args.data (),
16015                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16016                    * sizeof (struct symbol *)));
16017         }
16018
16019       /* Attach fields and member functions to the type.  */
16020       if (fi.nfields)
16021         dwarf2_attach_fields_to_type (&fi, type, cu);
16022       if (fi.nfnfields)
16023         {
16024           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16025
16026           /* Get the type which refers to the base class (possibly this
16027              class itself) which contains the vtable pointer for the current
16028              class from the DW_AT_containing_type attribute.  This use of
16029              DW_AT_containing_type is a GNU extension.  */
16030
16031           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16032             {
16033               struct type *t = die_containing_type (die, cu);
16034
16035               set_type_vptr_basetype (type, t);
16036               if (type == t)
16037                 {
16038                   int i;
16039
16040                   /* Our own class provides vtbl ptr.  */
16041                   for (i = TYPE_NFIELDS (t) - 1;
16042                        i >= TYPE_N_BASECLASSES (t);
16043                        --i)
16044                     {
16045                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16046
16047                       if (is_vtable_name (fieldname, cu))
16048                         {
16049                           set_type_vptr_fieldno (type, i);
16050                           break;
16051                         }
16052                     }
16053
16054                   /* Complain if virtual function table field not found.  */
16055                   if (i < TYPE_N_BASECLASSES (t))
16056                     complaint (&symfile_complaints,
16057                                _("virtual function table pointer "
16058                                  "not found when defining class '%s'"),
16059                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16060                                "");
16061                 }
16062               else
16063                 {
16064                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16065                 }
16066             }
16067           else if (cu->producer
16068                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16069             {
16070               /* The IBM XLC compiler does not provide direct indication
16071                  of the containing type, but the vtable pointer is
16072                  always named __vfp.  */
16073
16074               int i;
16075
16076               for (i = TYPE_NFIELDS (type) - 1;
16077                    i >= TYPE_N_BASECLASSES (type);
16078                    --i)
16079                 {
16080                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16081                     {
16082                       set_type_vptr_fieldno (type, i);
16083                       set_type_vptr_basetype (type, type);
16084                       break;
16085                     }
16086                 }
16087             }
16088         }
16089
16090       /* Copy fi.typedef_field_list linked list elements content into the
16091          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16092       if (fi.typedef_field_list)
16093         {
16094           int i = fi.typedef_field_list_count;
16095
16096           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16097           TYPE_TYPEDEF_FIELD_ARRAY (type)
16098             = ((struct decl_field *)
16099                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16100           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16101
16102           /* Reverse the list order to keep the debug info elements order.  */
16103           while (--i >= 0)
16104             {
16105               struct decl_field *dest, *src;
16106
16107               dest = &TYPE_TYPEDEF_FIELD (type, i);
16108               src = &fi.typedef_field_list->field;
16109               fi.typedef_field_list = fi.typedef_field_list->next;
16110               *dest = *src;
16111             }
16112         }
16113
16114       /* Copy fi.nested_types_list linked list elements content into the
16115          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16116       if (fi.nested_types_list != NULL && cu->language != language_ada)
16117         {
16118           int i = fi.nested_types_list_count;
16119
16120           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16121           TYPE_NESTED_TYPES_ARRAY (type)
16122             = ((struct decl_field *)
16123                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16124           TYPE_NESTED_TYPES_COUNT (type) = i;
16125
16126           /* Reverse the list order to keep the debug info elements order.  */
16127           while (--i >= 0)
16128             {
16129               struct decl_field *dest, *src;
16130
16131               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16132               src = &fi.nested_types_list->field;
16133               fi.nested_types_list = fi.nested_types_list->next;
16134               *dest = *src;
16135             }
16136         }
16137
16138       do_cleanups (back_to);
16139     }
16140
16141   quirk_gcc_member_function_pointer (type, objfile);
16142
16143   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16144      snapshots) has been known to create a die giving a declaration
16145      for a class that has, as a child, a die giving a definition for a
16146      nested class.  So we have to process our children even if the
16147      current die is a declaration.  Normally, of course, a declaration
16148      won't have any children at all.  */
16149
16150   child_die = die->child;
16151
16152   while (child_die != NULL && child_die->tag)
16153     {
16154       if (child_die->tag == DW_TAG_member
16155           || child_die->tag == DW_TAG_variable
16156           || child_die->tag == DW_TAG_inheritance
16157           || child_die->tag == DW_TAG_template_value_param
16158           || child_die->tag == DW_TAG_template_type_param)
16159         {
16160           /* Do nothing.  */
16161         }
16162       else
16163         process_die (child_die, cu);
16164
16165       child_die = sibling_die (child_die);
16166     }
16167
16168   /* Do not consider external references.  According to the DWARF standard,
16169      these DIEs are identified by the fact that they have no byte_size
16170      attribute, and a declaration attribute.  */
16171   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16172       || !die_is_declaration (die, cu))
16173     new_symbol (die, type, cu);
16174 }
16175
16176 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16177    update TYPE using some information only available in DIE's children.  */
16178
16179 static void
16180 update_enumeration_type_from_children (struct die_info *die,
16181                                        struct type *type,
16182                                        struct dwarf2_cu *cu)
16183 {
16184   struct die_info *child_die;
16185   int unsigned_enum = 1;
16186   int flag_enum = 1;
16187   ULONGEST mask = 0;
16188
16189   auto_obstack obstack;
16190
16191   for (child_die = die->child;
16192        child_die != NULL && child_die->tag;
16193        child_die = sibling_die (child_die))
16194     {
16195       struct attribute *attr;
16196       LONGEST value;
16197       const gdb_byte *bytes;
16198       struct dwarf2_locexpr_baton *baton;
16199       const char *name;
16200
16201       if (child_die->tag != DW_TAG_enumerator)
16202         continue;
16203
16204       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16205       if (attr == NULL)
16206         continue;
16207
16208       name = dwarf2_name (child_die, cu);
16209       if (name == NULL)
16210         name = "<anonymous enumerator>";
16211
16212       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16213                                &value, &bytes, &baton);
16214       if (value < 0)
16215         {
16216           unsigned_enum = 0;
16217           flag_enum = 0;
16218         }
16219       else if ((mask & value) != 0)
16220         flag_enum = 0;
16221       else
16222         mask |= value;
16223
16224       /* If we already know that the enum type is neither unsigned, nor
16225          a flag type, no need to look at the rest of the enumerates.  */
16226       if (!unsigned_enum && !flag_enum)
16227         break;
16228     }
16229
16230   if (unsigned_enum)
16231     TYPE_UNSIGNED (type) = 1;
16232   if (flag_enum)
16233     TYPE_FLAG_ENUM (type) = 1;
16234 }
16235
16236 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16237    complete the type's fields yet, or create any symbols.  */
16238
16239 static struct type *
16240 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16241 {
16242   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16243   struct type *type;
16244   struct attribute *attr;
16245   const char *name;
16246
16247   /* If the definition of this type lives in .debug_types, read that type.
16248      Don't follow DW_AT_specification though, that will take us back up
16249      the chain and we want to go down.  */
16250   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16251   if (attr)
16252     {
16253       type = get_DW_AT_signature_type (die, attr, cu);
16254
16255       /* The type's CU may not be the same as CU.
16256          Ensure TYPE is recorded with CU in die_type_hash.  */
16257       return set_die_type (die, type, cu);
16258     }
16259
16260   type = alloc_type (objfile);
16261
16262   TYPE_CODE (type) = TYPE_CODE_ENUM;
16263   name = dwarf2_full_name (NULL, die, cu);
16264   if (name != NULL)
16265     TYPE_TAG_NAME (type) = name;
16266
16267   attr = dwarf2_attr (die, DW_AT_type, cu);
16268   if (attr != NULL)
16269     {
16270       struct type *underlying_type = die_type (die, cu);
16271
16272       TYPE_TARGET_TYPE (type) = underlying_type;
16273     }
16274
16275   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16276   if (attr)
16277     {
16278       TYPE_LENGTH (type) = DW_UNSND (attr);
16279     }
16280   else
16281     {
16282       TYPE_LENGTH (type) = 0;
16283     }
16284
16285   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16286      declared as private in the package spec, and then defined only
16287      inside the package body.  Such types are known as Taft Amendment
16288      Types.  When another package uses such a type, an incomplete DIE
16289      may be generated by the compiler.  */
16290   if (die_is_declaration (die, cu))
16291     TYPE_STUB (type) = 1;
16292
16293   /* Finish the creation of this type by using the enum's children.
16294      We must call this even when the underlying type has been provided
16295      so that we can determine if we're looking at a "flag" enum.  */
16296   update_enumeration_type_from_children (die, type, cu);
16297
16298   /* If this type has an underlying type that is not a stub, then we
16299      may use its attributes.  We always use the "unsigned" attribute
16300      in this situation, because ordinarily we guess whether the type
16301      is unsigned -- but the guess can be wrong and the underlying type
16302      can tell us the reality.  However, we defer to a local size
16303      attribute if one exists, because this lets the compiler override
16304      the underlying type if needed.  */
16305   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16306     {
16307       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16308       if (TYPE_LENGTH (type) == 0)
16309         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16310     }
16311
16312   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16313
16314   return set_die_type (die, type, cu);
16315 }
16316
16317 /* Given a pointer to a die which begins an enumeration, process all
16318    the dies that define the members of the enumeration, and create the
16319    symbol for the enumeration type.
16320
16321    NOTE: We reverse the order of the element list.  */
16322
16323 static void
16324 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16325 {
16326   struct type *this_type;
16327
16328   this_type = get_die_type (die, cu);
16329   if (this_type == NULL)
16330     this_type = read_enumeration_type (die, cu);
16331
16332   if (die->child != NULL)
16333     {
16334       struct die_info *child_die;
16335       struct symbol *sym;
16336       struct field *fields = NULL;
16337       int num_fields = 0;
16338       const char *name;
16339
16340       child_die = die->child;
16341       while (child_die && child_die->tag)
16342         {
16343           if (child_die->tag != DW_TAG_enumerator)
16344             {
16345               process_die (child_die, cu);
16346             }
16347           else
16348             {
16349               name = dwarf2_name (child_die, cu);
16350               if (name)
16351                 {
16352                   sym = new_symbol (child_die, this_type, cu);
16353
16354                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16355                     {
16356                       fields = (struct field *)
16357                         xrealloc (fields,
16358                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16359                                   * sizeof (struct field));
16360                     }
16361
16362                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16363                   FIELD_TYPE (fields[num_fields]) = NULL;
16364                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16365                   FIELD_BITSIZE (fields[num_fields]) = 0;
16366
16367                   num_fields++;
16368                 }
16369             }
16370
16371           child_die = sibling_die (child_die);
16372         }
16373
16374       if (num_fields)
16375         {
16376           TYPE_NFIELDS (this_type) = num_fields;
16377           TYPE_FIELDS (this_type) = (struct field *)
16378             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16379           memcpy (TYPE_FIELDS (this_type), fields,
16380                   sizeof (struct field) * num_fields);
16381           xfree (fields);
16382         }
16383     }
16384
16385   /* If we are reading an enum from a .debug_types unit, and the enum
16386      is a declaration, and the enum is not the signatured type in the
16387      unit, then we do not want to add a symbol for it.  Adding a
16388      symbol would in some cases obscure the true definition of the
16389      enum, giving users an incomplete type when the definition is
16390      actually available.  Note that we do not want to do this for all
16391      enums which are just declarations, because C++0x allows forward
16392      enum declarations.  */
16393   if (cu->per_cu->is_debug_types
16394       && die_is_declaration (die, cu))
16395     {
16396       struct signatured_type *sig_type;
16397
16398       sig_type = (struct signatured_type *) cu->per_cu;
16399       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16400       if (sig_type->type_offset_in_section != die->sect_off)
16401         return;
16402     }
16403
16404   new_symbol (die, this_type, cu);
16405 }
16406
16407 /* Extract all information from a DW_TAG_array_type DIE and put it in
16408    the DIE's type field.  For now, this only handles one dimensional
16409    arrays.  */
16410
16411 static struct type *
16412 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16413 {
16414   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16415   struct die_info *child_die;
16416   struct type *type;
16417   struct type *element_type, *range_type, *index_type;
16418   struct attribute *attr;
16419   const char *name;
16420   struct dynamic_prop *byte_stride_prop = NULL;
16421   unsigned int bit_stride = 0;
16422
16423   element_type = die_type (die, cu);
16424
16425   /* The die_type call above may have already set the type for this DIE.  */
16426   type = get_die_type (die, cu);
16427   if (type)
16428     return type;
16429
16430   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16431   if (attr != NULL)
16432     {
16433       int stride_ok;
16434
16435       byte_stride_prop
16436         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16437       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16438       if (!stride_ok)
16439         {
16440           complaint (&symfile_complaints,
16441                      _("unable to read array DW_AT_byte_stride "
16442                        " - DIE at 0x%x [in module %s]"),
16443                      to_underlying (die->sect_off),
16444                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16445           /* Ignore this attribute.  We will likely not be able to print
16446              arrays of this type correctly, but there is little we can do
16447              to help if we cannot read the attribute's value.  */
16448           byte_stride_prop = NULL;
16449         }
16450     }
16451
16452   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16453   if (attr != NULL)
16454     bit_stride = DW_UNSND (attr);
16455
16456   /* Irix 6.2 native cc creates array types without children for
16457      arrays with unspecified length.  */
16458   if (die->child == NULL)
16459     {
16460       index_type = objfile_type (objfile)->builtin_int;
16461       range_type = create_static_range_type (NULL, index_type, 0, -1);
16462       type = create_array_type_with_stride (NULL, element_type, range_type,
16463                                             byte_stride_prop, bit_stride);
16464       return set_die_type (die, type, cu);
16465     }
16466
16467   std::vector<struct type *> range_types;
16468   child_die = die->child;
16469   while (child_die && child_die->tag)
16470     {
16471       if (child_die->tag == DW_TAG_subrange_type)
16472         {
16473           struct type *child_type = read_type_die (child_die, cu);
16474
16475           if (child_type != NULL)
16476             {
16477               /* The range type was succesfully read.  Save it for the
16478                  array type creation.  */
16479               range_types.push_back (child_type);
16480             }
16481         }
16482       child_die = sibling_die (child_die);
16483     }
16484
16485   /* Dwarf2 dimensions are output from left to right, create the
16486      necessary array types in backwards order.  */
16487
16488   type = element_type;
16489
16490   if (read_array_order (die, cu) == DW_ORD_col_major)
16491     {
16492       int i = 0;
16493
16494       while (i < range_types.size ())
16495         type = create_array_type_with_stride (NULL, type, range_types[i++],
16496                                               byte_stride_prop, bit_stride);
16497     }
16498   else
16499     {
16500       size_t ndim = range_types.size ();
16501       while (ndim-- > 0)
16502         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16503                                               byte_stride_prop, bit_stride);
16504     }
16505
16506   /* Understand Dwarf2 support for vector types (like they occur on
16507      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16508      array type.  This is not part of the Dwarf2/3 standard yet, but a
16509      custom vendor extension.  The main difference between a regular
16510      array and the vector variant is that vectors are passed by value
16511      to functions.  */
16512   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16513   if (attr)
16514     make_vector_type (type);
16515
16516   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16517      implementation may choose to implement triple vectors using this
16518      attribute.  */
16519   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16520   if (attr)
16521     {
16522       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16523         TYPE_LENGTH (type) = DW_UNSND (attr);
16524       else
16525         complaint (&symfile_complaints,
16526                    _("DW_AT_byte_size for array type smaller "
16527                      "than the total size of elements"));
16528     }
16529
16530   name = dwarf2_name (die, cu);
16531   if (name)
16532     TYPE_NAME (type) = name;
16533
16534   /* Install the type in the die.  */
16535   set_die_type (die, type, cu);
16536
16537   /* set_die_type should be already done.  */
16538   set_descriptive_type (type, die, cu);
16539
16540   return type;
16541 }
16542
16543 static enum dwarf_array_dim_ordering
16544 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16545 {
16546   struct attribute *attr;
16547
16548   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16549
16550   if (attr)
16551     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16552
16553   /* GNU F77 is a special case, as at 08/2004 array type info is the
16554      opposite order to the dwarf2 specification, but data is still
16555      laid out as per normal fortran.
16556
16557      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16558      version checking.  */
16559
16560   if (cu->language == language_fortran
16561       && cu->producer && strstr (cu->producer, "GNU F77"))
16562     {
16563       return DW_ORD_row_major;
16564     }
16565
16566   switch (cu->language_defn->la_array_ordering)
16567     {
16568     case array_column_major:
16569       return DW_ORD_col_major;
16570     case array_row_major:
16571     default:
16572       return DW_ORD_row_major;
16573     };
16574 }
16575
16576 /* Extract all information from a DW_TAG_set_type DIE and put it in
16577    the DIE's type field.  */
16578
16579 static struct type *
16580 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16581 {
16582   struct type *domain_type, *set_type;
16583   struct attribute *attr;
16584
16585   domain_type = die_type (die, cu);
16586
16587   /* The die_type call above may have already set the type for this DIE.  */
16588   set_type = get_die_type (die, cu);
16589   if (set_type)
16590     return set_type;
16591
16592   set_type = create_set_type (NULL, domain_type);
16593
16594   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16595   if (attr)
16596     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16597
16598   return set_die_type (die, set_type, cu);
16599 }
16600
16601 /* A helper for read_common_block that creates a locexpr baton.
16602    SYM is the symbol which we are marking as computed.
16603    COMMON_DIE is the DIE for the common block.
16604    COMMON_LOC is the location expression attribute for the common
16605    block itself.
16606    MEMBER_LOC is the location expression attribute for the particular
16607    member of the common block that we are processing.
16608    CU is the CU from which the above come.  */
16609
16610 static void
16611 mark_common_block_symbol_computed (struct symbol *sym,
16612                                    struct die_info *common_die,
16613                                    struct attribute *common_loc,
16614                                    struct attribute *member_loc,
16615                                    struct dwarf2_cu *cu)
16616 {
16617   struct dwarf2_per_objfile *dwarf2_per_objfile
16618     = cu->per_cu->dwarf2_per_objfile;
16619   struct objfile *objfile = dwarf2_per_objfile->objfile;
16620   struct dwarf2_locexpr_baton *baton;
16621   gdb_byte *ptr;
16622   unsigned int cu_off;
16623   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16624   LONGEST offset = 0;
16625
16626   gdb_assert (common_loc && member_loc);
16627   gdb_assert (attr_form_is_block (common_loc));
16628   gdb_assert (attr_form_is_block (member_loc)
16629               || attr_form_is_constant (member_loc));
16630
16631   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16632   baton->per_cu = cu->per_cu;
16633   gdb_assert (baton->per_cu);
16634
16635   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16636
16637   if (attr_form_is_constant (member_loc))
16638     {
16639       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16640       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16641     }
16642   else
16643     baton->size += DW_BLOCK (member_loc)->size;
16644
16645   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16646   baton->data = ptr;
16647
16648   *ptr++ = DW_OP_call4;
16649   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16650   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16651   ptr += 4;
16652
16653   if (attr_form_is_constant (member_loc))
16654     {
16655       *ptr++ = DW_OP_addr;
16656       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16657       ptr += cu->header.addr_size;
16658     }
16659   else
16660     {
16661       /* We have to copy the data here, because DW_OP_call4 will only
16662          use a DW_AT_location attribute.  */
16663       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16664       ptr += DW_BLOCK (member_loc)->size;
16665     }
16666
16667   *ptr++ = DW_OP_plus;
16668   gdb_assert (ptr - baton->data == baton->size);
16669
16670   SYMBOL_LOCATION_BATON (sym) = baton;
16671   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16672 }
16673
16674 /* Create appropriate locally-scoped variables for all the
16675    DW_TAG_common_block entries.  Also create a struct common_block
16676    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16677    is used to sepate the common blocks name namespace from regular
16678    variable names.  */
16679
16680 static void
16681 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16682 {
16683   struct attribute *attr;
16684
16685   attr = dwarf2_attr (die, DW_AT_location, cu);
16686   if (attr)
16687     {
16688       /* Support the .debug_loc offsets.  */
16689       if (attr_form_is_block (attr))
16690         {
16691           /* Ok.  */
16692         }
16693       else if (attr_form_is_section_offset (attr))
16694         {
16695           dwarf2_complex_location_expr_complaint ();
16696           attr = NULL;
16697         }
16698       else
16699         {
16700           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16701                                                  "common block member");
16702           attr = NULL;
16703         }
16704     }
16705
16706   if (die->child != NULL)
16707     {
16708       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16709       struct die_info *child_die;
16710       size_t n_entries = 0, size;
16711       struct common_block *common_block;
16712       struct symbol *sym;
16713
16714       for (child_die = die->child;
16715            child_die && child_die->tag;
16716            child_die = sibling_die (child_die))
16717         ++n_entries;
16718
16719       size = (sizeof (struct common_block)
16720               + (n_entries - 1) * sizeof (struct symbol *));
16721       common_block
16722         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16723                                                  size);
16724       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16725       common_block->n_entries = 0;
16726
16727       for (child_die = die->child;
16728            child_die && child_die->tag;
16729            child_die = sibling_die (child_die))
16730         {
16731           /* Create the symbol in the DW_TAG_common_block block in the current
16732              symbol scope.  */
16733           sym = new_symbol (child_die, NULL, cu);
16734           if (sym != NULL)
16735             {
16736               struct attribute *member_loc;
16737
16738               common_block->contents[common_block->n_entries++] = sym;
16739
16740               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16741                                         cu);
16742               if (member_loc)
16743                 {
16744                   /* GDB has handled this for a long time, but it is
16745                      not specified by DWARF.  It seems to have been
16746                      emitted by gfortran at least as recently as:
16747                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16748                   complaint (&symfile_complaints,
16749                              _("Variable in common block has "
16750                                "DW_AT_data_member_location "
16751                                "- DIE at 0x%x [in module %s]"),
16752                              to_underlying (child_die->sect_off),
16753                              objfile_name (objfile));
16754
16755                   if (attr_form_is_section_offset (member_loc))
16756                     dwarf2_complex_location_expr_complaint ();
16757                   else if (attr_form_is_constant (member_loc)
16758                            || attr_form_is_block (member_loc))
16759                     {
16760                       if (attr)
16761                         mark_common_block_symbol_computed (sym, die, attr,
16762                                                            member_loc, cu);
16763                     }
16764                   else
16765                     dwarf2_complex_location_expr_complaint ();
16766                 }
16767             }
16768         }
16769
16770       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16771       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16772     }
16773 }
16774
16775 /* Create a type for a C++ namespace.  */
16776
16777 static struct type *
16778 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16779 {
16780   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16781   const char *previous_prefix, *name;
16782   int is_anonymous;
16783   struct type *type;
16784
16785   /* For extensions, reuse the type of the original namespace.  */
16786   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16787     {
16788       struct die_info *ext_die;
16789       struct dwarf2_cu *ext_cu = cu;
16790
16791       ext_die = dwarf2_extension (die, &ext_cu);
16792       type = read_type_die (ext_die, ext_cu);
16793
16794       /* EXT_CU may not be the same as CU.
16795          Ensure TYPE is recorded with CU in die_type_hash.  */
16796       return set_die_type (die, type, cu);
16797     }
16798
16799   name = namespace_name (die, &is_anonymous, cu);
16800
16801   /* Now build the name of the current namespace.  */
16802
16803   previous_prefix = determine_prefix (die, cu);
16804   if (previous_prefix[0] != '\0')
16805     name = typename_concat (&objfile->objfile_obstack,
16806                             previous_prefix, name, 0, cu);
16807
16808   /* Create the type.  */
16809   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16810   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16811
16812   return set_die_type (die, type, cu);
16813 }
16814
16815 /* Read a namespace scope.  */
16816
16817 static void
16818 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16819 {
16820   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16821   int is_anonymous;
16822
16823   /* Add a symbol associated to this if we haven't seen the namespace
16824      before.  Also, add a using directive if it's an anonymous
16825      namespace.  */
16826
16827   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16828     {
16829       struct type *type;
16830
16831       type = read_type_die (die, cu);
16832       new_symbol (die, type, cu);
16833
16834       namespace_name (die, &is_anonymous, cu);
16835       if (is_anonymous)
16836         {
16837           const char *previous_prefix = determine_prefix (die, cu);
16838
16839           std::vector<const char *> excludes;
16840           add_using_directive (using_directives (cu->language),
16841                                previous_prefix, TYPE_NAME (type), NULL,
16842                                NULL, excludes, 0, &objfile->objfile_obstack);
16843         }
16844     }
16845
16846   if (die->child != NULL)
16847     {
16848       struct die_info *child_die = die->child;
16849
16850       while (child_die && child_die->tag)
16851         {
16852           process_die (child_die, cu);
16853           child_die = sibling_die (child_die);
16854         }
16855     }
16856 }
16857
16858 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16859    imported module.  Still we need that type as local Fortran "use ... only"
16860    declaration imports depend on the created type in determine_prefix.  */
16861
16862 static struct type *
16863 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16864 {
16865   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16866   const char *module_name;
16867   struct type *type;
16868
16869   module_name = dwarf2_name (die, cu);
16870   if (!module_name)
16871     complaint (&symfile_complaints,
16872                _("DW_TAG_module has no name, offset 0x%x"),
16873                to_underlying (die->sect_off));
16874   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16875
16876   /* determine_prefix uses TYPE_TAG_NAME.  */
16877   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16878
16879   return set_die_type (die, type, cu);
16880 }
16881
16882 /* Read a Fortran module.  */
16883
16884 static void
16885 read_module (struct die_info *die, struct dwarf2_cu *cu)
16886 {
16887   struct die_info *child_die = die->child;
16888   struct type *type;
16889
16890   type = read_type_die (die, cu);
16891   new_symbol (die, type, cu);
16892
16893   while (child_die && child_die->tag)
16894     {
16895       process_die (child_die, cu);
16896       child_die = sibling_die (child_die);
16897     }
16898 }
16899
16900 /* Return the name of the namespace represented by DIE.  Set
16901    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16902    namespace.  */
16903
16904 static const char *
16905 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16906 {
16907   struct die_info *current_die;
16908   const char *name = NULL;
16909
16910   /* Loop through the extensions until we find a name.  */
16911
16912   for (current_die = die;
16913        current_die != NULL;
16914        current_die = dwarf2_extension (die, &cu))
16915     {
16916       /* We don't use dwarf2_name here so that we can detect the absence
16917          of a name -> anonymous namespace.  */
16918       name = dwarf2_string_attr (die, DW_AT_name, cu);
16919
16920       if (name != NULL)
16921         break;
16922     }
16923
16924   /* Is it an anonymous namespace?  */
16925
16926   *is_anonymous = (name == NULL);
16927   if (*is_anonymous)
16928     name = CP_ANONYMOUS_NAMESPACE_STR;
16929
16930   return name;
16931 }
16932
16933 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16934    the user defined type vector.  */
16935
16936 static struct type *
16937 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16938 {
16939   struct gdbarch *gdbarch
16940     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16941   struct comp_unit_head *cu_header = &cu->header;
16942   struct type *type;
16943   struct attribute *attr_byte_size;
16944   struct attribute *attr_address_class;
16945   int byte_size, addr_class;
16946   struct type *target_type;
16947
16948   target_type = die_type (die, cu);
16949
16950   /* The die_type call above may have already set the type for this DIE.  */
16951   type = get_die_type (die, cu);
16952   if (type)
16953     return type;
16954
16955   type = lookup_pointer_type (target_type);
16956
16957   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16958   if (attr_byte_size)
16959     byte_size = DW_UNSND (attr_byte_size);
16960   else
16961     byte_size = cu_header->addr_size;
16962
16963   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16964   if (attr_address_class)
16965     addr_class = DW_UNSND (attr_address_class);
16966   else
16967     addr_class = DW_ADDR_none;
16968
16969   /* If the pointer size or address class is different than the
16970      default, create a type variant marked as such and set the
16971      length accordingly.  */
16972   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16973     {
16974       if (gdbarch_address_class_type_flags_p (gdbarch))
16975         {
16976           int type_flags;
16977
16978           type_flags = gdbarch_address_class_type_flags
16979                          (gdbarch, byte_size, addr_class);
16980           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16981                       == 0);
16982           type = make_type_with_address_space (type, type_flags);
16983         }
16984       else if (TYPE_LENGTH (type) != byte_size)
16985         {
16986           complaint (&symfile_complaints,
16987                      _("invalid pointer size %d"), byte_size);
16988         }
16989       else
16990         {
16991           /* Should we also complain about unhandled address classes?  */
16992         }
16993     }
16994
16995   TYPE_LENGTH (type) = byte_size;
16996   return set_die_type (die, type, cu);
16997 }
16998
16999 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17000    the user defined type vector.  */
17001
17002 static struct type *
17003 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17004 {
17005   struct type *type;
17006   struct type *to_type;
17007   struct type *domain;
17008
17009   to_type = die_type (die, cu);
17010   domain = die_containing_type (die, cu);
17011
17012   /* The calls above may have already set the type for this DIE.  */
17013   type = get_die_type (die, cu);
17014   if (type)
17015     return type;
17016
17017   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17018     type = lookup_methodptr_type (to_type);
17019   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17020     {
17021       struct type *new_type
17022         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17023
17024       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17025                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17026                             TYPE_VARARGS (to_type));
17027       type = lookup_methodptr_type (new_type);
17028     }
17029   else
17030     type = lookup_memberptr_type (to_type, domain);
17031
17032   return set_die_type (die, type, cu);
17033 }
17034
17035 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17036    the user defined type vector.  */
17037
17038 static struct type *
17039 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17040                           enum type_code refcode)
17041 {
17042   struct comp_unit_head *cu_header = &cu->header;
17043   struct type *type, *target_type;
17044   struct attribute *attr;
17045
17046   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17047
17048   target_type = die_type (die, cu);
17049
17050   /* The die_type call above may have already set the type for this DIE.  */
17051   type = get_die_type (die, cu);
17052   if (type)
17053     return type;
17054
17055   type = lookup_reference_type (target_type, refcode);
17056   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17057   if (attr)
17058     {
17059       TYPE_LENGTH (type) = DW_UNSND (attr);
17060     }
17061   else
17062     {
17063       TYPE_LENGTH (type) = cu_header->addr_size;
17064     }
17065   return set_die_type (die, type, cu);
17066 }
17067
17068 /* Add the given cv-qualifiers to the element type of the array.  GCC
17069    outputs DWARF type qualifiers that apply to an array, not the
17070    element type.  But GDB relies on the array element type to carry
17071    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17072    specification.  */
17073
17074 static struct type *
17075 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17076                    struct type *base_type, int cnst, int voltl)
17077 {
17078   struct type *el_type, *inner_array;
17079
17080   base_type = copy_type (base_type);
17081   inner_array = base_type;
17082
17083   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17084     {
17085       TYPE_TARGET_TYPE (inner_array) =
17086         copy_type (TYPE_TARGET_TYPE (inner_array));
17087       inner_array = TYPE_TARGET_TYPE (inner_array);
17088     }
17089
17090   el_type = TYPE_TARGET_TYPE (inner_array);
17091   cnst |= TYPE_CONST (el_type);
17092   voltl |= TYPE_VOLATILE (el_type);
17093   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17094
17095   return set_die_type (die, base_type, cu);
17096 }
17097
17098 static struct type *
17099 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17100 {
17101   struct type *base_type, *cv_type;
17102
17103   base_type = die_type (die, cu);
17104
17105   /* The die_type call above may have already set the type for this DIE.  */
17106   cv_type = get_die_type (die, cu);
17107   if (cv_type)
17108     return cv_type;
17109
17110   /* In case the const qualifier is applied to an array type, the element type
17111      is so qualified, not the array type (section 6.7.3 of C99).  */
17112   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17113     return add_array_cv_type (die, cu, base_type, 1, 0);
17114
17115   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17116   return set_die_type (die, cv_type, cu);
17117 }
17118
17119 static struct type *
17120 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17121 {
17122   struct type *base_type, *cv_type;
17123
17124   base_type = die_type (die, cu);
17125
17126   /* The die_type call above may have already set the type for this DIE.  */
17127   cv_type = get_die_type (die, cu);
17128   if (cv_type)
17129     return cv_type;
17130
17131   /* In case the volatile qualifier is applied to an array type, the
17132      element type is so qualified, not the array type (section 6.7.3
17133      of C99).  */
17134   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17135     return add_array_cv_type (die, cu, base_type, 0, 1);
17136
17137   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17138   return set_die_type (die, cv_type, cu);
17139 }
17140
17141 /* Handle DW_TAG_restrict_type.  */
17142
17143 static struct type *
17144 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17145 {
17146   struct type *base_type, *cv_type;
17147
17148   base_type = die_type (die, cu);
17149
17150   /* The die_type call above may have already set the type for this DIE.  */
17151   cv_type = get_die_type (die, cu);
17152   if (cv_type)
17153     return cv_type;
17154
17155   cv_type = make_restrict_type (base_type);
17156   return set_die_type (die, cv_type, cu);
17157 }
17158
17159 /* Handle DW_TAG_atomic_type.  */
17160
17161 static struct type *
17162 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17163 {
17164   struct type *base_type, *cv_type;
17165
17166   base_type = die_type (die, cu);
17167
17168   /* The die_type call above may have already set the type for this DIE.  */
17169   cv_type = get_die_type (die, cu);
17170   if (cv_type)
17171     return cv_type;
17172
17173   cv_type = make_atomic_type (base_type);
17174   return set_die_type (die, cv_type, cu);
17175 }
17176
17177 /* Extract all information from a DW_TAG_string_type DIE and add to
17178    the user defined type vector.  It isn't really a user defined type,
17179    but it behaves like one, with other DIE's using an AT_user_def_type
17180    attribute to reference it.  */
17181
17182 static struct type *
17183 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17184 {
17185   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17186   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17187   struct type *type, *range_type, *index_type, *char_type;
17188   struct attribute *attr;
17189   unsigned int length;
17190
17191   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17192   if (attr)
17193     {
17194       length = DW_UNSND (attr);
17195     }
17196   else
17197     {
17198       /* Check for the DW_AT_byte_size attribute.  */
17199       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17200       if (attr)
17201         {
17202           length = DW_UNSND (attr);
17203         }
17204       else
17205         {
17206           length = 1;
17207         }
17208     }
17209
17210   index_type = objfile_type (objfile)->builtin_int;
17211   range_type = create_static_range_type (NULL, index_type, 1, length);
17212   char_type = language_string_char_type (cu->language_defn, gdbarch);
17213   type = create_string_type (NULL, char_type, range_type);
17214
17215   return set_die_type (die, type, cu);
17216 }
17217
17218 /* Assuming that DIE corresponds to a function, returns nonzero
17219    if the function is prototyped.  */
17220
17221 static int
17222 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17223 {
17224   struct attribute *attr;
17225
17226   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17227   if (attr && (DW_UNSND (attr) != 0))
17228     return 1;
17229
17230   /* The DWARF standard implies that the DW_AT_prototyped attribute
17231      is only meaninful for C, but the concept also extends to other
17232      languages that allow unprototyped functions (Eg: Objective C).
17233      For all other languages, assume that functions are always
17234      prototyped.  */
17235   if (cu->language != language_c
17236       && cu->language != language_objc
17237       && cu->language != language_opencl)
17238     return 1;
17239
17240   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17241      prototyped and unprototyped functions; default to prototyped,
17242      since that is more common in modern code (and RealView warns
17243      about unprototyped functions).  */
17244   if (producer_is_realview (cu->producer))
17245     return 1;
17246
17247   return 0;
17248 }
17249
17250 /* Handle DIES due to C code like:
17251
17252    struct foo
17253    {
17254    int (*funcp)(int a, long l);
17255    int b;
17256    };
17257
17258    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17259
17260 static struct type *
17261 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17262 {
17263   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17264   struct type *type;            /* Type that this function returns.  */
17265   struct type *ftype;           /* Function that returns above type.  */
17266   struct attribute *attr;
17267
17268   type = die_type (die, cu);
17269
17270   /* The die_type call above may have already set the type for this DIE.  */
17271   ftype = get_die_type (die, cu);
17272   if (ftype)
17273     return ftype;
17274
17275   ftype = lookup_function_type (type);
17276
17277   if (prototyped_function_p (die, cu))
17278     TYPE_PROTOTYPED (ftype) = 1;
17279
17280   /* Store the calling convention in the type if it's available in
17281      the subroutine die.  Otherwise set the calling convention to
17282      the default value DW_CC_normal.  */
17283   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17284   if (attr)
17285     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17286   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17287     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17288   else
17289     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17290
17291   /* Record whether the function returns normally to its caller or not
17292      if the DWARF producer set that information.  */
17293   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17294   if (attr && (DW_UNSND (attr) != 0))
17295     TYPE_NO_RETURN (ftype) = 1;
17296
17297   /* We need to add the subroutine type to the die immediately so
17298      we don't infinitely recurse when dealing with parameters
17299      declared as the same subroutine type.  */
17300   set_die_type (die, ftype, cu);
17301
17302   if (die->child != NULL)
17303     {
17304       struct type *void_type = objfile_type (objfile)->builtin_void;
17305       struct die_info *child_die;
17306       int nparams, iparams;
17307
17308       /* Count the number of parameters.
17309          FIXME: GDB currently ignores vararg functions, but knows about
17310          vararg member functions.  */
17311       nparams = 0;
17312       child_die = die->child;
17313       while (child_die && child_die->tag)
17314         {
17315           if (child_die->tag == DW_TAG_formal_parameter)
17316             nparams++;
17317           else if (child_die->tag == DW_TAG_unspecified_parameters)
17318             TYPE_VARARGS (ftype) = 1;
17319           child_die = sibling_die (child_die);
17320         }
17321
17322       /* Allocate storage for parameters and fill them in.  */
17323       TYPE_NFIELDS (ftype) = nparams;
17324       TYPE_FIELDS (ftype) = (struct field *)
17325         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17326
17327       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17328          even if we error out during the parameters reading below.  */
17329       for (iparams = 0; iparams < nparams; iparams++)
17330         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17331
17332       iparams = 0;
17333       child_die = die->child;
17334       while (child_die && child_die->tag)
17335         {
17336           if (child_die->tag == DW_TAG_formal_parameter)
17337             {
17338               struct type *arg_type;
17339
17340               /* DWARF version 2 has no clean way to discern C++
17341                  static and non-static member functions.  G++ helps
17342                  GDB by marking the first parameter for non-static
17343                  member functions (which is the this pointer) as
17344                  artificial.  We pass this information to
17345                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17346
17347                  DWARF version 3 added DW_AT_object_pointer, which GCC
17348                  4.5 does not yet generate.  */
17349               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17350               if (attr)
17351                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17352               else
17353                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17354               arg_type = die_type (child_die, cu);
17355
17356               /* RealView does not mark THIS as const, which the testsuite
17357                  expects.  GCC marks THIS as const in method definitions,
17358                  but not in the class specifications (GCC PR 43053).  */
17359               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17360                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17361                 {
17362                   int is_this = 0;
17363                   struct dwarf2_cu *arg_cu = cu;
17364                   const char *name = dwarf2_name (child_die, cu);
17365
17366                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17367                   if (attr)
17368                     {
17369                       /* If the compiler emits this, use it.  */
17370                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17371                         is_this = 1;
17372                     }
17373                   else if (name && strcmp (name, "this") == 0)
17374                     /* Function definitions will have the argument names.  */
17375                     is_this = 1;
17376                   else if (name == NULL && iparams == 0)
17377                     /* Declarations may not have the names, so like
17378                        elsewhere in GDB, assume an artificial first
17379                        argument is "this".  */
17380                     is_this = 1;
17381
17382                   if (is_this)
17383                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17384                                              arg_type, 0);
17385                 }
17386
17387               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17388               iparams++;
17389             }
17390           child_die = sibling_die (child_die);
17391         }
17392     }
17393
17394   return ftype;
17395 }
17396
17397 static struct type *
17398 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17399 {
17400   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17401   const char *name = NULL;
17402   struct type *this_type, *target_type;
17403
17404   name = dwarf2_full_name (NULL, die, cu);
17405   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17406   TYPE_TARGET_STUB (this_type) = 1;
17407   set_die_type (die, this_type, cu);
17408   target_type = die_type (die, cu);
17409   if (target_type != this_type)
17410     TYPE_TARGET_TYPE (this_type) = target_type;
17411   else
17412     {
17413       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17414          spec and cause infinite loops in GDB.  */
17415       complaint (&symfile_complaints,
17416                  _("Self-referential DW_TAG_typedef "
17417                    "- DIE at 0x%x [in module %s]"),
17418                  to_underlying (die->sect_off), objfile_name (objfile));
17419       TYPE_TARGET_TYPE (this_type) = NULL;
17420     }
17421   return this_type;
17422 }
17423
17424 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17425    (which may be different from NAME) to the architecture back-end to allow
17426    it to guess the correct format if necessary.  */
17427
17428 static struct type *
17429 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17430                         const char *name_hint)
17431 {
17432   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17433   const struct floatformat **format;
17434   struct type *type;
17435
17436   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17437   if (format)
17438     type = init_float_type (objfile, bits, name, format);
17439   else
17440     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17441
17442   return type;
17443 }
17444
17445 /* Find a representation of a given base type and install
17446    it in the TYPE field of the die.  */
17447
17448 static struct type *
17449 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17450 {
17451   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17452   struct type *type;
17453   struct attribute *attr;
17454   int encoding = 0, bits = 0;
17455   const char *name;
17456
17457   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17458   if (attr)
17459     {
17460       encoding = DW_UNSND (attr);
17461     }
17462   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17463   if (attr)
17464     {
17465       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17466     }
17467   name = dwarf2_name (die, cu);
17468   if (!name)
17469     {
17470       complaint (&symfile_complaints,
17471                  _("DW_AT_name missing from DW_TAG_base_type"));
17472     }
17473
17474   switch (encoding)
17475     {
17476       case DW_ATE_address:
17477         /* Turn DW_ATE_address into a void * pointer.  */
17478         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17479         type = init_pointer_type (objfile, bits, name, type);
17480         break;
17481       case DW_ATE_boolean:
17482         type = init_boolean_type (objfile, bits, 1, name);
17483         break;
17484       case DW_ATE_complex_float:
17485         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17486         type = init_complex_type (objfile, name, type);
17487         break;
17488       case DW_ATE_decimal_float:
17489         type = init_decfloat_type (objfile, bits, name);
17490         break;
17491       case DW_ATE_float:
17492         type = dwarf2_init_float_type (objfile, bits, name, name);
17493         break;
17494       case DW_ATE_signed:
17495         type = init_integer_type (objfile, bits, 0, name);
17496         break;
17497       case DW_ATE_unsigned:
17498         if (cu->language == language_fortran
17499             && name
17500             && startswith (name, "character("))
17501           type = init_character_type (objfile, bits, 1, name);
17502         else
17503           type = init_integer_type (objfile, bits, 1, name);
17504         break;
17505       case DW_ATE_signed_char:
17506         if (cu->language == language_ada || cu->language == language_m2
17507             || cu->language == language_pascal
17508             || cu->language == language_fortran)
17509           type = init_character_type (objfile, bits, 0, name);
17510         else
17511           type = init_integer_type (objfile, bits, 0, name);
17512         break;
17513       case DW_ATE_unsigned_char:
17514         if (cu->language == language_ada || cu->language == language_m2
17515             || cu->language == language_pascal
17516             || cu->language == language_fortran
17517             || cu->language == language_rust)
17518           type = init_character_type (objfile, bits, 1, name);
17519         else
17520           type = init_integer_type (objfile, bits, 1, name);
17521         break;
17522       case DW_ATE_UTF:
17523         {
17524           gdbarch *arch = get_objfile_arch (objfile);
17525
17526           if (bits == 16)
17527             type = builtin_type (arch)->builtin_char16;
17528           else if (bits == 32)
17529             type = builtin_type (arch)->builtin_char32;
17530           else
17531             {
17532               complaint (&symfile_complaints,
17533                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17534                          bits);
17535               type = init_integer_type (objfile, bits, 1, name);
17536             }
17537           return set_die_type (die, type, cu);
17538         }
17539         break;
17540
17541       default:
17542         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17543                    dwarf_type_encoding_name (encoding));
17544         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17545         break;
17546     }
17547
17548   if (name && strcmp (name, "char") == 0)
17549     TYPE_NOSIGN (type) = 1;
17550
17551   return set_die_type (die, type, cu);
17552 }
17553
17554 /* Parse dwarf attribute if it's a block, reference or constant and put the
17555    resulting value of the attribute into struct bound_prop.
17556    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17557
17558 static int
17559 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17560                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17561 {
17562   struct dwarf2_property_baton *baton;
17563   struct obstack *obstack
17564     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17565
17566   if (attr == NULL || prop == NULL)
17567     return 0;
17568
17569   if (attr_form_is_block (attr))
17570     {
17571       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17572       baton->referenced_type = NULL;
17573       baton->locexpr.per_cu = cu->per_cu;
17574       baton->locexpr.size = DW_BLOCK (attr)->size;
17575       baton->locexpr.data = DW_BLOCK (attr)->data;
17576       prop->data.baton = baton;
17577       prop->kind = PROP_LOCEXPR;
17578       gdb_assert (prop->data.baton != NULL);
17579     }
17580   else if (attr_form_is_ref (attr))
17581     {
17582       struct dwarf2_cu *target_cu = cu;
17583       struct die_info *target_die;
17584       struct attribute *target_attr;
17585
17586       target_die = follow_die_ref (die, attr, &target_cu);
17587       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17588       if (target_attr == NULL)
17589         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17590                                    target_cu);
17591       if (target_attr == NULL)
17592         return 0;
17593
17594       switch (target_attr->name)
17595         {
17596           case DW_AT_location:
17597             if (attr_form_is_section_offset (target_attr))
17598               {
17599                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17600                 baton->referenced_type = die_type (target_die, target_cu);
17601                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17602                 prop->data.baton = baton;
17603                 prop->kind = PROP_LOCLIST;
17604                 gdb_assert (prop->data.baton != NULL);
17605               }
17606             else if (attr_form_is_block (target_attr))
17607               {
17608                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17609                 baton->referenced_type = die_type (target_die, target_cu);
17610                 baton->locexpr.per_cu = cu->per_cu;
17611                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17612                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17613                 prop->data.baton = baton;
17614                 prop->kind = PROP_LOCEXPR;
17615                 gdb_assert (prop->data.baton != NULL);
17616               }
17617             else
17618               {
17619                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17620                                                        "dynamic property");
17621                 return 0;
17622               }
17623             break;
17624           case DW_AT_data_member_location:
17625             {
17626               LONGEST offset;
17627
17628               if (!handle_data_member_location (target_die, target_cu,
17629                                                 &offset))
17630                 return 0;
17631
17632               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17633               baton->referenced_type = read_type_die (target_die->parent,
17634                                                       target_cu);
17635               baton->offset_info.offset = offset;
17636               baton->offset_info.type = die_type (target_die, target_cu);
17637               prop->data.baton = baton;
17638               prop->kind = PROP_ADDR_OFFSET;
17639               break;
17640             }
17641         }
17642     }
17643   else if (attr_form_is_constant (attr))
17644     {
17645       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17646       prop->kind = PROP_CONST;
17647     }
17648   else
17649     {
17650       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17651                                              dwarf2_name (die, cu));
17652       return 0;
17653     }
17654
17655   return 1;
17656 }
17657
17658 /* Read the given DW_AT_subrange DIE.  */
17659
17660 static struct type *
17661 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17662 {
17663   struct type *base_type, *orig_base_type;
17664   struct type *range_type;
17665   struct attribute *attr;
17666   struct dynamic_prop low, high;
17667   int low_default_is_valid;
17668   int high_bound_is_count = 0;
17669   const char *name;
17670   LONGEST negative_mask;
17671
17672   orig_base_type = die_type (die, cu);
17673   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17674      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17675      creating the range type, but we use the result of check_typedef
17676      when examining properties of the type.  */
17677   base_type = check_typedef (orig_base_type);
17678
17679   /* The die_type call above may have already set the type for this DIE.  */
17680   range_type = get_die_type (die, cu);
17681   if (range_type)
17682     return range_type;
17683
17684   low.kind = PROP_CONST;
17685   high.kind = PROP_CONST;
17686   high.data.const_val = 0;
17687
17688   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17689      omitting DW_AT_lower_bound.  */
17690   switch (cu->language)
17691     {
17692     case language_c:
17693     case language_cplus:
17694       low.data.const_val = 0;
17695       low_default_is_valid = 1;
17696       break;
17697     case language_fortran:
17698       low.data.const_val = 1;
17699       low_default_is_valid = 1;
17700       break;
17701     case language_d:
17702     case language_objc:
17703     case language_rust:
17704       low.data.const_val = 0;
17705       low_default_is_valid = (cu->header.version >= 4);
17706       break;
17707     case language_ada:
17708     case language_m2:
17709     case language_pascal:
17710       low.data.const_val = 1;
17711       low_default_is_valid = (cu->header.version >= 4);
17712       break;
17713     default:
17714       low.data.const_val = 0;
17715       low_default_is_valid = 0;
17716       break;
17717     }
17718
17719   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17720   if (attr)
17721     attr_to_dynamic_prop (attr, die, cu, &low);
17722   else if (!low_default_is_valid)
17723     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17724                                       "- DIE at 0x%x [in module %s]"),
17725                to_underlying (die->sect_off),
17726                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17727
17728   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17729   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17730     {
17731       attr = dwarf2_attr (die, DW_AT_count, cu);
17732       if (attr_to_dynamic_prop (attr, die, cu, &high))
17733         {
17734           /* If bounds are constant do the final calculation here.  */
17735           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17736             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17737           else
17738             high_bound_is_count = 1;
17739         }
17740     }
17741
17742   /* Dwarf-2 specifications explicitly allows to create subrange types
17743      without specifying a base type.
17744      In that case, the base type must be set to the type of
17745      the lower bound, upper bound or count, in that order, if any of these
17746      three attributes references an object that has a type.
17747      If no base type is found, the Dwarf-2 specifications say that
17748      a signed integer type of size equal to the size of an address should
17749      be used.
17750      For the following C code: `extern char gdb_int [];'
17751      GCC produces an empty range DIE.
17752      FIXME: muller/2010-05-28: Possible references to object for low bound,
17753      high bound or count are not yet handled by this code.  */
17754   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17755     {
17756       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17757       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17758       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17759       struct type *int_type = objfile_type (objfile)->builtin_int;
17760
17761       /* Test "int", "long int", and "long long int" objfile types,
17762          and select the first one having a size above or equal to the
17763          architecture address size.  */
17764       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17765         base_type = int_type;
17766       else
17767         {
17768           int_type = objfile_type (objfile)->builtin_long;
17769           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17770             base_type = int_type;
17771           else
17772             {
17773               int_type = objfile_type (objfile)->builtin_long_long;
17774               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17775                 base_type = int_type;
17776             }
17777         }
17778     }
17779
17780   /* Normally, the DWARF producers are expected to use a signed
17781      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17782      But this is unfortunately not always the case, as witnessed
17783      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17784      is used instead.  To work around that ambiguity, we treat
17785      the bounds as signed, and thus sign-extend their values, when
17786      the base type is signed.  */
17787   negative_mask =
17788     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17789   if (low.kind == PROP_CONST
17790       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17791     low.data.const_val |= negative_mask;
17792   if (high.kind == PROP_CONST
17793       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17794     high.data.const_val |= negative_mask;
17795
17796   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17797
17798   if (high_bound_is_count)
17799     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17800
17801   /* Ada expects an empty array on no boundary attributes.  */
17802   if (attr == NULL && cu->language != language_ada)
17803     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17804
17805   name = dwarf2_name (die, cu);
17806   if (name)
17807     TYPE_NAME (range_type) = name;
17808
17809   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17810   if (attr)
17811     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17812
17813   set_die_type (die, range_type, cu);
17814
17815   /* set_die_type should be already done.  */
17816   set_descriptive_type (range_type, die, cu);
17817
17818   return range_type;
17819 }
17820
17821 static struct type *
17822 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17823 {
17824   struct type *type;
17825
17826   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17827                     NULL);
17828   TYPE_NAME (type) = dwarf2_name (die, cu);
17829
17830   /* In Ada, an unspecified type is typically used when the description
17831      of the type is defered to a different unit.  When encountering
17832      such a type, we treat it as a stub, and try to resolve it later on,
17833      when needed.  */
17834   if (cu->language == language_ada)
17835     TYPE_STUB (type) = 1;
17836
17837   return set_die_type (die, type, cu);
17838 }
17839
17840 /* Read a single die and all its descendents.  Set the die's sibling
17841    field to NULL; set other fields in the die correctly, and set all
17842    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17843    location of the info_ptr after reading all of those dies.  PARENT
17844    is the parent of the die in question.  */
17845
17846 static struct die_info *
17847 read_die_and_children (const struct die_reader_specs *reader,
17848                        const gdb_byte *info_ptr,
17849                        const gdb_byte **new_info_ptr,
17850                        struct die_info *parent)
17851 {
17852   struct die_info *die;
17853   const gdb_byte *cur_ptr;
17854   int has_children;
17855
17856   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17857   if (die == NULL)
17858     {
17859       *new_info_ptr = cur_ptr;
17860       return NULL;
17861     }
17862   store_in_ref_table (die, reader->cu);
17863
17864   if (has_children)
17865     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17866   else
17867     {
17868       die->child = NULL;
17869       *new_info_ptr = cur_ptr;
17870     }
17871
17872   die->sibling = NULL;
17873   die->parent = parent;
17874   return die;
17875 }
17876
17877 /* Read a die, all of its descendents, and all of its siblings; set
17878    all of the fields of all of the dies correctly.  Arguments are as
17879    in read_die_and_children.  */
17880
17881 static struct die_info *
17882 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17883                          const gdb_byte *info_ptr,
17884                          const gdb_byte **new_info_ptr,
17885                          struct die_info *parent)
17886 {
17887   struct die_info *first_die, *last_sibling;
17888   const gdb_byte *cur_ptr;
17889
17890   cur_ptr = info_ptr;
17891   first_die = last_sibling = NULL;
17892
17893   while (1)
17894     {
17895       struct die_info *die
17896         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17897
17898       if (die == NULL)
17899         {
17900           *new_info_ptr = cur_ptr;
17901           return first_die;
17902         }
17903
17904       if (!first_die)
17905         first_die = die;
17906       else
17907         last_sibling->sibling = die;
17908
17909       last_sibling = die;
17910     }
17911 }
17912
17913 /* Read a die, all of its descendents, and all of its siblings; set
17914    all of the fields of all of the dies correctly.  Arguments are as
17915    in read_die_and_children.
17916    This the main entry point for reading a DIE and all its children.  */
17917
17918 static struct die_info *
17919 read_die_and_siblings (const struct die_reader_specs *reader,
17920                        const gdb_byte *info_ptr,
17921                        const gdb_byte **new_info_ptr,
17922                        struct die_info *parent)
17923 {
17924   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17925                                                   new_info_ptr, parent);
17926
17927   if (dwarf_die_debug)
17928     {
17929       fprintf_unfiltered (gdb_stdlog,
17930                           "Read die from %s@0x%x of %s:\n",
17931                           get_section_name (reader->die_section),
17932                           (unsigned) (info_ptr - reader->die_section->buffer),
17933                           bfd_get_filename (reader->abfd));
17934       dump_die (die, dwarf_die_debug);
17935     }
17936
17937   return die;
17938 }
17939
17940 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17941    attributes.
17942    The caller is responsible for filling in the extra attributes
17943    and updating (*DIEP)->num_attrs.
17944    Set DIEP to point to a newly allocated die with its information,
17945    except for its child, sibling, and parent fields.
17946    Set HAS_CHILDREN to tell whether the die has children or not.  */
17947
17948 static const gdb_byte *
17949 read_full_die_1 (const struct die_reader_specs *reader,
17950                  struct die_info **diep, const gdb_byte *info_ptr,
17951                  int *has_children, int num_extra_attrs)
17952 {
17953   unsigned int abbrev_number, bytes_read, i;
17954   struct abbrev_info *abbrev;
17955   struct die_info *die;
17956   struct dwarf2_cu *cu = reader->cu;
17957   bfd *abfd = reader->abfd;
17958
17959   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17960   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17961   info_ptr += bytes_read;
17962   if (!abbrev_number)
17963     {
17964       *diep = NULL;
17965       *has_children = 0;
17966       return info_ptr;
17967     }
17968
17969   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17970   if (!abbrev)
17971     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17972            abbrev_number,
17973            bfd_get_filename (abfd));
17974
17975   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17976   die->sect_off = sect_off;
17977   die->tag = abbrev->tag;
17978   die->abbrev = abbrev_number;
17979
17980   /* Make the result usable.
17981      The caller needs to update num_attrs after adding the extra
17982      attributes.  */
17983   die->num_attrs = abbrev->num_attrs;
17984
17985   for (i = 0; i < abbrev->num_attrs; ++i)
17986     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17987                                info_ptr);
17988
17989   *diep = die;
17990   *has_children = abbrev->has_children;
17991   return info_ptr;
17992 }
17993
17994 /* Read a die and all its attributes.
17995    Set DIEP to point to a newly allocated die with its information,
17996    except for its child, sibling, and parent fields.
17997    Set HAS_CHILDREN to tell whether the die has children or not.  */
17998
17999 static const gdb_byte *
18000 read_full_die (const struct die_reader_specs *reader,
18001                struct die_info **diep, const gdb_byte *info_ptr,
18002                int *has_children)
18003 {
18004   const gdb_byte *result;
18005
18006   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18007
18008   if (dwarf_die_debug)
18009     {
18010       fprintf_unfiltered (gdb_stdlog,
18011                           "Read die from %s@0x%x of %s:\n",
18012                           get_section_name (reader->die_section),
18013                           (unsigned) (info_ptr - reader->die_section->buffer),
18014                           bfd_get_filename (reader->abfd));
18015       dump_die (*diep, dwarf_die_debug);
18016     }
18017
18018   return result;
18019 }
18020 \f
18021 /* Abbreviation tables.
18022
18023    In DWARF version 2, the description of the debugging information is
18024    stored in a separate .debug_abbrev section.  Before we read any
18025    dies from a section we read in all abbreviations and install them
18026    in a hash table.  */
18027
18028 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18029
18030 struct abbrev_info *
18031 abbrev_table::alloc_abbrev ()
18032 {
18033   struct abbrev_info *abbrev;
18034
18035   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18036   memset (abbrev, 0, sizeof (struct abbrev_info));
18037
18038   return abbrev;
18039 }
18040
18041 /* Add an abbreviation to the table.  */
18042
18043 void
18044 abbrev_table::add_abbrev (unsigned int abbrev_number,
18045                           struct abbrev_info *abbrev)
18046 {
18047   unsigned int hash_number;
18048
18049   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18050   abbrev->next = m_abbrevs[hash_number];
18051   m_abbrevs[hash_number] = abbrev;
18052 }
18053
18054 /* Look up an abbrev in the table.
18055    Returns NULL if the abbrev is not found.  */
18056
18057 struct abbrev_info *
18058 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18059 {
18060   unsigned int hash_number;
18061   struct abbrev_info *abbrev;
18062
18063   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18064   abbrev = m_abbrevs[hash_number];
18065
18066   while (abbrev)
18067     {
18068       if (abbrev->number == abbrev_number)
18069         return abbrev;
18070       abbrev = abbrev->next;
18071     }
18072   return NULL;
18073 }
18074
18075 /* Read in an abbrev table.  */
18076
18077 static abbrev_table_up
18078 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18079                          struct dwarf2_section_info *section,
18080                          sect_offset sect_off)
18081 {
18082   struct objfile *objfile = dwarf2_per_objfile->objfile;
18083   bfd *abfd = get_section_bfd_owner (section);
18084   const gdb_byte *abbrev_ptr;
18085   struct abbrev_info *cur_abbrev;
18086   unsigned int abbrev_number, bytes_read, abbrev_name;
18087   unsigned int abbrev_form;
18088   struct attr_abbrev *cur_attrs;
18089   unsigned int allocated_attrs;
18090
18091   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18092
18093   dwarf2_read_section (objfile, section);
18094   abbrev_ptr = section->buffer + to_underlying (sect_off);
18095   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18096   abbrev_ptr += bytes_read;
18097
18098   allocated_attrs = ATTR_ALLOC_CHUNK;
18099   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18100
18101   /* Loop until we reach an abbrev number of 0.  */
18102   while (abbrev_number)
18103     {
18104       cur_abbrev = abbrev_table->alloc_abbrev ();
18105
18106       /* read in abbrev header */
18107       cur_abbrev->number = abbrev_number;
18108       cur_abbrev->tag
18109         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18110       abbrev_ptr += bytes_read;
18111       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18112       abbrev_ptr += 1;
18113
18114       /* now read in declarations */
18115       for (;;)
18116         {
18117           LONGEST implicit_const;
18118
18119           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18120           abbrev_ptr += bytes_read;
18121           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18122           abbrev_ptr += bytes_read;
18123           if (abbrev_form == DW_FORM_implicit_const)
18124             {
18125               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18126                                                    &bytes_read);
18127               abbrev_ptr += bytes_read;
18128             }
18129           else
18130             {
18131               /* Initialize it due to a false compiler warning.  */
18132               implicit_const = -1;
18133             }
18134
18135           if (abbrev_name == 0)
18136             break;
18137
18138           if (cur_abbrev->num_attrs == allocated_attrs)
18139             {
18140               allocated_attrs += ATTR_ALLOC_CHUNK;
18141               cur_attrs
18142                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18143             }
18144
18145           cur_attrs[cur_abbrev->num_attrs].name
18146             = (enum dwarf_attribute) abbrev_name;
18147           cur_attrs[cur_abbrev->num_attrs].form
18148             = (enum dwarf_form) abbrev_form;
18149           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18150           ++cur_abbrev->num_attrs;
18151         }
18152
18153       cur_abbrev->attrs =
18154         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18155                    cur_abbrev->num_attrs);
18156       memcpy (cur_abbrev->attrs, cur_attrs,
18157               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18158
18159       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18160
18161       /* Get next abbreviation.
18162          Under Irix6 the abbreviations for a compilation unit are not
18163          always properly terminated with an abbrev number of 0.
18164          Exit loop if we encounter an abbreviation which we have
18165          already read (which means we are about to read the abbreviations
18166          for the next compile unit) or if the end of the abbreviation
18167          table is reached.  */
18168       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18169         break;
18170       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18171       abbrev_ptr += bytes_read;
18172       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18173         break;
18174     }
18175
18176   xfree (cur_attrs);
18177   return abbrev_table;
18178 }
18179
18180 /* Returns nonzero if TAG represents a type that we might generate a partial
18181    symbol for.  */
18182
18183 static int
18184 is_type_tag_for_partial (int tag)
18185 {
18186   switch (tag)
18187     {
18188 #if 0
18189     /* Some types that would be reasonable to generate partial symbols for,
18190        that we don't at present.  */
18191     case DW_TAG_array_type:
18192     case DW_TAG_file_type:
18193     case DW_TAG_ptr_to_member_type:
18194     case DW_TAG_set_type:
18195     case DW_TAG_string_type:
18196     case DW_TAG_subroutine_type:
18197 #endif
18198     case DW_TAG_base_type:
18199     case DW_TAG_class_type:
18200     case DW_TAG_interface_type:
18201     case DW_TAG_enumeration_type:
18202     case DW_TAG_structure_type:
18203     case DW_TAG_subrange_type:
18204     case DW_TAG_typedef:
18205     case DW_TAG_union_type:
18206       return 1;
18207     default:
18208       return 0;
18209     }
18210 }
18211
18212 /* Load all DIEs that are interesting for partial symbols into memory.  */
18213
18214 static struct partial_die_info *
18215 load_partial_dies (const struct die_reader_specs *reader,
18216                    const gdb_byte *info_ptr, int building_psymtab)
18217 {
18218   struct dwarf2_cu *cu = reader->cu;
18219   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18220   struct partial_die_info *part_die;
18221   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18222   unsigned int bytes_read;
18223   unsigned int load_all = 0;
18224   int nesting_level = 1;
18225
18226   parent_die = NULL;
18227   last_die = NULL;
18228
18229   gdb_assert (cu->per_cu != NULL);
18230   if (cu->per_cu->load_all_dies)
18231     load_all = 1;
18232
18233   cu->partial_dies
18234     = htab_create_alloc_ex (cu->header.length / 12,
18235                             partial_die_hash,
18236                             partial_die_eq,
18237                             NULL,
18238                             &cu->comp_unit_obstack,
18239                             hashtab_obstack_allocate,
18240                             dummy_obstack_deallocate);
18241
18242   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18243
18244   while (1)
18245     {
18246       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18247
18248       /* A NULL abbrev means the end of a series of children.  */
18249       if (abbrev == NULL)
18250         {
18251           if (--nesting_level == 0)
18252             {
18253               /* PART_DIE was probably the last thing allocated on the
18254                  comp_unit_obstack, so we could call obstack_free
18255                  here.  We don't do that because the waste is small,
18256                  and will be cleaned up when we're done with this
18257                  compilation unit.  This way, we're also more robust
18258                  against other users of the comp_unit_obstack.  */
18259               return first_die;
18260             }
18261           info_ptr += bytes_read;
18262           last_die = parent_die;
18263           parent_die = parent_die->die_parent;
18264           continue;
18265         }
18266
18267       /* Check for template arguments.  We never save these; if
18268          they're seen, we just mark the parent, and go on our way.  */
18269       if (parent_die != NULL
18270           && cu->language == language_cplus
18271           && (abbrev->tag == DW_TAG_template_type_param
18272               || abbrev->tag == DW_TAG_template_value_param))
18273         {
18274           parent_die->has_template_arguments = 1;
18275
18276           if (!load_all)
18277             {
18278               /* We don't need a partial DIE for the template argument.  */
18279               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18280               continue;
18281             }
18282         }
18283
18284       /* We only recurse into c++ subprograms looking for template arguments.
18285          Skip their other children.  */
18286       if (!load_all
18287           && cu->language == language_cplus
18288           && parent_die != NULL
18289           && parent_die->tag == DW_TAG_subprogram)
18290         {
18291           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18292           continue;
18293         }
18294
18295       /* Check whether this DIE is interesting enough to save.  Normally
18296          we would not be interested in members here, but there may be
18297          later variables referencing them via DW_AT_specification (for
18298          static members).  */
18299       if (!load_all
18300           && !is_type_tag_for_partial (abbrev->tag)
18301           && abbrev->tag != DW_TAG_constant
18302           && abbrev->tag != DW_TAG_enumerator
18303           && abbrev->tag != DW_TAG_subprogram
18304           && abbrev->tag != DW_TAG_inlined_subroutine
18305           && abbrev->tag != DW_TAG_lexical_block
18306           && abbrev->tag != DW_TAG_variable
18307           && abbrev->tag != DW_TAG_namespace
18308           && abbrev->tag != DW_TAG_module
18309           && abbrev->tag != DW_TAG_member
18310           && abbrev->tag != DW_TAG_imported_unit
18311           && abbrev->tag != DW_TAG_imported_declaration)
18312         {
18313           /* Otherwise we skip to the next sibling, if any.  */
18314           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18315           continue;
18316         }
18317
18318       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18319                                    info_ptr);
18320
18321       /* This two-pass algorithm for processing partial symbols has a
18322          high cost in cache pressure.  Thus, handle some simple cases
18323          here which cover the majority of C partial symbols.  DIEs
18324          which neither have specification tags in them, nor could have
18325          specification tags elsewhere pointing at them, can simply be
18326          processed and discarded.
18327
18328          This segment is also optional; scan_partial_symbols and
18329          add_partial_symbol will handle these DIEs if we chain
18330          them in normally.  When compilers which do not emit large
18331          quantities of duplicate debug information are more common,
18332          this code can probably be removed.  */
18333
18334       /* Any complete simple types at the top level (pretty much all
18335          of them, for a language without namespaces), can be processed
18336          directly.  */
18337       if (parent_die == NULL
18338           && part_die->has_specification == 0
18339           && part_die->is_declaration == 0
18340           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18341               || part_die->tag == DW_TAG_base_type
18342               || part_die->tag == DW_TAG_subrange_type))
18343         {
18344           if (building_psymtab && part_die->name != NULL)
18345             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18346                                  VAR_DOMAIN, LOC_TYPEDEF,
18347                                  &objfile->static_psymbols,
18348                                  0, cu->language, objfile);
18349           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18350           continue;
18351         }
18352
18353       /* The exception for DW_TAG_typedef with has_children above is
18354          a workaround of GCC PR debug/47510.  In the case of this complaint
18355          type_name_no_tag_or_error will error on such types later.
18356
18357          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18358          it could not find the child DIEs referenced later, this is checked
18359          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18360
18361       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18362         complaint (&symfile_complaints,
18363                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18364                      "- DIE at 0x%x [in module %s]"),
18365                    to_underlying (part_die->sect_off), objfile_name (objfile));
18366
18367       /* If we're at the second level, and we're an enumerator, and
18368          our parent has no specification (meaning possibly lives in a
18369          namespace elsewhere), then we can add the partial symbol now
18370          instead of queueing it.  */
18371       if (part_die->tag == DW_TAG_enumerator
18372           && parent_die != NULL
18373           && parent_die->die_parent == NULL
18374           && parent_die->tag == DW_TAG_enumeration_type
18375           && parent_die->has_specification == 0)
18376         {
18377           if (part_die->name == NULL)
18378             complaint (&symfile_complaints,
18379                        _("malformed enumerator DIE ignored"));
18380           else if (building_psymtab)
18381             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18382                                  VAR_DOMAIN, LOC_CONST,
18383                                  cu->language == language_cplus
18384                                  ? &objfile->global_psymbols
18385                                  : &objfile->static_psymbols,
18386                                  0, cu->language, objfile);
18387
18388           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18389           continue;
18390         }
18391
18392       /* We'll save this DIE so link it in.  */
18393       part_die->die_parent = parent_die;
18394       part_die->die_sibling = NULL;
18395       part_die->die_child = NULL;
18396
18397       if (last_die && last_die == parent_die)
18398         last_die->die_child = part_die;
18399       else if (last_die)
18400         last_die->die_sibling = part_die;
18401
18402       last_die = part_die;
18403
18404       if (first_die == NULL)
18405         first_die = part_die;
18406
18407       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18408          find interesting need to be in the hash table, because we
18409          also have the parent/sibling/child chains; only those that we
18410          might refer to by offset later during partial symbol reading.
18411
18412          For now this means things that might have be the target of a
18413          DW_AT_specification, DW_AT_abstract_origin, or
18414          DW_AT_extension.  DW_AT_extension will refer only to
18415          namespaces; DW_AT_abstract_origin refers to functions (and
18416          many things under the function DIE, but we do not recurse
18417          into function DIEs during partial symbol reading) and
18418          possibly variables as well; DW_AT_specification refers to
18419          declarations.  Declarations ought to have the DW_AT_declaration
18420          flag.  It happens that GCC forgets to put it in sometimes, but
18421          only for functions, not for types.
18422
18423          Adding more things than necessary to the hash table is harmless
18424          except for the performance cost.  Adding too few will result in
18425          wasted time in find_partial_die, when we reread the compilation
18426          unit with load_all_dies set.  */
18427
18428       if (load_all
18429           || abbrev->tag == DW_TAG_constant
18430           || abbrev->tag == DW_TAG_subprogram
18431           || abbrev->tag == DW_TAG_variable
18432           || abbrev->tag == DW_TAG_namespace
18433           || part_die->is_declaration)
18434         {
18435           void **slot;
18436
18437           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18438                                            to_underlying (part_die->sect_off),
18439                                            INSERT);
18440           *slot = part_die;
18441         }
18442
18443       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18444
18445       /* For some DIEs we want to follow their children (if any).  For C
18446          we have no reason to follow the children of structures; for other
18447          languages we have to, so that we can get at method physnames
18448          to infer fully qualified class names, for DW_AT_specification,
18449          and for C++ template arguments.  For C++, we also look one level
18450          inside functions to find template arguments (if the name of the
18451          function does not already contain the template arguments).
18452
18453          For Ada, we need to scan the children of subprograms and lexical
18454          blocks as well because Ada allows the definition of nested
18455          entities that could be interesting for the debugger, such as
18456          nested subprograms for instance.  */
18457       if (last_die->has_children
18458           && (load_all
18459               || last_die->tag == DW_TAG_namespace
18460               || last_die->tag == DW_TAG_module
18461               || last_die->tag == DW_TAG_enumeration_type
18462               || (cu->language == language_cplus
18463                   && last_die->tag == DW_TAG_subprogram
18464                   && (last_die->name == NULL
18465                       || strchr (last_die->name, '<') == NULL))
18466               || (cu->language != language_c
18467                   && (last_die->tag == DW_TAG_class_type
18468                       || last_die->tag == DW_TAG_interface_type
18469                       || last_die->tag == DW_TAG_structure_type
18470                       || last_die->tag == DW_TAG_union_type))
18471               || (cu->language == language_ada
18472                   && (last_die->tag == DW_TAG_subprogram
18473                       || last_die->tag == DW_TAG_lexical_block))))
18474         {
18475           nesting_level++;
18476           parent_die = last_die;
18477           continue;
18478         }
18479
18480       /* Otherwise we skip to the next sibling, if any.  */
18481       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18482
18483       /* Back to the top, do it again.  */
18484     }
18485 }
18486
18487 /* Read a minimal amount of information into the minimal die structure.  */
18488
18489 static const gdb_byte *
18490 read_partial_die (const struct die_reader_specs *reader,
18491                   struct partial_die_info *part_die,
18492                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18493                   const gdb_byte *info_ptr)
18494 {
18495   struct dwarf2_cu *cu = reader->cu;
18496   struct dwarf2_per_objfile *dwarf2_per_objfile
18497     = cu->per_cu->dwarf2_per_objfile;
18498   struct objfile *objfile = dwarf2_per_objfile->objfile;
18499   const gdb_byte *buffer = reader->buffer;
18500   unsigned int i;
18501   struct attribute attr;
18502   int has_low_pc_attr = 0;
18503   int has_high_pc_attr = 0;
18504   int high_pc_relative = 0;
18505
18506   memset (part_die, 0, sizeof (struct partial_die_info));
18507
18508   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18509
18510   info_ptr += abbrev_len;
18511
18512   if (abbrev == NULL)
18513     return info_ptr;
18514
18515   part_die->tag = abbrev->tag;
18516   part_die->has_children = abbrev->has_children;
18517
18518   for (i = 0; i < abbrev->num_attrs; ++i)
18519     {
18520       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18521
18522       /* Store the data if it is of an attribute we want to keep in a
18523          partial symbol table.  */
18524       switch (attr.name)
18525         {
18526         case DW_AT_name:
18527           switch (part_die->tag)
18528             {
18529             case DW_TAG_compile_unit:
18530             case DW_TAG_partial_unit:
18531             case DW_TAG_type_unit:
18532               /* Compilation units have a DW_AT_name that is a filename, not
18533                  a source language identifier.  */
18534             case DW_TAG_enumeration_type:
18535             case DW_TAG_enumerator:
18536               /* These tags always have simple identifiers already; no need
18537                  to canonicalize them.  */
18538               part_die->name = DW_STRING (&attr);
18539               break;
18540             default:
18541               part_die->name
18542                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18543                                             &objfile->per_bfd->storage_obstack);
18544               break;
18545             }
18546           break;
18547         case DW_AT_linkage_name:
18548         case DW_AT_MIPS_linkage_name:
18549           /* Note that both forms of linkage name might appear.  We
18550              assume they will be the same, and we only store the last
18551              one we see.  */
18552           if (cu->language == language_ada)
18553             part_die->name = DW_STRING (&attr);
18554           part_die->linkage_name = DW_STRING (&attr);
18555           break;
18556         case DW_AT_low_pc:
18557           has_low_pc_attr = 1;
18558           part_die->lowpc = attr_value_as_address (&attr);
18559           break;
18560         case DW_AT_high_pc:
18561           has_high_pc_attr = 1;
18562           part_die->highpc = attr_value_as_address (&attr);
18563           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18564                 high_pc_relative = 1;
18565           break;
18566         case DW_AT_location:
18567           /* Support the .debug_loc offsets.  */
18568           if (attr_form_is_block (&attr))
18569             {
18570                part_die->d.locdesc = DW_BLOCK (&attr);
18571             }
18572           else if (attr_form_is_section_offset (&attr))
18573             {
18574               dwarf2_complex_location_expr_complaint ();
18575             }
18576           else
18577             {
18578               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18579                                                      "partial symbol information");
18580             }
18581           break;
18582         case DW_AT_external:
18583           part_die->is_external = DW_UNSND (&attr);
18584           break;
18585         case DW_AT_declaration:
18586           part_die->is_declaration = DW_UNSND (&attr);
18587           break;
18588         case DW_AT_type:
18589           part_die->has_type = 1;
18590           break;
18591         case DW_AT_abstract_origin:
18592         case DW_AT_specification:
18593         case DW_AT_extension:
18594           part_die->has_specification = 1;
18595           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18596           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18597                                    || cu->per_cu->is_dwz);
18598           break;
18599         case DW_AT_sibling:
18600           /* Ignore absolute siblings, they might point outside of
18601              the current compile unit.  */
18602           if (attr.form == DW_FORM_ref_addr)
18603             complaint (&symfile_complaints,
18604                        _("ignoring absolute DW_AT_sibling"));
18605           else
18606             {
18607               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18608               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18609
18610               if (sibling_ptr < info_ptr)
18611                 complaint (&symfile_complaints,
18612                            _("DW_AT_sibling points backwards"));
18613               else if (sibling_ptr > reader->buffer_end)
18614                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18615               else
18616                 part_die->sibling = sibling_ptr;
18617             }
18618           break;
18619         case DW_AT_byte_size:
18620           part_die->has_byte_size = 1;
18621           break;
18622         case DW_AT_const_value:
18623           part_die->has_const_value = 1;
18624           break;
18625         case DW_AT_calling_convention:
18626           /* DWARF doesn't provide a way to identify a program's source-level
18627              entry point.  DW_AT_calling_convention attributes are only meant
18628              to describe functions' calling conventions.
18629
18630              However, because it's a necessary piece of information in
18631              Fortran, and before DWARF 4 DW_CC_program was the only
18632              piece of debugging information whose definition refers to
18633              a 'main program' at all, several compilers marked Fortran
18634              main programs with DW_CC_program --- even when those
18635              functions use the standard calling conventions.
18636
18637              Although DWARF now specifies a way to provide this
18638              information, we support this practice for backward
18639              compatibility.  */
18640           if (DW_UNSND (&attr) == DW_CC_program
18641               && cu->language == language_fortran)
18642             part_die->main_subprogram = 1;
18643           break;
18644         case DW_AT_inline:
18645           if (DW_UNSND (&attr) == DW_INL_inlined
18646               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18647             part_die->may_be_inlined = 1;
18648           break;
18649
18650         case DW_AT_import:
18651           if (part_die->tag == DW_TAG_imported_unit)
18652             {
18653               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18654               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18655                                   || cu->per_cu->is_dwz);
18656             }
18657           break;
18658
18659         case DW_AT_main_subprogram:
18660           part_die->main_subprogram = DW_UNSND (&attr);
18661           break;
18662
18663         default:
18664           break;
18665         }
18666     }
18667
18668   if (high_pc_relative)
18669     part_die->highpc += part_die->lowpc;
18670
18671   if (has_low_pc_attr && has_high_pc_attr)
18672     {
18673       /* When using the GNU linker, .gnu.linkonce. sections are used to
18674          eliminate duplicate copies of functions and vtables and such.
18675          The linker will arbitrarily choose one and discard the others.
18676          The AT_*_pc values for such functions refer to local labels in
18677          these sections.  If the section from that file was discarded, the
18678          labels are not in the output, so the relocs get a value of 0.
18679          If this is a discarded function, mark the pc bounds as invalid,
18680          so that GDB will ignore it.  */
18681       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18682         {
18683           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18684
18685           complaint (&symfile_complaints,
18686                      _("DW_AT_low_pc %s is zero "
18687                        "for DIE at 0x%x [in module %s]"),
18688                      paddress (gdbarch, part_die->lowpc),
18689                      to_underlying (part_die->sect_off), objfile_name (objfile));
18690         }
18691       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18692       else if (part_die->lowpc >= part_die->highpc)
18693         {
18694           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18695
18696           complaint (&symfile_complaints,
18697                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18698                        "for DIE at 0x%x [in module %s]"),
18699                      paddress (gdbarch, part_die->lowpc),
18700                      paddress (gdbarch, part_die->highpc),
18701                      to_underlying (part_die->sect_off),
18702                      objfile_name (objfile));
18703         }
18704       else
18705         part_die->has_pc_info = 1;
18706     }
18707
18708   return info_ptr;
18709 }
18710
18711 /* Find a cached partial DIE at OFFSET in CU.  */
18712
18713 static struct partial_die_info *
18714 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18715 {
18716   struct partial_die_info *lookup_die = NULL;
18717   struct partial_die_info part_die;
18718
18719   part_die.sect_off = sect_off;
18720   lookup_die = ((struct partial_die_info *)
18721                 htab_find_with_hash (cu->partial_dies, &part_die,
18722                                      to_underlying (sect_off)));
18723
18724   return lookup_die;
18725 }
18726
18727 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18728    except in the case of .debug_types DIEs which do not reference
18729    outside their CU (they do however referencing other types via
18730    DW_FORM_ref_sig8).  */
18731
18732 static struct partial_die_info *
18733 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18734 {
18735   struct dwarf2_per_objfile *dwarf2_per_objfile
18736     = cu->per_cu->dwarf2_per_objfile;
18737   struct objfile *objfile = dwarf2_per_objfile->objfile;
18738   struct dwarf2_per_cu_data *per_cu = NULL;
18739   struct partial_die_info *pd = NULL;
18740
18741   if (offset_in_dwz == cu->per_cu->is_dwz
18742       && offset_in_cu_p (&cu->header, sect_off))
18743     {
18744       pd = find_partial_die_in_comp_unit (sect_off, cu);
18745       if (pd != NULL)
18746         return pd;
18747       /* We missed recording what we needed.
18748          Load all dies and try again.  */
18749       per_cu = cu->per_cu;
18750     }
18751   else
18752     {
18753       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18754       if (cu->per_cu->is_debug_types)
18755         {
18756           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18757                    " external reference to offset 0x%x [in module %s].\n"),
18758                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18759                  bfd_get_filename (objfile->obfd));
18760         }
18761       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18762                                                  dwarf2_per_objfile);
18763
18764       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18765         load_partial_comp_unit (per_cu);
18766
18767       per_cu->cu->last_used = 0;
18768       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18769     }
18770
18771   /* If we didn't find it, and not all dies have been loaded,
18772      load them all and try again.  */
18773
18774   if (pd == NULL && per_cu->load_all_dies == 0)
18775     {
18776       per_cu->load_all_dies = 1;
18777
18778       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18779          THIS_CU->cu may already be in use.  So we can't just free it and
18780          replace its DIEs with the ones we read in.  Instead, we leave those
18781          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18782          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18783          set.  */
18784       load_partial_comp_unit (per_cu);
18785
18786       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18787     }
18788
18789   if (pd == NULL)
18790     internal_error (__FILE__, __LINE__,
18791                     _("could not find partial DIE 0x%x "
18792                       "in cache [from module %s]\n"),
18793                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18794   return pd;
18795 }
18796
18797 /* See if we can figure out if the class lives in a namespace.  We do
18798    this by looking for a member function; its demangled name will
18799    contain namespace info, if there is any.  */
18800
18801 static void
18802 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18803                                   struct dwarf2_cu *cu)
18804 {
18805   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18806      what template types look like, because the demangler
18807      frequently doesn't give the same name as the debug info.  We
18808      could fix this by only using the demangled name to get the
18809      prefix (but see comment in read_structure_type).  */
18810
18811   struct partial_die_info *real_pdi;
18812   struct partial_die_info *child_pdi;
18813
18814   /* If this DIE (this DIE's specification, if any) has a parent, then
18815      we should not do this.  We'll prepend the parent's fully qualified
18816      name when we create the partial symbol.  */
18817
18818   real_pdi = struct_pdi;
18819   while (real_pdi->has_specification)
18820     real_pdi = find_partial_die (real_pdi->spec_offset,
18821                                  real_pdi->spec_is_dwz, cu);
18822
18823   if (real_pdi->die_parent != NULL)
18824     return;
18825
18826   for (child_pdi = struct_pdi->die_child;
18827        child_pdi != NULL;
18828        child_pdi = child_pdi->die_sibling)
18829     {
18830       if (child_pdi->tag == DW_TAG_subprogram
18831           && child_pdi->linkage_name != NULL)
18832         {
18833           char *actual_class_name
18834             = language_class_name_from_physname (cu->language_defn,
18835                                                  child_pdi->linkage_name);
18836           if (actual_class_name != NULL)
18837             {
18838               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18839               struct_pdi->name
18840                 = ((const char *)
18841                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18842                                   actual_class_name,
18843                                   strlen (actual_class_name)));
18844               xfree (actual_class_name);
18845             }
18846           break;
18847         }
18848     }
18849 }
18850
18851 /* Adjust PART_DIE before generating a symbol for it.  This function
18852    may set the is_external flag or change the DIE's name.  */
18853
18854 static void
18855 fixup_partial_die (struct partial_die_info *part_die,
18856                    struct dwarf2_cu *cu)
18857 {
18858   /* Once we've fixed up a die, there's no point in doing so again.
18859      This also avoids a memory leak if we were to call
18860      guess_partial_die_structure_name multiple times.  */
18861   if (part_die->fixup_called)
18862     return;
18863
18864   /* If we found a reference attribute and the DIE has no name, try
18865      to find a name in the referred to DIE.  */
18866
18867   if (part_die->name == NULL && part_die->has_specification)
18868     {
18869       struct partial_die_info *spec_die;
18870
18871       spec_die = find_partial_die (part_die->spec_offset,
18872                                    part_die->spec_is_dwz, cu);
18873
18874       fixup_partial_die (spec_die, cu);
18875
18876       if (spec_die->name)
18877         {
18878           part_die->name = spec_die->name;
18879
18880           /* Copy DW_AT_external attribute if it is set.  */
18881           if (spec_die->is_external)
18882             part_die->is_external = spec_die->is_external;
18883         }
18884     }
18885
18886   /* Set default names for some unnamed DIEs.  */
18887
18888   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18889     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18890
18891   /* If there is no parent die to provide a namespace, and there are
18892      children, see if we can determine the namespace from their linkage
18893      name.  */
18894   if (cu->language == language_cplus
18895       && !VEC_empty (dwarf2_section_info_def,
18896                      cu->per_cu->dwarf2_per_objfile->types)
18897       && part_die->die_parent == NULL
18898       && part_die->has_children
18899       && (part_die->tag == DW_TAG_class_type
18900           || part_die->tag == DW_TAG_structure_type
18901           || part_die->tag == DW_TAG_union_type))
18902     guess_partial_die_structure_name (part_die, cu);
18903
18904   /* GCC might emit a nameless struct or union that has a linkage
18905      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18906   if (part_die->name == NULL
18907       && (part_die->tag == DW_TAG_class_type
18908           || part_die->tag == DW_TAG_interface_type
18909           || part_die->tag == DW_TAG_structure_type
18910           || part_die->tag == DW_TAG_union_type)
18911       && part_die->linkage_name != NULL)
18912     {
18913       char *demangled;
18914
18915       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18916       if (demangled)
18917         {
18918           const char *base;
18919
18920           /* Strip any leading namespaces/classes, keep only the base name.
18921              DW_AT_name for named DIEs does not contain the prefixes.  */
18922           base = strrchr (demangled, ':');
18923           if (base && base > demangled && base[-1] == ':')
18924             base++;
18925           else
18926             base = demangled;
18927
18928           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18929           part_die->name
18930             = ((const char *)
18931                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18932                               base, strlen (base)));
18933           xfree (demangled);
18934         }
18935     }
18936
18937   part_die->fixup_called = 1;
18938 }
18939
18940 /* Read an attribute value described by an attribute form.  */
18941
18942 static const gdb_byte *
18943 read_attribute_value (const struct die_reader_specs *reader,
18944                       struct attribute *attr, unsigned form,
18945                       LONGEST implicit_const, const gdb_byte *info_ptr)
18946 {
18947   struct dwarf2_cu *cu = reader->cu;
18948   struct dwarf2_per_objfile *dwarf2_per_objfile
18949     = cu->per_cu->dwarf2_per_objfile;
18950   struct objfile *objfile = dwarf2_per_objfile->objfile;
18951   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18952   bfd *abfd = reader->abfd;
18953   struct comp_unit_head *cu_header = &cu->header;
18954   unsigned int bytes_read;
18955   struct dwarf_block *blk;
18956
18957   attr->form = (enum dwarf_form) form;
18958   switch (form)
18959     {
18960     case DW_FORM_ref_addr:
18961       if (cu->header.version == 2)
18962         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18963       else
18964         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18965                                        &cu->header, &bytes_read);
18966       info_ptr += bytes_read;
18967       break;
18968     case DW_FORM_GNU_ref_alt:
18969       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18970       info_ptr += bytes_read;
18971       break;
18972     case DW_FORM_addr:
18973       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18974       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18975       info_ptr += bytes_read;
18976       break;
18977     case DW_FORM_block2:
18978       blk = dwarf_alloc_block (cu);
18979       blk->size = read_2_bytes (abfd, info_ptr);
18980       info_ptr += 2;
18981       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18982       info_ptr += blk->size;
18983       DW_BLOCK (attr) = blk;
18984       break;
18985     case DW_FORM_block4:
18986       blk = dwarf_alloc_block (cu);
18987       blk->size = read_4_bytes (abfd, info_ptr);
18988       info_ptr += 4;
18989       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18990       info_ptr += blk->size;
18991       DW_BLOCK (attr) = blk;
18992       break;
18993     case DW_FORM_data2:
18994       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18995       info_ptr += 2;
18996       break;
18997     case DW_FORM_data4:
18998       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18999       info_ptr += 4;
19000       break;
19001     case DW_FORM_data8:
19002       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19003       info_ptr += 8;
19004       break;
19005     case DW_FORM_data16:
19006       blk = dwarf_alloc_block (cu);
19007       blk->size = 16;
19008       blk->data = read_n_bytes (abfd, info_ptr, 16);
19009       info_ptr += 16;
19010       DW_BLOCK (attr) = blk;
19011       break;
19012     case DW_FORM_sec_offset:
19013       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19014       info_ptr += bytes_read;
19015       break;
19016     case DW_FORM_string:
19017       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19018       DW_STRING_IS_CANONICAL (attr) = 0;
19019       info_ptr += bytes_read;
19020       break;
19021     case DW_FORM_strp:
19022       if (!cu->per_cu->is_dwz)
19023         {
19024           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19025                                                    abfd, info_ptr, cu_header,
19026                                                    &bytes_read);
19027           DW_STRING_IS_CANONICAL (attr) = 0;
19028           info_ptr += bytes_read;
19029           break;
19030         }
19031       /* FALLTHROUGH */
19032     case DW_FORM_line_strp:
19033       if (!cu->per_cu->is_dwz)
19034         {
19035           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19036                                                         abfd, info_ptr,
19037                                                         cu_header, &bytes_read);
19038           DW_STRING_IS_CANONICAL (attr) = 0;
19039           info_ptr += bytes_read;
19040           break;
19041         }
19042       /* FALLTHROUGH */
19043     case DW_FORM_GNU_strp_alt:
19044       {
19045         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19046         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19047                                           &bytes_read);
19048
19049         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19050                                                           dwz, str_offset);
19051         DW_STRING_IS_CANONICAL (attr) = 0;
19052         info_ptr += bytes_read;
19053       }
19054       break;
19055     case DW_FORM_exprloc:
19056     case DW_FORM_block:
19057       blk = dwarf_alloc_block (cu);
19058       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19059       info_ptr += bytes_read;
19060       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19061       info_ptr += blk->size;
19062       DW_BLOCK (attr) = blk;
19063       break;
19064     case DW_FORM_block1:
19065       blk = dwarf_alloc_block (cu);
19066       blk->size = read_1_byte (abfd, info_ptr);
19067       info_ptr += 1;
19068       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19069       info_ptr += blk->size;
19070       DW_BLOCK (attr) = blk;
19071       break;
19072     case DW_FORM_data1:
19073       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19074       info_ptr += 1;
19075       break;
19076     case DW_FORM_flag:
19077       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19078       info_ptr += 1;
19079       break;
19080     case DW_FORM_flag_present:
19081       DW_UNSND (attr) = 1;
19082       break;
19083     case DW_FORM_sdata:
19084       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19085       info_ptr += bytes_read;
19086       break;
19087     case DW_FORM_udata:
19088       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19089       info_ptr += bytes_read;
19090       break;
19091     case DW_FORM_ref1:
19092       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19093                          + read_1_byte (abfd, info_ptr));
19094       info_ptr += 1;
19095       break;
19096     case DW_FORM_ref2:
19097       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19098                          + read_2_bytes (abfd, info_ptr));
19099       info_ptr += 2;
19100       break;
19101     case DW_FORM_ref4:
19102       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19103                          + read_4_bytes (abfd, info_ptr));
19104       info_ptr += 4;
19105       break;
19106     case DW_FORM_ref8:
19107       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19108                          + read_8_bytes (abfd, info_ptr));
19109       info_ptr += 8;
19110       break;
19111     case DW_FORM_ref_sig8:
19112       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19113       info_ptr += 8;
19114       break;
19115     case DW_FORM_ref_udata:
19116       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19117                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19118       info_ptr += bytes_read;
19119       break;
19120     case DW_FORM_indirect:
19121       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19122       info_ptr += bytes_read;
19123       if (form == DW_FORM_implicit_const)
19124         {
19125           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19126           info_ptr += bytes_read;
19127         }
19128       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19129                                        info_ptr);
19130       break;
19131     case DW_FORM_implicit_const:
19132       DW_SND (attr) = implicit_const;
19133       break;
19134     case DW_FORM_GNU_addr_index:
19135       if (reader->dwo_file == NULL)
19136         {
19137           /* For now flag a hard error.
19138              Later we can turn this into a complaint.  */
19139           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19140                  dwarf_form_name (form),
19141                  bfd_get_filename (abfd));
19142         }
19143       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19144       info_ptr += bytes_read;
19145       break;
19146     case DW_FORM_GNU_str_index:
19147       if (reader->dwo_file == NULL)
19148         {
19149           /* For now flag a hard error.
19150              Later we can turn this into a complaint if warranted.  */
19151           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19152                  dwarf_form_name (form),
19153                  bfd_get_filename (abfd));
19154         }
19155       {
19156         ULONGEST str_index =
19157           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19158
19159         DW_STRING (attr) = read_str_index (reader, str_index);
19160         DW_STRING_IS_CANONICAL (attr) = 0;
19161         info_ptr += bytes_read;
19162       }
19163       break;
19164     default:
19165       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19166              dwarf_form_name (form),
19167              bfd_get_filename (abfd));
19168     }
19169
19170   /* Super hack.  */
19171   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19172     attr->form = DW_FORM_GNU_ref_alt;
19173
19174   /* We have seen instances where the compiler tried to emit a byte
19175      size attribute of -1 which ended up being encoded as an unsigned
19176      0xffffffff.  Although 0xffffffff is technically a valid size value,
19177      an object of this size seems pretty unlikely so we can relatively
19178      safely treat these cases as if the size attribute was invalid and
19179      treat them as zero by default.  */
19180   if (attr->name == DW_AT_byte_size
19181       && form == DW_FORM_data4
19182       && DW_UNSND (attr) >= 0xffffffff)
19183     {
19184       complaint
19185         (&symfile_complaints,
19186          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19187          hex_string (DW_UNSND (attr)));
19188       DW_UNSND (attr) = 0;
19189     }
19190
19191   return info_ptr;
19192 }
19193
19194 /* Read an attribute described by an abbreviated attribute.  */
19195
19196 static const gdb_byte *
19197 read_attribute (const struct die_reader_specs *reader,
19198                 struct attribute *attr, struct attr_abbrev *abbrev,
19199                 const gdb_byte *info_ptr)
19200 {
19201   attr->name = abbrev->name;
19202   return read_attribute_value (reader, attr, abbrev->form,
19203                                abbrev->implicit_const, info_ptr);
19204 }
19205
19206 /* Read dwarf information from a buffer.  */
19207
19208 static unsigned int
19209 read_1_byte (bfd *abfd, const gdb_byte *buf)
19210 {
19211   return bfd_get_8 (abfd, buf);
19212 }
19213
19214 static int
19215 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19216 {
19217   return bfd_get_signed_8 (abfd, buf);
19218 }
19219
19220 static unsigned int
19221 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19222 {
19223   return bfd_get_16 (abfd, buf);
19224 }
19225
19226 static int
19227 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19228 {
19229   return bfd_get_signed_16 (abfd, buf);
19230 }
19231
19232 static unsigned int
19233 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19234 {
19235   return bfd_get_32 (abfd, buf);
19236 }
19237
19238 static int
19239 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19240 {
19241   return bfd_get_signed_32 (abfd, buf);
19242 }
19243
19244 static ULONGEST
19245 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19246 {
19247   return bfd_get_64 (abfd, buf);
19248 }
19249
19250 static CORE_ADDR
19251 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19252               unsigned int *bytes_read)
19253 {
19254   struct comp_unit_head *cu_header = &cu->header;
19255   CORE_ADDR retval = 0;
19256
19257   if (cu_header->signed_addr_p)
19258     {
19259       switch (cu_header->addr_size)
19260         {
19261         case 2:
19262           retval = bfd_get_signed_16 (abfd, buf);
19263           break;
19264         case 4:
19265           retval = bfd_get_signed_32 (abfd, buf);
19266           break;
19267         case 8:
19268           retval = bfd_get_signed_64 (abfd, buf);
19269           break;
19270         default:
19271           internal_error (__FILE__, __LINE__,
19272                           _("read_address: bad switch, signed [in module %s]"),
19273                           bfd_get_filename (abfd));
19274         }
19275     }
19276   else
19277     {
19278       switch (cu_header->addr_size)
19279         {
19280         case 2:
19281           retval = bfd_get_16 (abfd, buf);
19282           break;
19283         case 4:
19284           retval = bfd_get_32 (abfd, buf);
19285           break;
19286         case 8:
19287           retval = bfd_get_64 (abfd, buf);
19288           break;
19289         default:
19290           internal_error (__FILE__, __LINE__,
19291                           _("read_address: bad switch, "
19292                             "unsigned [in module %s]"),
19293                           bfd_get_filename (abfd));
19294         }
19295     }
19296
19297   *bytes_read = cu_header->addr_size;
19298   return retval;
19299 }
19300
19301 /* Read the initial length from a section.  The (draft) DWARF 3
19302    specification allows the initial length to take up either 4 bytes
19303    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19304    bytes describe the length and all offsets will be 8 bytes in length
19305    instead of 4.
19306
19307    An older, non-standard 64-bit format is also handled by this
19308    function.  The older format in question stores the initial length
19309    as an 8-byte quantity without an escape value.  Lengths greater
19310    than 2^32 aren't very common which means that the initial 4 bytes
19311    is almost always zero.  Since a length value of zero doesn't make
19312    sense for the 32-bit format, this initial zero can be considered to
19313    be an escape value which indicates the presence of the older 64-bit
19314    format.  As written, the code can't detect (old format) lengths
19315    greater than 4GB.  If it becomes necessary to handle lengths
19316    somewhat larger than 4GB, we could allow other small values (such
19317    as the non-sensical values of 1, 2, and 3) to also be used as
19318    escape values indicating the presence of the old format.
19319
19320    The value returned via bytes_read should be used to increment the
19321    relevant pointer after calling read_initial_length().
19322
19323    [ Note:  read_initial_length() and read_offset() are based on the
19324      document entitled "DWARF Debugging Information Format", revision
19325      3, draft 8, dated November 19, 2001.  This document was obtained
19326      from:
19327
19328         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19329
19330      This document is only a draft and is subject to change.  (So beware.)
19331
19332      Details regarding the older, non-standard 64-bit format were
19333      determined empirically by examining 64-bit ELF files produced by
19334      the SGI toolchain on an IRIX 6.5 machine.
19335
19336      - Kevin, July 16, 2002
19337    ] */
19338
19339 static LONGEST
19340 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19341 {
19342   LONGEST length = bfd_get_32 (abfd, buf);
19343
19344   if (length == 0xffffffff)
19345     {
19346       length = bfd_get_64 (abfd, buf + 4);
19347       *bytes_read = 12;
19348     }
19349   else if (length == 0)
19350     {
19351       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19352       length = bfd_get_64 (abfd, buf);
19353       *bytes_read = 8;
19354     }
19355   else
19356     {
19357       *bytes_read = 4;
19358     }
19359
19360   return length;
19361 }
19362
19363 /* Cover function for read_initial_length.
19364    Returns the length of the object at BUF, and stores the size of the
19365    initial length in *BYTES_READ and stores the size that offsets will be in
19366    *OFFSET_SIZE.
19367    If the initial length size is not equivalent to that specified in
19368    CU_HEADER then issue a complaint.
19369    This is useful when reading non-comp-unit headers.  */
19370
19371 static LONGEST
19372 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19373                                         const struct comp_unit_head *cu_header,
19374                                         unsigned int *bytes_read,
19375                                         unsigned int *offset_size)
19376 {
19377   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19378
19379   gdb_assert (cu_header->initial_length_size == 4
19380               || cu_header->initial_length_size == 8
19381               || cu_header->initial_length_size == 12);
19382
19383   if (cu_header->initial_length_size != *bytes_read)
19384     complaint (&symfile_complaints,
19385                _("intermixed 32-bit and 64-bit DWARF sections"));
19386
19387   *offset_size = (*bytes_read == 4) ? 4 : 8;
19388   return length;
19389 }
19390
19391 /* Read an offset from the data stream.  The size of the offset is
19392    given by cu_header->offset_size.  */
19393
19394 static LONGEST
19395 read_offset (bfd *abfd, const gdb_byte *buf,
19396              const struct comp_unit_head *cu_header,
19397              unsigned int *bytes_read)
19398 {
19399   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19400
19401   *bytes_read = cu_header->offset_size;
19402   return offset;
19403 }
19404
19405 /* Read an offset from the data stream.  */
19406
19407 static LONGEST
19408 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19409 {
19410   LONGEST retval = 0;
19411
19412   switch (offset_size)
19413     {
19414     case 4:
19415       retval = bfd_get_32 (abfd, buf);
19416       break;
19417     case 8:
19418       retval = bfd_get_64 (abfd, buf);
19419       break;
19420     default:
19421       internal_error (__FILE__, __LINE__,
19422                       _("read_offset_1: bad switch [in module %s]"),
19423                       bfd_get_filename (abfd));
19424     }
19425
19426   return retval;
19427 }
19428
19429 static const gdb_byte *
19430 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19431 {
19432   /* If the size of a host char is 8 bits, we can return a pointer
19433      to the buffer, otherwise we have to copy the data to a buffer
19434      allocated on the temporary obstack.  */
19435   gdb_assert (HOST_CHAR_BIT == 8);
19436   return buf;
19437 }
19438
19439 static const char *
19440 read_direct_string (bfd *abfd, const gdb_byte *buf,
19441                     unsigned int *bytes_read_ptr)
19442 {
19443   /* If the size of a host char is 8 bits, we can return a pointer
19444      to the string, otherwise we have to copy the string to a buffer
19445      allocated on the temporary obstack.  */
19446   gdb_assert (HOST_CHAR_BIT == 8);
19447   if (*buf == '\0')
19448     {
19449       *bytes_read_ptr = 1;
19450       return NULL;
19451     }
19452   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19453   return (const char *) buf;
19454 }
19455
19456 /* Return pointer to string at section SECT offset STR_OFFSET with error
19457    reporting strings FORM_NAME and SECT_NAME.  */
19458
19459 static const char *
19460 read_indirect_string_at_offset_from (struct objfile *objfile,
19461                                      bfd *abfd, LONGEST str_offset,
19462                                      struct dwarf2_section_info *sect,
19463                                      const char *form_name,
19464                                      const char *sect_name)
19465 {
19466   dwarf2_read_section (objfile, sect);
19467   if (sect->buffer == NULL)
19468     error (_("%s used without %s section [in module %s]"),
19469            form_name, sect_name, bfd_get_filename (abfd));
19470   if (str_offset >= sect->size)
19471     error (_("%s pointing outside of %s section [in module %s]"),
19472            form_name, sect_name, bfd_get_filename (abfd));
19473   gdb_assert (HOST_CHAR_BIT == 8);
19474   if (sect->buffer[str_offset] == '\0')
19475     return NULL;
19476   return (const char *) (sect->buffer + str_offset);
19477 }
19478
19479 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19480
19481 static const char *
19482 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19483                                 bfd *abfd, LONGEST str_offset)
19484 {
19485   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19486                                               abfd, str_offset,
19487                                               &dwarf2_per_objfile->str,
19488                                               "DW_FORM_strp", ".debug_str");
19489 }
19490
19491 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19492
19493 static const char *
19494 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19495                                      bfd *abfd, LONGEST str_offset)
19496 {
19497   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19498                                               abfd, str_offset,
19499                                               &dwarf2_per_objfile->line_str,
19500                                               "DW_FORM_line_strp",
19501                                               ".debug_line_str");
19502 }
19503
19504 /* Read a string at offset STR_OFFSET in the .debug_str section from
19505    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19506    the string consists of a single NUL byte, return NULL; otherwise
19507    return a pointer to the string.  */
19508
19509 static const char *
19510 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19511                                LONGEST str_offset)
19512 {
19513   dwarf2_read_section (objfile, &dwz->str);
19514
19515   if (dwz->str.buffer == NULL)
19516     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19517              "section [in module %s]"),
19518            bfd_get_filename (dwz->dwz_bfd));
19519   if (str_offset >= dwz->str.size)
19520     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19521              ".debug_str section [in module %s]"),
19522            bfd_get_filename (dwz->dwz_bfd));
19523   gdb_assert (HOST_CHAR_BIT == 8);
19524   if (dwz->str.buffer[str_offset] == '\0')
19525     return NULL;
19526   return (const char *) (dwz->str.buffer + str_offset);
19527 }
19528
19529 /* Return pointer to string at .debug_str offset as read from BUF.
19530    BUF is assumed to be in a compilation unit described by CU_HEADER.
19531    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19532
19533 static const char *
19534 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19535                       const gdb_byte *buf,
19536                       const struct comp_unit_head *cu_header,
19537                       unsigned int *bytes_read_ptr)
19538 {
19539   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19540
19541   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19542 }
19543
19544 /* Return pointer to string at .debug_line_str offset as read from BUF.
19545    BUF is assumed to be in a compilation unit described by CU_HEADER.
19546    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19547
19548 static const char *
19549 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19550                            bfd *abfd, const gdb_byte *buf,
19551                            const struct comp_unit_head *cu_header,
19552                            unsigned int *bytes_read_ptr)
19553 {
19554   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19555
19556   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19557                                               str_offset);
19558 }
19559
19560 ULONGEST
19561 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19562                           unsigned int *bytes_read_ptr)
19563 {
19564   ULONGEST result;
19565   unsigned int num_read;
19566   int shift;
19567   unsigned char byte;
19568
19569   result = 0;
19570   shift = 0;
19571   num_read = 0;
19572   while (1)
19573     {
19574       byte = bfd_get_8 (abfd, buf);
19575       buf++;
19576       num_read++;
19577       result |= ((ULONGEST) (byte & 127) << shift);
19578       if ((byte & 128) == 0)
19579         {
19580           break;
19581         }
19582       shift += 7;
19583     }
19584   *bytes_read_ptr = num_read;
19585   return result;
19586 }
19587
19588 static LONGEST
19589 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19590                     unsigned int *bytes_read_ptr)
19591 {
19592   LONGEST result;
19593   int shift, num_read;
19594   unsigned char byte;
19595
19596   result = 0;
19597   shift = 0;
19598   num_read = 0;
19599   while (1)
19600     {
19601       byte = bfd_get_8 (abfd, buf);
19602       buf++;
19603       num_read++;
19604       result |= ((LONGEST) (byte & 127) << shift);
19605       shift += 7;
19606       if ((byte & 128) == 0)
19607         {
19608           break;
19609         }
19610     }
19611   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19612     result |= -(((LONGEST) 1) << shift);
19613   *bytes_read_ptr = num_read;
19614   return result;
19615 }
19616
19617 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19618    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19619    ADDR_SIZE is the size of addresses from the CU header.  */
19620
19621 static CORE_ADDR
19622 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19623                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19624 {
19625   struct objfile *objfile = dwarf2_per_objfile->objfile;
19626   bfd *abfd = objfile->obfd;
19627   const gdb_byte *info_ptr;
19628
19629   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19630   if (dwarf2_per_objfile->addr.buffer == NULL)
19631     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19632            objfile_name (objfile));
19633   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19634     error (_("DW_FORM_addr_index pointing outside of "
19635              ".debug_addr section [in module %s]"),
19636            objfile_name (objfile));
19637   info_ptr = (dwarf2_per_objfile->addr.buffer
19638               + addr_base + addr_index * addr_size);
19639   if (addr_size == 4)
19640     return bfd_get_32 (abfd, info_ptr);
19641   else
19642     return bfd_get_64 (abfd, info_ptr);
19643 }
19644
19645 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19646
19647 static CORE_ADDR
19648 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19649 {
19650   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19651                             cu->addr_base, cu->header.addr_size);
19652 }
19653
19654 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19655
19656 static CORE_ADDR
19657 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19658                              unsigned int *bytes_read)
19659 {
19660   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19661   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19662
19663   return read_addr_index (cu, addr_index);
19664 }
19665
19666 /* Data structure to pass results from dwarf2_read_addr_index_reader
19667    back to dwarf2_read_addr_index.  */
19668
19669 struct dwarf2_read_addr_index_data
19670 {
19671   ULONGEST addr_base;
19672   int addr_size;
19673 };
19674
19675 /* die_reader_func for dwarf2_read_addr_index.  */
19676
19677 static void
19678 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19679                                const gdb_byte *info_ptr,
19680                                struct die_info *comp_unit_die,
19681                                int has_children,
19682                                void *data)
19683 {
19684   struct dwarf2_cu *cu = reader->cu;
19685   struct dwarf2_read_addr_index_data *aidata =
19686     (struct dwarf2_read_addr_index_data *) data;
19687
19688   aidata->addr_base = cu->addr_base;
19689   aidata->addr_size = cu->header.addr_size;
19690 }
19691
19692 /* Given an index in .debug_addr, fetch the value.
19693    NOTE: This can be called during dwarf expression evaluation,
19694    long after the debug information has been read, and thus per_cu->cu
19695    may no longer exist.  */
19696
19697 CORE_ADDR
19698 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19699                         unsigned int addr_index)
19700 {
19701   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19702   struct objfile *objfile = dwarf2_per_objfile->objfile;
19703   struct dwarf2_cu *cu = per_cu->cu;
19704   ULONGEST addr_base;
19705   int addr_size;
19706
19707   /* We need addr_base and addr_size.
19708      If we don't have PER_CU->cu, we have to get it.
19709      Nasty, but the alternative is storing the needed info in PER_CU,
19710      which at this point doesn't seem justified: it's not clear how frequently
19711      it would get used and it would increase the size of every PER_CU.
19712      Entry points like dwarf2_per_cu_addr_size do a similar thing
19713      so we're not in uncharted territory here.
19714      Alas we need to be a bit more complicated as addr_base is contained
19715      in the DIE.
19716
19717      We don't need to read the entire CU(/TU).
19718      We just need the header and top level die.
19719
19720      IWBN to use the aging mechanism to let us lazily later discard the CU.
19721      For now we skip this optimization.  */
19722
19723   if (cu != NULL)
19724     {
19725       addr_base = cu->addr_base;
19726       addr_size = cu->header.addr_size;
19727     }
19728   else
19729     {
19730       struct dwarf2_read_addr_index_data aidata;
19731
19732       /* Note: We can't use init_cutu_and_read_dies_simple here,
19733          we need addr_base.  */
19734       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19735                                dwarf2_read_addr_index_reader, &aidata);
19736       addr_base = aidata.addr_base;
19737       addr_size = aidata.addr_size;
19738     }
19739
19740   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19741                             addr_size);
19742 }
19743
19744 /* Given a DW_FORM_GNU_str_index, fetch the string.
19745    This is only used by the Fission support.  */
19746
19747 static const char *
19748 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19749 {
19750   struct dwarf2_cu *cu = reader->cu;
19751   struct dwarf2_per_objfile *dwarf2_per_objfile
19752     = cu->per_cu->dwarf2_per_objfile;
19753   struct objfile *objfile = dwarf2_per_objfile->objfile;
19754   const char *objf_name = objfile_name (objfile);
19755   bfd *abfd = objfile->obfd;
19756   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19757   struct dwarf2_section_info *str_offsets_section =
19758     &reader->dwo_file->sections.str_offsets;
19759   const gdb_byte *info_ptr;
19760   ULONGEST str_offset;
19761   static const char form_name[] = "DW_FORM_GNU_str_index";
19762
19763   dwarf2_read_section (objfile, str_section);
19764   dwarf2_read_section (objfile, str_offsets_section);
19765   if (str_section->buffer == NULL)
19766     error (_("%s used without .debug_str.dwo section"
19767              " in CU at offset 0x%x [in module %s]"),
19768            form_name, to_underlying (cu->header.sect_off), objf_name);
19769   if (str_offsets_section->buffer == NULL)
19770     error (_("%s used without .debug_str_offsets.dwo section"
19771              " in CU at offset 0x%x [in module %s]"),
19772            form_name, to_underlying (cu->header.sect_off), objf_name);
19773   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19774     error (_("%s pointing outside of .debug_str_offsets.dwo"
19775              " section in CU at offset 0x%x [in module %s]"),
19776            form_name, to_underlying (cu->header.sect_off), objf_name);
19777   info_ptr = (str_offsets_section->buffer
19778               + str_index * cu->header.offset_size);
19779   if (cu->header.offset_size == 4)
19780     str_offset = bfd_get_32 (abfd, info_ptr);
19781   else
19782     str_offset = bfd_get_64 (abfd, info_ptr);
19783   if (str_offset >= str_section->size)
19784     error (_("Offset from %s pointing outside of"
19785              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19786            form_name, to_underlying (cu->header.sect_off), objf_name);
19787   return (const char *) (str_section->buffer + str_offset);
19788 }
19789
19790 /* Return the length of an LEB128 number in BUF.  */
19791
19792 static int
19793 leb128_size (const gdb_byte *buf)
19794 {
19795   const gdb_byte *begin = buf;
19796   gdb_byte byte;
19797
19798   while (1)
19799     {
19800       byte = *buf++;
19801       if ((byte & 128) == 0)
19802         return buf - begin;
19803     }
19804 }
19805
19806 static void
19807 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19808 {
19809   switch (lang)
19810     {
19811     case DW_LANG_C89:
19812     case DW_LANG_C99:
19813     case DW_LANG_C11:
19814     case DW_LANG_C:
19815     case DW_LANG_UPC:
19816       cu->language = language_c;
19817       break;
19818     case DW_LANG_Java:
19819     case DW_LANG_C_plus_plus:
19820     case DW_LANG_C_plus_plus_11:
19821     case DW_LANG_C_plus_plus_14:
19822       cu->language = language_cplus;
19823       break;
19824     case DW_LANG_D:
19825       cu->language = language_d;
19826       break;
19827     case DW_LANG_Fortran77:
19828     case DW_LANG_Fortran90:
19829     case DW_LANG_Fortran95:
19830     case DW_LANG_Fortran03:
19831     case DW_LANG_Fortran08:
19832       cu->language = language_fortran;
19833       break;
19834     case DW_LANG_Go:
19835       cu->language = language_go;
19836       break;
19837     case DW_LANG_Mips_Assembler:
19838       cu->language = language_asm;
19839       break;
19840     case DW_LANG_Ada83:
19841     case DW_LANG_Ada95:
19842       cu->language = language_ada;
19843       break;
19844     case DW_LANG_Modula2:
19845       cu->language = language_m2;
19846       break;
19847     case DW_LANG_Pascal83:
19848       cu->language = language_pascal;
19849       break;
19850     case DW_LANG_ObjC:
19851       cu->language = language_objc;
19852       break;
19853     case DW_LANG_Rust:
19854     case DW_LANG_Rust_old:
19855       cu->language = language_rust;
19856       break;
19857     case DW_LANG_Cobol74:
19858     case DW_LANG_Cobol85:
19859     default:
19860       cu->language = language_minimal;
19861       break;
19862     }
19863   cu->language_defn = language_def (cu->language);
19864 }
19865
19866 /* Return the named attribute or NULL if not there.  */
19867
19868 static struct attribute *
19869 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19870 {
19871   for (;;)
19872     {
19873       unsigned int i;
19874       struct attribute *spec = NULL;
19875
19876       for (i = 0; i < die->num_attrs; ++i)
19877         {
19878           if (die->attrs[i].name == name)
19879             return &die->attrs[i];
19880           if (die->attrs[i].name == DW_AT_specification
19881               || die->attrs[i].name == DW_AT_abstract_origin)
19882             spec = &die->attrs[i];
19883         }
19884
19885       if (!spec)
19886         break;
19887
19888       die = follow_die_ref (die, spec, &cu);
19889     }
19890
19891   return NULL;
19892 }
19893
19894 /* Return the named attribute or NULL if not there,
19895    but do not follow DW_AT_specification, etc.
19896    This is for use in contexts where we're reading .debug_types dies.
19897    Following DW_AT_specification, DW_AT_abstract_origin will take us
19898    back up the chain, and we want to go down.  */
19899
19900 static struct attribute *
19901 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19902 {
19903   unsigned int i;
19904
19905   for (i = 0; i < die->num_attrs; ++i)
19906     if (die->attrs[i].name == name)
19907       return &die->attrs[i];
19908
19909   return NULL;
19910 }
19911
19912 /* Return the string associated with a string-typed attribute, or NULL if it
19913    is either not found or is of an incorrect type.  */
19914
19915 static const char *
19916 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19917 {
19918   struct attribute *attr;
19919   const char *str = NULL;
19920
19921   attr = dwarf2_attr (die, name, cu);
19922
19923   if (attr != NULL)
19924     {
19925       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19926           || attr->form == DW_FORM_string
19927           || attr->form == DW_FORM_GNU_str_index
19928           || attr->form == DW_FORM_GNU_strp_alt)
19929         str = DW_STRING (attr);
19930       else
19931         complaint (&symfile_complaints,
19932                    _("string type expected for attribute %s for "
19933                      "DIE at 0x%x in module %s"),
19934                    dwarf_attr_name (name), to_underlying (die->sect_off),
19935                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19936     }
19937
19938   return str;
19939 }
19940
19941 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19942    and holds a non-zero value.  This function should only be used for
19943    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19944
19945 static int
19946 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19947 {
19948   struct attribute *attr = dwarf2_attr (die, name, cu);
19949
19950   return (attr && DW_UNSND (attr));
19951 }
19952
19953 static int
19954 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19955 {
19956   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19957      which value is non-zero.  However, we have to be careful with
19958      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19959      (via dwarf2_flag_true_p) follows this attribute.  So we may
19960      end up accidently finding a declaration attribute that belongs
19961      to a different DIE referenced by the specification attribute,
19962      even though the given DIE does not have a declaration attribute.  */
19963   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19964           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19965 }
19966
19967 /* Return the die giving the specification for DIE, if there is
19968    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19969    containing the return value on output.  If there is no
19970    specification, but there is an abstract origin, that is
19971    returned.  */
19972
19973 static struct die_info *
19974 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19975 {
19976   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19977                                              *spec_cu);
19978
19979   if (spec_attr == NULL)
19980     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19981
19982   if (spec_attr == NULL)
19983     return NULL;
19984   else
19985     return follow_die_ref (die, spec_attr, spec_cu);
19986 }
19987
19988 /* Stub for free_line_header to match void * callback types.  */
19989
19990 static void
19991 free_line_header_voidp (void *arg)
19992 {
19993   struct line_header *lh = (struct line_header *) arg;
19994
19995   delete lh;
19996 }
19997
19998 void
19999 line_header::add_include_dir (const char *include_dir)
20000 {
20001   if (dwarf_line_debug >= 2)
20002     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20003                         include_dirs.size () + 1, include_dir);
20004
20005   include_dirs.push_back (include_dir);
20006 }
20007
20008 void
20009 line_header::add_file_name (const char *name,
20010                             dir_index d_index,
20011                             unsigned int mod_time,
20012                             unsigned int length)
20013 {
20014   if (dwarf_line_debug >= 2)
20015     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20016                         (unsigned) file_names.size () + 1, name);
20017
20018   file_names.emplace_back (name, d_index, mod_time, length);
20019 }
20020
20021 /* A convenience function to find the proper .debug_line section for a CU.  */
20022
20023 static struct dwarf2_section_info *
20024 get_debug_line_section (struct dwarf2_cu *cu)
20025 {
20026   struct dwarf2_section_info *section;
20027   struct dwarf2_per_objfile *dwarf2_per_objfile
20028     = cu->per_cu->dwarf2_per_objfile;
20029
20030   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20031      DWO file.  */
20032   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20033     section = &cu->dwo_unit->dwo_file->sections.line;
20034   else if (cu->per_cu->is_dwz)
20035     {
20036       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20037
20038       section = &dwz->line;
20039     }
20040   else
20041     section = &dwarf2_per_objfile->line;
20042
20043   return section;
20044 }
20045
20046 /* Read directory or file name entry format, starting with byte of
20047    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20048    entries count and the entries themselves in the described entry
20049    format.  */
20050
20051 static void
20052 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20053                         bfd *abfd, const gdb_byte **bufp,
20054                         struct line_header *lh,
20055                         const struct comp_unit_head *cu_header,
20056                         void (*callback) (struct line_header *lh,
20057                                           const char *name,
20058                                           dir_index d_index,
20059                                           unsigned int mod_time,
20060                                           unsigned int length))
20061 {
20062   gdb_byte format_count, formati;
20063   ULONGEST data_count, datai;
20064   const gdb_byte *buf = *bufp;
20065   const gdb_byte *format_header_data;
20066   unsigned int bytes_read;
20067
20068   format_count = read_1_byte (abfd, buf);
20069   buf += 1;
20070   format_header_data = buf;
20071   for (formati = 0; formati < format_count; formati++)
20072     {
20073       read_unsigned_leb128 (abfd, buf, &bytes_read);
20074       buf += bytes_read;
20075       read_unsigned_leb128 (abfd, buf, &bytes_read);
20076       buf += bytes_read;
20077     }
20078
20079   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20080   buf += bytes_read;
20081   for (datai = 0; datai < data_count; datai++)
20082     {
20083       const gdb_byte *format = format_header_data;
20084       struct file_entry fe;
20085
20086       for (formati = 0; formati < format_count; formati++)
20087         {
20088           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20089           format += bytes_read;
20090
20091           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20092           format += bytes_read;
20093
20094           gdb::optional<const char *> string;
20095           gdb::optional<unsigned int> uint;
20096
20097           switch (form)
20098             {
20099             case DW_FORM_string:
20100               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20101               buf += bytes_read;
20102               break;
20103
20104             case DW_FORM_line_strp:
20105               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20106                                                          abfd, buf,
20107                                                          cu_header,
20108                                                          &bytes_read));
20109               buf += bytes_read;
20110               break;
20111
20112             case DW_FORM_data1:
20113               uint.emplace (read_1_byte (abfd, buf));
20114               buf += 1;
20115               break;
20116
20117             case DW_FORM_data2:
20118               uint.emplace (read_2_bytes (abfd, buf));
20119               buf += 2;
20120               break;
20121
20122             case DW_FORM_data4:
20123               uint.emplace (read_4_bytes (abfd, buf));
20124               buf += 4;
20125               break;
20126
20127             case DW_FORM_data8:
20128               uint.emplace (read_8_bytes (abfd, buf));
20129               buf += 8;
20130               break;
20131
20132             case DW_FORM_udata:
20133               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20134               buf += bytes_read;
20135               break;
20136
20137             case DW_FORM_block:
20138               /* It is valid only for DW_LNCT_timestamp which is ignored by
20139                  current GDB.  */
20140               break;
20141             }
20142
20143           switch (content_type)
20144             {
20145             case DW_LNCT_path:
20146               if (string.has_value ())
20147                 fe.name = *string;
20148               break;
20149             case DW_LNCT_directory_index:
20150               if (uint.has_value ())
20151                 fe.d_index = (dir_index) *uint;
20152               break;
20153             case DW_LNCT_timestamp:
20154               if (uint.has_value ())
20155                 fe.mod_time = *uint;
20156               break;
20157             case DW_LNCT_size:
20158               if (uint.has_value ())
20159                 fe.length = *uint;
20160               break;
20161             case DW_LNCT_MD5:
20162               break;
20163             default:
20164               complaint (&symfile_complaints,
20165                          _("Unknown format content type %s"),
20166                          pulongest (content_type));
20167             }
20168         }
20169
20170       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20171     }
20172
20173   *bufp = buf;
20174 }
20175
20176 /* Read the statement program header starting at OFFSET in
20177    .debug_line, or .debug_line.dwo.  Return a pointer
20178    to a struct line_header, allocated using xmalloc.
20179    Returns NULL if there is a problem reading the header, e.g., if it
20180    has a version we don't understand.
20181
20182    NOTE: the strings in the include directory and file name tables of
20183    the returned object point into the dwarf line section buffer,
20184    and must not be freed.  */
20185
20186 static line_header_up
20187 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20188 {
20189   const gdb_byte *line_ptr;
20190   unsigned int bytes_read, offset_size;
20191   int i;
20192   const char *cur_dir, *cur_file;
20193   struct dwarf2_section_info *section;
20194   bfd *abfd;
20195   struct dwarf2_per_objfile *dwarf2_per_objfile
20196     = cu->per_cu->dwarf2_per_objfile;
20197
20198   section = get_debug_line_section (cu);
20199   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20200   if (section->buffer == NULL)
20201     {
20202       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20203         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20204       else
20205         complaint (&symfile_complaints, _("missing .debug_line section"));
20206       return 0;
20207     }
20208
20209   /* We can't do this until we know the section is non-empty.
20210      Only then do we know we have such a section.  */
20211   abfd = get_section_bfd_owner (section);
20212
20213   /* Make sure that at least there's room for the total_length field.
20214      That could be 12 bytes long, but we're just going to fudge that.  */
20215   if (to_underlying (sect_off) + 4 >= section->size)
20216     {
20217       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20218       return 0;
20219     }
20220
20221   line_header_up lh (new line_header ());
20222
20223   lh->sect_off = sect_off;
20224   lh->offset_in_dwz = cu->per_cu->is_dwz;
20225
20226   line_ptr = section->buffer + to_underlying (sect_off);
20227
20228   /* Read in the header.  */
20229   lh->total_length =
20230     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20231                                             &bytes_read, &offset_size);
20232   line_ptr += bytes_read;
20233   if (line_ptr + lh->total_length > (section->buffer + section->size))
20234     {
20235       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20236       return 0;
20237     }
20238   lh->statement_program_end = line_ptr + lh->total_length;
20239   lh->version = read_2_bytes (abfd, line_ptr);
20240   line_ptr += 2;
20241   if (lh->version > 5)
20242     {
20243       /* This is a version we don't understand.  The format could have
20244          changed in ways we don't handle properly so just punt.  */
20245       complaint (&symfile_complaints,
20246                  _("unsupported version in .debug_line section"));
20247       return NULL;
20248     }
20249   if (lh->version >= 5)
20250     {
20251       gdb_byte segment_selector_size;
20252
20253       /* Skip address size.  */
20254       read_1_byte (abfd, line_ptr);
20255       line_ptr += 1;
20256
20257       segment_selector_size = read_1_byte (abfd, line_ptr);
20258       line_ptr += 1;
20259       if (segment_selector_size != 0)
20260         {
20261           complaint (&symfile_complaints,
20262                      _("unsupported segment selector size %u "
20263                        "in .debug_line section"),
20264                      segment_selector_size);
20265           return NULL;
20266         }
20267     }
20268   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20269   line_ptr += offset_size;
20270   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20271   line_ptr += 1;
20272   if (lh->version >= 4)
20273     {
20274       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20275       line_ptr += 1;
20276     }
20277   else
20278     lh->maximum_ops_per_instruction = 1;
20279
20280   if (lh->maximum_ops_per_instruction == 0)
20281     {
20282       lh->maximum_ops_per_instruction = 1;
20283       complaint (&symfile_complaints,
20284                  _("invalid maximum_ops_per_instruction "
20285                    "in `.debug_line' section"));
20286     }
20287
20288   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20289   line_ptr += 1;
20290   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20291   line_ptr += 1;
20292   lh->line_range = read_1_byte (abfd, line_ptr);
20293   line_ptr += 1;
20294   lh->opcode_base = read_1_byte (abfd, line_ptr);
20295   line_ptr += 1;
20296   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20297
20298   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20299   for (i = 1; i < lh->opcode_base; ++i)
20300     {
20301       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20302       line_ptr += 1;
20303     }
20304
20305   if (lh->version >= 5)
20306     {
20307       /* Read directory table.  */
20308       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20309                               &cu->header,
20310                               [] (struct line_header *lh, const char *name,
20311                                   dir_index d_index, unsigned int mod_time,
20312                                   unsigned int length)
20313         {
20314           lh->add_include_dir (name);
20315         });
20316
20317       /* Read file name table.  */
20318       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20319                               &cu->header,
20320                               [] (struct line_header *lh, const char *name,
20321                                   dir_index d_index, unsigned int mod_time,
20322                                   unsigned int length)
20323         {
20324           lh->add_file_name (name, d_index, mod_time, length);
20325         });
20326     }
20327   else
20328     {
20329       /* Read directory table.  */
20330       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20331         {
20332           line_ptr += bytes_read;
20333           lh->add_include_dir (cur_dir);
20334         }
20335       line_ptr += bytes_read;
20336
20337       /* Read file name table.  */
20338       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20339         {
20340           unsigned int mod_time, length;
20341           dir_index d_index;
20342
20343           line_ptr += bytes_read;
20344           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20345           line_ptr += bytes_read;
20346           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20347           line_ptr += bytes_read;
20348           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20349           line_ptr += bytes_read;
20350
20351           lh->add_file_name (cur_file, d_index, mod_time, length);
20352         }
20353       line_ptr += bytes_read;
20354     }
20355   lh->statement_program_start = line_ptr;
20356
20357   if (line_ptr > (section->buffer + section->size))
20358     complaint (&symfile_complaints,
20359                _("line number info header doesn't "
20360                  "fit in `.debug_line' section"));
20361
20362   return lh;
20363 }
20364
20365 /* Subroutine of dwarf_decode_lines to simplify it.
20366    Return the file name of the psymtab for included file FILE_INDEX
20367    in line header LH of PST.
20368    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20369    If space for the result is malloc'd, *NAME_HOLDER will be set.
20370    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20371
20372 static const char *
20373 psymtab_include_file_name (const struct line_header *lh, int file_index,
20374                            const struct partial_symtab *pst,
20375                            const char *comp_dir,
20376                            gdb::unique_xmalloc_ptr<char> *name_holder)
20377 {
20378   const file_entry &fe = lh->file_names[file_index];
20379   const char *include_name = fe.name;
20380   const char *include_name_to_compare = include_name;
20381   const char *pst_filename;
20382   int file_is_pst;
20383
20384   const char *dir_name = fe.include_dir (lh);
20385
20386   gdb::unique_xmalloc_ptr<char> hold_compare;
20387   if (!IS_ABSOLUTE_PATH (include_name)
20388       && (dir_name != NULL || comp_dir != NULL))
20389     {
20390       /* Avoid creating a duplicate psymtab for PST.
20391          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20392          Before we do the comparison, however, we need to account
20393          for DIR_NAME and COMP_DIR.
20394          First prepend dir_name (if non-NULL).  If we still don't
20395          have an absolute path prepend comp_dir (if non-NULL).
20396          However, the directory we record in the include-file's
20397          psymtab does not contain COMP_DIR (to match the
20398          corresponding symtab(s)).
20399
20400          Example:
20401
20402          bash$ cd /tmp
20403          bash$ gcc -g ./hello.c
20404          include_name = "hello.c"
20405          dir_name = "."
20406          DW_AT_comp_dir = comp_dir = "/tmp"
20407          DW_AT_name = "./hello.c"
20408
20409       */
20410
20411       if (dir_name != NULL)
20412         {
20413           name_holder->reset (concat (dir_name, SLASH_STRING,
20414                                       include_name, (char *) NULL));
20415           include_name = name_holder->get ();
20416           include_name_to_compare = include_name;
20417         }
20418       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20419         {
20420           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20421                                       include_name, (char *) NULL));
20422           include_name_to_compare = hold_compare.get ();
20423         }
20424     }
20425
20426   pst_filename = pst->filename;
20427   gdb::unique_xmalloc_ptr<char> copied_name;
20428   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20429     {
20430       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20431                                  pst_filename, (char *) NULL));
20432       pst_filename = copied_name.get ();
20433     }
20434
20435   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20436
20437   if (file_is_pst)
20438     return NULL;
20439   return include_name;
20440 }
20441
20442 /* State machine to track the state of the line number program.  */
20443
20444 class lnp_state_machine
20445 {
20446 public:
20447   /* Initialize a machine state for the start of a line number
20448      program.  */
20449   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20450
20451   file_entry *current_file ()
20452   {
20453     /* lh->file_names is 0-based, but the file name numbers in the
20454        statement program are 1-based.  */
20455     return m_line_header->file_name_at (m_file);
20456   }
20457
20458   /* Record the line in the state machine.  END_SEQUENCE is true if
20459      we're processing the end of a sequence.  */
20460   void record_line (bool end_sequence);
20461
20462   /* Check address and if invalid nop-out the rest of the lines in this
20463      sequence.  */
20464   void check_line_address (struct dwarf2_cu *cu,
20465                            const gdb_byte *line_ptr,
20466                            CORE_ADDR lowpc, CORE_ADDR address);
20467
20468   void handle_set_discriminator (unsigned int discriminator)
20469   {
20470     m_discriminator = discriminator;
20471     m_line_has_non_zero_discriminator |= discriminator != 0;
20472   }
20473
20474   /* Handle DW_LNE_set_address.  */
20475   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20476   {
20477     m_op_index = 0;
20478     address += baseaddr;
20479     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20480   }
20481
20482   /* Handle DW_LNS_advance_pc.  */
20483   void handle_advance_pc (CORE_ADDR adjust);
20484
20485   /* Handle a special opcode.  */
20486   void handle_special_opcode (unsigned char op_code);
20487
20488   /* Handle DW_LNS_advance_line.  */
20489   void handle_advance_line (int line_delta)
20490   {
20491     advance_line (line_delta);
20492   }
20493
20494   /* Handle DW_LNS_set_file.  */
20495   void handle_set_file (file_name_index file);
20496
20497   /* Handle DW_LNS_negate_stmt.  */
20498   void handle_negate_stmt ()
20499   {
20500     m_is_stmt = !m_is_stmt;
20501   }
20502
20503   /* Handle DW_LNS_const_add_pc.  */
20504   void handle_const_add_pc ();
20505
20506   /* Handle DW_LNS_fixed_advance_pc.  */
20507   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20508   {
20509     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20510     m_op_index = 0;
20511   }
20512
20513   /* Handle DW_LNS_copy.  */
20514   void handle_copy ()
20515   {
20516     record_line (false);
20517     m_discriminator = 0;
20518   }
20519
20520   /* Handle DW_LNE_end_sequence.  */
20521   void handle_end_sequence ()
20522   {
20523     m_record_line_callback = ::record_line;
20524   }
20525
20526 private:
20527   /* Advance the line by LINE_DELTA.  */
20528   void advance_line (int line_delta)
20529   {
20530     m_line += line_delta;
20531
20532     if (line_delta != 0)
20533       m_line_has_non_zero_discriminator = m_discriminator != 0;
20534   }
20535
20536   gdbarch *m_gdbarch;
20537
20538   /* True if we're recording lines.
20539      Otherwise we're building partial symtabs and are just interested in
20540      finding include files mentioned by the line number program.  */
20541   bool m_record_lines_p;
20542
20543   /* The line number header.  */
20544   line_header *m_line_header;
20545
20546   /* These are part of the standard DWARF line number state machine,
20547      and initialized according to the DWARF spec.  */
20548
20549   unsigned char m_op_index = 0;
20550   /* The line table index (1-based) of the current file.  */
20551   file_name_index m_file = (file_name_index) 1;
20552   unsigned int m_line = 1;
20553
20554   /* These are initialized in the constructor.  */
20555
20556   CORE_ADDR m_address;
20557   bool m_is_stmt;
20558   unsigned int m_discriminator;
20559
20560   /* Additional bits of state we need to track.  */
20561
20562   /* The last file that we called dwarf2_start_subfile for.
20563      This is only used for TLLs.  */
20564   unsigned int m_last_file = 0;
20565   /* The last file a line number was recorded for.  */
20566   struct subfile *m_last_subfile = NULL;
20567
20568   /* The function to call to record a line.  */
20569   record_line_ftype *m_record_line_callback = NULL;
20570
20571   /* The last line number that was recorded, used to coalesce
20572      consecutive entries for the same line.  This can happen, for
20573      example, when discriminators are present.  PR 17276.  */
20574   unsigned int m_last_line = 0;
20575   bool m_line_has_non_zero_discriminator = false;
20576 };
20577
20578 void
20579 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20580 {
20581   CORE_ADDR addr_adj = (((m_op_index + adjust)
20582                          / m_line_header->maximum_ops_per_instruction)
20583                         * m_line_header->minimum_instruction_length);
20584   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20585   m_op_index = ((m_op_index + adjust)
20586                 % m_line_header->maximum_ops_per_instruction);
20587 }
20588
20589 void
20590 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20591 {
20592   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20593   CORE_ADDR addr_adj = (((m_op_index
20594                           + (adj_opcode / m_line_header->line_range))
20595                          / m_line_header->maximum_ops_per_instruction)
20596                         * m_line_header->minimum_instruction_length);
20597   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20598   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20599                 % m_line_header->maximum_ops_per_instruction);
20600
20601   int line_delta = (m_line_header->line_base
20602                     + (adj_opcode % m_line_header->line_range));
20603   advance_line (line_delta);
20604   record_line (false);
20605   m_discriminator = 0;
20606 }
20607
20608 void
20609 lnp_state_machine::handle_set_file (file_name_index file)
20610 {
20611   m_file = file;
20612
20613   const file_entry *fe = current_file ();
20614   if (fe == NULL)
20615     dwarf2_debug_line_missing_file_complaint ();
20616   else if (m_record_lines_p)
20617     {
20618       const char *dir = fe->include_dir (m_line_header);
20619
20620       m_last_subfile = current_subfile;
20621       m_line_has_non_zero_discriminator = m_discriminator != 0;
20622       dwarf2_start_subfile (fe->name, dir);
20623     }
20624 }
20625
20626 void
20627 lnp_state_machine::handle_const_add_pc ()
20628 {
20629   CORE_ADDR adjust
20630     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20631
20632   CORE_ADDR addr_adj
20633     = (((m_op_index + adjust)
20634         / m_line_header->maximum_ops_per_instruction)
20635        * m_line_header->minimum_instruction_length);
20636
20637   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20638   m_op_index = ((m_op_index + adjust)
20639                 % m_line_header->maximum_ops_per_instruction);
20640 }
20641
20642 /* Ignore this record_line request.  */
20643
20644 static void
20645 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20646 {
20647   return;
20648 }
20649
20650 /* Return non-zero if we should add LINE to the line number table.
20651    LINE is the line to add, LAST_LINE is the last line that was added,
20652    LAST_SUBFILE is the subfile for LAST_LINE.
20653    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20654    had a non-zero discriminator.
20655
20656    We have to be careful in the presence of discriminators.
20657    E.g., for this line:
20658
20659      for (i = 0; i < 100000; i++);
20660
20661    clang can emit four line number entries for that one line,
20662    each with a different discriminator.
20663    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20664
20665    However, we want gdb to coalesce all four entries into one.
20666    Otherwise the user could stepi into the middle of the line and
20667    gdb would get confused about whether the pc really was in the
20668    middle of the line.
20669
20670    Things are further complicated by the fact that two consecutive
20671    line number entries for the same line is a heuristic used by gcc
20672    to denote the end of the prologue.  So we can't just discard duplicate
20673    entries, we have to be selective about it.  The heuristic we use is
20674    that we only collapse consecutive entries for the same line if at least
20675    one of those entries has a non-zero discriminator.  PR 17276.
20676
20677    Note: Addresses in the line number state machine can never go backwards
20678    within one sequence, thus this coalescing is ok.  */
20679
20680 static int
20681 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20682                      int line_has_non_zero_discriminator,
20683                      struct subfile *last_subfile)
20684 {
20685   if (current_subfile != last_subfile)
20686     return 1;
20687   if (line != last_line)
20688     return 1;
20689   /* Same line for the same file that we've seen already.
20690      As a last check, for pr 17276, only record the line if the line
20691      has never had a non-zero discriminator.  */
20692   if (!line_has_non_zero_discriminator)
20693     return 1;
20694   return 0;
20695 }
20696
20697 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20698    in the line table of subfile SUBFILE.  */
20699
20700 static void
20701 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20702                      unsigned int line, CORE_ADDR address,
20703                      record_line_ftype p_record_line)
20704 {
20705   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20706
20707   if (dwarf_line_debug)
20708     {
20709       fprintf_unfiltered (gdb_stdlog,
20710                           "Recording line %u, file %s, address %s\n",
20711                           line, lbasename (subfile->name),
20712                           paddress (gdbarch, address));
20713     }
20714
20715   (*p_record_line) (subfile, line, addr);
20716 }
20717
20718 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20719    Mark the end of a set of line number records.
20720    The arguments are the same as for dwarf_record_line_1.
20721    If SUBFILE is NULL the request is ignored.  */
20722
20723 static void
20724 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20725                    CORE_ADDR address, record_line_ftype p_record_line)
20726 {
20727   if (subfile == NULL)
20728     return;
20729
20730   if (dwarf_line_debug)
20731     {
20732       fprintf_unfiltered (gdb_stdlog,
20733                           "Finishing current line, file %s, address %s\n",
20734                           lbasename (subfile->name),
20735                           paddress (gdbarch, address));
20736     }
20737
20738   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20739 }
20740
20741 void
20742 lnp_state_machine::record_line (bool end_sequence)
20743 {
20744   if (dwarf_line_debug)
20745     {
20746       fprintf_unfiltered (gdb_stdlog,
20747                           "Processing actual line %u: file %u,"
20748                           " address %s, is_stmt %u, discrim %u\n",
20749                           m_line, to_underlying (m_file),
20750                           paddress (m_gdbarch, m_address),
20751                           m_is_stmt, m_discriminator);
20752     }
20753
20754   file_entry *fe = current_file ();
20755
20756   if (fe == NULL)
20757     dwarf2_debug_line_missing_file_complaint ();
20758   /* For now we ignore lines not starting on an instruction boundary.
20759      But not when processing end_sequence for compatibility with the
20760      previous version of the code.  */
20761   else if (m_op_index == 0 || end_sequence)
20762     {
20763       fe->included_p = 1;
20764       if (m_record_lines_p && m_is_stmt)
20765         {
20766           if (m_last_subfile != current_subfile || end_sequence)
20767             {
20768               dwarf_finish_line (m_gdbarch, m_last_subfile,
20769                                  m_address, m_record_line_callback);
20770             }
20771
20772           if (!end_sequence)
20773             {
20774               if (dwarf_record_line_p (m_line, m_last_line,
20775                                        m_line_has_non_zero_discriminator,
20776                                        m_last_subfile))
20777                 {
20778                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20779                                        m_line, m_address,
20780                                        m_record_line_callback);
20781                 }
20782               m_last_subfile = current_subfile;
20783               m_last_line = m_line;
20784             }
20785         }
20786     }
20787 }
20788
20789 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20790                                       bool record_lines_p)
20791 {
20792   m_gdbarch = arch;
20793   m_record_lines_p = record_lines_p;
20794   m_line_header = lh;
20795
20796   m_record_line_callback = ::record_line;
20797
20798   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20799      was a line entry for it so that the backend has a chance to adjust it
20800      and also record it in case it needs it.  This is currently used by MIPS
20801      code, cf. `mips_adjust_dwarf2_line'.  */
20802   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20803   m_is_stmt = lh->default_is_stmt;
20804   m_discriminator = 0;
20805 }
20806
20807 void
20808 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20809                                        const gdb_byte *line_ptr,
20810                                        CORE_ADDR lowpc, CORE_ADDR address)
20811 {
20812   /* If address < lowpc then it's not a usable value, it's outside the
20813      pc range of the CU.  However, we restrict the test to only address
20814      values of zero to preserve GDB's previous behaviour which is to
20815      handle the specific case of a function being GC'd by the linker.  */
20816
20817   if (address == 0 && address < lowpc)
20818     {
20819       /* This line table is for a function which has been
20820          GCd by the linker.  Ignore it.  PR gdb/12528 */
20821
20822       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20823       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20824
20825       complaint (&symfile_complaints,
20826                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20827                  line_offset, objfile_name (objfile));
20828       m_record_line_callback = noop_record_line;
20829       /* Note: record_line_callback is left as noop_record_line until
20830          we see DW_LNE_end_sequence.  */
20831     }
20832 }
20833
20834 /* Subroutine of dwarf_decode_lines to simplify it.
20835    Process the line number information in LH.
20836    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20837    program in order to set included_p for every referenced header.  */
20838
20839 static void
20840 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20841                       const int decode_for_pst_p, CORE_ADDR lowpc)
20842 {
20843   const gdb_byte *line_ptr, *extended_end;
20844   const gdb_byte *line_end;
20845   unsigned int bytes_read, extended_len;
20846   unsigned char op_code, extended_op;
20847   CORE_ADDR baseaddr;
20848   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20849   bfd *abfd = objfile->obfd;
20850   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20851   /* True if we're recording line info (as opposed to building partial
20852      symtabs and just interested in finding include files mentioned by
20853      the line number program).  */
20854   bool record_lines_p = !decode_for_pst_p;
20855
20856   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20857
20858   line_ptr = lh->statement_program_start;
20859   line_end = lh->statement_program_end;
20860
20861   /* Read the statement sequences until there's nothing left.  */
20862   while (line_ptr < line_end)
20863     {
20864       /* The DWARF line number program state machine.  Reset the state
20865          machine at the start of each sequence.  */
20866       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20867       bool end_sequence = false;
20868
20869       if (record_lines_p)
20870         {
20871           /* Start a subfile for the current file of the state
20872              machine.  */
20873           const file_entry *fe = state_machine.current_file ();
20874
20875           if (fe != NULL)
20876             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20877         }
20878
20879       /* Decode the table.  */
20880       while (line_ptr < line_end && !end_sequence)
20881         {
20882           op_code = read_1_byte (abfd, line_ptr);
20883           line_ptr += 1;
20884
20885           if (op_code >= lh->opcode_base)
20886             {
20887               /* Special opcode.  */
20888               state_machine.handle_special_opcode (op_code);
20889             }
20890           else switch (op_code)
20891             {
20892             case DW_LNS_extended_op:
20893               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20894                                                    &bytes_read);
20895               line_ptr += bytes_read;
20896               extended_end = line_ptr + extended_len;
20897               extended_op = read_1_byte (abfd, line_ptr);
20898               line_ptr += 1;
20899               switch (extended_op)
20900                 {
20901                 case DW_LNE_end_sequence:
20902                   state_machine.handle_end_sequence ();
20903                   end_sequence = true;
20904                   break;
20905                 case DW_LNE_set_address:
20906                   {
20907                     CORE_ADDR address
20908                       = read_address (abfd, line_ptr, cu, &bytes_read);
20909                     line_ptr += bytes_read;
20910
20911                     state_machine.check_line_address (cu, line_ptr,
20912                                                       lowpc, address);
20913                     state_machine.handle_set_address (baseaddr, address);
20914                   }
20915                   break;
20916                 case DW_LNE_define_file:
20917                   {
20918                     const char *cur_file;
20919                     unsigned int mod_time, length;
20920                     dir_index dindex;
20921
20922                     cur_file = read_direct_string (abfd, line_ptr,
20923                                                    &bytes_read);
20924                     line_ptr += bytes_read;
20925                     dindex = (dir_index)
20926                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20927                     line_ptr += bytes_read;
20928                     mod_time =
20929                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20930                     line_ptr += bytes_read;
20931                     length =
20932                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20933                     line_ptr += bytes_read;
20934                     lh->add_file_name (cur_file, dindex, mod_time, length);
20935                   }
20936                   break;
20937                 case DW_LNE_set_discriminator:
20938                   {
20939                     /* The discriminator is not interesting to the
20940                        debugger; just ignore it.  We still need to
20941                        check its value though:
20942                        if there are consecutive entries for the same
20943                        (non-prologue) line we want to coalesce them.
20944                        PR 17276.  */
20945                     unsigned int discr
20946                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20947                     line_ptr += bytes_read;
20948
20949                     state_machine.handle_set_discriminator (discr);
20950                   }
20951                   break;
20952                 default:
20953                   complaint (&symfile_complaints,
20954                              _("mangled .debug_line section"));
20955                   return;
20956                 }
20957               /* Make sure that we parsed the extended op correctly.  If e.g.
20958                  we expected a different address size than the producer used,
20959                  we may have read the wrong number of bytes.  */
20960               if (line_ptr != extended_end)
20961                 {
20962                   complaint (&symfile_complaints,
20963                              _("mangled .debug_line section"));
20964                   return;
20965                 }
20966               break;
20967             case DW_LNS_copy:
20968               state_machine.handle_copy ();
20969               break;
20970             case DW_LNS_advance_pc:
20971               {
20972                 CORE_ADDR adjust
20973                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20974                 line_ptr += bytes_read;
20975
20976                 state_machine.handle_advance_pc (adjust);
20977               }
20978               break;
20979             case DW_LNS_advance_line:
20980               {
20981                 int line_delta
20982                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20983                 line_ptr += bytes_read;
20984
20985                 state_machine.handle_advance_line (line_delta);
20986               }
20987               break;
20988             case DW_LNS_set_file:
20989               {
20990                 file_name_index file
20991                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20992                                                             &bytes_read);
20993                 line_ptr += bytes_read;
20994
20995                 state_machine.handle_set_file (file);
20996               }
20997               break;
20998             case DW_LNS_set_column:
20999               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21000               line_ptr += bytes_read;
21001               break;
21002             case DW_LNS_negate_stmt:
21003               state_machine.handle_negate_stmt ();
21004               break;
21005             case DW_LNS_set_basic_block:
21006               break;
21007             /* Add to the address register of the state machine the
21008                address increment value corresponding to special opcode
21009                255.  I.e., this value is scaled by the minimum
21010                instruction length since special opcode 255 would have
21011                scaled the increment.  */
21012             case DW_LNS_const_add_pc:
21013               state_machine.handle_const_add_pc ();
21014               break;
21015             case DW_LNS_fixed_advance_pc:
21016               {
21017                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21018                 line_ptr += 2;
21019
21020                 state_machine.handle_fixed_advance_pc (addr_adj);
21021               }
21022               break;
21023             default:
21024               {
21025                 /* Unknown standard opcode, ignore it.  */
21026                 int i;
21027
21028                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21029                   {
21030                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21031                     line_ptr += bytes_read;
21032                   }
21033               }
21034             }
21035         }
21036
21037       if (!end_sequence)
21038         dwarf2_debug_line_missing_end_sequence_complaint ();
21039
21040       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21041          in which case we still finish recording the last line).  */
21042       state_machine.record_line (true);
21043     }
21044 }
21045
21046 /* Decode the Line Number Program (LNP) for the given line_header
21047    structure and CU.  The actual information extracted and the type
21048    of structures created from the LNP depends on the value of PST.
21049
21050    1. If PST is NULL, then this procedure uses the data from the program
21051       to create all necessary symbol tables, and their linetables.
21052
21053    2. If PST is not NULL, this procedure reads the program to determine
21054       the list of files included by the unit represented by PST, and
21055       builds all the associated partial symbol tables.
21056
21057    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21058    It is used for relative paths in the line table.
21059    NOTE: When processing partial symtabs (pst != NULL),
21060    comp_dir == pst->dirname.
21061
21062    NOTE: It is important that psymtabs have the same file name (via strcmp)
21063    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21064    symtab we don't use it in the name of the psymtabs we create.
21065    E.g. expand_line_sal requires this when finding psymtabs to expand.
21066    A good testcase for this is mb-inline.exp.
21067
21068    LOWPC is the lowest address in CU (or 0 if not known).
21069
21070    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21071    for its PC<->lines mapping information.  Otherwise only the filename
21072    table is read in.  */
21073
21074 static void
21075 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21076                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21077                     CORE_ADDR lowpc, int decode_mapping)
21078 {
21079   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21080   const int decode_for_pst_p = (pst != NULL);
21081
21082   if (decode_mapping)
21083     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21084
21085   if (decode_for_pst_p)
21086     {
21087       int file_index;
21088
21089       /* Now that we're done scanning the Line Header Program, we can
21090          create the psymtab of each included file.  */
21091       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21092         if (lh->file_names[file_index].included_p == 1)
21093           {
21094             gdb::unique_xmalloc_ptr<char> name_holder;
21095             const char *include_name =
21096               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21097                                          &name_holder);
21098             if (include_name != NULL)
21099               dwarf2_create_include_psymtab (include_name, pst, objfile);
21100           }
21101     }
21102   else
21103     {
21104       /* Make sure a symtab is created for every file, even files
21105          which contain only variables (i.e. no code with associated
21106          line numbers).  */
21107       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21108       int i;
21109
21110       for (i = 0; i < lh->file_names.size (); i++)
21111         {
21112           file_entry &fe = lh->file_names[i];
21113
21114           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21115
21116           if (current_subfile->symtab == NULL)
21117             {
21118               current_subfile->symtab
21119                 = allocate_symtab (cust, current_subfile->name);
21120             }
21121           fe.symtab = current_subfile->symtab;
21122         }
21123     }
21124 }
21125
21126 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21127    DIRNAME the name of the source directory which contains FILENAME
21128    or NULL if not known.
21129    This routine tries to keep line numbers from identical absolute and
21130    relative file names in a common subfile.
21131
21132    Using the `list' example from the GDB testsuite, which resides in
21133    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21134    of /srcdir/list0.c yields the following debugging information for list0.c:
21135
21136    DW_AT_name:          /srcdir/list0.c
21137    DW_AT_comp_dir:      /compdir
21138    files.files[0].name: list0.h
21139    files.files[0].dir:  /srcdir
21140    files.files[1].name: list0.c
21141    files.files[1].dir:  /srcdir
21142
21143    The line number information for list0.c has to end up in a single
21144    subfile, so that `break /srcdir/list0.c:1' works as expected.
21145    start_subfile will ensure that this happens provided that we pass the
21146    concatenation of files.files[1].dir and files.files[1].name as the
21147    subfile's name.  */
21148
21149 static void
21150 dwarf2_start_subfile (const char *filename, const char *dirname)
21151 {
21152   char *copy = NULL;
21153
21154   /* In order not to lose the line information directory,
21155      we concatenate it to the filename when it makes sense.
21156      Note that the Dwarf3 standard says (speaking of filenames in line
21157      information): ``The directory index is ignored for file names
21158      that represent full path names''.  Thus ignoring dirname in the
21159      `else' branch below isn't an issue.  */
21160
21161   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21162     {
21163       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21164       filename = copy;
21165     }
21166
21167   start_subfile (filename);
21168
21169   if (copy != NULL)
21170     xfree (copy);
21171 }
21172
21173 /* Start a symtab for DWARF.
21174    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21175
21176 static struct compunit_symtab *
21177 dwarf2_start_symtab (struct dwarf2_cu *cu,
21178                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21179 {
21180   struct compunit_symtab *cust
21181     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21182                     low_pc, cu->language);
21183
21184   record_debugformat ("DWARF 2");
21185   record_producer (cu->producer);
21186
21187   /* We assume that we're processing GCC output.  */
21188   processing_gcc_compilation = 2;
21189
21190   cu->processing_has_namespace_info = 0;
21191
21192   return cust;
21193 }
21194
21195 static void
21196 var_decode_location (struct attribute *attr, struct symbol *sym,
21197                      struct dwarf2_cu *cu)
21198 {
21199   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21200   struct comp_unit_head *cu_header = &cu->header;
21201
21202   /* NOTE drow/2003-01-30: There used to be a comment and some special
21203      code here to turn a symbol with DW_AT_external and a
21204      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21205      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21206      with some versions of binutils) where shared libraries could have
21207      relocations against symbols in their debug information - the
21208      minimal symbol would have the right address, but the debug info
21209      would not.  It's no longer necessary, because we will explicitly
21210      apply relocations when we read in the debug information now.  */
21211
21212   /* A DW_AT_location attribute with no contents indicates that a
21213      variable has been optimized away.  */
21214   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21215     {
21216       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21217       return;
21218     }
21219
21220   /* Handle one degenerate form of location expression specially, to
21221      preserve GDB's previous behavior when section offsets are
21222      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21223      then mark this symbol as LOC_STATIC.  */
21224
21225   if (attr_form_is_block (attr)
21226       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21227            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21228           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21229               && (DW_BLOCK (attr)->size
21230                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21231     {
21232       unsigned int dummy;
21233
21234       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21235         SYMBOL_VALUE_ADDRESS (sym) =
21236           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21237       else
21238         SYMBOL_VALUE_ADDRESS (sym) =
21239           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21240       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21241       fixup_symbol_section (sym, objfile);
21242       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21243                                               SYMBOL_SECTION (sym));
21244       return;
21245     }
21246
21247   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21248      expression evaluator, and use LOC_COMPUTED only when necessary
21249      (i.e. when the value of a register or memory location is
21250      referenced, or a thread-local block, etc.).  Then again, it might
21251      not be worthwhile.  I'm assuming that it isn't unless performance
21252      or memory numbers show me otherwise.  */
21253
21254   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21255
21256   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21257     cu->has_loclist = 1;
21258 }
21259
21260 /* Given a pointer to a DWARF information entry, figure out if we need
21261    to make a symbol table entry for it, and if so, create a new entry
21262    and return a pointer to it.
21263    If TYPE is NULL, determine symbol type from the die, otherwise
21264    used the passed type.
21265    If SPACE is not NULL, use it to hold the new symbol.  If it is
21266    NULL, allocate a new symbol on the objfile's obstack.  */
21267
21268 static struct symbol *
21269 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21270             struct symbol *space)
21271 {
21272   struct dwarf2_per_objfile *dwarf2_per_objfile
21273     = cu->per_cu->dwarf2_per_objfile;
21274   struct objfile *objfile = dwarf2_per_objfile->objfile;
21275   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21276   struct symbol *sym = NULL;
21277   const char *name;
21278   struct attribute *attr = NULL;
21279   struct attribute *attr2 = NULL;
21280   CORE_ADDR baseaddr;
21281   struct pending **list_to_add = NULL;
21282
21283   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21284
21285   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21286
21287   name = dwarf2_name (die, cu);
21288   if (name)
21289     {
21290       const char *linkagename;
21291       int suppress_add = 0;
21292
21293       if (space)
21294         sym = space;
21295       else
21296         sym = allocate_symbol (objfile);
21297       OBJSTAT (objfile, n_syms++);
21298
21299       /* Cache this symbol's name and the name's demangled form (if any).  */
21300       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21301       linkagename = dwarf2_physname (name, die, cu);
21302       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21303
21304       /* Fortran does not have mangling standard and the mangling does differ
21305          between gfortran, iFort etc.  */
21306       if (cu->language == language_fortran
21307           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21308         symbol_set_demangled_name (&(sym->ginfo),
21309                                    dwarf2_full_name (name, die, cu),
21310                                    NULL);
21311
21312       /* Default assumptions.
21313          Use the passed type or decode it from the die.  */
21314       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21315       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21316       if (type != NULL)
21317         SYMBOL_TYPE (sym) = type;
21318       else
21319         SYMBOL_TYPE (sym) = die_type (die, cu);
21320       attr = dwarf2_attr (die,
21321                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21322                           cu);
21323       if (attr)
21324         {
21325           SYMBOL_LINE (sym) = DW_UNSND (attr);
21326         }
21327
21328       attr = dwarf2_attr (die,
21329                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21330                           cu);
21331       if (attr)
21332         {
21333           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21334           struct file_entry *fe;
21335
21336           if (cu->line_header != NULL)
21337             fe = cu->line_header->file_name_at (file_index);
21338           else
21339             fe = NULL;
21340
21341           if (fe == NULL)
21342             complaint (&symfile_complaints,
21343                        _("file index out of range"));
21344           else
21345             symbol_set_symtab (sym, fe->symtab);
21346         }
21347
21348       switch (die->tag)
21349         {
21350         case DW_TAG_label:
21351           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21352           if (attr)
21353             {
21354               CORE_ADDR addr;
21355
21356               addr = attr_value_as_address (attr);
21357               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21358               SYMBOL_VALUE_ADDRESS (sym) = addr;
21359             }
21360           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21361           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21362           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21363           add_symbol_to_list (sym, cu->list_in_scope);
21364           break;
21365         case DW_TAG_subprogram:
21366           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21367              finish_block.  */
21368           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21369           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21370           if ((attr2 && (DW_UNSND (attr2) != 0))
21371               || cu->language == language_ada)
21372             {
21373               /* Subprograms marked external are stored as a global symbol.
21374                  Ada subprograms, whether marked external or not, are always
21375                  stored as a global symbol, because we want to be able to
21376                  access them globally.  For instance, we want to be able
21377                  to break on a nested subprogram without having to
21378                  specify the context.  */
21379               list_to_add = &global_symbols;
21380             }
21381           else
21382             {
21383               list_to_add = cu->list_in_scope;
21384             }
21385           break;
21386         case DW_TAG_inlined_subroutine:
21387           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21388              finish_block.  */
21389           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21390           SYMBOL_INLINED (sym) = 1;
21391           list_to_add = cu->list_in_scope;
21392           break;
21393         case DW_TAG_template_value_param:
21394           suppress_add = 1;
21395           /* Fall through.  */
21396         case DW_TAG_constant:
21397         case DW_TAG_variable:
21398         case DW_TAG_member:
21399           /* Compilation with minimal debug info may result in
21400              variables with missing type entries.  Change the
21401              misleading `void' type to something sensible.  */
21402           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21403             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21404
21405           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21406           /* In the case of DW_TAG_member, we should only be called for
21407              static const members.  */
21408           if (die->tag == DW_TAG_member)
21409             {
21410               /* dwarf2_add_field uses die_is_declaration,
21411                  so we do the same.  */
21412               gdb_assert (die_is_declaration (die, cu));
21413               gdb_assert (attr);
21414             }
21415           if (attr)
21416             {
21417               dwarf2_const_value (attr, sym, cu);
21418               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21419               if (!suppress_add)
21420                 {
21421                   if (attr2 && (DW_UNSND (attr2) != 0))
21422                     list_to_add = &global_symbols;
21423                   else
21424                     list_to_add = cu->list_in_scope;
21425                 }
21426               break;
21427             }
21428           attr = dwarf2_attr (die, DW_AT_location, cu);
21429           if (attr)
21430             {
21431               var_decode_location (attr, sym, cu);
21432               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21433
21434               /* Fortran explicitly imports any global symbols to the local
21435                  scope by DW_TAG_common_block.  */
21436               if (cu->language == language_fortran && die->parent
21437                   && die->parent->tag == DW_TAG_common_block)
21438                 attr2 = NULL;
21439
21440               if (SYMBOL_CLASS (sym) == LOC_STATIC
21441                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21442                   && !dwarf2_per_objfile->has_section_at_zero)
21443                 {
21444                   /* When a static variable is eliminated by the linker,
21445                      the corresponding debug information is not stripped
21446                      out, but the variable address is set to null;
21447                      do not add such variables into symbol table.  */
21448                 }
21449               else if (attr2 && (DW_UNSND (attr2) != 0))
21450                 {
21451                   /* Workaround gfortran PR debug/40040 - it uses
21452                      DW_AT_location for variables in -fPIC libraries which may
21453                      get overriden by other libraries/executable and get
21454                      a different address.  Resolve it by the minimal symbol
21455                      which may come from inferior's executable using copy
21456                      relocation.  Make this workaround only for gfortran as for
21457                      other compilers GDB cannot guess the minimal symbol
21458                      Fortran mangling kind.  */
21459                   if (cu->language == language_fortran && die->parent
21460                       && die->parent->tag == DW_TAG_module
21461                       && cu->producer
21462                       && startswith (cu->producer, "GNU Fortran"))
21463                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21464
21465                   /* A variable with DW_AT_external is never static,
21466                      but it may be block-scoped.  */
21467                   list_to_add = (cu->list_in_scope == &file_symbols
21468                                  ? &global_symbols : cu->list_in_scope);
21469                 }
21470               else
21471                 list_to_add = cu->list_in_scope;
21472             }
21473           else
21474             {
21475               /* We do not know the address of this symbol.
21476                  If it is an external symbol and we have type information
21477                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21478                  The address of the variable will then be determined from
21479                  the minimal symbol table whenever the variable is
21480                  referenced.  */
21481               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21482
21483               /* Fortran explicitly imports any global symbols to the local
21484                  scope by DW_TAG_common_block.  */
21485               if (cu->language == language_fortran && die->parent
21486                   && die->parent->tag == DW_TAG_common_block)
21487                 {
21488                   /* SYMBOL_CLASS doesn't matter here because
21489                      read_common_block is going to reset it.  */
21490                   if (!suppress_add)
21491                     list_to_add = cu->list_in_scope;
21492                 }
21493               else if (attr2 && (DW_UNSND (attr2) != 0)
21494                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21495                 {
21496                   /* A variable with DW_AT_external is never static, but it
21497                      may be block-scoped.  */
21498                   list_to_add = (cu->list_in_scope == &file_symbols
21499                                  ? &global_symbols : cu->list_in_scope);
21500
21501                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21502                 }
21503               else if (!die_is_declaration (die, cu))
21504                 {
21505                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21506                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21507                   if (!suppress_add)
21508                     list_to_add = cu->list_in_scope;
21509                 }
21510             }
21511           break;
21512         case DW_TAG_formal_parameter:
21513           /* If we are inside a function, mark this as an argument.  If
21514              not, we might be looking at an argument to an inlined function
21515              when we do not have enough information to show inlined frames;
21516              pretend it's a local variable in that case so that the user can
21517              still see it.  */
21518           if (context_stack_depth > 0
21519               && context_stack[context_stack_depth - 1].name != NULL)
21520             SYMBOL_IS_ARGUMENT (sym) = 1;
21521           attr = dwarf2_attr (die, DW_AT_location, cu);
21522           if (attr)
21523             {
21524               var_decode_location (attr, sym, cu);
21525             }
21526           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21527           if (attr)
21528             {
21529               dwarf2_const_value (attr, sym, cu);
21530             }
21531
21532           list_to_add = cu->list_in_scope;
21533           break;
21534         case DW_TAG_unspecified_parameters:
21535           /* From varargs functions; gdb doesn't seem to have any
21536              interest in this information, so just ignore it for now.
21537              (FIXME?) */
21538           break;
21539         case DW_TAG_template_type_param:
21540           suppress_add = 1;
21541           /* Fall through.  */
21542         case DW_TAG_class_type:
21543         case DW_TAG_interface_type:
21544         case DW_TAG_structure_type:
21545         case DW_TAG_union_type:
21546         case DW_TAG_set_type:
21547         case DW_TAG_enumeration_type:
21548           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21549           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21550
21551           {
21552             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21553                really ever be static objects: otherwise, if you try
21554                to, say, break of a class's method and you're in a file
21555                which doesn't mention that class, it won't work unless
21556                the check for all static symbols in lookup_symbol_aux
21557                saves you.  See the OtherFileClass tests in
21558                gdb.c++/namespace.exp.  */
21559
21560             if (!suppress_add)
21561               {
21562                 list_to_add = (cu->list_in_scope == &file_symbols
21563                                && cu->language == language_cplus
21564                                ? &global_symbols : cu->list_in_scope);
21565
21566                 /* The semantics of C++ state that "struct foo {
21567                    ... }" also defines a typedef for "foo".  */
21568                 if (cu->language == language_cplus
21569                     || cu->language == language_ada
21570                     || cu->language == language_d
21571                     || cu->language == language_rust)
21572                   {
21573                     /* The symbol's name is already allocated along
21574                        with this objfile, so we don't need to
21575                        duplicate it for the type.  */
21576                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21577                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21578                   }
21579               }
21580           }
21581           break;
21582         case DW_TAG_typedef:
21583           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21584           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21585           list_to_add = cu->list_in_scope;
21586           break;
21587         case DW_TAG_base_type:
21588         case DW_TAG_subrange_type:
21589           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21590           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21591           list_to_add = cu->list_in_scope;
21592           break;
21593         case DW_TAG_enumerator:
21594           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21595           if (attr)
21596             {
21597               dwarf2_const_value (attr, sym, cu);
21598             }
21599           {
21600             /* NOTE: carlton/2003-11-10: See comment above in the
21601                DW_TAG_class_type, etc. block.  */
21602
21603             list_to_add = (cu->list_in_scope == &file_symbols
21604                            && cu->language == language_cplus
21605                            ? &global_symbols : cu->list_in_scope);
21606           }
21607           break;
21608         case DW_TAG_imported_declaration:
21609         case DW_TAG_namespace:
21610           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21611           list_to_add = &global_symbols;
21612           break;
21613         case DW_TAG_module:
21614           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21615           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21616           list_to_add = &global_symbols;
21617           break;
21618         case DW_TAG_common_block:
21619           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21620           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21621           add_symbol_to_list (sym, cu->list_in_scope);
21622           break;
21623         default:
21624           /* Not a tag we recognize.  Hopefully we aren't processing
21625              trash data, but since we must specifically ignore things
21626              we don't recognize, there is nothing else we should do at
21627              this point.  */
21628           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21629                      dwarf_tag_name (die->tag));
21630           break;
21631         }
21632
21633       if (suppress_add)
21634         {
21635           sym->hash_next = objfile->template_symbols;
21636           objfile->template_symbols = sym;
21637           list_to_add = NULL;
21638         }
21639
21640       if (list_to_add != NULL)
21641         add_symbol_to_list (sym, list_to_add);
21642
21643       /* For the benefit of old versions of GCC, check for anonymous
21644          namespaces based on the demangled name.  */
21645       if (!cu->processing_has_namespace_info
21646           && cu->language == language_cplus)
21647         cp_scan_for_anonymous_namespaces (sym, objfile);
21648     }
21649   return (sym);
21650 }
21651
21652 /* Given an attr with a DW_FORM_dataN value in host byte order,
21653    zero-extend it as appropriate for the symbol's type.  The DWARF
21654    standard (v4) is not entirely clear about the meaning of using
21655    DW_FORM_dataN for a constant with a signed type, where the type is
21656    wider than the data.  The conclusion of a discussion on the DWARF
21657    list was that this is unspecified.  We choose to always zero-extend
21658    because that is the interpretation long in use by GCC.  */
21659
21660 static gdb_byte *
21661 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21662                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21663 {
21664   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21665   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21666                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21667   LONGEST l = DW_UNSND (attr);
21668
21669   if (bits < sizeof (*value) * 8)
21670     {
21671       l &= ((LONGEST) 1 << bits) - 1;
21672       *value = l;
21673     }
21674   else if (bits == sizeof (*value) * 8)
21675     *value = l;
21676   else
21677     {
21678       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21679       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21680       return bytes;
21681     }
21682
21683   return NULL;
21684 }
21685
21686 /* Read a constant value from an attribute.  Either set *VALUE, or if
21687    the value does not fit in *VALUE, set *BYTES - either already
21688    allocated on the objfile obstack, or newly allocated on OBSTACK,
21689    or, set *BATON, if we translated the constant to a location
21690    expression.  */
21691
21692 static void
21693 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21694                          const char *name, struct obstack *obstack,
21695                          struct dwarf2_cu *cu,
21696                          LONGEST *value, const gdb_byte **bytes,
21697                          struct dwarf2_locexpr_baton **baton)
21698 {
21699   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21700   struct comp_unit_head *cu_header = &cu->header;
21701   struct dwarf_block *blk;
21702   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21703                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21704
21705   *value = 0;
21706   *bytes = NULL;
21707   *baton = NULL;
21708
21709   switch (attr->form)
21710     {
21711     case DW_FORM_addr:
21712     case DW_FORM_GNU_addr_index:
21713       {
21714         gdb_byte *data;
21715
21716         if (TYPE_LENGTH (type) != cu_header->addr_size)
21717           dwarf2_const_value_length_mismatch_complaint (name,
21718                                                         cu_header->addr_size,
21719                                                         TYPE_LENGTH (type));
21720         /* Symbols of this form are reasonably rare, so we just
21721            piggyback on the existing location code rather than writing
21722            a new implementation of symbol_computed_ops.  */
21723         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21724         (*baton)->per_cu = cu->per_cu;
21725         gdb_assert ((*baton)->per_cu);
21726
21727         (*baton)->size = 2 + cu_header->addr_size;
21728         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21729         (*baton)->data = data;
21730
21731         data[0] = DW_OP_addr;
21732         store_unsigned_integer (&data[1], cu_header->addr_size,
21733                                 byte_order, DW_ADDR (attr));
21734         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21735       }
21736       break;
21737     case DW_FORM_string:
21738     case DW_FORM_strp:
21739     case DW_FORM_GNU_str_index:
21740     case DW_FORM_GNU_strp_alt:
21741       /* DW_STRING is already allocated on the objfile obstack, point
21742          directly to it.  */
21743       *bytes = (const gdb_byte *) DW_STRING (attr);
21744       break;
21745     case DW_FORM_block1:
21746     case DW_FORM_block2:
21747     case DW_FORM_block4:
21748     case DW_FORM_block:
21749     case DW_FORM_exprloc:
21750     case DW_FORM_data16:
21751       blk = DW_BLOCK (attr);
21752       if (TYPE_LENGTH (type) != blk->size)
21753         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21754                                                       TYPE_LENGTH (type));
21755       *bytes = blk->data;
21756       break;
21757
21758       /* The DW_AT_const_value attributes are supposed to carry the
21759          symbol's value "represented as it would be on the target
21760          architecture."  By the time we get here, it's already been
21761          converted to host endianness, so we just need to sign- or
21762          zero-extend it as appropriate.  */
21763     case DW_FORM_data1:
21764       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21765       break;
21766     case DW_FORM_data2:
21767       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21768       break;
21769     case DW_FORM_data4:
21770       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21771       break;
21772     case DW_FORM_data8:
21773       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21774       break;
21775
21776     case DW_FORM_sdata:
21777     case DW_FORM_implicit_const:
21778       *value = DW_SND (attr);
21779       break;
21780
21781     case DW_FORM_udata:
21782       *value = DW_UNSND (attr);
21783       break;
21784
21785     default:
21786       complaint (&symfile_complaints,
21787                  _("unsupported const value attribute form: '%s'"),
21788                  dwarf_form_name (attr->form));
21789       *value = 0;
21790       break;
21791     }
21792 }
21793
21794
21795 /* Copy constant value from an attribute to a symbol.  */
21796
21797 static void
21798 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21799                     struct dwarf2_cu *cu)
21800 {
21801   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21802   LONGEST value;
21803   const gdb_byte *bytes;
21804   struct dwarf2_locexpr_baton *baton;
21805
21806   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21807                            SYMBOL_PRINT_NAME (sym),
21808                            &objfile->objfile_obstack, cu,
21809                            &value, &bytes, &baton);
21810
21811   if (baton != NULL)
21812     {
21813       SYMBOL_LOCATION_BATON (sym) = baton;
21814       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21815     }
21816   else if (bytes != NULL)
21817      {
21818       SYMBOL_VALUE_BYTES (sym) = bytes;
21819       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21820     }
21821   else
21822     {
21823       SYMBOL_VALUE (sym) = value;
21824       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21825     }
21826 }
21827
21828 /* Return the type of the die in question using its DW_AT_type attribute.  */
21829
21830 static struct type *
21831 die_type (struct die_info *die, struct dwarf2_cu *cu)
21832 {
21833   struct attribute *type_attr;
21834
21835   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21836   if (!type_attr)
21837     {
21838       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21839       /* A missing DW_AT_type represents a void type.  */
21840       return objfile_type (objfile)->builtin_void;
21841     }
21842
21843   return lookup_die_type (die, type_attr, cu);
21844 }
21845
21846 /* True iff CU's producer generates GNAT Ada auxiliary information
21847    that allows to find parallel types through that information instead
21848    of having to do expensive parallel lookups by type name.  */
21849
21850 static int
21851 need_gnat_info (struct dwarf2_cu *cu)
21852 {
21853   /* Assume that the Ada compiler was GNAT, which always produces
21854      the auxiliary information.  */
21855   return (cu->language == language_ada);
21856 }
21857
21858 /* Return the auxiliary type of the die in question using its
21859    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21860    attribute is not present.  */
21861
21862 static struct type *
21863 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21864 {
21865   struct attribute *type_attr;
21866
21867   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21868   if (!type_attr)
21869     return NULL;
21870
21871   return lookup_die_type (die, type_attr, cu);
21872 }
21873
21874 /* If DIE has a descriptive_type attribute, then set the TYPE's
21875    descriptive type accordingly.  */
21876
21877 static void
21878 set_descriptive_type (struct type *type, struct die_info *die,
21879                       struct dwarf2_cu *cu)
21880 {
21881   struct type *descriptive_type = die_descriptive_type (die, cu);
21882
21883   if (descriptive_type)
21884     {
21885       ALLOCATE_GNAT_AUX_TYPE (type);
21886       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21887     }
21888 }
21889
21890 /* Return the containing type of the die in question using its
21891    DW_AT_containing_type attribute.  */
21892
21893 static struct type *
21894 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21895 {
21896   struct attribute *type_attr;
21897   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21898
21899   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21900   if (!type_attr)
21901     error (_("Dwarf Error: Problem turning containing type into gdb type "
21902              "[in module %s]"), objfile_name (objfile));
21903
21904   return lookup_die_type (die, type_attr, cu);
21905 }
21906
21907 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21908
21909 static struct type *
21910 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21911 {
21912   struct dwarf2_per_objfile *dwarf2_per_objfile
21913     = cu->per_cu->dwarf2_per_objfile;
21914   struct objfile *objfile = dwarf2_per_objfile->objfile;
21915   char *message, *saved;
21916
21917   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21918                         objfile_name (objfile),
21919                         to_underlying (cu->header.sect_off),
21920                         to_underlying (die->sect_off));
21921   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21922                                   message, strlen (message));
21923   xfree (message);
21924
21925   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21926 }
21927
21928 /* Look up the type of DIE in CU using its type attribute ATTR.
21929    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21930    DW_AT_containing_type.
21931    If there is no type substitute an error marker.  */
21932
21933 static struct type *
21934 lookup_die_type (struct die_info *die, const struct attribute *attr,
21935                  struct dwarf2_cu *cu)
21936 {
21937   struct dwarf2_per_objfile *dwarf2_per_objfile
21938     = cu->per_cu->dwarf2_per_objfile;
21939   struct objfile *objfile = dwarf2_per_objfile->objfile;
21940   struct type *this_type;
21941
21942   gdb_assert (attr->name == DW_AT_type
21943               || attr->name == DW_AT_GNAT_descriptive_type
21944               || attr->name == DW_AT_containing_type);
21945
21946   /* First see if we have it cached.  */
21947
21948   if (attr->form == DW_FORM_GNU_ref_alt)
21949     {
21950       struct dwarf2_per_cu_data *per_cu;
21951       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21952
21953       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21954                                                  dwarf2_per_objfile);
21955       this_type = get_die_type_at_offset (sect_off, per_cu);
21956     }
21957   else if (attr_form_is_ref (attr))
21958     {
21959       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21960
21961       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21962     }
21963   else if (attr->form == DW_FORM_ref_sig8)
21964     {
21965       ULONGEST signature = DW_SIGNATURE (attr);
21966
21967       return get_signatured_type (die, signature, cu);
21968     }
21969   else
21970     {
21971       complaint (&symfile_complaints,
21972                  _("Dwarf Error: Bad type attribute %s in DIE"
21973                    " at 0x%x [in module %s]"),
21974                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21975                  objfile_name (objfile));
21976       return build_error_marker_type (cu, die);
21977     }
21978
21979   /* If not cached we need to read it in.  */
21980
21981   if (this_type == NULL)
21982     {
21983       struct die_info *type_die = NULL;
21984       struct dwarf2_cu *type_cu = cu;
21985
21986       if (attr_form_is_ref (attr))
21987         type_die = follow_die_ref (die, attr, &type_cu);
21988       if (type_die == NULL)
21989         return build_error_marker_type (cu, die);
21990       /* If we find the type now, it's probably because the type came
21991          from an inter-CU reference and the type's CU got expanded before
21992          ours.  */
21993       this_type = read_type_die (type_die, type_cu);
21994     }
21995
21996   /* If we still don't have a type use an error marker.  */
21997
21998   if (this_type == NULL)
21999     return build_error_marker_type (cu, die);
22000
22001   return this_type;
22002 }
22003
22004 /* Return the type in DIE, CU.
22005    Returns NULL for invalid types.
22006
22007    This first does a lookup in die_type_hash,
22008    and only reads the die in if necessary.
22009
22010    NOTE: This can be called when reading in partial or full symbols.  */
22011
22012 static struct type *
22013 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22014 {
22015   struct type *this_type;
22016
22017   this_type = get_die_type (die, cu);
22018   if (this_type)
22019     return this_type;
22020
22021   return read_type_die_1 (die, cu);
22022 }
22023
22024 /* Read the type in DIE, CU.
22025    Returns NULL for invalid types.  */
22026
22027 static struct type *
22028 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22029 {
22030   struct type *this_type = NULL;
22031
22032   switch (die->tag)
22033     {
22034     case DW_TAG_class_type:
22035     case DW_TAG_interface_type:
22036     case DW_TAG_structure_type:
22037     case DW_TAG_union_type:
22038       this_type = read_structure_type (die, cu);
22039       break;
22040     case DW_TAG_enumeration_type:
22041       this_type = read_enumeration_type (die, cu);
22042       break;
22043     case DW_TAG_subprogram:
22044     case DW_TAG_subroutine_type:
22045     case DW_TAG_inlined_subroutine:
22046       this_type = read_subroutine_type (die, cu);
22047       break;
22048     case DW_TAG_array_type:
22049       this_type = read_array_type (die, cu);
22050       break;
22051     case DW_TAG_set_type:
22052       this_type = read_set_type (die, cu);
22053       break;
22054     case DW_TAG_pointer_type:
22055       this_type = read_tag_pointer_type (die, cu);
22056       break;
22057     case DW_TAG_ptr_to_member_type:
22058       this_type = read_tag_ptr_to_member_type (die, cu);
22059       break;
22060     case DW_TAG_reference_type:
22061       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22062       break;
22063     case DW_TAG_rvalue_reference_type:
22064       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22065       break;
22066     case DW_TAG_const_type:
22067       this_type = read_tag_const_type (die, cu);
22068       break;
22069     case DW_TAG_volatile_type:
22070       this_type = read_tag_volatile_type (die, cu);
22071       break;
22072     case DW_TAG_restrict_type:
22073       this_type = read_tag_restrict_type (die, cu);
22074       break;
22075     case DW_TAG_string_type:
22076       this_type = read_tag_string_type (die, cu);
22077       break;
22078     case DW_TAG_typedef:
22079       this_type = read_typedef (die, cu);
22080       break;
22081     case DW_TAG_subrange_type:
22082       this_type = read_subrange_type (die, cu);
22083       break;
22084     case DW_TAG_base_type:
22085       this_type = read_base_type (die, cu);
22086       break;
22087     case DW_TAG_unspecified_type:
22088       this_type = read_unspecified_type (die, cu);
22089       break;
22090     case DW_TAG_namespace:
22091       this_type = read_namespace_type (die, cu);
22092       break;
22093     case DW_TAG_module:
22094       this_type = read_module_type (die, cu);
22095       break;
22096     case DW_TAG_atomic_type:
22097       this_type = read_tag_atomic_type (die, cu);
22098       break;
22099     default:
22100       complaint (&symfile_complaints,
22101                  _("unexpected tag in read_type_die: '%s'"),
22102                  dwarf_tag_name (die->tag));
22103       break;
22104     }
22105
22106   return this_type;
22107 }
22108
22109 /* See if we can figure out if the class lives in a namespace.  We do
22110    this by looking for a member function; its demangled name will
22111    contain namespace info, if there is any.
22112    Return the computed name or NULL.
22113    Space for the result is allocated on the objfile's obstack.
22114    This is the full-die version of guess_partial_die_structure_name.
22115    In this case we know DIE has no useful parent.  */
22116
22117 static char *
22118 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22119 {
22120   struct die_info *spec_die;
22121   struct dwarf2_cu *spec_cu;
22122   struct die_info *child;
22123   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22124
22125   spec_cu = cu;
22126   spec_die = die_specification (die, &spec_cu);
22127   if (spec_die != NULL)
22128     {
22129       die = spec_die;
22130       cu = spec_cu;
22131     }
22132
22133   for (child = die->child;
22134        child != NULL;
22135        child = child->sibling)
22136     {
22137       if (child->tag == DW_TAG_subprogram)
22138         {
22139           const char *linkage_name = dw2_linkage_name (child, cu);
22140
22141           if (linkage_name != NULL)
22142             {
22143               char *actual_name
22144                 = language_class_name_from_physname (cu->language_defn,
22145                                                      linkage_name);
22146               char *name = NULL;
22147
22148               if (actual_name != NULL)
22149                 {
22150                   const char *die_name = dwarf2_name (die, cu);
22151
22152                   if (die_name != NULL
22153                       && strcmp (die_name, actual_name) != 0)
22154                     {
22155                       /* Strip off the class name from the full name.
22156                          We want the prefix.  */
22157                       int die_name_len = strlen (die_name);
22158                       int actual_name_len = strlen (actual_name);
22159
22160                       /* Test for '::' as a sanity check.  */
22161                       if (actual_name_len > die_name_len + 2
22162                           && actual_name[actual_name_len
22163                                          - die_name_len - 1] == ':')
22164                         name = (char *) obstack_copy0 (
22165                           &objfile->per_bfd->storage_obstack,
22166                           actual_name, actual_name_len - die_name_len - 2);
22167                     }
22168                 }
22169               xfree (actual_name);
22170               return name;
22171             }
22172         }
22173     }
22174
22175   return NULL;
22176 }
22177
22178 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22179    prefix part in such case.  See
22180    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22181
22182 static const char *
22183 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22184 {
22185   struct attribute *attr;
22186   const char *base;
22187
22188   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22189       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22190     return NULL;
22191
22192   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22193     return NULL;
22194
22195   attr = dw2_linkage_name_attr (die, cu);
22196   if (attr == NULL || DW_STRING (attr) == NULL)
22197     return NULL;
22198
22199   /* dwarf2_name had to be already called.  */
22200   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22201
22202   /* Strip the base name, keep any leading namespaces/classes.  */
22203   base = strrchr (DW_STRING (attr), ':');
22204   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22205     return "";
22206
22207   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22208   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22209                                  DW_STRING (attr),
22210                                  &base[-1] - DW_STRING (attr));
22211 }
22212
22213 /* Return the name of the namespace/class that DIE is defined within,
22214    or "" if we can't tell.  The caller should not xfree the result.
22215
22216    For example, if we're within the method foo() in the following
22217    code:
22218
22219    namespace N {
22220      class C {
22221        void foo () {
22222        }
22223      };
22224    }
22225
22226    then determine_prefix on foo's die will return "N::C".  */
22227
22228 static const char *
22229 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22230 {
22231   struct dwarf2_per_objfile *dwarf2_per_objfile
22232     = cu->per_cu->dwarf2_per_objfile;
22233   struct die_info *parent, *spec_die;
22234   struct dwarf2_cu *spec_cu;
22235   struct type *parent_type;
22236   const char *retval;
22237
22238   if (cu->language != language_cplus
22239       && cu->language != language_fortran && cu->language != language_d
22240       && cu->language != language_rust)
22241     return "";
22242
22243   retval = anonymous_struct_prefix (die, cu);
22244   if (retval)
22245     return retval;
22246
22247   /* We have to be careful in the presence of DW_AT_specification.
22248      For example, with GCC 3.4, given the code
22249
22250      namespace N {
22251        void foo() {
22252          // Definition of N::foo.
22253        }
22254      }
22255
22256      then we'll have a tree of DIEs like this:
22257
22258      1: DW_TAG_compile_unit
22259        2: DW_TAG_namespace        // N
22260          3: DW_TAG_subprogram     // declaration of N::foo
22261        4: DW_TAG_subprogram       // definition of N::foo
22262             DW_AT_specification   // refers to die #3
22263
22264      Thus, when processing die #4, we have to pretend that we're in
22265      the context of its DW_AT_specification, namely the contex of die
22266      #3.  */
22267   spec_cu = cu;
22268   spec_die = die_specification (die, &spec_cu);
22269   if (spec_die == NULL)
22270     parent = die->parent;
22271   else
22272     {
22273       parent = spec_die->parent;
22274       cu = spec_cu;
22275     }
22276
22277   if (parent == NULL)
22278     return "";
22279   else if (parent->building_fullname)
22280     {
22281       const char *name;
22282       const char *parent_name;
22283
22284       /* It has been seen on RealView 2.2 built binaries,
22285          DW_TAG_template_type_param types actually _defined_ as
22286          children of the parent class:
22287
22288          enum E {};
22289          template class <class Enum> Class{};
22290          Class<enum E> class_e;
22291
22292          1: DW_TAG_class_type (Class)
22293            2: DW_TAG_enumeration_type (E)
22294              3: DW_TAG_enumerator (enum1:0)
22295              3: DW_TAG_enumerator (enum2:1)
22296              ...
22297            2: DW_TAG_template_type_param
22298               DW_AT_type  DW_FORM_ref_udata (E)
22299
22300          Besides being broken debug info, it can put GDB into an
22301          infinite loop.  Consider:
22302
22303          When we're building the full name for Class<E>, we'll start
22304          at Class, and go look over its template type parameters,
22305          finding E.  We'll then try to build the full name of E, and
22306          reach here.  We're now trying to build the full name of E,
22307          and look over the parent DIE for containing scope.  In the
22308          broken case, if we followed the parent DIE of E, we'd again
22309          find Class, and once again go look at its template type
22310          arguments, etc., etc.  Simply don't consider such parent die
22311          as source-level parent of this die (it can't be, the language
22312          doesn't allow it), and break the loop here.  */
22313       name = dwarf2_name (die, cu);
22314       parent_name = dwarf2_name (parent, cu);
22315       complaint (&symfile_complaints,
22316                  _("template param type '%s' defined within parent '%s'"),
22317                  name ? name : "<unknown>",
22318                  parent_name ? parent_name : "<unknown>");
22319       return "";
22320     }
22321   else
22322     switch (parent->tag)
22323       {
22324       case DW_TAG_namespace:
22325         parent_type = read_type_die (parent, cu);
22326         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22327            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22328            Work around this problem here.  */
22329         if (cu->language == language_cplus
22330             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22331           return "";
22332         /* We give a name to even anonymous namespaces.  */
22333         return TYPE_TAG_NAME (parent_type);
22334       case DW_TAG_class_type:
22335       case DW_TAG_interface_type:
22336       case DW_TAG_structure_type:
22337       case DW_TAG_union_type:
22338       case DW_TAG_module:
22339         parent_type = read_type_die (parent, cu);
22340         if (TYPE_TAG_NAME (parent_type) != NULL)
22341           return TYPE_TAG_NAME (parent_type);
22342         else
22343           /* An anonymous structure is only allowed non-static data
22344              members; no typedefs, no member functions, et cetera.
22345              So it does not need a prefix.  */
22346           return "";
22347       case DW_TAG_compile_unit:
22348       case DW_TAG_partial_unit:
22349         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22350         if (cu->language == language_cplus
22351             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22352             && die->child != NULL
22353             && (die->tag == DW_TAG_class_type
22354                 || die->tag == DW_TAG_structure_type
22355                 || die->tag == DW_TAG_union_type))
22356           {
22357             char *name = guess_full_die_structure_name (die, cu);
22358             if (name != NULL)
22359               return name;
22360           }
22361         return "";
22362       case DW_TAG_enumeration_type:
22363         parent_type = read_type_die (parent, cu);
22364         if (TYPE_DECLARED_CLASS (parent_type))
22365           {
22366             if (TYPE_TAG_NAME (parent_type) != NULL)
22367               return TYPE_TAG_NAME (parent_type);
22368             return "";
22369           }
22370         /* Fall through.  */
22371       default:
22372         return determine_prefix (parent, cu);
22373       }
22374 }
22375
22376 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22377    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22378    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22379    an obconcat, otherwise allocate storage for the result.  The CU argument is
22380    used to determine the language and hence, the appropriate separator.  */
22381
22382 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22383
22384 static char *
22385 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22386                  int physname, struct dwarf2_cu *cu)
22387 {
22388   const char *lead = "";
22389   const char *sep;
22390
22391   if (suffix == NULL || suffix[0] == '\0'
22392       || prefix == NULL || prefix[0] == '\0')
22393     sep = "";
22394   else if (cu->language == language_d)
22395     {
22396       /* For D, the 'main' function could be defined in any module, but it
22397          should never be prefixed.  */
22398       if (strcmp (suffix, "D main") == 0)
22399         {
22400           prefix = "";
22401           sep = "";
22402         }
22403       else
22404         sep = ".";
22405     }
22406   else if (cu->language == language_fortran && physname)
22407     {
22408       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22409          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22410
22411       lead = "__";
22412       sep = "_MOD_";
22413     }
22414   else
22415     sep = "::";
22416
22417   if (prefix == NULL)
22418     prefix = "";
22419   if (suffix == NULL)
22420     suffix = "";
22421
22422   if (obs == NULL)
22423     {
22424       char *retval
22425         = ((char *)
22426            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22427
22428       strcpy (retval, lead);
22429       strcat (retval, prefix);
22430       strcat (retval, sep);
22431       strcat (retval, suffix);
22432       return retval;
22433     }
22434   else
22435     {
22436       /* We have an obstack.  */
22437       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22438     }
22439 }
22440
22441 /* Return sibling of die, NULL if no sibling.  */
22442
22443 static struct die_info *
22444 sibling_die (struct die_info *die)
22445 {
22446   return die->sibling;
22447 }
22448
22449 /* Get name of a die, return NULL if not found.  */
22450
22451 static const char *
22452 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22453                           struct obstack *obstack)
22454 {
22455   if (name && cu->language == language_cplus)
22456     {
22457       std::string canon_name = cp_canonicalize_string (name);
22458
22459       if (!canon_name.empty ())
22460         {
22461           if (canon_name != name)
22462             name = (const char *) obstack_copy0 (obstack,
22463                                                  canon_name.c_str (),
22464                                                  canon_name.length ());
22465         }
22466     }
22467
22468   return name;
22469 }
22470
22471 /* Get name of a die, return NULL if not found.
22472    Anonymous namespaces are converted to their magic string.  */
22473
22474 static const char *
22475 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22476 {
22477   struct attribute *attr;
22478   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22479
22480   attr = dwarf2_attr (die, DW_AT_name, cu);
22481   if ((!attr || !DW_STRING (attr))
22482       && die->tag != DW_TAG_namespace
22483       && die->tag != DW_TAG_class_type
22484       && die->tag != DW_TAG_interface_type
22485       && die->tag != DW_TAG_structure_type
22486       && die->tag != DW_TAG_union_type)
22487     return NULL;
22488
22489   switch (die->tag)
22490     {
22491     case DW_TAG_compile_unit:
22492     case DW_TAG_partial_unit:
22493       /* Compilation units have a DW_AT_name that is a filename, not
22494          a source language identifier.  */
22495     case DW_TAG_enumeration_type:
22496     case DW_TAG_enumerator:
22497       /* These tags always have simple identifiers already; no need
22498          to canonicalize them.  */
22499       return DW_STRING (attr);
22500
22501     case DW_TAG_namespace:
22502       if (attr != NULL && DW_STRING (attr) != NULL)
22503         return DW_STRING (attr);
22504       return CP_ANONYMOUS_NAMESPACE_STR;
22505
22506     case DW_TAG_class_type:
22507     case DW_TAG_interface_type:
22508     case DW_TAG_structure_type:
22509     case DW_TAG_union_type:
22510       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22511          structures or unions.  These were of the form "._%d" in GCC 4.1,
22512          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22513          and GCC 4.4.  We work around this problem by ignoring these.  */
22514       if (attr && DW_STRING (attr)
22515           && (startswith (DW_STRING (attr), "._")
22516               || startswith (DW_STRING (attr), "<anonymous")))
22517         return NULL;
22518
22519       /* GCC might emit a nameless typedef that has a linkage name.  See
22520          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22521       if (!attr || DW_STRING (attr) == NULL)
22522         {
22523           char *demangled = NULL;
22524
22525           attr = dw2_linkage_name_attr (die, cu);
22526           if (attr == NULL || DW_STRING (attr) == NULL)
22527             return NULL;
22528
22529           /* Avoid demangling DW_STRING (attr) the second time on a second
22530              call for the same DIE.  */
22531           if (!DW_STRING_IS_CANONICAL (attr))
22532             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22533
22534           if (demangled)
22535             {
22536               const char *base;
22537
22538               /* FIXME: we already did this for the partial symbol... */
22539               DW_STRING (attr)
22540                 = ((const char *)
22541                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22542                                   demangled, strlen (demangled)));
22543               DW_STRING_IS_CANONICAL (attr) = 1;
22544               xfree (demangled);
22545
22546               /* Strip any leading namespaces/classes, keep only the base name.
22547                  DW_AT_name for named DIEs does not contain the prefixes.  */
22548               base = strrchr (DW_STRING (attr), ':');
22549               if (base && base > DW_STRING (attr) && base[-1] == ':')
22550                 return &base[1];
22551               else
22552                 return DW_STRING (attr);
22553             }
22554         }
22555       break;
22556
22557     default:
22558       break;
22559     }
22560
22561   if (!DW_STRING_IS_CANONICAL (attr))
22562     {
22563       DW_STRING (attr)
22564         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22565                                     &objfile->per_bfd->storage_obstack);
22566       DW_STRING_IS_CANONICAL (attr) = 1;
22567     }
22568   return DW_STRING (attr);
22569 }
22570
22571 /* Return the die that this die in an extension of, or NULL if there
22572    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22573    containing the return value on output.  */
22574
22575 static struct die_info *
22576 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22577 {
22578   struct attribute *attr;
22579
22580   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22581   if (attr == NULL)
22582     return NULL;
22583
22584   return follow_die_ref (die, attr, ext_cu);
22585 }
22586
22587 /* Convert a DIE tag into its string name.  */
22588
22589 static const char *
22590 dwarf_tag_name (unsigned tag)
22591 {
22592   const char *name = get_DW_TAG_name (tag);
22593
22594   if (name == NULL)
22595     return "DW_TAG_<unknown>";
22596
22597   return name;
22598 }
22599
22600 /* Convert a DWARF attribute code into its string name.  */
22601
22602 static const char *
22603 dwarf_attr_name (unsigned attr)
22604 {
22605   const char *name;
22606
22607 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22608   if (attr == DW_AT_MIPS_fde)
22609     return "DW_AT_MIPS_fde";
22610 #else
22611   if (attr == DW_AT_HP_block_index)
22612     return "DW_AT_HP_block_index";
22613 #endif
22614
22615   name = get_DW_AT_name (attr);
22616
22617   if (name == NULL)
22618     return "DW_AT_<unknown>";
22619
22620   return name;
22621 }
22622
22623 /* Convert a DWARF value form code into its string name.  */
22624
22625 static const char *
22626 dwarf_form_name (unsigned form)
22627 {
22628   const char *name = get_DW_FORM_name (form);
22629
22630   if (name == NULL)
22631     return "DW_FORM_<unknown>";
22632
22633   return name;
22634 }
22635
22636 static const char *
22637 dwarf_bool_name (unsigned mybool)
22638 {
22639   if (mybool)
22640     return "TRUE";
22641   else
22642     return "FALSE";
22643 }
22644
22645 /* Convert a DWARF type code into its string name.  */
22646
22647 static const char *
22648 dwarf_type_encoding_name (unsigned enc)
22649 {
22650   const char *name = get_DW_ATE_name (enc);
22651
22652   if (name == NULL)
22653     return "DW_ATE_<unknown>";
22654
22655   return name;
22656 }
22657
22658 static void
22659 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22660 {
22661   unsigned int i;
22662
22663   print_spaces (indent, f);
22664   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22665                       dwarf_tag_name (die->tag), die->abbrev,
22666                       to_underlying (die->sect_off));
22667
22668   if (die->parent != NULL)
22669     {
22670       print_spaces (indent, f);
22671       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22672                           to_underlying (die->parent->sect_off));
22673     }
22674
22675   print_spaces (indent, f);
22676   fprintf_unfiltered (f, "  has children: %s\n",
22677            dwarf_bool_name (die->child != NULL));
22678
22679   print_spaces (indent, f);
22680   fprintf_unfiltered (f, "  attributes:\n");
22681
22682   for (i = 0; i < die->num_attrs; ++i)
22683     {
22684       print_spaces (indent, f);
22685       fprintf_unfiltered (f, "    %s (%s) ",
22686                dwarf_attr_name (die->attrs[i].name),
22687                dwarf_form_name (die->attrs[i].form));
22688
22689       switch (die->attrs[i].form)
22690         {
22691         case DW_FORM_addr:
22692         case DW_FORM_GNU_addr_index:
22693           fprintf_unfiltered (f, "address: ");
22694           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22695           break;
22696         case DW_FORM_block2:
22697         case DW_FORM_block4:
22698         case DW_FORM_block:
22699         case DW_FORM_block1:
22700           fprintf_unfiltered (f, "block: size %s",
22701                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22702           break;
22703         case DW_FORM_exprloc:
22704           fprintf_unfiltered (f, "expression: size %s",
22705                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22706           break;
22707         case DW_FORM_data16:
22708           fprintf_unfiltered (f, "constant of 16 bytes");
22709           break;
22710         case DW_FORM_ref_addr:
22711           fprintf_unfiltered (f, "ref address: ");
22712           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22713           break;
22714         case DW_FORM_GNU_ref_alt:
22715           fprintf_unfiltered (f, "alt ref address: ");
22716           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22717           break;
22718         case DW_FORM_ref1:
22719         case DW_FORM_ref2:
22720         case DW_FORM_ref4:
22721         case DW_FORM_ref8:
22722         case DW_FORM_ref_udata:
22723           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22724                               (long) (DW_UNSND (&die->attrs[i])));
22725           break;
22726         case DW_FORM_data1:
22727         case DW_FORM_data2:
22728         case DW_FORM_data4:
22729         case DW_FORM_data8:
22730         case DW_FORM_udata:
22731         case DW_FORM_sdata:
22732           fprintf_unfiltered (f, "constant: %s",
22733                               pulongest (DW_UNSND (&die->attrs[i])));
22734           break;
22735         case DW_FORM_sec_offset:
22736           fprintf_unfiltered (f, "section offset: %s",
22737                               pulongest (DW_UNSND (&die->attrs[i])));
22738           break;
22739         case DW_FORM_ref_sig8:
22740           fprintf_unfiltered (f, "signature: %s",
22741                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22742           break;
22743         case DW_FORM_string:
22744         case DW_FORM_strp:
22745         case DW_FORM_line_strp:
22746         case DW_FORM_GNU_str_index:
22747         case DW_FORM_GNU_strp_alt:
22748           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22749                    DW_STRING (&die->attrs[i])
22750                    ? DW_STRING (&die->attrs[i]) : "",
22751                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22752           break;
22753         case DW_FORM_flag:
22754           if (DW_UNSND (&die->attrs[i]))
22755             fprintf_unfiltered (f, "flag: TRUE");
22756           else
22757             fprintf_unfiltered (f, "flag: FALSE");
22758           break;
22759         case DW_FORM_flag_present:
22760           fprintf_unfiltered (f, "flag: TRUE");
22761           break;
22762         case DW_FORM_indirect:
22763           /* The reader will have reduced the indirect form to
22764              the "base form" so this form should not occur.  */
22765           fprintf_unfiltered (f, 
22766                               "unexpected attribute form: DW_FORM_indirect");
22767           break;
22768         case DW_FORM_implicit_const:
22769           fprintf_unfiltered (f, "constant: %s",
22770                               plongest (DW_SND (&die->attrs[i])));
22771           break;
22772         default:
22773           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22774                    die->attrs[i].form);
22775           break;
22776         }
22777       fprintf_unfiltered (f, "\n");
22778     }
22779 }
22780
22781 static void
22782 dump_die_for_error (struct die_info *die)
22783 {
22784   dump_die_shallow (gdb_stderr, 0, die);
22785 }
22786
22787 static void
22788 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22789 {
22790   int indent = level * 4;
22791
22792   gdb_assert (die != NULL);
22793
22794   if (level >= max_level)
22795     return;
22796
22797   dump_die_shallow (f, indent, die);
22798
22799   if (die->child != NULL)
22800     {
22801       print_spaces (indent, f);
22802       fprintf_unfiltered (f, "  Children:");
22803       if (level + 1 < max_level)
22804         {
22805           fprintf_unfiltered (f, "\n");
22806           dump_die_1 (f, level + 1, max_level, die->child);
22807         }
22808       else
22809         {
22810           fprintf_unfiltered (f,
22811                               " [not printed, max nesting level reached]\n");
22812         }
22813     }
22814
22815   if (die->sibling != NULL && level > 0)
22816     {
22817       dump_die_1 (f, level, max_level, die->sibling);
22818     }
22819 }
22820
22821 /* This is called from the pdie macro in gdbinit.in.
22822    It's not static so gcc will keep a copy callable from gdb.  */
22823
22824 void
22825 dump_die (struct die_info *die, int max_level)
22826 {
22827   dump_die_1 (gdb_stdlog, 0, max_level, die);
22828 }
22829
22830 static void
22831 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22832 {
22833   void **slot;
22834
22835   slot = htab_find_slot_with_hash (cu->die_hash, die,
22836                                    to_underlying (die->sect_off),
22837                                    INSERT);
22838
22839   *slot = die;
22840 }
22841
22842 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22843    required kind.  */
22844
22845 static sect_offset
22846 dwarf2_get_ref_die_offset (const struct attribute *attr)
22847 {
22848   if (attr_form_is_ref (attr))
22849     return (sect_offset) DW_UNSND (attr);
22850
22851   complaint (&symfile_complaints,
22852              _("unsupported die ref attribute form: '%s'"),
22853              dwarf_form_name (attr->form));
22854   return {};
22855 }
22856
22857 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22858  * the value held by the attribute is not constant.  */
22859
22860 static LONGEST
22861 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22862 {
22863   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22864     return DW_SND (attr);
22865   else if (attr->form == DW_FORM_udata
22866            || attr->form == DW_FORM_data1
22867            || attr->form == DW_FORM_data2
22868            || attr->form == DW_FORM_data4
22869            || attr->form == DW_FORM_data8)
22870     return DW_UNSND (attr);
22871   else
22872     {
22873       /* For DW_FORM_data16 see attr_form_is_constant.  */
22874       complaint (&symfile_complaints,
22875                  _("Attribute value is not a constant (%s)"),
22876                  dwarf_form_name (attr->form));
22877       return default_value;
22878     }
22879 }
22880
22881 /* Follow reference or signature attribute ATTR of SRC_DIE.
22882    On entry *REF_CU is the CU of SRC_DIE.
22883    On exit *REF_CU is the CU of the result.  */
22884
22885 static struct die_info *
22886 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22887                        struct dwarf2_cu **ref_cu)
22888 {
22889   struct die_info *die;
22890
22891   if (attr_form_is_ref (attr))
22892     die = follow_die_ref (src_die, attr, ref_cu);
22893   else if (attr->form == DW_FORM_ref_sig8)
22894     die = follow_die_sig (src_die, attr, ref_cu);
22895   else
22896     {
22897       dump_die_for_error (src_die);
22898       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22899              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22900     }
22901
22902   return die;
22903 }
22904
22905 /* Follow reference OFFSET.
22906    On entry *REF_CU is the CU of the source die referencing OFFSET.
22907    On exit *REF_CU is the CU of the result.
22908    Returns NULL if OFFSET is invalid.  */
22909
22910 static struct die_info *
22911 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22912                    struct dwarf2_cu **ref_cu)
22913 {
22914   struct die_info temp_die;
22915   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22916   struct dwarf2_per_objfile *dwarf2_per_objfile
22917     = cu->per_cu->dwarf2_per_objfile;
22918   struct objfile *objfile = dwarf2_per_objfile->objfile;
22919
22920   gdb_assert (cu->per_cu != NULL);
22921
22922   target_cu = cu;
22923
22924   if (cu->per_cu->is_debug_types)
22925     {
22926       /* .debug_types CUs cannot reference anything outside their CU.
22927          If they need to, they have to reference a signatured type via
22928          DW_FORM_ref_sig8.  */
22929       if (!offset_in_cu_p (&cu->header, sect_off))
22930         return NULL;
22931     }
22932   else if (offset_in_dwz != cu->per_cu->is_dwz
22933            || !offset_in_cu_p (&cu->header, sect_off))
22934     {
22935       struct dwarf2_per_cu_data *per_cu;
22936
22937       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22938                                                  dwarf2_per_objfile);
22939
22940       /* If necessary, add it to the queue and load its DIEs.  */
22941       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22942         load_full_comp_unit (per_cu, cu->language);
22943
22944       target_cu = per_cu->cu;
22945     }
22946   else if (cu->dies == NULL)
22947     {
22948       /* We're loading full DIEs during partial symbol reading.  */
22949       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22950       load_full_comp_unit (cu->per_cu, language_minimal);
22951     }
22952
22953   *ref_cu = target_cu;
22954   temp_die.sect_off = sect_off;
22955   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22956                                                   &temp_die,
22957                                                   to_underlying (sect_off));
22958 }
22959
22960 /* Follow reference attribute ATTR of SRC_DIE.
22961    On entry *REF_CU is the CU of SRC_DIE.
22962    On exit *REF_CU is the CU of the result.  */
22963
22964 static struct die_info *
22965 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22966                 struct dwarf2_cu **ref_cu)
22967 {
22968   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22969   struct dwarf2_cu *cu = *ref_cu;
22970   struct die_info *die;
22971
22972   die = follow_die_offset (sect_off,
22973                            (attr->form == DW_FORM_GNU_ref_alt
22974                             || cu->per_cu->is_dwz),
22975                            ref_cu);
22976   if (!die)
22977     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22978            "at 0x%x [in module %s]"),
22979            to_underlying (sect_off), to_underlying (src_die->sect_off),
22980            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22981
22982   return die;
22983 }
22984
22985 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22986    Returned value is intended for DW_OP_call*.  Returned
22987    dwarf2_locexpr_baton->data has lifetime of
22988    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22989
22990 struct dwarf2_locexpr_baton
22991 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22992                                struct dwarf2_per_cu_data *per_cu,
22993                                CORE_ADDR (*get_frame_pc) (void *baton),
22994                                void *baton)
22995 {
22996   struct dwarf2_cu *cu;
22997   struct die_info *die;
22998   struct attribute *attr;
22999   struct dwarf2_locexpr_baton retval;
23000   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23001   struct dwarf2_per_objfile *dwarf2_per_objfile
23002     = get_dwarf2_per_objfile (objfile);
23003
23004   if (per_cu->cu == NULL)
23005     load_cu (per_cu);
23006   cu = per_cu->cu;
23007   if (cu == NULL)
23008     {
23009       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23010          Instead just throw an error, not much else we can do.  */
23011       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23012              to_underlying (sect_off), objfile_name (objfile));
23013     }
23014
23015   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23016   if (!die)
23017     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23018            to_underlying (sect_off), objfile_name (objfile));
23019
23020   attr = dwarf2_attr (die, DW_AT_location, cu);
23021   if (!attr)
23022     {
23023       /* DWARF: "If there is no such attribute, then there is no effect.".
23024          DATA is ignored if SIZE is 0.  */
23025
23026       retval.data = NULL;
23027       retval.size = 0;
23028     }
23029   else if (attr_form_is_section_offset (attr))
23030     {
23031       struct dwarf2_loclist_baton loclist_baton;
23032       CORE_ADDR pc = (*get_frame_pc) (baton);
23033       size_t size;
23034
23035       fill_in_loclist_baton (cu, &loclist_baton, attr);
23036
23037       retval.data = dwarf2_find_location_expression (&loclist_baton,
23038                                                      &size, pc);
23039       retval.size = size;
23040     }
23041   else
23042     {
23043       if (!attr_form_is_block (attr))
23044         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
23045                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23046                to_underlying (sect_off), objfile_name (objfile));
23047
23048       retval.data = DW_BLOCK (attr)->data;
23049       retval.size = DW_BLOCK (attr)->size;
23050     }
23051   retval.per_cu = cu->per_cu;
23052
23053   age_cached_comp_units (dwarf2_per_objfile);
23054
23055   return retval;
23056 }
23057
23058 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23059    offset.  */
23060
23061 struct dwarf2_locexpr_baton
23062 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23063                              struct dwarf2_per_cu_data *per_cu,
23064                              CORE_ADDR (*get_frame_pc) (void *baton),
23065                              void *baton)
23066 {
23067   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23068
23069   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23070 }
23071
23072 /* Write a constant of a given type as target-ordered bytes into
23073    OBSTACK.  */
23074
23075 static const gdb_byte *
23076 write_constant_as_bytes (struct obstack *obstack,
23077                          enum bfd_endian byte_order,
23078                          struct type *type,
23079                          ULONGEST value,
23080                          LONGEST *len)
23081 {
23082   gdb_byte *result;
23083
23084   *len = TYPE_LENGTH (type);
23085   result = (gdb_byte *) obstack_alloc (obstack, *len);
23086   store_unsigned_integer (result, *len, byte_order, value);
23087
23088   return result;
23089 }
23090
23091 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23092    pointer to the constant bytes and set LEN to the length of the
23093    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23094    does not have a DW_AT_const_value, return NULL.  */
23095
23096 const gdb_byte *
23097 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23098                              struct dwarf2_per_cu_data *per_cu,
23099                              struct obstack *obstack,
23100                              LONGEST *len)
23101 {
23102   struct dwarf2_cu *cu;
23103   struct die_info *die;
23104   struct attribute *attr;
23105   const gdb_byte *result = NULL;
23106   struct type *type;
23107   LONGEST value;
23108   enum bfd_endian byte_order;
23109   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23110
23111   if (per_cu->cu == NULL)
23112     load_cu (per_cu);
23113   cu = per_cu->cu;
23114   if (cu == NULL)
23115     {
23116       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23117          Instead just throw an error, not much else we can do.  */
23118       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23119              to_underlying (sect_off), objfile_name (objfile));
23120     }
23121
23122   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23123   if (!die)
23124     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23125            to_underlying (sect_off), objfile_name (objfile));
23126
23127
23128   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23129   if (attr == NULL)
23130     return NULL;
23131
23132   byte_order = (bfd_big_endian (objfile->obfd)
23133                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23134
23135   switch (attr->form)
23136     {
23137     case DW_FORM_addr:
23138     case DW_FORM_GNU_addr_index:
23139       {
23140         gdb_byte *tem;
23141
23142         *len = cu->header.addr_size;
23143         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23144         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23145         result = tem;
23146       }
23147       break;
23148     case DW_FORM_string:
23149     case DW_FORM_strp:
23150     case DW_FORM_GNU_str_index:
23151     case DW_FORM_GNU_strp_alt:
23152       /* DW_STRING is already allocated on the objfile obstack, point
23153          directly to it.  */
23154       result = (const gdb_byte *) DW_STRING (attr);
23155       *len = strlen (DW_STRING (attr));
23156       break;
23157     case DW_FORM_block1:
23158     case DW_FORM_block2:
23159     case DW_FORM_block4:
23160     case DW_FORM_block:
23161     case DW_FORM_exprloc:
23162     case DW_FORM_data16:
23163       result = DW_BLOCK (attr)->data;
23164       *len = DW_BLOCK (attr)->size;
23165       break;
23166
23167       /* The DW_AT_const_value attributes are supposed to carry the
23168          symbol's value "represented as it would be on the target
23169          architecture."  By the time we get here, it's already been
23170          converted to host endianness, so we just need to sign- or
23171          zero-extend it as appropriate.  */
23172     case DW_FORM_data1:
23173       type = die_type (die, cu);
23174       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23175       if (result == NULL)
23176         result = write_constant_as_bytes (obstack, byte_order,
23177                                           type, value, len);
23178       break;
23179     case DW_FORM_data2:
23180       type = die_type (die, cu);
23181       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23182       if (result == NULL)
23183         result = write_constant_as_bytes (obstack, byte_order,
23184                                           type, value, len);
23185       break;
23186     case DW_FORM_data4:
23187       type = die_type (die, cu);
23188       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23189       if (result == NULL)
23190         result = write_constant_as_bytes (obstack, byte_order,
23191                                           type, value, len);
23192       break;
23193     case DW_FORM_data8:
23194       type = die_type (die, cu);
23195       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23196       if (result == NULL)
23197         result = write_constant_as_bytes (obstack, byte_order,
23198                                           type, value, len);
23199       break;
23200
23201     case DW_FORM_sdata:
23202     case DW_FORM_implicit_const:
23203       type = die_type (die, cu);
23204       result = write_constant_as_bytes (obstack, byte_order,
23205                                         type, DW_SND (attr), len);
23206       break;
23207
23208     case DW_FORM_udata:
23209       type = die_type (die, cu);
23210       result = write_constant_as_bytes (obstack, byte_order,
23211                                         type, DW_UNSND (attr), len);
23212       break;
23213
23214     default:
23215       complaint (&symfile_complaints,
23216                  _("unsupported const value attribute form: '%s'"),
23217                  dwarf_form_name (attr->form));
23218       break;
23219     }
23220
23221   return result;
23222 }
23223
23224 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23225    valid type for this die is found.  */
23226
23227 struct type *
23228 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23229                                 struct dwarf2_per_cu_data *per_cu)
23230 {
23231   struct dwarf2_cu *cu;
23232   struct die_info *die;
23233
23234   if (per_cu->cu == NULL)
23235     load_cu (per_cu);
23236   cu = per_cu->cu;
23237   if (!cu)
23238     return NULL;
23239
23240   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23241   if (!die)
23242     return NULL;
23243
23244   return die_type (die, cu);
23245 }
23246
23247 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23248    PER_CU.  */
23249
23250 struct type *
23251 dwarf2_get_die_type (cu_offset die_offset,
23252                      struct dwarf2_per_cu_data *per_cu)
23253 {
23254   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23255   return get_die_type_at_offset (die_offset_sect, per_cu);
23256 }
23257
23258 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23259    On entry *REF_CU is the CU of SRC_DIE.
23260    On exit *REF_CU is the CU of the result.
23261    Returns NULL if the referenced DIE isn't found.  */
23262
23263 static struct die_info *
23264 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23265                   struct dwarf2_cu **ref_cu)
23266 {
23267   struct die_info temp_die;
23268   struct dwarf2_cu *sig_cu;
23269   struct die_info *die;
23270
23271   /* While it might be nice to assert sig_type->type == NULL here,
23272      we can get here for DW_AT_imported_declaration where we need
23273      the DIE not the type.  */
23274
23275   /* If necessary, add it to the queue and load its DIEs.  */
23276
23277   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23278     read_signatured_type (sig_type);
23279
23280   sig_cu = sig_type->per_cu.cu;
23281   gdb_assert (sig_cu != NULL);
23282   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23283   temp_die.sect_off = sig_type->type_offset_in_section;
23284   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23285                                                  to_underlying (temp_die.sect_off));
23286   if (die)
23287     {
23288       struct dwarf2_per_objfile *dwarf2_per_objfile
23289         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23290
23291       /* For .gdb_index version 7 keep track of included TUs.
23292          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23293       if (dwarf2_per_objfile->index_table != NULL
23294           && dwarf2_per_objfile->index_table->version <= 7)
23295         {
23296           VEC_safe_push (dwarf2_per_cu_ptr,
23297                          (*ref_cu)->per_cu->imported_symtabs,
23298                          sig_cu->per_cu);
23299         }
23300
23301       *ref_cu = sig_cu;
23302       return die;
23303     }
23304
23305   return NULL;
23306 }
23307
23308 /* Follow signatured type referenced by ATTR in SRC_DIE.
23309    On entry *REF_CU is the CU of SRC_DIE.
23310    On exit *REF_CU is the CU of the result.
23311    The result is the DIE of the type.
23312    If the referenced type cannot be found an error is thrown.  */
23313
23314 static struct die_info *
23315 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23316                 struct dwarf2_cu **ref_cu)
23317 {
23318   ULONGEST signature = DW_SIGNATURE (attr);
23319   struct signatured_type *sig_type;
23320   struct die_info *die;
23321
23322   gdb_assert (attr->form == DW_FORM_ref_sig8);
23323
23324   sig_type = lookup_signatured_type (*ref_cu, signature);
23325   /* sig_type will be NULL if the signatured type is missing from
23326      the debug info.  */
23327   if (sig_type == NULL)
23328     {
23329       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23330                " from DIE at 0x%x [in module %s]"),
23331              hex_string (signature), to_underlying (src_die->sect_off),
23332              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23333     }
23334
23335   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23336   if (die == NULL)
23337     {
23338       dump_die_for_error (src_die);
23339       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23340                " from DIE at 0x%x [in module %s]"),
23341              hex_string (signature), to_underlying (src_die->sect_off),
23342              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23343     }
23344
23345   return die;
23346 }
23347
23348 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23349    reading in and processing the type unit if necessary.  */
23350
23351 static struct type *
23352 get_signatured_type (struct die_info *die, ULONGEST signature,
23353                      struct dwarf2_cu *cu)
23354 {
23355   struct dwarf2_per_objfile *dwarf2_per_objfile
23356     = cu->per_cu->dwarf2_per_objfile;
23357   struct signatured_type *sig_type;
23358   struct dwarf2_cu *type_cu;
23359   struct die_info *type_die;
23360   struct type *type;
23361
23362   sig_type = lookup_signatured_type (cu, signature);
23363   /* sig_type will be NULL if the signatured type is missing from
23364      the debug info.  */
23365   if (sig_type == NULL)
23366     {
23367       complaint (&symfile_complaints,
23368                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23369                    " from DIE at 0x%x [in module %s]"),
23370                  hex_string (signature), to_underlying (die->sect_off),
23371                  objfile_name (dwarf2_per_objfile->objfile));
23372       return build_error_marker_type (cu, die);
23373     }
23374
23375   /* If we already know the type we're done.  */
23376   if (sig_type->type != NULL)
23377     return sig_type->type;
23378
23379   type_cu = cu;
23380   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23381   if (type_die != NULL)
23382     {
23383       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23384          is created.  This is important, for example, because for c++ classes
23385          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23386       type = read_type_die (type_die, type_cu);
23387       if (type == NULL)
23388         {
23389           complaint (&symfile_complaints,
23390                      _("Dwarf Error: Cannot build signatured type %s"
23391                        " referenced from DIE at 0x%x [in module %s]"),
23392                      hex_string (signature), to_underlying (die->sect_off),
23393                      objfile_name (dwarf2_per_objfile->objfile));
23394           type = build_error_marker_type (cu, die);
23395         }
23396     }
23397   else
23398     {
23399       complaint (&symfile_complaints,
23400                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23401                    " from DIE at 0x%x [in module %s]"),
23402                  hex_string (signature), to_underlying (die->sect_off),
23403                  objfile_name (dwarf2_per_objfile->objfile));
23404       type = build_error_marker_type (cu, die);
23405     }
23406   sig_type->type = type;
23407
23408   return type;
23409 }
23410
23411 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23412    reading in and processing the type unit if necessary.  */
23413
23414 static struct type *
23415 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23416                           struct dwarf2_cu *cu) /* ARI: editCase function */
23417 {
23418   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23419   if (attr_form_is_ref (attr))
23420     {
23421       struct dwarf2_cu *type_cu = cu;
23422       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23423
23424       return read_type_die (type_die, type_cu);
23425     }
23426   else if (attr->form == DW_FORM_ref_sig8)
23427     {
23428       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23429     }
23430   else
23431     {
23432       struct dwarf2_per_objfile *dwarf2_per_objfile
23433         = cu->per_cu->dwarf2_per_objfile;
23434
23435       complaint (&symfile_complaints,
23436                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23437                    " at 0x%x [in module %s]"),
23438                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23439                  objfile_name (dwarf2_per_objfile->objfile));
23440       return build_error_marker_type (cu, die);
23441     }
23442 }
23443
23444 /* Load the DIEs associated with type unit PER_CU into memory.  */
23445
23446 static void
23447 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23448 {
23449   struct signatured_type *sig_type;
23450
23451   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23452   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23453
23454   /* We have the per_cu, but we need the signatured_type.
23455      Fortunately this is an easy translation.  */
23456   gdb_assert (per_cu->is_debug_types);
23457   sig_type = (struct signatured_type *) per_cu;
23458
23459   gdb_assert (per_cu->cu == NULL);
23460
23461   read_signatured_type (sig_type);
23462
23463   gdb_assert (per_cu->cu != NULL);
23464 }
23465
23466 /* die_reader_func for read_signatured_type.
23467    This is identical to load_full_comp_unit_reader,
23468    but is kept separate for now.  */
23469
23470 static void
23471 read_signatured_type_reader (const struct die_reader_specs *reader,
23472                              const gdb_byte *info_ptr,
23473                              struct die_info *comp_unit_die,
23474                              int has_children,
23475                              void *data)
23476 {
23477   struct dwarf2_cu *cu = reader->cu;
23478
23479   gdb_assert (cu->die_hash == NULL);
23480   cu->die_hash =
23481     htab_create_alloc_ex (cu->header.length / 12,
23482                           die_hash,
23483                           die_eq,
23484                           NULL,
23485                           &cu->comp_unit_obstack,
23486                           hashtab_obstack_allocate,
23487                           dummy_obstack_deallocate);
23488
23489   if (has_children)
23490     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23491                                                   &info_ptr, comp_unit_die);
23492   cu->dies = comp_unit_die;
23493   /* comp_unit_die is not stored in die_hash, no need.  */
23494
23495   /* We try not to read any attributes in this function, because not
23496      all CUs needed for references have been loaded yet, and symbol
23497      table processing isn't initialized.  But we have to set the CU language,
23498      or we won't be able to build types correctly.
23499      Similarly, if we do not read the producer, we can not apply
23500      producer-specific interpretation.  */
23501   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23502 }
23503
23504 /* Read in a signatured type and build its CU and DIEs.
23505    If the type is a stub for the real type in a DWO file,
23506    read in the real type from the DWO file as well.  */
23507
23508 static void
23509 read_signatured_type (struct signatured_type *sig_type)
23510 {
23511   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23512
23513   gdb_assert (per_cu->is_debug_types);
23514   gdb_assert (per_cu->cu == NULL);
23515
23516   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23517                            read_signatured_type_reader, NULL);
23518   sig_type->per_cu.tu_read = 1;
23519 }
23520
23521 /* Decode simple location descriptions.
23522    Given a pointer to a dwarf block that defines a location, compute
23523    the location and return the value.
23524
23525    NOTE drow/2003-11-18: This function is called in two situations
23526    now: for the address of static or global variables (partial symbols
23527    only) and for offsets into structures which are expected to be
23528    (more or less) constant.  The partial symbol case should go away,
23529    and only the constant case should remain.  That will let this
23530    function complain more accurately.  A few special modes are allowed
23531    without complaint for global variables (for instance, global
23532    register values and thread-local values).
23533
23534    A location description containing no operations indicates that the
23535    object is optimized out.  The return value is 0 for that case.
23536    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23537    callers will only want a very basic result and this can become a
23538    complaint.
23539
23540    Note that stack[0] is unused except as a default error return.  */
23541
23542 static CORE_ADDR
23543 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23544 {
23545   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23546   size_t i;
23547   size_t size = blk->size;
23548   const gdb_byte *data = blk->data;
23549   CORE_ADDR stack[64];
23550   int stacki;
23551   unsigned int bytes_read, unsnd;
23552   gdb_byte op;
23553
23554   i = 0;
23555   stacki = 0;
23556   stack[stacki] = 0;
23557   stack[++stacki] = 0;
23558
23559   while (i < size)
23560     {
23561       op = data[i++];
23562       switch (op)
23563         {
23564         case DW_OP_lit0:
23565         case DW_OP_lit1:
23566         case DW_OP_lit2:
23567         case DW_OP_lit3:
23568         case DW_OP_lit4:
23569         case DW_OP_lit5:
23570         case DW_OP_lit6:
23571         case DW_OP_lit7:
23572         case DW_OP_lit8:
23573         case DW_OP_lit9:
23574         case DW_OP_lit10:
23575         case DW_OP_lit11:
23576         case DW_OP_lit12:
23577         case DW_OP_lit13:
23578         case DW_OP_lit14:
23579         case DW_OP_lit15:
23580         case DW_OP_lit16:
23581         case DW_OP_lit17:
23582         case DW_OP_lit18:
23583         case DW_OP_lit19:
23584         case DW_OP_lit20:
23585         case DW_OP_lit21:
23586         case DW_OP_lit22:
23587         case DW_OP_lit23:
23588         case DW_OP_lit24:
23589         case DW_OP_lit25:
23590         case DW_OP_lit26:
23591         case DW_OP_lit27:
23592         case DW_OP_lit28:
23593         case DW_OP_lit29:
23594         case DW_OP_lit30:
23595         case DW_OP_lit31:
23596           stack[++stacki] = op - DW_OP_lit0;
23597           break;
23598
23599         case DW_OP_reg0:
23600         case DW_OP_reg1:
23601         case DW_OP_reg2:
23602         case DW_OP_reg3:
23603         case DW_OP_reg4:
23604         case DW_OP_reg5:
23605         case DW_OP_reg6:
23606         case DW_OP_reg7:
23607         case DW_OP_reg8:
23608         case DW_OP_reg9:
23609         case DW_OP_reg10:
23610         case DW_OP_reg11:
23611         case DW_OP_reg12:
23612         case DW_OP_reg13:
23613         case DW_OP_reg14:
23614         case DW_OP_reg15:
23615         case DW_OP_reg16:
23616         case DW_OP_reg17:
23617         case DW_OP_reg18:
23618         case DW_OP_reg19:
23619         case DW_OP_reg20:
23620         case DW_OP_reg21:
23621         case DW_OP_reg22:
23622         case DW_OP_reg23:
23623         case DW_OP_reg24:
23624         case DW_OP_reg25:
23625         case DW_OP_reg26:
23626         case DW_OP_reg27:
23627         case DW_OP_reg28:
23628         case DW_OP_reg29:
23629         case DW_OP_reg30:
23630         case DW_OP_reg31:
23631           stack[++stacki] = op - DW_OP_reg0;
23632           if (i < size)
23633             dwarf2_complex_location_expr_complaint ();
23634           break;
23635
23636         case DW_OP_regx:
23637           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23638           i += bytes_read;
23639           stack[++stacki] = unsnd;
23640           if (i < size)
23641             dwarf2_complex_location_expr_complaint ();
23642           break;
23643
23644         case DW_OP_addr:
23645           stack[++stacki] = read_address (objfile->obfd, &data[i],
23646                                           cu, &bytes_read);
23647           i += bytes_read;
23648           break;
23649
23650         case DW_OP_const1u:
23651           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23652           i += 1;
23653           break;
23654
23655         case DW_OP_const1s:
23656           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23657           i += 1;
23658           break;
23659
23660         case DW_OP_const2u:
23661           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23662           i += 2;
23663           break;
23664
23665         case DW_OP_const2s:
23666           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23667           i += 2;
23668           break;
23669
23670         case DW_OP_const4u:
23671           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23672           i += 4;
23673           break;
23674
23675         case DW_OP_const4s:
23676           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23677           i += 4;
23678           break;
23679
23680         case DW_OP_const8u:
23681           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23682           i += 8;
23683           break;
23684
23685         case DW_OP_constu:
23686           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23687                                                   &bytes_read);
23688           i += bytes_read;
23689           break;
23690
23691         case DW_OP_consts:
23692           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23693           i += bytes_read;
23694           break;
23695
23696         case DW_OP_dup:
23697           stack[stacki + 1] = stack[stacki];
23698           stacki++;
23699           break;
23700
23701         case DW_OP_plus:
23702           stack[stacki - 1] += stack[stacki];
23703           stacki--;
23704           break;
23705
23706         case DW_OP_plus_uconst:
23707           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23708                                                  &bytes_read);
23709           i += bytes_read;
23710           break;
23711
23712         case DW_OP_minus:
23713           stack[stacki - 1] -= stack[stacki];
23714           stacki--;
23715           break;
23716
23717         case DW_OP_deref:
23718           /* If we're not the last op, then we definitely can't encode
23719              this using GDB's address_class enum.  This is valid for partial
23720              global symbols, although the variable's address will be bogus
23721              in the psymtab.  */
23722           if (i < size)
23723             dwarf2_complex_location_expr_complaint ();
23724           break;
23725
23726         case DW_OP_GNU_push_tls_address:
23727         case DW_OP_form_tls_address:
23728           /* The top of the stack has the offset from the beginning
23729              of the thread control block at which the variable is located.  */
23730           /* Nothing should follow this operator, so the top of stack would
23731              be returned.  */
23732           /* This is valid for partial global symbols, but the variable's
23733              address will be bogus in the psymtab.  Make it always at least
23734              non-zero to not look as a variable garbage collected by linker
23735              which have DW_OP_addr 0.  */
23736           if (i < size)
23737             dwarf2_complex_location_expr_complaint ();
23738           stack[stacki]++;
23739           break;
23740
23741         case DW_OP_GNU_uninit:
23742           break;
23743
23744         case DW_OP_GNU_addr_index:
23745         case DW_OP_GNU_const_index:
23746           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23747                                                          &bytes_read);
23748           i += bytes_read;
23749           break;
23750
23751         default:
23752           {
23753             const char *name = get_DW_OP_name (op);
23754
23755             if (name)
23756               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23757                          name);
23758             else
23759               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23760                          op);
23761           }
23762
23763           return (stack[stacki]);
23764         }
23765
23766       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23767          outside of the allocated space.  Also enforce minimum>0.  */
23768       if (stacki >= ARRAY_SIZE (stack) - 1)
23769         {
23770           complaint (&symfile_complaints,
23771                      _("location description stack overflow"));
23772           return 0;
23773         }
23774
23775       if (stacki <= 0)
23776         {
23777           complaint (&symfile_complaints,
23778                      _("location description stack underflow"));
23779           return 0;
23780         }
23781     }
23782   return (stack[stacki]);
23783 }
23784
23785 /* memory allocation interface */
23786
23787 static struct dwarf_block *
23788 dwarf_alloc_block (struct dwarf2_cu *cu)
23789 {
23790   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23791 }
23792
23793 static struct die_info *
23794 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23795 {
23796   struct die_info *die;
23797   size_t size = sizeof (struct die_info);
23798
23799   if (num_attrs > 1)
23800     size += (num_attrs - 1) * sizeof (struct attribute);
23801
23802   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23803   memset (die, 0, sizeof (struct die_info));
23804   return (die);
23805 }
23806
23807 \f
23808 /* Macro support.  */
23809
23810 /* Return file name relative to the compilation directory of file number I in
23811    *LH's file name table.  The result is allocated using xmalloc; the caller is
23812    responsible for freeing it.  */
23813
23814 static char *
23815 file_file_name (int file, struct line_header *lh)
23816 {
23817   /* Is the file number a valid index into the line header's file name
23818      table?  Remember that file numbers start with one, not zero.  */
23819   if (1 <= file && file <= lh->file_names.size ())
23820     {
23821       const file_entry &fe = lh->file_names[file - 1];
23822
23823       if (!IS_ABSOLUTE_PATH (fe.name))
23824         {
23825           const char *dir = fe.include_dir (lh);
23826           if (dir != NULL)
23827             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23828         }
23829       return xstrdup (fe.name);
23830     }
23831   else
23832     {
23833       /* The compiler produced a bogus file number.  We can at least
23834          record the macro definitions made in the file, even if we
23835          won't be able to find the file by name.  */
23836       char fake_name[80];
23837
23838       xsnprintf (fake_name, sizeof (fake_name),
23839                  "<bad macro file number %d>", file);
23840
23841       complaint (&symfile_complaints,
23842                  _("bad file number in macro information (%d)"),
23843                  file);
23844
23845       return xstrdup (fake_name);
23846     }
23847 }
23848
23849 /* Return the full name of file number I in *LH's file name table.
23850    Use COMP_DIR as the name of the current directory of the
23851    compilation.  The result is allocated using xmalloc; the caller is
23852    responsible for freeing it.  */
23853 static char *
23854 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23855 {
23856   /* Is the file number a valid index into the line header's file name
23857      table?  Remember that file numbers start with one, not zero.  */
23858   if (1 <= file && file <= lh->file_names.size ())
23859     {
23860       char *relative = file_file_name (file, lh);
23861
23862       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23863         return relative;
23864       return reconcat (relative, comp_dir, SLASH_STRING,
23865                        relative, (char *) NULL);
23866     }
23867   else
23868     return file_file_name (file, lh);
23869 }
23870
23871
23872 static struct macro_source_file *
23873 macro_start_file (int file, int line,
23874                   struct macro_source_file *current_file,
23875                   struct line_header *lh)
23876 {
23877   /* File name relative to the compilation directory of this source file.  */
23878   char *file_name = file_file_name (file, lh);
23879
23880   if (! current_file)
23881     {
23882       /* Note: We don't create a macro table for this compilation unit
23883          at all until we actually get a filename.  */
23884       struct macro_table *macro_table = get_macro_table ();
23885
23886       /* If we have no current file, then this must be the start_file
23887          directive for the compilation unit's main source file.  */
23888       current_file = macro_set_main (macro_table, file_name);
23889       macro_define_special (macro_table);
23890     }
23891   else
23892     current_file = macro_include (current_file, line, file_name);
23893
23894   xfree (file_name);
23895
23896   return current_file;
23897 }
23898
23899 static const char *
23900 consume_improper_spaces (const char *p, const char *body)
23901 {
23902   if (*p == ' ')
23903     {
23904       complaint (&symfile_complaints,
23905                  _("macro definition contains spaces "
23906                    "in formal argument list:\n`%s'"),
23907                  body);
23908
23909       while (*p == ' ')
23910         p++;
23911     }
23912
23913   return p;
23914 }
23915
23916
23917 static void
23918 parse_macro_definition (struct macro_source_file *file, int line,
23919                         const char *body)
23920 {
23921   const char *p;
23922
23923   /* The body string takes one of two forms.  For object-like macro
23924      definitions, it should be:
23925
23926         <macro name> " " <definition>
23927
23928      For function-like macro definitions, it should be:
23929
23930         <macro name> "() " <definition>
23931      or
23932         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23933
23934      Spaces may appear only where explicitly indicated, and in the
23935      <definition>.
23936
23937      The Dwarf 2 spec says that an object-like macro's name is always
23938      followed by a space, but versions of GCC around March 2002 omit
23939      the space when the macro's definition is the empty string.
23940
23941      The Dwarf 2 spec says that there should be no spaces between the
23942      formal arguments in a function-like macro's formal argument list,
23943      but versions of GCC around March 2002 include spaces after the
23944      commas.  */
23945
23946
23947   /* Find the extent of the macro name.  The macro name is terminated
23948      by either a space or null character (for an object-like macro) or
23949      an opening paren (for a function-like macro).  */
23950   for (p = body; *p; p++)
23951     if (*p == ' ' || *p == '(')
23952       break;
23953
23954   if (*p == ' ' || *p == '\0')
23955     {
23956       /* It's an object-like macro.  */
23957       int name_len = p - body;
23958       char *name = savestring (body, name_len);
23959       const char *replacement;
23960
23961       if (*p == ' ')
23962         replacement = body + name_len + 1;
23963       else
23964         {
23965           dwarf2_macro_malformed_definition_complaint (body);
23966           replacement = body + name_len;
23967         }
23968
23969       macro_define_object (file, line, name, replacement);
23970
23971       xfree (name);
23972     }
23973   else if (*p == '(')
23974     {
23975       /* It's a function-like macro.  */
23976       char *name = savestring (body, p - body);
23977       int argc = 0;
23978       int argv_size = 1;
23979       char **argv = XNEWVEC (char *, argv_size);
23980
23981       p++;
23982
23983       p = consume_improper_spaces (p, body);
23984
23985       /* Parse the formal argument list.  */
23986       while (*p && *p != ')')
23987         {
23988           /* Find the extent of the current argument name.  */
23989           const char *arg_start = p;
23990
23991           while (*p && *p != ',' && *p != ')' && *p != ' ')
23992             p++;
23993
23994           if (! *p || p == arg_start)
23995             dwarf2_macro_malformed_definition_complaint (body);
23996           else
23997             {
23998               /* Make sure argv has room for the new argument.  */
23999               if (argc >= argv_size)
24000                 {
24001                   argv_size *= 2;
24002                   argv = XRESIZEVEC (char *, argv, argv_size);
24003                 }
24004
24005               argv[argc++] = savestring (arg_start, p - arg_start);
24006             }
24007
24008           p = consume_improper_spaces (p, body);
24009
24010           /* Consume the comma, if present.  */
24011           if (*p == ',')
24012             {
24013               p++;
24014
24015               p = consume_improper_spaces (p, body);
24016             }
24017         }
24018
24019       if (*p == ')')
24020         {
24021           p++;
24022
24023           if (*p == ' ')
24024             /* Perfectly formed definition, no complaints.  */
24025             macro_define_function (file, line, name,
24026                                    argc, (const char **) argv,
24027                                    p + 1);
24028           else if (*p == '\0')
24029             {
24030               /* Complain, but do define it.  */
24031               dwarf2_macro_malformed_definition_complaint (body);
24032               macro_define_function (file, line, name,
24033                                      argc, (const char **) argv,
24034                                      p);
24035             }
24036           else
24037             /* Just complain.  */
24038             dwarf2_macro_malformed_definition_complaint (body);
24039         }
24040       else
24041         /* Just complain.  */
24042         dwarf2_macro_malformed_definition_complaint (body);
24043
24044       xfree (name);
24045       {
24046         int i;
24047
24048         for (i = 0; i < argc; i++)
24049           xfree (argv[i]);
24050       }
24051       xfree (argv);
24052     }
24053   else
24054     dwarf2_macro_malformed_definition_complaint (body);
24055 }
24056
24057 /* Skip some bytes from BYTES according to the form given in FORM.
24058    Returns the new pointer.  */
24059
24060 static const gdb_byte *
24061 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24062                  enum dwarf_form form,
24063                  unsigned int offset_size,
24064                  struct dwarf2_section_info *section)
24065 {
24066   unsigned int bytes_read;
24067
24068   switch (form)
24069     {
24070     case DW_FORM_data1:
24071     case DW_FORM_flag:
24072       ++bytes;
24073       break;
24074
24075     case DW_FORM_data2:
24076       bytes += 2;
24077       break;
24078
24079     case DW_FORM_data4:
24080       bytes += 4;
24081       break;
24082
24083     case DW_FORM_data8:
24084       bytes += 8;
24085       break;
24086
24087     case DW_FORM_data16:
24088       bytes += 16;
24089       break;
24090
24091     case DW_FORM_string:
24092       read_direct_string (abfd, bytes, &bytes_read);
24093       bytes += bytes_read;
24094       break;
24095
24096     case DW_FORM_sec_offset:
24097     case DW_FORM_strp:
24098     case DW_FORM_GNU_strp_alt:
24099       bytes += offset_size;
24100       break;
24101
24102     case DW_FORM_block:
24103       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24104       bytes += bytes_read;
24105       break;
24106
24107     case DW_FORM_block1:
24108       bytes += 1 + read_1_byte (abfd, bytes);
24109       break;
24110     case DW_FORM_block2:
24111       bytes += 2 + read_2_bytes (abfd, bytes);
24112       break;
24113     case DW_FORM_block4:
24114       bytes += 4 + read_4_bytes (abfd, bytes);
24115       break;
24116
24117     case DW_FORM_sdata:
24118     case DW_FORM_udata:
24119     case DW_FORM_GNU_addr_index:
24120     case DW_FORM_GNU_str_index:
24121       bytes = gdb_skip_leb128 (bytes, buffer_end);
24122       if (bytes == NULL)
24123         {
24124           dwarf2_section_buffer_overflow_complaint (section);
24125           return NULL;
24126         }
24127       break;
24128
24129     case DW_FORM_implicit_const:
24130       break;
24131
24132     default:
24133       {
24134         complaint (&symfile_complaints,
24135                    _("invalid form 0x%x in `%s'"),
24136                    form, get_section_name (section));
24137         return NULL;
24138       }
24139     }
24140
24141   return bytes;
24142 }
24143
24144 /* A helper for dwarf_decode_macros that handles skipping an unknown
24145    opcode.  Returns an updated pointer to the macro data buffer; or,
24146    on error, issues a complaint and returns NULL.  */
24147
24148 static const gdb_byte *
24149 skip_unknown_opcode (unsigned int opcode,
24150                      const gdb_byte **opcode_definitions,
24151                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24152                      bfd *abfd,
24153                      unsigned int offset_size,
24154                      struct dwarf2_section_info *section)
24155 {
24156   unsigned int bytes_read, i;
24157   unsigned long arg;
24158   const gdb_byte *defn;
24159
24160   if (opcode_definitions[opcode] == NULL)
24161     {
24162       complaint (&symfile_complaints,
24163                  _("unrecognized DW_MACFINO opcode 0x%x"),
24164                  opcode);
24165       return NULL;
24166     }
24167
24168   defn = opcode_definitions[opcode];
24169   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24170   defn += bytes_read;
24171
24172   for (i = 0; i < arg; ++i)
24173     {
24174       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24175                                  (enum dwarf_form) defn[i], offset_size,
24176                                  section);
24177       if (mac_ptr == NULL)
24178         {
24179           /* skip_form_bytes already issued the complaint.  */
24180           return NULL;
24181         }
24182     }
24183
24184   return mac_ptr;
24185 }
24186
24187 /* A helper function which parses the header of a macro section.
24188    If the macro section is the extended (for now called "GNU") type,
24189    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24190    the header, or issues a complaint and returns NULL on error.  */
24191
24192 static const gdb_byte *
24193 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24194                           bfd *abfd,
24195                           const gdb_byte *mac_ptr,
24196                           unsigned int *offset_size,
24197                           int section_is_gnu)
24198 {
24199   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24200
24201   if (section_is_gnu)
24202     {
24203       unsigned int version, flags;
24204
24205       version = read_2_bytes (abfd, mac_ptr);
24206       if (version != 4 && version != 5)
24207         {
24208           complaint (&symfile_complaints,
24209                      _("unrecognized version `%d' in .debug_macro section"),
24210                      version);
24211           return NULL;
24212         }
24213       mac_ptr += 2;
24214
24215       flags = read_1_byte (abfd, mac_ptr);
24216       ++mac_ptr;
24217       *offset_size = (flags & 1) ? 8 : 4;
24218
24219       if ((flags & 2) != 0)
24220         /* We don't need the line table offset.  */
24221         mac_ptr += *offset_size;
24222
24223       /* Vendor opcode descriptions.  */
24224       if ((flags & 4) != 0)
24225         {
24226           unsigned int i, count;
24227
24228           count = read_1_byte (abfd, mac_ptr);
24229           ++mac_ptr;
24230           for (i = 0; i < count; ++i)
24231             {
24232               unsigned int opcode, bytes_read;
24233               unsigned long arg;
24234
24235               opcode = read_1_byte (abfd, mac_ptr);
24236               ++mac_ptr;
24237               opcode_definitions[opcode] = mac_ptr;
24238               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24239               mac_ptr += bytes_read;
24240               mac_ptr += arg;
24241             }
24242         }
24243     }
24244
24245   return mac_ptr;
24246 }
24247
24248 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24249    including DW_MACRO_import.  */
24250
24251 static void
24252 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24253                           bfd *abfd,
24254                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24255                           struct macro_source_file *current_file,
24256                           struct line_header *lh,
24257                           struct dwarf2_section_info *section,
24258                           int section_is_gnu, int section_is_dwz,
24259                           unsigned int offset_size,
24260                           htab_t include_hash)
24261 {
24262   struct objfile *objfile = dwarf2_per_objfile->objfile;
24263   enum dwarf_macro_record_type macinfo_type;
24264   int at_commandline;
24265   const gdb_byte *opcode_definitions[256];
24266
24267   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24268                                       &offset_size, section_is_gnu);
24269   if (mac_ptr == NULL)
24270     {
24271       /* We already issued a complaint.  */
24272       return;
24273     }
24274
24275   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24276      GDB is still reading the definitions from command line.  First
24277      DW_MACINFO_start_file will need to be ignored as it was already executed
24278      to create CURRENT_FILE for the main source holding also the command line
24279      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24280      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24281
24282   at_commandline = 1;
24283
24284   do
24285     {
24286       /* Do we at least have room for a macinfo type byte?  */
24287       if (mac_ptr >= mac_end)
24288         {
24289           dwarf2_section_buffer_overflow_complaint (section);
24290           break;
24291         }
24292
24293       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24294       mac_ptr++;
24295
24296       /* Note that we rely on the fact that the corresponding GNU and
24297          DWARF constants are the same.  */
24298       DIAGNOSTIC_PUSH
24299       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24300       switch (macinfo_type)
24301         {
24302           /* A zero macinfo type indicates the end of the macro
24303              information.  */
24304         case 0:
24305           break;
24306
24307         case DW_MACRO_define:
24308         case DW_MACRO_undef:
24309         case DW_MACRO_define_strp:
24310         case DW_MACRO_undef_strp:
24311         case DW_MACRO_define_sup:
24312         case DW_MACRO_undef_sup:
24313           {
24314             unsigned int bytes_read;
24315             int line;
24316             const char *body;
24317             int is_define;
24318
24319             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24320             mac_ptr += bytes_read;
24321
24322             if (macinfo_type == DW_MACRO_define
24323                 || macinfo_type == DW_MACRO_undef)
24324               {
24325                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24326                 mac_ptr += bytes_read;
24327               }
24328             else
24329               {
24330                 LONGEST str_offset;
24331
24332                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24333                 mac_ptr += offset_size;
24334
24335                 if (macinfo_type == DW_MACRO_define_sup
24336                     || macinfo_type == DW_MACRO_undef_sup
24337                     || section_is_dwz)
24338                   {
24339                     struct dwz_file *dwz
24340                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24341
24342                     body = read_indirect_string_from_dwz (objfile,
24343                                                           dwz, str_offset);
24344                   }
24345                 else
24346                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24347                                                          abfd, str_offset);
24348               }
24349
24350             is_define = (macinfo_type == DW_MACRO_define
24351                          || macinfo_type == DW_MACRO_define_strp
24352                          || macinfo_type == DW_MACRO_define_sup);
24353             if (! current_file)
24354               {
24355                 /* DWARF violation as no main source is present.  */
24356                 complaint (&symfile_complaints,
24357                            _("debug info with no main source gives macro %s "
24358                              "on line %d: %s"),
24359                            is_define ? _("definition") : _("undefinition"),
24360                            line, body);
24361                 break;
24362               }
24363             if ((line == 0 && !at_commandline)
24364                 || (line != 0 && at_commandline))
24365               complaint (&symfile_complaints,
24366                          _("debug info gives %s macro %s with %s line %d: %s"),
24367                          at_commandline ? _("command-line") : _("in-file"),
24368                          is_define ? _("definition") : _("undefinition"),
24369                          line == 0 ? _("zero") : _("non-zero"), line, body);
24370
24371             if (is_define)
24372               parse_macro_definition (current_file, line, body);
24373             else
24374               {
24375                 gdb_assert (macinfo_type == DW_MACRO_undef
24376                             || macinfo_type == DW_MACRO_undef_strp
24377                             || macinfo_type == DW_MACRO_undef_sup);
24378                 macro_undef (current_file, line, body);
24379               }
24380           }
24381           break;
24382
24383         case DW_MACRO_start_file:
24384           {
24385             unsigned int bytes_read;
24386             int line, file;
24387
24388             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24389             mac_ptr += bytes_read;
24390             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24391             mac_ptr += bytes_read;
24392
24393             if ((line == 0 && !at_commandline)
24394                 || (line != 0 && at_commandline))
24395               complaint (&symfile_complaints,
24396                          _("debug info gives source %d included "
24397                            "from %s at %s line %d"),
24398                          file, at_commandline ? _("command-line") : _("file"),
24399                          line == 0 ? _("zero") : _("non-zero"), line);
24400
24401             if (at_commandline)
24402               {
24403                 /* This DW_MACRO_start_file was executed in the
24404                    pass one.  */
24405                 at_commandline = 0;
24406               }
24407             else
24408               current_file = macro_start_file (file, line, current_file, lh);
24409           }
24410           break;
24411
24412         case DW_MACRO_end_file:
24413           if (! current_file)
24414             complaint (&symfile_complaints,
24415                        _("macro debug info has an unmatched "
24416                          "`close_file' directive"));
24417           else
24418             {
24419               current_file = current_file->included_by;
24420               if (! current_file)
24421                 {
24422                   enum dwarf_macro_record_type next_type;
24423
24424                   /* GCC circa March 2002 doesn't produce the zero
24425                      type byte marking the end of the compilation
24426                      unit.  Complain if it's not there, but exit no
24427                      matter what.  */
24428
24429                   /* Do we at least have room for a macinfo type byte?  */
24430                   if (mac_ptr >= mac_end)
24431                     {
24432                       dwarf2_section_buffer_overflow_complaint (section);
24433                       return;
24434                     }
24435
24436                   /* We don't increment mac_ptr here, so this is just
24437                      a look-ahead.  */
24438                   next_type
24439                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24440                                                                   mac_ptr);
24441                   if (next_type != 0)
24442                     complaint (&symfile_complaints,
24443                                _("no terminating 0-type entry for "
24444                                  "macros in `.debug_macinfo' section"));
24445
24446                   return;
24447                 }
24448             }
24449           break;
24450
24451         case DW_MACRO_import:
24452         case DW_MACRO_import_sup:
24453           {
24454             LONGEST offset;
24455             void **slot;
24456             bfd *include_bfd = abfd;
24457             struct dwarf2_section_info *include_section = section;
24458             const gdb_byte *include_mac_end = mac_end;
24459             int is_dwz = section_is_dwz;
24460             const gdb_byte *new_mac_ptr;
24461
24462             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24463             mac_ptr += offset_size;
24464
24465             if (macinfo_type == DW_MACRO_import_sup)
24466               {
24467                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24468
24469                 dwarf2_read_section (objfile, &dwz->macro);
24470
24471                 include_section = &dwz->macro;
24472                 include_bfd = get_section_bfd_owner (include_section);
24473                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24474                 is_dwz = 1;
24475               }
24476
24477             new_mac_ptr = include_section->buffer + offset;
24478             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24479
24480             if (*slot != NULL)
24481               {
24482                 /* This has actually happened; see
24483                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24484                 complaint (&symfile_complaints,
24485                            _("recursive DW_MACRO_import in "
24486                              ".debug_macro section"));
24487               }
24488             else
24489               {
24490                 *slot = (void *) new_mac_ptr;
24491
24492                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24493                                           include_bfd, new_mac_ptr,
24494                                           include_mac_end, current_file, lh,
24495                                           section, section_is_gnu, is_dwz,
24496                                           offset_size, include_hash);
24497
24498                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24499               }
24500           }
24501           break;
24502
24503         case DW_MACINFO_vendor_ext:
24504           if (!section_is_gnu)
24505             {
24506               unsigned int bytes_read;
24507
24508               /* This reads the constant, but since we don't recognize
24509                  any vendor extensions, we ignore it.  */
24510               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24511               mac_ptr += bytes_read;
24512               read_direct_string (abfd, mac_ptr, &bytes_read);
24513               mac_ptr += bytes_read;
24514
24515               /* We don't recognize any vendor extensions.  */
24516               break;
24517             }
24518           /* FALLTHROUGH */
24519
24520         default:
24521           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24522                                          mac_ptr, mac_end, abfd, offset_size,
24523                                          section);
24524           if (mac_ptr == NULL)
24525             return;
24526           break;
24527         }
24528       DIAGNOSTIC_POP
24529     } while (macinfo_type != 0);
24530 }
24531
24532 static void
24533 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24534                      int section_is_gnu)
24535 {
24536   struct dwarf2_per_objfile *dwarf2_per_objfile
24537     = cu->per_cu->dwarf2_per_objfile;
24538   struct objfile *objfile = dwarf2_per_objfile->objfile;
24539   struct line_header *lh = cu->line_header;
24540   bfd *abfd;
24541   const gdb_byte *mac_ptr, *mac_end;
24542   struct macro_source_file *current_file = 0;
24543   enum dwarf_macro_record_type macinfo_type;
24544   unsigned int offset_size = cu->header.offset_size;
24545   const gdb_byte *opcode_definitions[256];
24546   void **slot;
24547   struct dwarf2_section_info *section;
24548   const char *section_name;
24549
24550   if (cu->dwo_unit != NULL)
24551     {
24552       if (section_is_gnu)
24553         {
24554           section = &cu->dwo_unit->dwo_file->sections.macro;
24555           section_name = ".debug_macro.dwo";
24556         }
24557       else
24558         {
24559           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24560           section_name = ".debug_macinfo.dwo";
24561         }
24562     }
24563   else
24564     {
24565       if (section_is_gnu)
24566         {
24567           section = &dwarf2_per_objfile->macro;
24568           section_name = ".debug_macro";
24569         }
24570       else
24571         {
24572           section = &dwarf2_per_objfile->macinfo;
24573           section_name = ".debug_macinfo";
24574         }
24575     }
24576
24577   dwarf2_read_section (objfile, section);
24578   if (section->buffer == NULL)
24579     {
24580       complaint (&symfile_complaints, _("missing %s section"), section_name);
24581       return;
24582     }
24583   abfd = get_section_bfd_owner (section);
24584
24585   /* First pass: Find the name of the base filename.
24586      This filename is needed in order to process all macros whose definition
24587      (or undefinition) comes from the command line.  These macros are defined
24588      before the first DW_MACINFO_start_file entry, and yet still need to be
24589      associated to the base file.
24590
24591      To determine the base file name, we scan the macro definitions until we
24592      reach the first DW_MACINFO_start_file entry.  We then initialize
24593      CURRENT_FILE accordingly so that any macro definition found before the
24594      first DW_MACINFO_start_file can still be associated to the base file.  */
24595
24596   mac_ptr = section->buffer + offset;
24597   mac_end = section->buffer + section->size;
24598
24599   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24600                                       &offset_size, section_is_gnu);
24601   if (mac_ptr == NULL)
24602     {
24603       /* We already issued a complaint.  */
24604       return;
24605     }
24606
24607   do
24608     {
24609       /* Do we at least have room for a macinfo type byte?  */
24610       if (mac_ptr >= mac_end)
24611         {
24612           /* Complaint is printed during the second pass as GDB will probably
24613              stop the first pass earlier upon finding
24614              DW_MACINFO_start_file.  */
24615           break;
24616         }
24617
24618       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24619       mac_ptr++;
24620
24621       /* Note that we rely on the fact that the corresponding GNU and
24622          DWARF constants are the same.  */
24623       DIAGNOSTIC_PUSH
24624       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24625       switch (macinfo_type)
24626         {
24627           /* A zero macinfo type indicates the end of the macro
24628              information.  */
24629         case 0:
24630           break;
24631
24632         case DW_MACRO_define:
24633         case DW_MACRO_undef:
24634           /* Only skip the data by MAC_PTR.  */
24635           {
24636             unsigned int bytes_read;
24637
24638             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24639             mac_ptr += bytes_read;
24640             read_direct_string (abfd, mac_ptr, &bytes_read);
24641             mac_ptr += bytes_read;
24642           }
24643           break;
24644
24645         case DW_MACRO_start_file:
24646           {
24647             unsigned int bytes_read;
24648             int line, file;
24649
24650             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24651             mac_ptr += bytes_read;
24652             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24653             mac_ptr += bytes_read;
24654
24655             current_file = macro_start_file (file, line, current_file, lh);
24656           }
24657           break;
24658
24659         case DW_MACRO_end_file:
24660           /* No data to skip by MAC_PTR.  */
24661           break;
24662
24663         case DW_MACRO_define_strp:
24664         case DW_MACRO_undef_strp:
24665         case DW_MACRO_define_sup:
24666         case DW_MACRO_undef_sup:
24667           {
24668             unsigned int bytes_read;
24669
24670             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24671             mac_ptr += bytes_read;
24672             mac_ptr += offset_size;
24673           }
24674           break;
24675
24676         case DW_MACRO_import:
24677         case DW_MACRO_import_sup:
24678           /* Note that, according to the spec, a transparent include
24679              chain cannot call DW_MACRO_start_file.  So, we can just
24680              skip this opcode.  */
24681           mac_ptr += offset_size;
24682           break;
24683
24684         case DW_MACINFO_vendor_ext:
24685           /* Only skip the data by MAC_PTR.  */
24686           if (!section_is_gnu)
24687             {
24688               unsigned int bytes_read;
24689
24690               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24691               mac_ptr += bytes_read;
24692               read_direct_string (abfd, mac_ptr, &bytes_read);
24693               mac_ptr += bytes_read;
24694             }
24695           /* FALLTHROUGH */
24696
24697         default:
24698           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24699                                          mac_ptr, mac_end, abfd, offset_size,
24700                                          section);
24701           if (mac_ptr == NULL)
24702             return;
24703           break;
24704         }
24705       DIAGNOSTIC_POP
24706     } while (macinfo_type != 0 && current_file == NULL);
24707
24708   /* Second pass: Process all entries.
24709
24710      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24711      command-line macro definitions/undefinitions.  This flag is unset when we
24712      reach the first DW_MACINFO_start_file entry.  */
24713
24714   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24715                                            htab_eq_pointer,
24716                                            NULL, xcalloc, xfree));
24717   mac_ptr = section->buffer + offset;
24718   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24719   *slot = (void *) mac_ptr;
24720   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24721                             abfd, mac_ptr, mac_end,
24722                             current_file, lh, section,
24723                             section_is_gnu, 0, offset_size,
24724                             include_hash.get ());
24725 }
24726
24727 /* Check if the attribute's form is a DW_FORM_block*
24728    if so return true else false.  */
24729
24730 static int
24731 attr_form_is_block (const struct attribute *attr)
24732 {
24733   return (attr == NULL ? 0 :
24734       attr->form == DW_FORM_block1
24735       || attr->form == DW_FORM_block2
24736       || attr->form == DW_FORM_block4
24737       || attr->form == DW_FORM_block
24738       || attr->form == DW_FORM_exprloc);
24739 }
24740
24741 /* Return non-zero if ATTR's value is a section offset --- classes
24742    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24743    You may use DW_UNSND (attr) to retrieve such offsets.
24744
24745    Section 7.5.4, "Attribute Encodings", explains that no attribute
24746    may have a value that belongs to more than one of these classes; it
24747    would be ambiguous if we did, because we use the same forms for all
24748    of them.  */
24749
24750 static int
24751 attr_form_is_section_offset (const struct attribute *attr)
24752 {
24753   return (attr->form == DW_FORM_data4
24754           || attr->form == DW_FORM_data8
24755           || attr->form == DW_FORM_sec_offset);
24756 }
24757
24758 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24759    zero otherwise.  When this function returns true, you can apply
24760    dwarf2_get_attr_constant_value to it.
24761
24762    However, note that for some attributes you must check
24763    attr_form_is_section_offset before using this test.  DW_FORM_data4
24764    and DW_FORM_data8 are members of both the constant class, and of
24765    the classes that contain offsets into other debug sections
24766    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24767    that, if an attribute's can be either a constant or one of the
24768    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24769    taken as section offsets, not constants.
24770
24771    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24772    cannot handle that.  */
24773
24774 static int
24775 attr_form_is_constant (const struct attribute *attr)
24776 {
24777   switch (attr->form)
24778     {
24779     case DW_FORM_sdata:
24780     case DW_FORM_udata:
24781     case DW_FORM_data1:
24782     case DW_FORM_data2:
24783     case DW_FORM_data4:
24784     case DW_FORM_data8:
24785     case DW_FORM_implicit_const:
24786       return 1;
24787     default:
24788       return 0;
24789     }
24790 }
24791
24792
24793 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24794    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24795
24796 static int
24797 attr_form_is_ref (const struct attribute *attr)
24798 {
24799   switch (attr->form)
24800     {
24801     case DW_FORM_ref_addr:
24802     case DW_FORM_ref1:
24803     case DW_FORM_ref2:
24804     case DW_FORM_ref4:
24805     case DW_FORM_ref8:
24806     case DW_FORM_ref_udata:
24807     case DW_FORM_GNU_ref_alt:
24808       return 1;
24809     default:
24810       return 0;
24811     }
24812 }
24813
24814 /* Return the .debug_loc section to use for CU.
24815    For DWO files use .debug_loc.dwo.  */
24816
24817 static struct dwarf2_section_info *
24818 cu_debug_loc_section (struct dwarf2_cu *cu)
24819 {
24820   struct dwarf2_per_objfile *dwarf2_per_objfile
24821     = cu->per_cu->dwarf2_per_objfile;
24822
24823   if (cu->dwo_unit)
24824     {
24825       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24826       
24827       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24828     }
24829   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24830                                   : &dwarf2_per_objfile->loc);
24831 }
24832
24833 /* A helper function that fills in a dwarf2_loclist_baton.  */
24834
24835 static void
24836 fill_in_loclist_baton (struct dwarf2_cu *cu,
24837                        struct dwarf2_loclist_baton *baton,
24838                        const struct attribute *attr)
24839 {
24840   struct dwarf2_per_objfile *dwarf2_per_objfile
24841     = cu->per_cu->dwarf2_per_objfile;
24842   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24843
24844   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24845
24846   baton->per_cu = cu->per_cu;
24847   gdb_assert (baton->per_cu);
24848   /* We don't know how long the location list is, but make sure we
24849      don't run off the edge of the section.  */
24850   baton->size = section->size - DW_UNSND (attr);
24851   baton->data = section->buffer + DW_UNSND (attr);
24852   baton->base_address = cu->base_address;
24853   baton->from_dwo = cu->dwo_unit != NULL;
24854 }
24855
24856 static void
24857 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24858                              struct dwarf2_cu *cu, int is_block)
24859 {
24860   struct dwarf2_per_objfile *dwarf2_per_objfile
24861     = cu->per_cu->dwarf2_per_objfile;
24862   struct objfile *objfile = dwarf2_per_objfile->objfile;
24863   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24864
24865   if (attr_form_is_section_offset (attr)
24866       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24867          the section.  If so, fall through to the complaint in the
24868          other branch.  */
24869       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24870     {
24871       struct dwarf2_loclist_baton *baton;
24872
24873       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24874
24875       fill_in_loclist_baton (cu, baton, attr);
24876
24877       if (cu->base_known == 0)
24878         complaint (&symfile_complaints,
24879                    _("Location list used without "
24880                      "specifying the CU base address."));
24881
24882       SYMBOL_ACLASS_INDEX (sym) = (is_block
24883                                    ? dwarf2_loclist_block_index
24884                                    : dwarf2_loclist_index);
24885       SYMBOL_LOCATION_BATON (sym) = baton;
24886     }
24887   else
24888     {
24889       struct dwarf2_locexpr_baton *baton;
24890
24891       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24892       baton->per_cu = cu->per_cu;
24893       gdb_assert (baton->per_cu);
24894
24895       if (attr_form_is_block (attr))
24896         {
24897           /* Note that we're just copying the block's data pointer
24898              here, not the actual data.  We're still pointing into the
24899              info_buffer for SYM's objfile; right now we never release
24900              that buffer, but when we do clean up properly this may
24901              need to change.  */
24902           baton->size = DW_BLOCK (attr)->size;
24903           baton->data = DW_BLOCK (attr)->data;
24904         }
24905       else
24906         {
24907           dwarf2_invalid_attrib_class_complaint ("location description",
24908                                                  SYMBOL_NATURAL_NAME (sym));
24909           baton->size = 0;
24910         }
24911
24912       SYMBOL_ACLASS_INDEX (sym) = (is_block
24913                                    ? dwarf2_locexpr_block_index
24914                                    : dwarf2_locexpr_index);
24915       SYMBOL_LOCATION_BATON (sym) = baton;
24916     }
24917 }
24918
24919 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24920    came from a separate debuginfo file, then the master objfile is
24921    returned.  */
24922
24923 struct objfile *
24924 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24925 {
24926   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24927
24928   /* Return the master objfile, so that we can report and look up the
24929      correct file containing this variable.  */
24930   if (objfile->separate_debug_objfile_backlink)
24931     objfile = objfile->separate_debug_objfile_backlink;
24932
24933   return objfile;
24934 }
24935
24936 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24937    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24938    CU_HEADERP first.  */
24939
24940 static const struct comp_unit_head *
24941 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24942                        struct dwarf2_per_cu_data *per_cu)
24943 {
24944   const gdb_byte *info_ptr;
24945
24946   if (per_cu->cu)
24947     return &per_cu->cu->header;
24948
24949   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24950
24951   memset (cu_headerp, 0, sizeof (*cu_headerp));
24952   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24953                        rcuh_kind::COMPILE);
24954
24955   return cu_headerp;
24956 }
24957
24958 /* Return the address size given in the compilation unit header for CU.  */
24959
24960 int
24961 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24962 {
24963   struct comp_unit_head cu_header_local;
24964   const struct comp_unit_head *cu_headerp;
24965
24966   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24967
24968   return cu_headerp->addr_size;
24969 }
24970
24971 /* Return the offset size given in the compilation unit header for CU.  */
24972
24973 int
24974 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24975 {
24976   struct comp_unit_head cu_header_local;
24977   const struct comp_unit_head *cu_headerp;
24978
24979   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24980
24981   return cu_headerp->offset_size;
24982 }
24983
24984 /* See its dwarf2loc.h declaration.  */
24985
24986 int
24987 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24988 {
24989   struct comp_unit_head cu_header_local;
24990   const struct comp_unit_head *cu_headerp;
24991
24992   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24993
24994   if (cu_headerp->version == 2)
24995     return cu_headerp->addr_size;
24996   else
24997     return cu_headerp->offset_size;
24998 }
24999
25000 /* Return the text offset of the CU.  The returned offset comes from
25001    this CU's objfile.  If this objfile came from a separate debuginfo
25002    file, then the offset may be different from the corresponding
25003    offset in the parent objfile.  */
25004
25005 CORE_ADDR
25006 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25007 {
25008   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25009
25010   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25011 }
25012
25013 /* Return DWARF version number of PER_CU.  */
25014
25015 short
25016 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25017 {
25018   return per_cu->dwarf_version;
25019 }
25020
25021 /* Locate the .debug_info compilation unit from CU's objfile which contains
25022    the DIE at OFFSET.  Raises an error on failure.  */
25023
25024 static struct dwarf2_per_cu_data *
25025 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25026                                   unsigned int offset_in_dwz,
25027                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25028 {
25029   struct dwarf2_per_cu_data *this_cu;
25030   int low, high;
25031   const sect_offset *cu_off;
25032
25033   low = 0;
25034   high = dwarf2_per_objfile->n_comp_units - 1;
25035   while (high > low)
25036     {
25037       struct dwarf2_per_cu_data *mid_cu;
25038       int mid = low + (high - low) / 2;
25039
25040       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25041       cu_off = &mid_cu->sect_off;
25042       if (mid_cu->is_dwz > offset_in_dwz
25043           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25044         high = mid;
25045       else
25046         low = mid + 1;
25047     }
25048   gdb_assert (low == high);
25049   this_cu = dwarf2_per_objfile->all_comp_units[low];
25050   cu_off = &this_cu->sect_off;
25051   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25052     {
25053       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25054         error (_("Dwarf Error: could not find partial DIE containing "
25055                "offset 0x%x [in module %s]"),
25056                to_underlying (sect_off),
25057                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25058
25059       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25060                   <= sect_off);
25061       return dwarf2_per_objfile->all_comp_units[low-1];
25062     }
25063   else
25064     {
25065       this_cu = dwarf2_per_objfile->all_comp_units[low];
25066       if (low == dwarf2_per_objfile->n_comp_units - 1
25067           && sect_off >= this_cu->sect_off + this_cu->length)
25068         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
25069       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25070       return this_cu;
25071     }
25072 }
25073
25074 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25075
25076 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25077   : per_cu (per_cu_),
25078     mark (0),
25079     has_loclist (0),
25080     checked_producer (0),
25081     producer_is_gxx_lt_4_6 (0),
25082     producer_is_gcc_lt_4_3 (0),
25083     producer_is_icc_lt_14 (0),
25084     processing_has_namespace_info (0)
25085 {
25086   per_cu->cu = this;
25087 }
25088
25089 /* Destroy a dwarf2_cu.  */
25090
25091 dwarf2_cu::~dwarf2_cu ()
25092 {
25093   per_cu->cu = NULL;
25094 }
25095
25096 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25097
25098 static void
25099 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25100                        enum language pretend_language)
25101 {
25102   struct attribute *attr;
25103
25104   /* Set the language we're debugging.  */
25105   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25106   if (attr)
25107     set_cu_language (DW_UNSND (attr), cu);
25108   else
25109     {
25110       cu->language = pretend_language;
25111       cu->language_defn = language_def (cu->language);
25112     }
25113
25114   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25115 }
25116
25117 /* Free all cached compilation units.  */
25118
25119 static void
25120 free_cached_comp_units (void *data)
25121 {
25122   struct dwarf2_per_objfile *dwarf2_per_objfile
25123     = (struct dwarf2_per_objfile *) data;
25124
25125   dwarf2_per_objfile->free_cached_comp_units ();
25126 }
25127
25128 /* Increase the age counter on each cached compilation unit, and free
25129    any that are too old.  */
25130
25131 static void
25132 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25133 {
25134   struct dwarf2_per_cu_data *per_cu, **last_chain;
25135
25136   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25137   per_cu = dwarf2_per_objfile->read_in_chain;
25138   while (per_cu != NULL)
25139     {
25140       per_cu->cu->last_used ++;
25141       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25142         dwarf2_mark (per_cu->cu);
25143       per_cu = per_cu->cu->read_in_chain;
25144     }
25145
25146   per_cu = dwarf2_per_objfile->read_in_chain;
25147   last_chain = &dwarf2_per_objfile->read_in_chain;
25148   while (per_cu != NULL)
25149     {
25150       struct dwarf2_per_cu_data *next_cu;
25151
25152       next_cu = per_cu->cu->read_in_chain;
25153
25154       if (!per_cu->cu->mark)
25155         {
25156           delete per_cu->cu;
25157           *last_chain = next_cu;
25158         }
25159       else
25160         last_chain = &per_cu->cu->read_in_chain;
25161
25162       per_cu = next_cu;
25163     }
25164 }
25165
25166 /* Remove a single compilation unit from the cache.  */
25167
25168 static void
25169 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25170 {
25171   struct dwarf2_per_cu_data *per_cu, **last_chain;
25172   struct dwarf2_per_objfile *dwarf2_per_objfile
25173     = target_per_cu->dwarf2_per_objfile;
25174
25175   per_cu = dwarf2_per_objfile->read_in_chain;
25176   last_chain = &dwarf2_per_objfile->read_in_chain;
25177   while (per_cu != NULL)
25178     {
25179       struct dwarf2_per_cu_data *next_cu;
25180
25181       next_cu = per_cu->cu->read_in_chain;
25182
25183       if (per_cu == target_per_cu)
25184         {
25185           delete per_cu->cu;
25186           per_cu->cu = NULL;
25187           *last_chain = next_cu;
25188           break;
25189         }
25190       else
25191         last_chain = &per_cu->cu->read_in_chain;
25192
25193       per_cu = next_cu;
25194     }
25195 }
25196
25197 /* Release all extra memory associated with OBJFILE.  */
25198
25199 void
25200 dwarf2_free_objfile (struct objfile *objfile)
25201 {
25202   struct dwarf2_per_objfile *dwarf2_per_objfile
25203     = get_dwarf2_per_objfile (objfile);
25204
25205   if (dwarf2_per_objfile == NULL)
25206     return;
25207
25208   dwarf2_per_objfile->~dwarf2_per_objfile ();
25209 }
25210
25211 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25212    We store these in a hash table separate from the DIEs, and preserve them
25213    when the DIEs are flushed out of cache.
25214
25215    The CU "per_cu" pointer is needed because offset alone is not enough to
25216    uniquely identify the type.  A file may have multiple .debug_types sections,
25217    or the type may come from a DWO file.  Furthermore, while it's more logical
25218    to use per_cu->section+offset, with Fission the section with the data is in
25219    the DWO file but we don't know that section at the point we need it.
25220    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25221    because we can enter the lookup routine, get_die_type_at_offset, from
25222    outside this file, and thus won't necessarily have PER_CU->cu.
25223    Fortunately, PER_CU is stable for the life of the objfile.  */
25224
25225 struct dwarf2_per_cu_offset_and_type
25226 {
25227   const struct dwarf2_per_cu_data *per_cu;
25228   sect_offset sect_off;
25229   struct type *type;
25230 };
25231
25232 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25233
25234 static hashval_t
25235 per_cu_offset_and_type_hash (const void *item)
25236 {
25237   const struct dwarf2_per_cu_offset_and_type *ofs
25238     = (const struct dwarf2_per_cu_offset_and_type *) item;
25239
25240   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25241 }
25242
25243 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25244
25245 static int
25246 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25247 {
25248   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25249     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25250   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25251     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25252
25253   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25254           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25255 }
25256
25257 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25258    table if necessary.  For convenience, return TYPE.
25259
25260    The DIEs reading must have careful ordering to:
25261     * Not cause infite loops trying to read in DIEs as a prerequisite for
25262       reading current DIE.
25263     * Not trying to dereference contents of still incompletely read in types
25264       while reading in other DIEs.
25265     * Enable referencing still incompletely read in types just by a pointer to
25266       the type without accessing its fields.
25267
25268    Therefore caller should follow these rules:
25269      * Try to fetch any prerequisite types we may need to build this DIE type
25270        before building the type and calling set_die_type.
25271      * After building type call set_die_type for current DIE as soon as
25272        possible before fetching more types to complete the current type.
25273      * Make the type as complete as possible before fetching more types.  */
25274
25275 static struct type *
25276 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25277 {
25278   struct dwarf2_per_objfile *dwarf2_per_objfile
25279     = cu->per_cu->dwarf2_per_objfile;
25280   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25281   struct objfile *objfile = dwarf2_per_objfile->objfile;
25282   struct attribute *attr;
25283   struct dynamic_prop prop;
25284
25285   /* For Ada types, make sure that the gnat-specific data is always
25286      initialized (if not already set).  There are a few types where
25287      we should not be doing so, because the type-specific area is
25288      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25289      where the type-specific area is used to store the floatformat).
25290      But this is not a problem, because the gnat-specific information
25291      is actually not needed for these types.  */
25292   if (need_gnat_info (cu)
25293       && TYPE_CODE (type) != TYPE_CODE_FUNC
25294       && TYPE_CODE (type) != TYPE_CODE_FLT
25295       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25296       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25297       && TYPE_CODE (type) != TYPE_CODE_METHOD
25298       && !HAVE_GNAT_AUX_INFO (type))
25299     INIT_GNAT_SPECIFIC (type);
25300
25301   /* Read DW_AT_allocated and set in type.  */
25302   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25303   if (attr_form_is_block (attr))
25304     {
25305       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25306         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25307     }
25308   else if (attr != NULL)
25309     {
25310       complaint (&symfile_complaints,
25311                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25312                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25313                  to_underlying (die->sect_off));
25314     }
25315
25316   /* Read DW_AT_associated and set in type.  */
25317   attr = dwarf2_attr (die, DW_AT_associated, cu);
25318   if (attr_form_is_block (attr))
25319     {
25320       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25321         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25322     }
25323   else if (attr != NULL)
25324     {
25325       complaint (&symfile_complaints,
25326                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25327                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25328                  to_underlying (die->sect_off));
25329     }
25330
25331   /* Read DW_AT_data_location and set in type.  */
25332   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25333   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25334     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25335
25336   if (dwarf2_per_objfile->die_type_hash == NULL)
25337     {
25338       dwarf2_per_objfile->die_type_hash =
25339         htab_create_alloc_ex (127,
25340                               per_cu_offset_and_type_hash,
25341                               per_cu_offset_and_type_eq,
25342                               NULL,
25343                               &objfile->objfile_obstack,
25344                               hashtab_obstack_allocate,
25345                               dummy_obstack_deallocate);
25346     }
25347
25348   ofs.per_cu = cu->per_cu;
25349   ofs.sect_off = die->sect_off;
25350   ofs.type = type;
25351   slot = (struct dwarf2_per_cu_offset_and_type **)
25352     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25353   if (*slot)
25354     complaint (&symfile_complaints,
25355                _("A problem internal to GDB: DIE 0x%x has type already set"),
25356                to_underlying (die->sect_off));
25357   *slot = XOBNEW (&objfile->objfile_obstack,
25358                   struct dwarf2_per_cu_offset_and_type);
25359   **slot = ofs;
25360   return type;
25361 }
25362
25363 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25364    or return NULL if the die does not have a saved type.  */
25365
25366 static struct type *
25367 get_die_type_at_offset (sect_offset sect_off,
25368                         struct dwarf2_per_cu_data *per_cu)
25369 {
25370   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25371   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25372
25373   if (dwarf2_per_objfile->die_type_hash == NULL)
25374     return NULL;
25375
25376   ofs.per_cu = per_cu;
25377   ofs.sect_off = sect_off;
25378   slot = ((struct dwarf2_per_cu_offset_and_type *)
25379           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25380   if (slot)
25381     return slot->type;
25382   else
25383     return NULL;
25384 }
25385
25386 /* Look up the type for DIE in CU in die_type_hash,
25387    or return NULL if DIE does not have a saved type.  */
25388
25389 static struct type *
25390 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25391 {
25392   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25393 }
25394
25395 /* Add a dependence relationship from CU to REF_PER_CU.  */
25396
25397 static void
25398 dwarf2_add_dependence (struct dwarf2_cu *cu,
25399                        struct dwarf2_per_cu_data *ref_per_cu)
25400 {
25401   void **slot;
25402
25403   if (cu->dependencies == NULL)
25404     cu->dependencies
25405       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25406                               NULL, &cu->comp_unit_obstack,
25407                               hashtab_obstack_allocate,
25408                               dummy_obstack_deallocate);
25409
25410   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25411   if (*slot == NULL)
25412     *slot = ref_per_cu;
25413 }
25414
25415 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25416    Set the mark field in every compilation unit in the
25417    cache that we must keep because we are keeping CU.  */
25418
25419 static int
25420 dwarf2_mark_helper (void **slot, void *data)
25421 {
25422   struct dwarf2_per_cu_data *per_cu;
25423
25424   per_cu = (struct dwarf2_per_cu_data *) *slot;
25425
25426   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25427      reading of the chain.  As such dependencies remain valid it is not much
25428      useful to track and undo them during QUIT cleanups.  */
25429   if (per_cu->cu == NULL)
25430     return 1;
25431
25432   if (per_cu->cu->mark)
25433     return 1;
25434   per_cu->cu->mark = 1;
25435
25436   if (per_cu->cu->dependencies != NULL)
25437     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25438
25439   return 1;
25440 }
25441
25442 /* Set the mark field in CU and in every other compilation unit in the
25443    cache that we must keep because we are keeping CU.  */
25444
25445 static void
25446 dwarf2_mark (struct dwarf2_cu *cu)
25447 {
25448   if (cu->mark)
25449     return;
25450   cu->mark = 1;
25451   if (cu->dependencies != NULL)
25452     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25453 }
25454
25455 static void
25456 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25457 {
25458   while (per_cu)
25459     {
25460       per_cu->cu->mark = 0;
25461       per_cu = per_cu->cu->read_in_chain;
25462     }
25463 }
25464
25465 /* Trivial hash function for partial_die_info: the hash value of a DIE
25466    is its offset in .debug_info for this objfile.  */
25467
25468 static hashval_t
25469 partial_die_hash (const void *item)
25470 {
25471   const struct partial_die_info *part_die
25472     = (const struct partial_die_info *) item;
25473
25474   return to_underlying (part_die->sect_off);
25475 }
25476
25477 /* Trivial comparison function for partial_die_info structures: two DIEs
25478    are equal if they have the same offset.  */
25479
25480 static int
25481 partial_die_eq (const void *item_lhs, const void *item_rhs)
25482 {
25483   const struct partial_die_info *part_die_lhs
25484     = (const struct partial_die_info *) item_lhs;
25485   const struct partial_die_info *part_die_rhs
25486     = (const struct partial_die_info *) item_rhs;
25487
25488   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25489 }
25490
25491 static struct cmd_list_element *set_dwarf_cmdlist;
25492 static struct cmd_list_element *show_dwarf_cmdlist;
25493
25494 static void
25495 set_dwarf_cmd (const char *args, int from_tty)
25496 {
25497   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25498              gdb_stdout);
25499 }
25500
25501 static void
25502 show_dwarf_cmd (const char *args, int from_tty)
25503 {
25504   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25505 }
25506
25507 /* The "save gdb-index" command.  */
25508
25509 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25510    error checking.  */
25511
25512 static void
25513 file_write (FILE *file, const void *data, size_t size)
25514 {
25515   if (fwrite (data, 1, size, file) != size)
25516     error (_("couldn't data write to file"));
25517 }
25518
25519 /* Write the contents of VEC to FILE, with error checking.  */
25520
25521 template<typename Elem, typename Alloc>
25522 static void
25523 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25524 {
25525   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25526 }
25527
25528 /* In-memory buffer to prepare data to be written later to a file.  */
25529 class data_buf
25530 {
25531 public:
25532   /* Copy DATA to the end of the buffer.  */
25533   template<typename T>
25534   void append_data (const T &data)
25535   {
25536     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25537                reinterpret_cast<const gdb_byte *> (&data + 1),
25538                grow (sizeof (data)));
25539   }
25540
25541   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25542      terminating zero is appended too.  */
25543   void append_cstr0 (const char *cstr)
25544   {
25545     const size_t size = strlen (cstr) + 1;
25546     std::copy (cstr, cstr + size, grow (size));
25547   }
25548
25549   /* Store INPUT as ULEB128 to the end of buffer.  */
25550   void append_unsigned_leb128 (ULONGEST input)
25551   {
25552     for (;;)
25553       {
25554         gdb_byte output = input & 0x7f;
25555         input >>= 7;
25556         if (input)
25557           output |= 0x80;
25558         append_data (output);
25559         if (input == 0)
25560           break;
25561       }
25562   }
25563
25564   /* Accept a host-format integer in VAL and append it to the buffer
25565      as a target-format integer which is LEN bytes long.  */
25566   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25567   {
25568     ::store_unsigned_integer (grow (len), len, byte_order, val);
25569   }
25570
25571   /* Return the size of the buffer.  */
25572   size_t size () const
25573   {
25574     return m_vec.size ();
25575   }
25576
25577   /* Return true iff the buffer is empty.  */
25578   bool empty () const
25579   {
25580     return m_vec.empty ();
25581   }
25582
25583   /* Write the buffer to FILE.  */
25584   void file_write (FILE *file) const
25585   {
25586     ::file_write (file, m_vec);
25587   }
25588
25589 private:
25590   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25591      the start of the new block.  */
25592   gdb_byte *grow (size_t size)
25593   {
25594     m_vec.resize (m_vec.size () + size);
25595     return &*m_vec.end () - size;
25596   }
25597
25598   gdb::byte_vector m_vec;
25599 };
25600
25601 /* An entry in the symbol table.  */
25602 struct symtab_index_entry
25603 {
25604   /* The name of the symbol.  */
25605   const char *name;
25606   /* The offset of the name in the constant pool.  */
25607   offset_type index_offset;
25608   /* A sorted vector of the indices of all the CUs that hold an object
25609      of this name.  */
25610   std::vector<offset_type> cu_indices;
25611 };
25612
25613 /* The symbol table.  This is a power-of-2-sized hash table.  */
25614 struct mapped_symtab
25615 {
25616   mapped_symtab ()
25617   {
25618     data.resize (1024);
25619   }
25620
25621   offset_type n_elements = 0;
25622   std::vector<symtab_index_entry> data;
25623 };
25624
25625 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25626    the slot.
25627    
25628    Function is used only during write_hash_table so no index format backward
25629    compatibility is needed.  */
25630
25631 static symtab_index_entry &
25632 find_slot (struct mapped_symtab *symtab, const char *name)
25633 {
25634   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25635
25636   index = hash & (symtab->data.size () - 1);
25637   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25638
25639   for (;;)
25640     {
25641       if (symtab->data[index].name == NULL
25642           || strcmp (name, symtab->data[index].name) == 0)
25643         return symtab->data[index];
25644       index = (index + step) & (symtab->data.size () - 1);
25645     }
25646 }
25647
25648 /* Expand SYMTAB's hash table.  */
25649
25650 static void
25651 hash_expand (struct mapped_symtab *symtab)
25652 {
25653   auto old_entries = std::move (symtab->data);
25654
25655   symtab->data.clear ();
25656   symtab->data.resize (old_entries.size () * 2);
25657
25658   for (auto &it : old_entries)
25659     if (it.name != NULL)
25660       {
25661         auto &ref = find_slot (symtab, it.name);
25662         ref = std::move (it);
25663       }
25664 }
25665
25666 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25667    CU_INDEX is the index of the CU in which the symbol appears.
25668    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25669
25670 static void
25671 add_index_entry (struct mapped_symtab *symtab, const char *name,
25672                  int is_static, gdb_index_symbol_kind kind,
25673                  offset_type cu_index)
25674 {
25675   offset_type cu_index_and_attrs;
25676
25677   ++symtab->n_elements;
25678   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25679     hash_expand (symtab);
25680
25681   symtab_index_entry &slot = find_slot (symtab, name);
25682   if (slot.name == NULL)
25683     {
25684       slot.name = name;
25685       /* index_offset is set later.  */
25686     }
25687
25688   cu_index_and_attrs = 0;
25689   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25690   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25691   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25692
25693   /* We don't want to record an index value twice as we want to avoid the
25694      duplication.
25695      We process all global symbols and then all static symbols
25696      (which would allow us to avoid the duplication by only having to check
25697      the last entry pushed), but a symbol could have multiple kinds in one CU.
25698      To keep things simple we don't worry about the duplication here and
25699      sort and uniqufy the list after we've processed all symbols.  */
25700   slot.cu_indices.push_back (cu_index_and_attrs);
25701 }
25702
25703 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25704
25705 static void
25706 uniquify_cu_indices (struct mapped_symtab *symtab)
25707 {
25708   for (auto &entry : symtab->data)
25709     {
25710       if (entry.name != NULL && !entry.cu_indices.empty ())
25711         {
25712           auto &cu_indices = entry.cu_indices;
25713           std::sort (cu_indices.begin (), cu_indices.end ());
25714           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25715           cu_indices.erase (from, cu_indices.end ());
25716         }
25717     }
25718 }
25719
25720 /* A form of 'const char *' suitable for container keys.  Only the
25721    pointer is stored.  The strings themselves are compared, not the
25722    pointers.  */
25723 class c_str_view
25724 {
25725 public:
25726   c_str_view (const char *cstr)
25727     : m_cstr (cstr)
25728   {}
25729
25730   bool operator== (const c_str_view &other) const
25731   {
25732     return strcmp (m_cstr, other.m_cstr) == 0;
25733   }
25734
25735   /* Return the underlying C string.  Note, the returned string is
25736      only a reference with lifetime of this object.  */
25737   const char *c_str () const
25738   {
25739     return m_cstr;
25740   }
25741
25742 private:
25743   friend class c_str_view_hasher;
25744   const char *const m_cstr;
25745 };
25746
25747 /* A std::unordered_map::hasher for c_str_view that uses the right
25748    hash function for strings in a mapped index.  */
25749 class c_str_view_hasher
25750 {
25751 public:
25752   size_t operator () (const c_str_view &x) const
25753   {
25754     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25755   }
25756 };
25757
25758 /* A std::unordered_map::hasher for std::vector<>.  */
25759 template<typename T>
25760 class vector_hasher
25761 {
25762 public:
25763   size_t operator () (const std::vector<T> &key) const
25764   {
25765     return iterative_hash (key.data (),
25766                            sizeof (key.front ()) * key.size (), 0);
25767   }
25768 };
25769
25770 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25771    constant pool entries going into the data buffer CPOOL.  */
25772
25773 static void
25774 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25775 {
25776   {
25777     /* Elements are sorted vectors of the indices of all the CUs that
25778        hold an object of this name.  */
25779     std::unordered_map<std::vector<offset_type>, offset_type,
25780                        vector_hasher<offset_type>>
25781       symbol_hash_table;
25782
25783     /* We add all the index vectors to the constant pool first, to
25784        ensure alignment is ok.  */
25785     for (symtab_index_entry &entry : symtab->data)
25786       {
25787         if (entry.name == NULL)
25788           continue;
25789         gdb_assert (entry.index_offset == 0);
25790
25791         /* Finding before inserting is faster than always trying to
25792            insert, because inserting always allocates a node, does the
25793            lookup, and then destroys the new node if another node
25794            already had the same key.  C++17 try_emplace will avoid
25795            this.  */
25796         const auto found
25797           = symbol_hash_table.find (entry.cu_indices);
25798         if (found != symbol_hash_table.end ())
25799           {
25800             entry.index_offset = found->second;
25801             continue;
25802           }
25803
25804         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25805         entry.index_offset = cpool.size ();
25806         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25807         for (const auto index : entry.cu_indices)
25808           cpool.append_data (MAYBE_SWAP (index));
25809       }
25810   }
25811
25812   /* Now write out the hash table.  */
25813   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25814   for (const auto &entry : symtab->data)
25815     {
25816       offset_type str_off, vec_off;
25817
25818       if (entry.name != NULL)
25819         {
25820           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25821           if (insertpair.second)
25822             cpool.append_cstr0 (entry.name);
25823           str_off = insertpair.first->second;
25824           vec_off = entry.index_offset;
25825         }
25826       else
25827         {
25828           /* While 0 is a valid constant pool index, it is not valid
25829              to have 0 for both offsets.  */
25830           str_off = 0;
25831           vec_off = 0;
25832         }
25833
25834       output.append_data (MAYBE_SWAP (str_off));
25835       output.append_data (MAYBE_SWAP (vec_off));
25836     }
25837 }
25838
25839 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25840
25841 /* Helper struct for building the address table.  */
25842 struct addrmap_index_data
25843 {
25844   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25845     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25846   {}
25847
25848   struct objfile *objfile;
25849   data_buf &addr_vec;
25850   psym_index_map &cu_index_htab;
25851
25852   /* Non-zero if the previous_* fields are valid.
25853      We can't write an entry until we see the next entry (since it is only then
25854      that we know the end of the entry).  */
25855   int previous_valid;
25856   /* Index of the CU in the table of all CUs in the index file.  */
25857   unsigned int previous_cu_index;
25858   /* Start address of the CU.  */
25859   CORE_ADDR previous_cu_start;
25860 };
25861
25862 /* Write an address entry to ADDR_VEC.  */
25863
25864 static void
25865 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25866                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25867 {
25868   CORE_ADDR baseaddr;
25869
25870   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25871
25872   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25873   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25874   addr_vec.append_data (MAYBE_SWAP (cu_index));
25875 }
25876
25877 /* Worker function for traversing an addrmap to build the address table.  */
25878
25879 static int
25880 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25881 {
25882   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25883   struct partial_symtab *pst = (struct partial_symtab *) obj;
25884
25885   if (data->previous_valid)
25886     add_address_entry (data->objfile, data->addr_vec,
25887                        data->previous_cu_start, start_addr,
25888                        data->previous_cu_index);
25889
25890   data->previous_cu_start = start_addr;
25891   if (pst != NULL)
25892     {
25893       const auto it = data->cu_index_htab.find (pst);
25894       gdb_assert (it != data->cu_index_htab.cend ());
25895       data->previous_cu_index = it->second;
25896       data->previous_valid = 1;
25897     }
25898   else
25899     data->previous_valid = 0;
25900
25901   return 0;
25902 }
25903
25904 /* Write OBJFILE's address map to ADDR_VEC.
25905    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25906    in the index file.  */
25907
25908 static void
25909 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25910                    psym_index_map &cu_index_htab)
25911 {
25912   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25913
25914   /* When writing the address table, we have to cope with the fact that
25915      the addrmap iterator only provides the start of a region; we have to
25916      wait until the next invocation to get the start of the next region.  */
25917
25918   addrmap_index_data.objfile = objfile;
25919   addrmap_index_data.previous_valid = 0;
25920
25921   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25922                    &addrmap_index_data);
25923
25924   /* It's highly unlikely the last entry (end address = 0xff...ff)
25925      is valid, but we should still handle it.
25926      The end address is recorded as the start of the next region, but that
25927      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25928      anyway.  */
25929   if (addrmap_index_data.previous_valid)
25930     add_address_entry (objfile, addr_vec,
25931                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25932                        addrmap_index_data.previous_cu_index);
25933 }
25934
25935 /* Return the symbol kind of PSYM.  */
25936
25937 static gdb_index_symbol_kind
25938 symbol_kind (struct partial_symbol *psym)
25939 {
25940   domain_enum domain = PSYMBOL_DOMAIN (psym);
25941   enum address_class aclass = PSYMBOL_CLASS (psym);
25942
25943   switch (domain)
25944     {
25945     case VAR_DOMAIN:
25946       switch (aclass)
25947         {
25948         case LOC_BLOCK:
25949           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25950         case LOC_TYPEDEF:
25951           return GDB_INDEX_SYMBOL_KIND_TYPE;
25952         case LOC_COMPUTED:
25953         case LOC_CONST_BYTES:
25954         case LOC_OPTIMIZED_OUT:
25955         case LOC_STATIC:
25956           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25957         case LOC_CONST:
25958           /* Note: It's currently impossible to recognize psyms as enum values
25959              short of reading the type info.  For now punt.  */
25960           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25961         default:
25962           /* There are other LOC_FOO values that one might want to classify
25963              as variables, but dwarf2read.c doesn't currently use them.  */
25964           return GDB_INDEX_SYMBOL_KIND_OTHER;
25965         }
25966     case STRUCT_DOMAIN:
25967       return GDB_INDEX_SYMBOL_KIND_TYPE;
25968     default:
25969       return GDB_INDEX_SYMBOL_KIND_OTHER;
25970     }
25971 }
25972
25973 /* Add a list of partial symbols to SYMTAB.  */
25974
25975 static void
25976 write_psymbols (struct mapped_symtab *symtab,
25977                 std::unordered_set<partial_symbol *> &psyms_seen,
25978                 struct partial_symbol **psymp,
25979                 int count,
25980                 offset_type cu_index,
25981                 int is_static)
25982 {
25983   for (; count-- > 0; ++psymp)
25984     {
25985       struct partial_symbol *psym = *psymp;
25986
25987       if (SYMBOL_LANGUAGE (psym) == language_ada)
25988         error (_("Ada is not currently supported by the index"));
25989
25990       /* Only add a given psymbol once.  */
25991       if (psyms_seen.insert (psym).second)
25992         {
25993           gdb_index_symbol_kind kind = symbol_kind (psym);
25994
25995           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25996                            is_static, kind, cu_index);
25997         }
25998     }
25999 }
26000
26001 /* A helper struct used when iterating over debug_types.  */
26002 struct signatured_type_index_data
26003 {
26004   signatured_type_index_data (data_buf &types_list_,
26005                               std::unordered_set<partial_symbol *> &psyms_seen_)
26006     : types_list (types_list_), psyms_seen (psyms_seen_)
26007   {}
26008
26009   struct objfile *objfile;
26010   struct mapped_symtab *symtab;
26011   data_buf &types_list;
26012   std::unordered_set<partial_symbol *> &psyms_seen;
26013   int cu_index;
26014 };
26015
26016 /* A helper function that writes a single signatured_type to an
26017    obstack.  */
26018
26019 static int
26020 write_one_signatured_type (void **slot, void *d)
26021 {
26022   struct signatured_type_index_data *info
26023     = (struct signatured_type_index_data *) d;
26024   struct signatured_type *entry = (struct signatured_type *) *slot;
26025   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26026
26027   write_psymbols (info->symtab,
26028                   info->psyms_seen,
26029                   &info->objfile->global_psymbols[psymtab->globals_offset],
26030                   psymtab->n_global_syms, info->cu_index,
26031                   0);
26032   write_psymbols (info->symtab,
26033                   info->psyms_seen,
26034                   &info->objfile->static_psymbols[psymtab->statics_offset],
26035                   psymtab->n_static_syms, info->cu_index,
26036                   1);
26037
26038   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26039                                 to_underlying (entry->per_cu.sect_off));
26040   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26041                                 to_underlying (entry->type_offset_in_tu));
26042   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26043
26044   ++info->cu_index;
26045
26046   return 1;
26047 }
26048
26049 /* Recurse into all "included" dependencies and count their symbols as
26050    if they appeared in this psymtab.  */
26051
26052 static void
26053 recursively_count_psymbols (struct partial_symtab *psymtab,
26054                             size_t &psyms_seen)
26055 {
26056   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26057     if (psymtab->dependencies[i]->user != NULL)
26058       recursively_count_psymbols (psymtab->dependencies[i],
26059                                   psyms_seen);
26060
26061   psyms_seen += psymtab->n_global_syms;
26062   psyms_seen += psymtab->n_static_syms;
26063 }
26064
26065 /* Recurse into all "included" dependencies and write their symbols as
26066    if they appeared in this psymtab.  */
26067
26068 static void
26069 recursively_write_psymbols (struct objfile *objfile,
26070                             struct partial_symtab *psymtab,
26071                             struct mapped_symtab *symtab,
26072                             std::unordered_set<partial_symbol *> &psyms_seen,
26073                             offset_type cu_index)
26074 {
26075   int i;
26076
26077   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26078     if (psymtab->dependencies[i]->user != NULL)
26079       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26080                                   symtab, psyms_seen, cu_index);
26081
26082   write_psymbols (symtab,
26083                   psyms_seen,
26084                   &objfile->global_psymbols[psymtab->globals_offset],
26085                   psymtab->n_global_syms, cu_index,
26086                   0);
26087   write_psymbols (symtab,
26088                   psyms_seen,
26089                   &objfile->static_psymbols[psymtab->statics_offset],
26090                   psymtab->n_static_syms, cu_index,
26091                   1);
26092 }
26093
26094 /* DWARF-5 .debug_names builder.  */
26095 class debug_names
26096 {
26097 public:
26098   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26099                bfd_endian dwarf5_byte_order)
26100     : m_dwarf5_byte_order (dwarf5_byte_order),
26101       m_dwarf32 (dwarf5_byte_order),
26102       m_dwarf64 (dwarf5_byte_order),
26103       m_dwarf (is_dwarf64
26104                ? static_cast<dwarf &> (m_dwarf64)
26105                : static_cast<dwarf &> (m_dwarf32)),
26106       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26107       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26108       m_debugstrlookup (dwarf2_per_objfile)
26109   {}
26110
26111   int dwarf5_offset_size () const
26112   {
26113     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26114     return dwarf5_is_dwarf64 ? 8 : 4;
26115   }
26116
26117   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26118   enum class unit_kind { cu, tu };
26119
26120   /* Insert one symbol.  */
26121   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26122                unit_kind kind)
26123   {
26124     const int dwarf_tag = psymbol_tag (psym);
26125     if (dwarf_tag == 0)
26126       return;
26127     const char *const name = SYMBOL_SEARCH_NAME (psym);
26128     const auto insertpair
26129       = m_name_to_value_set.emplace (c_str_view (name),
26130                                      std::set<symbol_value> ());
26131     std::set<symbol_value> &value_set = insertpair.first->second;
26132     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26133   }
26134
26135   /* Build all the tables.  All symbols must be already inserted.
26136      This function does not call file_write, caller has to do it
26137      afterwards.  */
26138   void build ()
26139   {
26140     /* Verify the build method has not be called twice.  */
26141     gdb_assert (m_abbrev_table.empty ());
26142     const size_t name_count = m_name_to_value_set.size ();
26143     m_bucket_table.resize
26144       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26145     m_hash_table.reserve (name_count);
26146     m_name_table_string_offs.reserve (name_count);
26147     m_name_table_entry_offs.reserve (name_count);
26148
26149     /* Map each hash of symbol to its name and value.  */
26150     struct hash_it_pair
26151     {
26152       uint32_t hash;
26153       decltype (m_name_to_value_set)::const_iterator it;
26154     };
26155     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26156     bucket_hash.resize (m_bucket_table.size ());
26157     for (decltype (m_name_to_value_set)::const_iterator it
26158            = m_name_to_value_set.cbegin ();
26159          it != m_name_to_value_set.cend ();
26160          ++it)
26161       {
26162         const char *const name = it->first.c_str ();
26163         const uint32_t hash = dwarf5_djb_hash (name);
26164         hash_it_pair hashitpair;
26165         hashitpair.hash = hash;
26166         hashitpair.it = it;
26167         auto &slot = bucket_hash[hash % bucket_hash.size()];
26168         slot.push_front (std::move (hashitpair));
26169       }
26170     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26171       {
26172         const std::forward_list<hash_it_pair> &hashitlist
26173           = bucket_hash[bucket_ix];
26174         if (hashitlist.empty ())
26175           continue;
26176         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26177         /* The hashes array is indexed starting at 1.  */
26178         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26179                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26180                                 m_hash_table.size () + 1);
26181         for (const hash_it_pair &hashitpair : hashitlist)
26182           {
26183             m_hash_table.push_back (0);
26184             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26185                                                         (&m_hash_table.back ()),
26186                                     sizeof (m_hash_table.back ()),
26187                                     m_dwarf5_byte_order, hashitpair.hash);
26188             const c_str_view &name = hashitpair.it->first;
26189             const std::set<symbol_value> &value_set = hashitpair.it->second;
26190             m_name_table_string_offs.push_back_reorder
26191               (m_debugstrlookup.lookup (name.c_str ()));
26192             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26193             gdb_assert (!value_set.empty ());
26194             for (const symbol_value &value : value_set)
26195               {
26196                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26197                                                         value.is_static,
26198                                                         value.kind)];
26199                 if (idx == 0)
26200                   {
26201                     idx = m_idx_next++;
26202                     m_abbrev_table.append_unsigned_leb128 (idx);
26203                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26204                     m_abbrev_table.append_unsigned_leb128
26205                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26206                                                            : DW_IDX_type_unit);
26207                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26208                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26209                                                            ? DW_IDX_GNU_internal
26210                                                            : DW_IDX_GNU_external);
26211                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26212
26213                     /* Terminate attributes list.  */
26214                     m_abbrev_table.append_unsigned_leb128 (0);
26215                     m_abbrev_table.append_unsigned_leb128 (0);
26216                   }
26217
26218                 m_entry_pool.append_unsigned_leb128 (idx);
26219                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26220               }
26221
26222             /* Terminate the list of CUs.  */
26223             m_entry_pool.append_unsigned_leb128 (0);
26224           }
26225       }
26226     gdb_assert (m_hash_table.size () == name_count);
26227
26228     /* Terminate tags list.  */
26229     m_abbrev_table.append_unsigned_leb128 (0);
26230   }
26231
26232   /* Return .debug_names bucket count.  This must be called only after
26233      calling the build method.  */
26234   uint32_t bucket_count () const
26235   {
26236     /* Verify the build method has been already called.  */
26237     gdb_assert (!m_abbrev_table.empty ());
26238     const uint32_t retval = m_bucket_table.size ();
26239
26240     /* Check for overflow.  */
26241     gdb_assert (retval == m_bucket_table.size ());
26242     return retval;
26243   }
26244
26245   /* Return .debug_names names count.  This must be called only after
26246      calling the build method.  */
26247   uint32_t name_count () const
26248   {
26249     /* Verify the build method has been already called.  */
26250     gdb_assert (!m_abbrev_table.empty ());
26251     const uint32_t retval = m_hash_table.size ();
26252
26253     /* Check for overflow.  */
26254     gdb_assert (retval == m_hash_table.size ());
26255     return retval;
26256   }
26257
26258   /* Return number of bytes of .debug_names abbreviation table.  This
26259      must be called only after calling the build method.  */
26260   uint32_t abbrev_table_bytes () const
26261   {
26262     gdb_assert (!m_abbrev_table.empty ());
26263     return m_abbrev_table.size ();
26264   }
26265
26266   /* Recurse into all "included" dependencies and store their symbols
26267      as if they appeared in this psymtab.  */
26268   void recursively_write_psymbols
26269     (struct objfile *objfile,
26270      struct partial_symtab *psymtab,
26271      std::unordered_set<partial_symbol *> &psyms_seen,
26272      int cu_index)
26273   {
26274     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26275       if (psymtab->dependencies[i]->user != NULL)
26276         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26277                                     psyms_seen, cu_index);
26278
26279     write_psymbols (psyms_seen,
26280                     &objfile->global_psymbols[psymtab->globals_offset],
26281                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26282     write_psymbols (psyms_seen,
26283                     &objfile->static_psymbols[psymtab->statics_offset],
26284                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26285   }
26286
26287   /* Return number of bytes the .debug_names section will have.  This
26288      must be called only after calling the build method.  */
26289   size_t bytes () const
26290   {
26291     /* Verify the build method has been already called.  */
26292     gdb_assert (!m_abbrev_table.empty ());
26293     size_t expected_bytes = 0;
26294     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26295     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26296     expected_bytes += m_name_table_string_offs.bytes ();
26297     expected_bytes += m_name_table_entry_offs.bytes ();
26298     expected_bytes += m_abbrev_table.size ();
26299     expected_bytes += m_entry_pool.size ();
26300     return expected_bytes;
26301   }
26302
26303   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26304      FILE_STR.  This must be called only after calling the build
26305      method.  */
26306   void file_write (FILE *file_names, FILE *file_str) const
26307   {
26308     /* Verify the build method has been already called.  */
26309     gdb_assert (!m_abbrev_table.empty ());
26310     ::file_write (file_names, m_bucket_table);
26311     ::file_write (file_names, m_hash_table);
26312     m_name_table_string_offs.file_write (file_names);
26313     m_name_table_entry_offs.file_write (file_names);
26314     m_abbrev_table.file_write (file_names);
26315     m_entry_pool.file_write (file_names);
26316     m_debugstrlookup.file_write (file_str);
26317   }
26318
26319   /* A helper user data for write_one_signatured_type.  */
26320   class write_one_signatured_type_data
26321   {
26322   public:
26323     write_one_signatured_type_data (debug_names &nametable_,
26324                                     signatured_type_index_data &&info_)
26325     : nametable (nametable_), info (std::move (info_))
26326     {}
26327     debug_names &nametable;
26328     struct signatured_type_index_data info;
26329   };
26330
26331   /* A helper function to pass write_one_signatured_type to
26332      htab_traverse_noresize.  */
26333   static int
26334   write_one_signatured_type (void **slot, void *d)
26335   {
26336     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26337     struct signatured_type_index_data *info = &data->info;
26338     struct signatured_type *entry = (struct signatured_type *) *slot;
26339
26340     data->nametable.write_one_signatured_type (entry, info);
26341
26342     return 1;
26343   }
26344
26345 private:
26346
26347   /* Storage for symbol names mapping them to their .debug_str section
26348      offsets.  */
26349   class debug_str_lookup
26350   {
26351   public:
26352
26353     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26354        All .debug_str section strings are automatically stored.  */
26355     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26356       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26357         m_dwarf2_per_objfile (dwarf2_per_objfile)
26358     {
26359       dwarf2_read_section (dwarf2_per_objfile->objfile,
26360                            &dwarf2_per_objfile->str);
26361       if (dwarf2_per_objfile->str.buffer == NULL)
26362         return;
26363       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26364            data < (dwarf2_per_objfile->str.buffer
26365                    + dwarf2_per_objfile->str.size);)
26366         {
26367           const char *const s = reinterpret_cast<const char *> (data);
26368           const auto insertpair
26369             = m_str_table.emplace (c_str_view (s),
26370                                    data - dwarf2_per_objfile->str.buffer);
26371           if (!insertpair.second)
26372             complaint (&symfile_complaints,
26373                        _("Duplicate string \"%s\" in "
26374                          ".debug_str section [in module %s]"),
26375                        s, bfd_get_filename (m_abfd));
26376           data += strlen (s) + 1;
26377         }
26378     }
26379
26380     /* Return offset of symbol name S in the .debug_str section.  Add
26381        such symbol to the section's end if it does not exist there
26382        yet.  */
26383     size_t lookup (const char *s)
26384     {
26385       const auto it = m_str_table.find (c_str_view (s));
26386       if (it != m_str_table.end ())
26387         return it->second;
26388       const size_t offset = (m_dwarf2_per_objfile->str.size
26389                              + m_str_add_buf.size ());
26390       m_str_table.emplace (c_str_view (s), offset);
26391       m_str_add_buf.append_cstr0 (s);
26392       return offset;
26393     }
26394
26395     /* Append the end of the .debug_str section to FILE.  */
26396     void file_write (FILE *file) const
26397     {
26398       m_str_add_buf.file_write (file);
26399     }
26400
26401   private:
26402     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26403     bfd *const m_abfd;
26404     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26405
26406     /* Data to add at the end of .debug_str for new needed symbol names.  */
26407     data_buf m_str_add_buf;
26408   };
26409
26410   /* Container to map used DWARF tags to their .debug_names abbreviation
26411      tags.  */
26412   class index_key
26413   {
26414   public:
26415     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26416       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26417     {
26418     }
26419
26420     bool
26421     operator== (const index_key &other) const
26422     {
26423       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26424               && kind == other.kind);
26425     }
26426
26427     const int dwarf_tag;
26428     const bool is_static;
26429     const unit_kind kind;
26430   };
26431
26432   /* Provide std::unordered_map::hasher for index_key.  */
26433   class index_key_hasher
26434   {
26435   public:
26436     size_t
26437     operator () (const index_key &key) const
26438     {
26439       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26440     }
26441   };
26442
26443   /* Parameters of one symbol entry.  */
26444   class symbol_value
26445   {
26446   public:
26447     const int dwarf_tag, cu_index;
26448     const bool is_static;
26449     const unit_kind kind;
26450
26451     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26452                   unit_kind kind_)
26453       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26454         kind (kind_)
26455     {}
26456
26457     bool
26458     operator< (const symbol_value &other) const
26459     {
26460 #define X(n) \
26461   do \
26462     { \
26463       if (n < other.n) \
26464         return true; \
26465       if (n > other.n) \
26466         return false; \
26467     } \
26468   while (0)
26469       X (dwarf_tag);
26470       X (is_static);
26471       X (kind);
26472       X (cu_index);
26473 #undef X
26474       return false;
26475     }
26476   };
26477
26478   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26479      output.  */
26480   class offset_vec
26481   {
26482   protected:
26483     const bfd_endian dwarf5_byte_order;
26484   public:
26485     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26486       : dwarf5_byte_order (dwarf5_byte_order_)
26487     {}
26488
26489     /* Call std::vector::reserve for NELEM elements.  */
26490     virtual void reserve (size_t nelem) = 0;
26491
26492     /* Call std::vector::push_back with store_unsigned_integer byte
26493        reordering for ELEM.  */
26494     virtual void push_back_reorder (size_t elem) = 0;
26495
26496     /* Return expected output size in bytes.  */
26497     virtual size_t bytes () const = 0;
26498
26499     /* Write name table to FILE.  */
26500     virtual void file_write (FILE *file) const = 0;
26501   };
26502
26503   /* Template to unify DWARF-32 and DWARF-64 output.  */
26504   template<typename OffsetSize>
26505   class offset_vec_tmpl : public offset_vec
26506   {
26507   public:
26508     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26509       : offset_vec (dwarf5_byte_order_)
26510     {}
26511
26512     /* Implement offset_vec::reserve.  */
26513     void reserve (size_t nelem) override
26514     {
26515       m_vec.reserve (nelem);
26516     }
26517
26518     /* Implement offset_vec::push_back_reorder.  */
26519     void push_back_reorder (size_t elem) override
26520     {
26521       m_vec.push_back (elem);
26522       /* Check for overflow.  */
26523       gdb_assert (m_vec.back () == elem);
26524       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26525                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26526     }
26527
26528     /* Implement offset_vec::bytes.  */
26529     size_t bytes () const override
26530     {
26531       return m_vec.size () * sizeof (m_vec[0]);
26532     }
26533
26534     /* Implement offset_vec::file_write.  */
26535     void file_write (FILE *file) const override
26536     {
26537       ::file_write (file, m_vec);
26538     }
26539
26540   private:
26541     std::vector<OffsetSize> m_vec;
26542   };
26543
26544   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26545      respecting name table width.  */
26546   class dwarf
26547   {
26548   public:
26549     offset_vec &name_table_string_offs, &name_table_entry_offs;
26550
26551     dwarf (offset_vec &name_table_string_offs_,
26552            offset_vec &name_table_entry_offs_)
26553       : name_table_string_offs (name_table_string_offs_),
26554         name_table_entry_offs (name_table_entry_offs_)
26555     {
26556     }
26557   };
26558
26559   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26560      respecting name table width.  */
26561   template<typename OffsetSize>
26562   class dwarf_tmpl : public dwarf
26563   {
26564   public:
26565     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26566       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26567         m_name_table_string_offs (dwarf5_byte_order_),
26568         m_name_table_entry_offs (dwarf5_byte_order_)
26569     {}
26570
26571   private:
26572     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26573     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26574   };
26575
26576   /* Try to reconstruct original DWARF tag for given partial_symbol.
26577      This function is not DWARF-5 compliant but it is sufficient for
26578      GDB as a DWARF-5 index consumer.  */
26579   static int psymbol_tag (const struct partial_symbol *psym)
26580   {
26581     domain_enum domain = PSYMBOL_DOMAIN (psym);
26582     enum address_class aclass = PSYMBOL_CLASS (psym);
26583
26584     switch (domain)
26585       {
26586       case VAR_DOMAIN:
26587         switch (aclass)
26588           {
26589           case LOC_BLOCK:
26590             return DW_TAG_subprogram;
26591           case LOC_TYPEDEF:
26592             return DW_TAG_typedef;
26593           case LOC_COMPUTED:
26594           case LOC_CONST_BYTES:
26595           case LOC_OPTIMIZED_OUT:
26596           case LOC_STATIC:
26597             return DW_TAG_variable;
26598           case LOC_CONST:
26599             /* Note: It's currently impossible to recognize psyms as enum values
26600                short of reading the type info.  For now punt.  */
26601             return DW_TAG_variable;
26602           default:
26603             /* There are other LOC_FOO values that one might want to classify
26604                as variables, but dwarf2read.c doesn't currently use them.  */
26605             return DW_TAG_variable;
26606           }
26607       case STRUCT_DOMAIN:
26608         return DW_TAG_structure_type;
26609       default:
26610         return 0;
26611       }
26612   }
26613
26614   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26615   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26616                        struct partial_symbol **psymp, int count, int cu_index,
26617                        bool is_static, unit_kind kind)
26618   {
26619     for (; count-- > 0; ++psymp)
26620       {
26621         struct partial_symbol *psym = *psymp;
26622
26623         if (SYMBOL_LANGUAGE (psym) == language_ada)
26624           error (_("Ada is not currently supported by the index"));
26625
26626         /* Only add a given psymbol once.  */
26627         if (psyms_seen.insert (psym).second)
26628           insert (psym, cu_index, is_static, kind);
26629       }
26630   }
26631
26632   /* A helper function that writes a single signatured_type
26633      to a debug_names.  */
26634   void
26635   write_one_signatured_type (struct signatured_type *entry,
26636                              struct signatured_type_index_data *info)
26637   {
26638     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26639
26640     write_psymbols (info->psyms_seen,
26641                     &info->objfile->global_psymbols[psymtab->globals_offset],
26642                     psymtab->n_global_syms, info->cu_index, false,
26643                     unit_kind::tu);
26644     write_psymbols (info->psyms_seen,
26645                     &info->objfile->static_psymbols[psymtab->statics_offset],
26646                     psymtab->n_static_syms, info->cu_index, true,
26647                     unit_kind::tu);
26648
26649     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26650                                   to_underlying (entry->per_cu.sect_off));
26651
26652     ++info->cu_index;
26653   }
26654
26655   /* Store value of each symbol.  */
26656   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26657     m_name_to_value_set;
26658
26659   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26660      order.  */
26661   std::vector<uint32_t> m_bucket_table;
26662   std::vector<uint32_t> m_hash_table;
26663
26664   const bfd_endian m_dwarf5_byte_order;
26665   dwarf_tmpl<uint32_t> m_dwarf32;
26666   dwarf_tmpl<uint64_t> m_dwarf64;
26667   dwarf &m_dwarf;
26668   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26669   debug_str_lookup m_debugstrlookup;
26670
26671   /* Map each used .debug_names abbreviation tag parameter to its
26672      index value.  */
26673   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26674
26675   /* Next unused .debug_names abbreviation tag for
26676      m_indexkey_to_idx.  */
26677   int m_idx_next = 1;
26678
26679   /* .debug_names abbreviation table.  */
26680   data_buf m_abbrev_table;
26681
26682   /* .debug_names entry pool.  */
26683   data_buf m_entry_pool;
26684 };
26685
26686 /* Return iff any of the needed offsets does not fit into 32-bit
26687    .debug_names section.  */
26688
26689 static bool
26690 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26691 {
26692   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26693     {
26694       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26695
26696       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26697         return true;
26698     }
26699   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26700     {
26701       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26702       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26703
26704       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26705         return true;
26706     }
26707   return false;
26708 }
26709
26710 /* The psyms_seen set is potentially going to be largish (~40k
26711    elements when indexing a -g3 build of GDB itself).  Estimate the
26712    number of elements in order to avoid too many rehashes, which
26713    require rebuilding buckets and thus many trips to
26714    malloc/free.  */
26715
26716 static size_t
26717 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26718 {
26719   size_t psyms_count = 0;
26720   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26721     {
26722       struct dwarf2_per_cu_data *per_cu
26723         = dwarf2_per_objfile->all_comp_units[i];
26724       struct partial_symtab *psymtab = per_cu->v.psymtab;
26725
26726       if (psymtab != NULL && psymtab->user == NULL)
26727         recursively_count_psymbols (psymtab, psyms_count);
26728     }
26729   /* Generating an index for gdb itself shows a ratio of
26730      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26731   return psyms_count / 4;
26732 }
26733
26734 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26735    Return how many bytes were expected to be written into OUT_FILE.  */
26736
26737 static size_t
26738 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26739 {
26740   struct objfile *objfile = dwarf2_per_objfile->objfile;
26741   mapped_symtab symtab;
26742   data_buf cu_list;
26743
26744   /* While we're scanning CU's create a table that maps a psymtab pointer
26745      (which is what addrmap records) to its index (which is what is recorded
26746      in the index file).  This will later be needed to write the address
26747      table.  */
26748   psym_index_map cu_index_htab;
26749   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26750
26751   /* The CU list is already sorted, so we don't need to do additional
26752      work here.  Also, the debug_types entries do not appear in
26753      all_comp_units, but only in their own hash table.  */
26754
26755   std::unordered_set<partial_symbol *> psyms_seen
26756     (psyms_seen_size (dwarf2_per_objfile));
26757   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26758     {
26759       struct dwarf2_per_cu_data *per_cu
26760         = dwarf2_per_objfile->all_comp_units[i];
26761       struct partial_symtab *psymtab = per_cu->v.psymtab;
26762
26763       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26764          It may be referenced from a local scope but in such case it does not
26765          need to be present in .gdb_index.  */
26766       if (psymtab == NULL)
26767         continue;
26768
26769       if (psymtab->user == NULL)
26770         recursively_write_psymbols (objfile, psymtab, &symtab,
26771                                     psyms_seen, i);
26772
26773       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26774       gdb_assert (insertpair.second);
26775
26776       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26777                            to_underlying (per_cu->sect_off));
26778       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26779     }
26780
26781   /* Dump the address map.  */
26782   data_buf addr_vec;
26783   write_address_map (objfile, addr_vec, cu_index_htab);
26784
26785   /* Write out the .debug_type entries, if any.  */
26786   data_buf types_cu_list;
26787   if (dwarf2_per_objfile->signatured_types)
26788     {
26789       signatured_type_index_data sig_data (types_cu_list,
26790                                            psyms_seen);
26791
26792       sig_data.objfile = objfile;
26793       sig_data.symtab = &symtab;
26794       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26795       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26796                               write_one_signatured_type, &sig_data);
26797     }
26798
26799   /* Now that we've processed all symbols we can shrink their cu_indices
26800      lists.  */
26801   uniquify_cu_indices (&symtab);
26802
26803   data_buf symtab_vec, constant_pool;
26804   write_hash_table (&symtab, symtab_vec, constant_pool);
26805
26806   data_buf contents;
26807   const offset_type size_of_contents = 6 * sizeof (offset_type);
26808   offset_type total_len = size_of_contents;
26809
26810   /* The version number.  */
26811   contents.append_data (MAYBE_SWAP (8));
26812
26813   /* The offset of the CU list from the start of the file.  */
26814   contents.append_data (MAYBE_SWAP (total_len));
26815   total_len += cu_list.size ();
26816
26817   /* The offset of the types CU list from the start of the file.  */
26818   contents.append_data (MAYBE_SWAP (total_len));
26819   total_len += types_cu_list.size ();
26820
26821   /* The offset of the address table from the start of the file.  */
26822   contents.append_data (MAYBE_SWAP (total_len));
26823   total_len += addr_vec.size ();
26824
26825   /* The offset of the symbol table from the start of the file.  */
26826   contents.append_data (MAYBE_SWAP (total_len));
26827   total_len += symtab_vec.size ();
26828
26829   /* The offset of the constant pool from the start of the file.  */
26830   contents.append_data (MAYBE_SWAP (total_len));
26831   total_len += constant_pool.size ();
26832
26833   gdb_assert (contents.size () == size_of_contents);
26834
26835   contents.file_write (out_file);
26836   cu_list.file_write (out_file);
26837   types_cu_list.file_write (out_file);
26838   addr_vec.file_write (out_file);
26839   symtab_vec.file_write (out_file);
26840   constant_pool.file_write (out_file);
26841
26842   return total_len;
26843 }
26844
26845 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26846 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26847
26848 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26849    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26850    many bytes were expected to be written into OUT_FILE.  */
26851
26852 static size_t
26853 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26854                    FILE *out_file, FILE *out_file_str)
26855 {
26856   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26857   struct objfile *objfile = dwarf2_per_objfile->objfile;
26858   const enum bfd_endian dwarf5_byte_order
26859     = gdbarch_byte_order (get_objfile_arch (objfile));
26860
26861   /* The CU list is already sorted, so we don't need to do additional
26862      work here.  Also, the debug_types entries do not appear in
26863      all_comp_units, but only in their own hash table.  */
26864   data_buf cu_list;
26865   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26866                          dwarf5_byte_order);
26867   std::unordered_set<partial_symbol *>
26868     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26869   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26870     {
26871       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26872       partial_symtab *psymtab = per_cu->v.psymtab;
26873
26874       /* CU of a shared file from 'dwz -m' may be unused by this main
26875          file.  It may be referenced from a local scope but in such
26876          case it does not need to be present in .debug_names.  */
26877       if (psymtab == NULL)
26878         continue;
26879
26880       if (psymtab->user == NULL)
26881         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26882
26883       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26884                            to_underlying (per_cu->sect_off));
26885     }
26886
26887   /* Write out the .debug_type entries, if any.  */
26888   data_buf types_cu_list;
26889   if (dwarf2_per_objfile->signatured_types)
26890     {
26891       debug_names::write_one_signatured_type_data sig_data (nametable,
26892                         signatured_type_index_data (types_cu_list, psyms_seen));
26893
26894       sig_data.info.objfile = objfile;
26895       /* It is used only for gdb_index.  */
26896       sig_data.info.symtab = nullptr;
26897       sig_data.info.cu_index = 0;
26898       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26899                               debug_names::write_one_signatured_type,
26900                               &sig_data);
26901     }
26902
26903   nametable.build ();
26904
26905   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26906
26907   const offset_type bytes_of_header
26908     = ((dwarf5_is_dwarf64 ? 12 : 4)
26909        + 2 + 2 + 7 * 4
26910        + sizeof (dwarf5_gdb_augmentation));
26911   size_t expected_bytes = 0;
26912   expected_bytes += bytes_of_header;
26913   expected_bytes += cu_list.size ();
26914   expected_bytes += types_cu_list.size ();
26915   expected_bytes += nametable.bytes ();
26916   data_buf header;
26917
26918   if (!dwarf5_is_dwarf64)
26919     {
26920       const uint64_t size64 = expected_bytes - 4;
26921       gdb_assert (size64 < 0xfffffff0);
26922       header.append_uint (4, dwarf5_byte_order, size64);
26923     }
26924   else
26925     {
26926       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26927       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26928     }
26929
26930   /* The version number.  */
26931   header.append_uint (2, dwarf5_byte_order, 5);
26932
26933   /* Padding.  */
26934   header.append_uint (2, dwarf5_byte_order, 0);
26935
26936   /* comp_unit_count - The number of CUs in the CU list.  */
26937   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26938
26939   /* local_type_unit_count - The number of TUs in the local TU
26940      list.  */
26941   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26942
26943   /* foreign_type_unit_count - The number of TUs in the foreign TU
26944      list.  */
26945   header.append_uint (4, dwarf5_byte_order, 0);
26946
26947   /* bucket_count - The number of hash buckets in the hash lookup
26948      table.  */
26949   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26950
26951   /* name_count - The number of unique names in the index.  */
26952   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26953
26954   /* abbrev_table_size - The size in bytes of the abbreviations
26955      table.  */
26956   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26957
26958   /* augmentation_string_size - The size in bytes of the augmentation
26959      string.  This value is rounded up to a multiple of 4.  */
26960   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26961   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26962   header.append_data (dwarf5_gdb_augmentation);
26963
26964   gdb_assert (header.size () == bytes_of_header);
26965
26966   header.file_write (out_file);
26967   cu_list.file_write (out_file);
26968   types_cu_list.file_write (out_file);
26969   nametable.file_write (out_file, out_file_str);
26970
26971   return expected_bytes;
26972 }
26973
26974 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26975    position is at the end of the file.  */
26976
26977 static void
26978 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26979 {
26980   const auto file_size = ftell (file);
26981   if (file_size == -1)
26982     error (_("Can't get `%s' size"), filename);
26983   gdb_assert (file_size == expected_size);
26984 }
26985
26986 /* Create an index file for OBJFILE in the directory DIR.  */
26987
26988 static void
26989 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
26990                          const char *dir,
26991                          dw_index_kind index_kind)
26992 {
26993   struct objfile *objfile = dwarf2_per_objfile->objfile;
26994
26995   if (dwarf2_per_objfile->using_index)
26996     error (_("Cannot use an index to create the index"));
26997
26998   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26999     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27000
27001   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27002     return;
27003
27004   struct stat st;
27005   if (stat (objfile_name (objfile), &st) < 0)
27006     perror_with_name (objfile_name (objfile));
27007
27008   std::string filename (std::string (dir) + SLASH_STRING
27009                         + lbasename (objfile_name (objfile))
27010                         + (index_kind == dw_index_kind::DEBUG_NAMES
27011                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27012
27013   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27014   if (!out_file)
27015     error (_("Can't open `%s' for writing"), filename.c_str ());
27016
27017   /* Order matters here; we want FILE to be closed before FILENAME is
27018      unlinked, because on MS-Windows one cannot delete a file that is
27019      still open.  (Don't call anything here that might throw until
27020      file_closer is created.)  */
27021   gdb::unlinker unlink_file (filename.c_str ());
27022   gdb_file_up close_out_file (out_file);
27023
27024   if (index_kind == dw_index_kind::DEBUG_NAMES)
27025     {
27026       std::string filename_str (std::string (dir) + SLASH_STRING
27027                                 + lbasename (objfile_name (objfile))
27028                                 + DEBUG_STR_SUFFIX);
27029       FILE *out_file_str
27030         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27031       if (!out_file_str)
27032         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27033       gdb::unlinker unlink_file_str (filename_str.c_str ());
27034       gdb_file_up close_out_file_str (out_file_str);
27035
27036       const size_t total_len
27037         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27038       assert_file_size (out_file, filename.c_str (), total_len);
27039
27040       /* We want to keep the file .debug_str file too.  */
27041       unlink_file_str.keep ();
27042     }
27043   else
27044     {
27045       const size_t total_len
27046         = write_gdbindex (dwarf2_per_objfile, out_file);
27047       assert_file_size (out_file, filename.c_str (), total_len);
27048     }
27049
27050   /* We want to keep the file.  */
27051   unlink_file.keep ();
27052 }
27053
27054 /* Implementation of the `save gdb-index' command.
27055    
27056    Note that the .gdb_index file format used by this command is
27057    documented in the GDB manual.  Any changes here must be documented
27058    there.  */
27059
27060 static void
27061 save_gdb_index_command (const char *arg, int from_tty)
27062 {
27063   struct objfile *objfile;
27064   const char dwarf5space[] = "-dwarf-5 ";
27065   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27066
27067   if (!arg)
27068     arg = "";
27069
27070   arg = skip_spaces (arg);
27071   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27072     {
27073       index_kind = dw_index_kind::DEBUG_NAMES;
27074       arg += strlen (dwarf5space);
27075       arg = skip_spaces (arg);
27076     }
27077
27078   if (!*arg)
27079     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27080
27081   ALL_OBJFILES (objfile)
27082   {
27083     struct stat st;
27084
27085     /* If the objfile does not correspond to an actual file, skip it.  */
27086     if (stat (objfile_name (objfile), &st) < 0)
27087       continue;
27088
27089     struct dwarf2_per_objfile *dwarf2_per_objfile
27090       = get_dwarf2_per_objfile (objfile);
27091
27092     if (dwarf2_per_objfile != NULL)
27093       {
27094         TRY
27095           {
27096             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27097           }
27098         CATCH (except, RETURN_MASK_ERROR)
27099           {
27100             exception_fprintf (gdb_stderr, except,
27101                                _("Error while writing index for `%s': "),
27102                                objfile_name (objfile));
27103           }
27104         END_CATCH
27105       }
27106
27107   }
27108 }
27109
27110 \f
27111
27112 int dwarf_always_disassemble;
27113
27114 static void
27115 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27116                                struct cmd_list_element *c, const char *value)
27117 {
27118   fprintf_filtered (file,
27119                     _("Whether to always disassemble "
27120                       "DWARF expressions is %s.\n"),
27121                     value);
27122 }
27123
27124 static void
27125 show_check_physname (struct ui_file *file, int from_tty,
27126                      struct cmd_list_element *c, const char *value)
27127 {
27128   fprintf_filtered (file,
27129                     _("Whether to check \"physname\" is %s.\n"),
27130                     value);
27131 }
27132
27133 void
27134 _initialize_dwarf2_read (void)
27135 {
27136   struct cmd_list_element *c;
27137
27138   dwarf2_objfile_data_key = register_objfile_data ();
27139
27140   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27141 Set DWARF specific variables.\n\
27142 Configure DWARF variables such as the cache size"),
27143                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27144                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27145
27146   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27147 Show DWARF specific variables\n\
27148 Show DWARF variables such as the cache size"),
27149                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27150                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27151
27152   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27153                             &dwarf_max_cache_age, _("\
27154 Set the upper bound on the age of cached DWARF compilation units."), _("\
27155 Show the upper bound on the age of cached DWARF compilation units."), _("\
27156 A higher limit means that cached compilation units will be stored\n\
27157 in memory longer, and more total memory will be used.  Zero disables\n\
27158 caching, which can slow down startup."),
27159                             NULL,
27160                             show_dwarf_max_cache_age,
27161                             &set_dwarf_cmdlist,
27162                             &show_dwarf_cmdlist);
27163
27164   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27165                            &dwarf_always_disassemble, _("\
27166 Set whether `info address' always disassembles DWARF expressions."), _("\
27167 Show whether `info address' always disassembles DWARF expressions."), _("\
27168 When enabled, DWARF expressions are always printed in an assembly-like\n\
27169 syntax.  When disabled, expressions will be printed in a more\n\
27170 conversational style, when possible."),
27171                            NULL,
27172                            show_dwarf_always_disassemble,
27173                            &set_dwarf_cmdlist,
27174                            &show_dwarf_cmdlist);
27175
27176   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27177 Set debugging of the DWARF reader."), _("\
27178 Show debugging of the DWARF reader."), _("\
27179 When enabled (non-zero), debugging messages are printed during DWARF\n\
27180 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27181 information.  A value greater than 1 provides more verbose information."),
27182                             NULL,
27183                             NULL,
27184                             &setdebuglist, &showdebuglist);
27185
27186   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27187 Set debugging of the DWARF DIE reader."), _("\
27188 Show debugging of the DWARF DIE reader."), _("\
27189 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27190 The value is the maximum depth to print."),
27191                              NULL,
27192                              NULL,
27193                              &setdebuglist, &showdebuglist);
27194
27195   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27196 Set debugging of the dwarf line reader."), _("\
27197 Show debugging of the dwarf line reader."), _("\
27198 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27199 A value of 1 (one) provides basic information.\n\
27200 A value greater than 1 provides more verbose information."),
27201                              NULL,
27202                              NULL,
27203                              &setdebuglist, &showdebuglist);
27204
27205   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27206 Set cross-checking of \"physname\" code against demangler."), _("\
27207 Show cross-checking of \"physname\" code against demangler."), _("\
27208 When enabled, GDB's internal \"physname\" code is checked against\n\
27209 the demangler."),
27210                            NULL, show_check_physname,
27211                            &setdebuglist, &showdebuglist);
27212
27213   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27214                            no_class, &use_deprecated_index_sections, _("\
27215 Set whether to use deprecated gdb_index sections."), _("\
27216 Show whether to use deprecated gdb_index sections."), _("\
27217 When enabled, deprecated .gdb_index sections are used anyway.\n\
27218 Normally they are ignored either because of a missing feature or\n\
27219 performance issue.\n\
27220 Warning: This option must be enabled before gdb reads the file."),
27221                            NULL,
27222                            NULL,
27223                            &setlist, &showlist);
27224
27225   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27226                _("\
27227 Save a gdb-index file.\n\
27228 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27229 \n\
27230 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27231 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27232 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27233                &save_cmdlist);
27234   set_cmd_completer (c, filename_completer);
27235
27236   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27237                                                         &dwarf2_locexpr_funcs);
27238   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27239                                                         &dwarf2_loclist_funcs);
27240
27241   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27242                                         &dwarf2_block_frame_base_locexpr_funcs);
27243   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27244                                         &dwarf2_block_frame_base_loclist_funcs);
27245
27246 #if GDB_SELF_TEST
27247   selftests::register_test ("dw2_expand_symtabs_matching",
27248                             selftests::dw2_expand_symtabs_matching::run_test);
27249 #endif
27250 }