Replace objfile field in dwarf2_cu and dwarf2_per_cu_data with dwarf2_per_objfile
[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 typedef struct symbol *symbolp;
91 DEF_VEC_P (symbolp);
92
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97
98 /* When non-zero, dump DIEs after they are read in.  */
99 static unsigned int dwarf_die_debug = 0;
100
101 /* When non-zero, dump line number entries as they are read in.  */
102 static unsigned int dwarf_line_debug = 0;
103
104 /* When non-zero, cross-check physname against demangler.  */
105 static int check_physname = 0;
106
107 /* When non-zero, do not reject deprecated .gdb_index sections.  */
108 static int use_deprecated_index_sections = 0;
109
110 static const struct objfile_data *dwarf2_objfile_data_key;
111
112 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
113
114 static int dwarf2_locexpr_index;
115 static int dwarf2_loclist_index;
116 static int dwarf2_locexpr_block_index;
117 static int dwarf2_loclist_block_index;
118
119 /* A descriptor for dwarf sections.
120
121    S.ASECTION, SIZE are typically initialized when the objfile is first
122    scanned.  BUFFER, READIN are filled in later when the section is read.
123    If the section contained compressed data then SIZE is updated to record
124    the uncompressed size of the section.
125
126    DWP file format V2 introduces a wrinkle that is easiest to handle by
127    creating the concept of virtual sections contained within a real section.
128    In DWP V2 the sections of the input DWO files are concatenated together
129    into one section, but section offsets are kept relative to the original
130    input section.
131    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
132    the real section this "virtual" section is contained in, and BUFFER,SIZE
133    describe the virtual section.  */
134
135 struct dwarf2_section_info
136 {
137   union
138   {
139     /* If this is a real section, the bfd section.  */
140     asection *section;
141     /* If this is a virtual section, pointer to the containing ("real")
142        section.  */
143     struct dwarf2_section_info *containing_section;
144   } s;
145   /* Pointer to section data, only valid if readin.  */
146   const gdb_byte *buffer;
147   /* The size of the section, real or virtual.  */
148   bfd_size_type size;
149   /* If this is a virtual section, the offset in the real section.
150      Only valid if is_virtual.  */
151   bfd_size_type virtual_offset;
152   /* True if we have tried to read this section.  */
153   char readin;
154   /* True if this is a virtual section, False otherwise.
155      This specifies which of s.section and s.containing_section to use.  */
156   char is_virtual;
157 };
158
159 typedef struct dwarf2_section_info dwarf2_section_info_def;
160 DEF_VEC_O (dwarf2_section_info_def);
161
162 /* All offsets in the index are of this type.  It must be
163    architecture-independent.  */
164 typedef uint32_t offset_type;
165
166 DEF_VEC_I (offset_type);
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((unsigned int) (value) <= 1); \
172     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
173   } while (0)
174
175 /* Ensure only legit values are used.  */
176 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
177   do { \
178     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
179                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
180     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
184 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
185   do { \
186     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
187     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
188   } while (0)
189
190 #if WORDS_BIGENDIAN
191
192 /* Convert VALUE between big- and little-endian.  */
193
194 static offset_type
195 byte_swap (offset_type value)
196 {
197   offset_type result;
198
199   result = (value & 0xff) << 24;
200   result |= (value & 0xff00) << 8;
201   result |= (value & 0xff0000) >> 8;
202   result |= (value & 0xff000000) >> 24;
203   return result;
204 }
205
206 #define MAYBE_SWAP(V)  byte_swap (V)
207
208 #else
209 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
210 #endif /* WORDS_BIGENDIAN */
211
212 /* An index into a (C++) symbol name component in a symbol name as
213    recorded in the mapped_index's symbol table.  For each C++ symbol
214    in the symbol table, we record one entry for the start of each
215    component in the symbol in a table of name components, and then
216    sort the table, in order to be able to binary search symbol names,
217    ignoring leading namespaces, both completion and regular look up.
218    For example, for symbol "A::B::C", we'll have an entry that points
219    to "A::B::C", another that points to "B::C", and another for "C".
220    Note that function symbols in GDB index have no parameter
221    information, just the function/method names.  You can convert a
222    name_component to a "const char *" using the
223    'mapped_index::symbol_name_at(offset_type)' method.  */
224
225 struct name_component
226 {
227   /* Offset in the symbol name where the component starts.  Stored as
228      a (32-bit) offset instead of a pointer to save memory and improve
229      locality on 64-bit architectures.  */
230   offset_type name_offset;
231
232   /* The symbol's index in the symbol and constant pool tables of a
233      mapped_index.  */
234   offset_type idx;
235 };
236
237 /* Base class containing bits shared by both .gdb_index and
238    .debug_name indexes.  */
239
240 struct mapped_index_base
241 {
242   /* The name_component table (a sorted vector).  See name_component's
243      description above.  */
244   std::vector<name_component> name_components;
245
246   /* How NAME_COMPONENTS is sorted.  */
247   enum case_sensitivity name_components_casing;
248
249   /* Return the number of names in the symbol table.  */
250   virtual size_t symbol_name_count () const = 0;
251
252   /* Get the name of the symbol at IDX in the symbol table.  */
253   virtual const char *symbol_name_at (offset_type idx) const = 0;
254
255   /* Return whether the name at IDX in the symbol table should be
256      ignored.  */
257   virtual bool symbol_name_slot_invalid (offset_type idx) const
258   {
259     return false;
260   }
261
262   /* Build the symbol name component sorted vector, if we haven't
263      yet.  */
264   void build_name_components ();
265
266   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
267      possible matches for LN_NO_PARAMS in the name component
268      vector.  */
269   std::pair<std::vector<name_component>::const_iterator,
270             std::vector<name_component>::const_iterator>
271     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
272
273   /* Prevent deleting/destroying via a base class pointer.  */
274 protected:
275   ~mapped_index_base() = default;
276 };
277
278 /* A description of the mapped index.  The file format is described in
279    a comment by the code that writes the index.  */
280 struct mapped_index final : public mapped_index_base
281 {
282   /* A slot/bucket in the symbol table hash.  */
283   struct symbol_table_slot
284   {
285     const offset_type name;
286     const offset_type vec;
287   };
288
289   /* Index data format version.  */
290   int version;
291
292   /* The total length of the buffer.  */
293   off_t total_size;
294
295   /* The address table data.  */
296   gdb::array_view<const gdb_byte> address_table;
297
298   /* The symbol table, implemented as a hash table.  */
299   gdb::array_view<symbol_table_slot> symbol_table;
300
301   /* A pointer to the constant pool.  */
302   const char *constant_pool;
303
304   bool symbol_name_slot_invalid (offset_type idx) const override
305   {
306     const auto &bucket = this->symbol_table[idx];
307     return bucket.name == 0 && bucket.vec;
308   }
309
310   /* Convenience method to get at the name of the symbol at IDX in the
311      symbol table.  */
312   const char *symbol_name_at (offset_type idx) const override
313   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
314
315   size_t symbol_name_count () const override
316   { return this->symbol_table.size (); }
317 };
318
319 /* A description of the mapped .debug_names.
320    Uninitialized map has CU_COUNT 0.  */
321 struct mapped_debug_names final : public mapped_index_base
322 {
323   bfd_endian dwarf5_byte_order;
324   bool dwarf5_is_dwarf64;
325   bool augmentation_is_gdb;
326   uint8_t offset_size;
327   uint32_t cu_count = 0;
328   uint32_t tu_count, bucket_count, name_count;
329   const gdb_byte *cu_table_reordered, *tu_table_reordered;
330   const uint32_t *bucket_table_reordered, *hash_table_reordered;
331   const gdb_byte *name_table_string_offs_reordered;
332   const gdb_byte *name_table_entry_offs_reordered;
333   const gdb_byte *entry_pool;
334
335   struct index_val
336   {
337     ULONGEST dwarf_tag;
338     struct attr
339     {
340       /* Attribute name DW_IDX_*.  */
341       ULONGEST dw_idx;
342
343       /* Attribute form DW_FORM_*.  */
344       ULONGEST form;
345
346       /* Value if FORM is DW_FORM_implicit_const.  */
347       LONGEST implicit_const;
348     };
349     std::vector<attr> attr_vec;
350   };
351
352   std::unordered_map<ULONGEST, index_val> abbrev_map;
353
354   const char *namei_to_name (uint32_t namei) const;
355
356   /* Implementation of the mapped_index_base virtual interface, for
357      the name_components cache.  */
358
359   const char *symbol_name_at (offset_type idx) const override
360   { return namei_to_name (idx); }
361
362   size_t symbol_name_count () const override
363   { return this->name_count; }
364 };
365
366 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
367 DEF_VEC_P (dwarf2_per_cu_ptr);
368
369 struct tu_stats
370 {
371   int nr_uniq_abbrev_tables;
372   int nr_symtabs;
373   int nr_symtab_sharers;
374   int nr_stmt_less_type_units;
375   int nr_all_type_units_reallocs;
376 };
377
378 /* Collection of data recorded per objfile.
379    This hangs off of dwarf2_objfile_data_key.  */
380
381 struct dwarf2_per_objfile
382 {
383   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
384      dwarf2 section names, or is NULL if the standard ELF names are
385      used.  */
386   dwarf2_per_objfile (struct objfile *objfile,
387                       const dwarf2_debug_sections *names);
388
389   ~dwarf2_per_objfile ();
390
391   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
392
393   /* Free all cached compilation units.  */
394   void free_cached_comp_units ();
395 private:
396   /* This function is mapped across the sections and remembers the
397      offset and size of each of the debugging sections we are
398      interested in.  */
399   void locate_sections (bfd *abfd, asection *sectp,
400                         const dwarf2_debug_sections &names);
401
402 public:
403   dwarf2_section_info info {};
404   dwarf2_section_info abbrev {};
405   dwarf2_section_info line {};
406   dwarf2_section_info loc {};
407   dwarf2_section_info loclists {};
408   dwarf2_section_info macinfo {};
409   dwarf2_section_info macro {};
410   dwarf2_section_info str {};
411   dwarf2_section_info line_str {};
412   dwarf2_section_info ranges {};
413   dwarf2_section_info rnglists {};
414   dwarf2_section_info addr {};
415   dwarf2_section_info frame {};
416   dwarf2_section_info eh_frame {};
417   dwarf2_section_info gdb_index {};
418   dwarf2_section_info debug_names {};
419   dwarf2_section_info debug_aranges {};
420
421   VEC (dwarf2_section_info_def) *types = NULL;
422
423   /* Back link.  */
424   struct objfile *objfile = NULL;
425
426   /* Table of all the compilation units.  This is used to locate
427      the target compilation unit of a particular reference.  */
428   struct dwarf2_per_cu_data **all_comp_units = NULL;
429
430   /* The number of compilation units in ALL_COMP_UNITS.  */
431   int n_comp_units = 0;
432
433   /* The number of .debug_types-related CUs.  */
434   int n_type_units = 0;
435
436   /* The number of elements allocated in all_type_units.
437      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
438   int n_allocated_type_units = 0;
439
440   /* The .debug_types-related CUs (TUs).
441      This is stored in malloc space because we may realloc it.  */
442   struct signatured_type **all_type_units = NULL;
443
444   /* Table of struct type_unit_group objects.
445      The hash key is the DW_AT_stmt_list value.  */
446   htab_t type_unit_groups {};
447
448   /* A table mapping .debug_types signatures to its signatured_type entry.
449      This is NULL if the .debug_types section hasn't been read in yet.  */
450   htab_t signatured_types {};
451
452   /* Type unit statistics, to see how well the scaling improvements
453      are doing.  */
454   struct tu_stats tu_stats {};
455
456   /* A chain of compilation units that are currently read in, so that
457      they can be freed later.  */
458   dwarf2_per_cu_data *read_in_chain = NULL;
459
460   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
461      This is NULL if the table hasn't been allocated yet.  */
462   htab_t dwo_files {};
463
464   /* True if we've checked for whether there is a DWP file.  */
465   bool dwp_checked = false;
466
467   /* The DWP file if there is one, or NULL.  */
468   struct dwp_file *dwp_file = NULL;
469
470   /* The shared '.dwz' file, if one exists.  This is used when the
471      original data was compressed using 'dwz -m'.  */
472   struct dwz_file *dwz_file = NULL;
473
474   /* A flag indicating whether this objfile has a section loaded at a
475      VMA of 0.  */
476   bool has_section_at_zero = false;
477
478   /* True if we are using the mapped index,
479      or we are faking it for OBJF_READNOW's sake.  */
480   bool using_index = false;
481
482   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
483   mapped_index *index_table = NULL;
484
485   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
486   std::unique_ptr<mapped_debug_names> debug_names_table;
487
488   /* When using index_table, this keeps track of all quick_file_names entries.
489      TUs typically share line table entries with a CU, so we maintain a
490      separate table of all line table entries to support the sharing.
491      Note that while there can be way more TUs than CUs, we've already
492      sorted all the TUs into "type unit groups", grouped by their
493      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
494      CU and its associated TU group if there is one.  */
495   htab_t quick_file_names_table {};
496
497   /* Set during partial symbol reading, to prevent queueing of full
498      symbols.  */
499   bool reading_partial_symbols = false;
500
501   /* Table mapping type DIEs to their struct type *.
502      This is NULL if not allocated yet.
503      The mapping is done via (CU/TU + DIE offset) -> type.  */
504   htab_t die_type_hash {};
505
506   /* The CUs we recently read.  */
507   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
508
509   /* Table containing line_header indexed by offset and offset_in_dwz.  */
510   htab_t line_header_hash {};
511
512   /* Table containing all filenames.  This is an optional because the
513      table is lazily constructed on first access.  */
514   gdb::optional<filename_seen_cache> filenames_cache;
515 };
516
517 static struct dwarf2_per_objfile *dwarf2_per_objfile;
518
519 /* Default names of the debugging sections.  */
520
521 /* Note that if the debugging section has been compressed, it might
522    have a name like .zdebug_info.  */
523
524 static const struct dwarf2_debug_sections dwarf2_elf_names =
525 {
526   { ".debug_info", ".zdebug_info" },
527   { ".debug_abbrev", ".zdebug_abbrev" },
528   { ".debug_line", ".zdebug_line" },
529   { ".debug_loc", ".zdebug_loc" },
530   { ".debug_loclists", ".zdebug_loclists" },
531   { ".debug_macinfo", ".zdebug_macinfo" },
532   { ".debug_macro", ".zdebug_macro" },
533   { ".debug_str", ".zdebug_str" },
534   { ".debug_line_str", ".zdebug_line_str" },
535   { ".debug_ranges", ".zdebug_ranges" },
536   { ".debug_rnglists", ".zdebug_rnglists" },
537   { ".debug_types", ".zdebug_types" },
538   { ".debug_addr", ".zdebug_addr" },
539   { ".debug_frame", ".zdebug_frame" },
540   { ".eh_frame", NULL },
541   { ".gdb_index", ".zgdb_index" },
542   { ".debug_names", ".zdebug_names" },
543   { ".debug_aranges", ".zdebug_aranges" },
544   23
545 };
546
547 /* List of DWO/DWP sections.  */
548
549 static const struct dwop_section_names
550 {
551   struct dwarf2_section_names abbrev_dwo;
552   struct dwarf2_section_names info_dwo;
553   struct dwarf2_section_names line_dwo;
554   struct dwarf2_section_names loc_dwo;
555   struct dwarf2_section_names loclists_dwo;
556   struct dwarf2_section_names macinfo_dwo;
557   struct dwarf2_section_names macro_dwo;
558   struct dwarf2_section_names str_dwo;
559   struct dwarf2_section_names str_offsets_dwo;
560   struct dwarf2_section_names types_dwo;
561   struct dwarf2_section_names cu_index;
562   struct dwarf2_section_names tu_index;
563 }
564 dwop_section_names =
565 {
566   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
567   { ".debug_info.dwo", ".zdebug_info.dwo" },
568   { ".debug_line.dwo", ".zdebug_line.dwo" },
569   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
570   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
571   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
572   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
573   { ".debug_str.dwo", ".zdebug_str.dwo" },
574   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
575   { ".debug_types.dwo", ".zdebug_types.dwo" },
576   { ".debug_cu_index", ".zdebug_cu_index" },
577   { ".debug_tu_index", ".zdebug_tu_index" },
578 };
579
580 /* local data types */
581
582 /* The data in a compilation unit header, after target2host
583    translation, looks like this.  */
584 struct comp_unit_head
585 {
586   unsigned int length;
587   short version;
588   unsigned char addr_size;
589   unsigned char signed_addr_p;
590   sect_offset abbrev_sect_off;
591
592   /* Size of file offsets; either 4 or 8.  */
593   unsigned int offset_size;
594
595   /* Size of the length field; either 4 or 12.  */
596   unsigned int initial_length_size;
597
598   enum dwarf_unit_type unit_type;
599
600   /* Offset to the first byte of this compilation unit header in the
601      .debug_info section, for resolving relative reference dies.  */
602   sect_offset sect_off;
603
604   /* Offset to first die in this cu from the start of the cu.
605      This will be the first byte following the compilation unit header.  */
606   cu_offset first_die_cu_offset;
607
608   /* 64-bit signature of this type unit - it is valid only for
609      UNIT_TYPE DW_UT_type.  */
610   ULONGEST signature;
611
612   /* For types, offset in the type's DIE of the type defined by this TU.  */
613   cu_offset type_cu_offset_in_tu;
614 };
615
616 /* Type used for delaying computation of method physnames.
617    See comments for compute_delayed_physnames.  */
618 struct delayed_method_info
619 {
620   /* The type to which the method is attached, i.e., its parent class.  */
621   struct type *type;
622
623   /* The index of the method in the type's function fieldlists.  */
624   int fnfield_index;
625
626   /* The index of the method in the fieldlist.  */
627   int index;
628
629   /* The name of the DIE.  */
630   const char *name;
631
632   /*  The DIE associated with this method.  */
633   struct die_info *die;
634 };
635
636 typedef struct delayed_method_info delayed_method_info;
637 DEF_VEC_O (delayed_method_info);
638
639 /* Internal state when decoding a particular compilation unit.  */
640 struct dwarf2_cu
641 {
642   /* The dwarf2_per_objfile containing this compilation unit.  */
643   struct dwarf2_per_objfile *dwarf2_per_objfile;
644
645   /* The header of the compilation unit.  */
646   struct comp_unit_head header;
647
648   /* Base address of this compilation unit.  */
649   CORE_ADDR base_address;
650
651   /* Non-zero if base_address has been set.  */
652   int base_known;
653
654   /* The language we are debugging.  */
655   enum language language;
656   const struct language_defn *language_defn;
657
658   const char *producer;
659
660   /* The generic symbol table building routines have separate lists for
661      file scope symbols and all all other scopes (local scopes).  So
662      we need to select the right one to pass to add_symbol_to_list().
663      We do it by keeping a pointer to the correct list in list_in_scope.
664
665      FIXME: The original dwarf code just treated the file scope as the
666      first local scope, and all other local scopes as nested local
667      scopes, and worked fine.  Check to see if we really need to
668      distinguish these in buildsym.c.  */
669   struct pending **list_in_scope;
670
671   /* The abbrev table for this CU.
672      Normally this points to the abbrev table in the objfile.
673      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
674   struct abbrev_table *abbrev_table;
675
676   /* Hash table holding all the loaded partial DIEs
677      with partial_die->offset.SECT_OFF as hash.  */
678   htab_t partial_dies;
679
680   /* Storage for things with the same lifetime as this read-in compilation
681      unit, including partial DIEs.  */
682   struct obstack comp_unit_obstack;
683
684   /* When multiple dwarf2_cu structures are living in memory, this field
685      chains them all together, so that they can be released efficiently.
686      We will probably also want a generation counter so that most-recently-used
687      compilation units are cached...  */
688   struct dwarf2_per_cu_data *read_in_chain;
689
690   /* Backlink to our per_cu entry.  */
691   struct dwarf2_per_cu_data *per_cu;
692
693   /* How many compilation units ago was this CU last referenced?  */
694   int last_used;
695
696   /* A hash table of DIE cu_offset for following references with
697      die_info->offset.sect_off as hash.  */
698   htab_t die_hash;
699
700   /* Full DIEs if read in.  */
701   struct die_info *dies;
702
703   /* A set of pointers to dwarf2_per_cu_data objects for compilation
704      units referenced by this one.  Only set during full symbol processing;
705      partial symbol tables do not have dependencies.  */
706   htab_t dependencies;
707
708   /* Header data from the line table, during full symbol processing.  */
709   struct line_header *line_header;
710   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
711      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
712      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
713      to the line header as long as this DIE is being processed.  See
714      process_die_scope.  */
715   die_info *line_header_die_owner;
716
717   /* A list of methods which need to have physnames computed
718      after all type information has been read.  */
719   VEC (delayed_method_info) *method_list;
720
721   /* To be copied to symtab->call_site_htab.  */
722   htab_t call_site_htab;
723
724   /* Non-NULL if this CU came from a DWO file.
725      There is an invariant here that is important to remember:
726      Except for attributes copied from the top level DIE in the "main"
727      (or "stub") file in preparation for reading the DWO file
728      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
729      Either there isn't a DWO file (in which case this is NULL and the point
730      is moot), or there is and either we're not going to read it (in which
731      case this is NULL) or there is and we are reading it (in which case this
732      is non-NULL).  */
733   struct dwo_unit *dwo_unit;
734
735   /* The DW_AT_addr_base attribute if present, zero otherwise
736      (zero is a valid value though).
737      Note this value comes from the Fission stub CU/TU's DIE.  */
738   ULONGEST addr_base;
739
740   /* The DW_AT_ranges_base attribute if present, zero otherwise
741      (zero is a valid value though).
742      Note this value comes from the Fission stub CU/TU's DIE.
743      Also note that the value is zero in the non-DWO case so this value can
744      be used without needing to know whether DWO files are in use or not.
745      N.B. This does not apply to DW_AT_ranges appearing in
746      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
747      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
748      DW_AT_ranges_base *would* have to be applied, and we'd have to care
749      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
750   ULONGEST ranges_base;
751
752   /* Mark used when releasing cached dies.  */
753   unsigned int mark : 1;
754
755   /* This CU references .debug_loc.  See the symtab->locations_valid field.
756      This test is imperfect as there may exist optimized debug code not using
757      any location list and still facing inlining issues if handled as
758      unoptimized code.  For a future better test see GCC PR other/32998.  */
759   unsigned int has_loclist : 1;
760
761   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
762      if all the producer_is_* fields are valid.  This information is cached
763      because profiling CU expansion showed excessive time spent in
764      producer_is_gxx_lt_4_6.  */
765   unsigned int checked_producer : 1;
766   unsigned int producer_is_gxx_lt_4_6 : 1;
767   unsigned int producer_is_gcc_lt_4_3 : 1;
768   unsigned int producer_is_icc_lt_14 : 1;
769
770   /* When set, the file that we're processing is known to have
771      debugging info for C++ namespaces.  GCC 3.3.x did not produce
772      this information, but later versions do.  */
773
774   unsigned int processing_has_namespace_info : 1;
775 };
776
777 /* Persistent data held for a compilation unit, even when not
778    processing it.  We put a pointer to this structure in the
779    read_symtab_private field of the psymtab.  */
780
781 struct dwarf2_per_cu_data
782 {
783   /* The start offset and length of this compilation unit.
784      NOTE: Unlike comp_unit_head.length, this length includes
785      initial_length_size.
786      If the DIE refers to a DWO file, this is always of the original die,
787      not the DWO file.  */
788   sect_offset sect_off;
789   unsigned int length;
790
791   /* DWARF standard version this data has been read from (such as 4 or 5).  */
792   short dwarf_version;
793
794   /* Flag indicating this compilation unit will be read in before
795      any of the current compilation units are processed.  */
796   unsigned int queued : 1;
797
798   /* This flag will be set when reading partial DIEs if we need to load
799      absolutely all DIEs for this compilation unit, instead of just the ones
800      we think are interesting.  It gets set if we look for a DIE in the
801      hash table and don't find it.  */
802   unsigned int load_all_dies : 1;
803
804   /* Non-zero if this CU is from .debug_types.
805      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
806      this is non-zero.  */
807   unsigned int is_debug_types : 1;
808
809   /* Non-zero if this CU is from the .dwz file.  */
810   unsigned int is_dwz : 1;
811
812   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
813      This flag is only valid if is_debug_types is true.
814      We can't read a CU directly from a DWO file: There are required
815      attributes in the stub.  */
816   unsigned int reading_dwo_directly : 1;
817
818   /* Non-zero if the TU has been read.
819      This is used to assist the "Stay in DWO Optimization" for Fission:
820      When reading a DWO, it's faster to read TUs from the DWO instead of
821      fetching them from random other DWOs (due to comdat folding).
822      If the TU has already been read, the optimization is unnecessary
823      (and unwise - we don't want to change where gdb thinks the TU lives
824      "midflight").
825      This flag is only valid if is_debug_types is true.  */
826   unsigned int tu_read : 1;
827
828   /* The section this CU/TU lives in.
829      If the DIE refers to a DWO file, this is always the original die,
830      not the DWO file.  */
831   struct dwarf2_section_info *section;
832
833   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
834      of the CU cache it gets reset to NULL again.  This is left as NULL for
835      dummy CUs (a CU header, but nothing else).  */
836   struct dwarf2_cu *cu;
837
838   /* The corresponding dwarf2_per_objfile.  */
839   struct dwarf2_per_objfile *dwarf2_per_objfile;
840
841   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
842      is active.  Otherwise, the 'psymtab' field is active.  */
843   union
844   {
845     /* The partial symbol table associated with this compilation unit,
846        or NULL for unread partial units.  */
847     struct partial_symtab *psymtab;
848
849     /* Data needed by the "quick" functions.  */
850     struct dwarf2_per_cu_quick_data *quick;
851   } v;
852
853   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
854      while reading psymtabs, used to compute the psymtab dependencies,
855      and then cleared.  Then it is filled in again while reading full
856      symbols, and only deleted when the objfile is destroyed.
857
858      This is also used to work around a difference between the way gold
859      generates .gdb_index version <=7 and the way gdb does.  Arguably this
860      is a gold bug.  For symbols coming from TUs, gold records in the index
861      the CU that includes the TU instead of the TU itself.  This breaks
862      dw2_lookup_symbol: It assumes that if the index says symbol X lives
863      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
864      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
865      we need to look in TU Z to find X.  Fortunately, this is akin to
866      DW_TAG_imported_unit, so we just use the same mechanism: For
867      .gdb_index version <=7 this also records the TUs that the CU referred
868      to.  Concurrently with this change gdb was modified to emit version 8
869      indices so we only pay a price for gold generated indices.
870      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
871   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
872 };
873
874 /* Entry in the signatured_types hash table.  */
875
876 struct signatured_type
877 {
878   /* The "per_cu" object of this type.
879      This struct is used iff per_cu.is_debug_types.
880      N.B.: This is the first member so that it's easy to convert pointers
881      between them.  */
882   struct dwarf2_per_cu_data per_cu;
883
884   /* The type's signature.  */
885   ULONGEST signature;
886
887   /* Offset in the TU of the type's DIE, as read from the TU header.
888      If this TU is a DWO stub and the definition lives in a DWO file
889      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
890   cu_offset type_offset_in_tu;
891
892   /* Offset in the section of the type's DIE.
893      If the definition lives in a DWO file, this is the offset in the
894      .debug_types.dwo section.
895      The value is zero until the actual value is known.
896      Zero is otherwise not a valid section offset.  */
897   sect_offset type_offset_in_section;
898
899   /* Type units are grouped by their DW_AT_stmt_list entry so that they
900      can share them.  This points to the containing symtab.  */
901   struct type_unit_group *type_unit_group;
902
903   /* The type.
904      The first time we encounter this type we fully read it in and install it
905      in the symbol tables.  Subsequent times we only need the type.  */
906   struct type *type;
907
908   /* Containing DWO unit.
909      This field is valid iff per_cu.reading_dwo_directly.  */
910   struct dwo_unit *dwo_unit;
911 };
912
913 typedef struct signatured_type *sig_type_ptr;
914 DEF_VEC_P (sig_type_ptr);
915
916 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
917    This includes type_unit_group and quick_file_names.  */
918
919 struct stmt_list_hash
920 {
921   /* The DWO unit this table is from or NULL if there is none.  */
922   struct dwo_unit *dwo_unit;
923
924   /* Offset in .debug_line or .debug_line.dwo.  */
925   sect_offset line_sect_off;
926 };
927
928 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
929    an object of this type.  */
930
931 struct type_unit_group
932 {
933   /* dwarf2read.c's main "handle" on a TU symtab.
934      To simplify things we create an artificial CU that "includes" all the
935      type units using this stmt_list so that the rest of the code still has
936      a "per_cu" handle on the symtab.
937      This PER_CU is recognized by having no section.  */
938 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
939   struct dwarf2_per_cu_data per_cu;
940
941   /* The TUs that share this DW_AT_stmt_list entry.
942      This is added to while parsing type units to build partial symtabs,
943      and is deleted afterwards and not used again.  */
944   VEC (sig_type_ptr) *tus;
945
946   /* The compunit symtab.
947      Type units in a group needn't all be defined in the same source file,
948      so we create an essentially anonymous symtab as the compunit symtab.  */
949   struct compunit_symtab *compunit_symtab;
950
951   /* The data used to construct the hash key.  */
952   struct stmt_list_hash hash;
953
954   /* The number of symtabs from the line header.
955      The value here must match line_header.num_file_names.  */
956   unsigned int num_symtabs;
957
958   /* The symbol tables for this TU (obtained from the files listed in
959      DW_AT_stmt_list).
960      WARNING: The order of entries here must match the order of entries
961      in the line header.  After the first TU using this type_unit_group, the
962      line header for the subsequent TUs is recreated from this.  This is done
963      because we need to use the same symtabs for each TU using the same
964      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
965      there's no guarantee the line header doesn't have duplicate entries.  */
966   struct symtab **symtabs;
967 };
968
969 /* These sections are what may appear in a (real or virtual) DWO file.  */
970
971 struct dwo_sections
972 {
973   struct dwarf2_section_info abbrev;
974   struct dwarf2_section_info line;
975   struct dwarf2_section_info loc;
976   struct dwarf2_section_info loclists;
977   struct dwarf2_section_info macinfo;
978   struct dwarf2_section_info macro;
979   struct dwarf2_section_info str;
980   struct dwarf2_section_info str_offsets;
981   /* In the case of a virtual DWO file, these two are unused.  */
982   struct dwarf2_section_info info;
983   VEC (dwarf2_section_info_def) *types;
984 };
985
986 /* CUs/TUs in DWP/DWO files.  */
987
988 struct dwo_unit
989 {
990   /* Backlink to the containing struct dwo_file.  */
991   struct dwo_file *dwo_file;
992
993   /* The "id" that distinguishes this CU/TU.
994      .debug_info calls this "dwo_id", .debug_types calls this "signature".
995      Since signatures came first, we stick with it for consistency.  */
996   ULONGEST signature;
997
998   /* The section this CU/TU lives in, in the DWO file.  */
999   struct dwarf2_section_info *section;
1000
1001   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1002   sect_offset sect_off;
1003   unsigned int length;
1004
1005   /* For types, offset in the type's DIE of the type defined by this TU.  */
1006   cu_offset type_offset_in_tu;
1007 };
1008
1009 /* include/dwarf2.h defines the DWP section codes.
1010    It defines a max value but it doesn't define a min value, which we
1011    use for error checking, so provide one.  */
1012
1013 enum dwp_v2_section_ids
1014 {
1015   DW_SECT_MIN = 1
1016 };
1017
1018 /* Data for one DWO file.
1019
1020    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1021    appears in a DWP file).  DWP files don't really have DWO files per se -
1022    comdat folding of types "loses" the DWO file they came from, and from
1023    a high level view DWP files appear to contain a mass of random types.
1024    However, to maintain consistency with the non-DWP case we pretend DWP
1025    files contain virtual DWO files, and we assign each TU with one virtual
1026    DWO file (generally based on the line and abbrev section offsets -
1027    a heuristic that seems to work in practice).  */
1028
1029 struct dwo_file
1030 {
1031   /* The DW_AT_GNU_dwo_name attribute.
1032      For virtual DWO files the name is constructed from the section offsets
1033      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1034      from related CU+TUs.  */
1035   const char *dwo_name;
1036
1037   /* The DW_AT_comp_dir attribute.  */
1038   const char *comp_dir;
1039
1040   /* The bfd, when the file is open.  Otherwise this is NULL.
1041      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1042   bfd *dbfd;
1043
1044   /* The sections that make up this DWO file.
1045      Remember that for virtual DWO files in DWP V2, these are virtual
1046      sections (for lack of a better name).  */
1047   struct dwo_sections sections;
1048
1049   /* The CUs in the file.
1050      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1051      an extension to handle LLVM's Link Time Optimization output (where
1052      multiple source files may be compiled into a single object/dwo pair). */
1053   htab_t cus;
1054
1055   /* Table of TUs in the file.
1056      Each element is a struct dwo_unit.  */
1057   htab_t tus;
1058 };
1059
1060 /* These sections are what may appear in a DWP file.  */
1061
1062 struct dwp_sections
1063 {
1064   /* These are used by both DWP version 1 and 2.  */
1065   struct dwarf2_section_info str;
1066   struct dwarf2_section_info cu_index;
1067   struct dwarf2_section_info tu_index;
1068
1069   /* These are only used by DWP version 2 files.
1070      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1071      sections are referenced by section number, and are not recorded here.
1072      In DWP version 2 there is at most one copy of all these sections, each
1073      section being (effectively) comprised of the concatenation of all of the
1074      individual sections that exist in the version 1 format.
1075      To keep the code simple we treat each of these concatenated pieces as a
1076      section itself (a virtual section?).  */
1077   struct dwarf2_section_info abbrev;
1078   struct dwarf2_section_info info;
1079   struct dwarf2_section_info line;
1080   struct dwarf2_section_info loc;
1081   struct dwarf2_section_info macinfo;
1082   struct dwarf2_section_info macro;
1083   struct dwarf2_section_info str_offsets;
1084   struct dwarf2_section_info types;
1085 };
1086
1087 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1088    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1089
1090 struct virtual_v1_dwo_sections
1091 {
1092   struct dwarf2_section_info abbrev;
1093   struct dwarf2_section_info line;
1094   struct dwarf2_section_info loc;
1095   struct dwarf2_section_info macinfo;
1096   struct dwarf2_section_info macro;
1097   struct dwarf2_section_info str_offsets;
1098   /* Each DWP hash table entry records one CU or one TU.
1099      That is recorded here, and copied to dwo_unit.section.  */
1100   struct dwarf2_section_info info_or_types;
1101 };
1102
1103 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1104    In version 2, the sections of the DWO files are concatenated together
1105    and stored in one section of that name.  Thus each ELF section contains
1106    several "virtual" sections.  */
1107
1108 struct virtual_v2_dwo_sections
1109 {
1110   bfd_size_type abbrev_offset;
1111   bfd_size_type abbrev_size;
1112
1113   bfd_size_type line_offset;
1114   bfd_size_type line_size;
1115
1116   bfd_size_type loc_offset;
1117   bfd_size_type loc_size;
1118
1119   bfd_size_type macinfo_offset;
1120   bfd_size_type macinfo_size;
1121
1122   bfd_size_type macro_offset;
1123   bfd_size_type macro_size;
1124
1125   bfd_size_type str_offsets_offset;
1126   bfd_size_type str_offsets_size;
1127
1128   /* Each DWP hash table entry records one CU or one TU.
1129      That is recorded here, and copied to dwo_unit.section.  */
1130   bfd_size_type info_or_types_offset;
1131   bfd_size_type info_or_types_size;
1132 };
1133
1134 /* Contents of DWP hash tables.  */
1135
1136 struct dwp_hash_table
1137 {
1138   uint32_t version, nr_columns;
1139   uint32_t nr_units, nr_slots;
1140   const gdb_byte *hash_table, *unit_table;
1141   union
1142   {
1143     struct
1144     {
1145       const gdb_byte *indices;
1146     } v1;
1147     struct
1148     {
1149       /* This is indexed by column number and gives the id of the section
1150          in that column.  */
1151 #define MAX_NR_V2_DWO_SECTIONS \
1152   (1 /* .debug_info or .debug_types */ \
1153    + 1 /* .debug_abbrev */ \
1154    + 1 /* .debug_line */ \
1155    + 1 /* .debug_loc */ \
1156    + 1 /* .debug_str_offsets */ \
1157    + 1 /* .debug_macro or .debug_macinfo */)
1158       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1159       const gdb_byte *offsets;
1160       const gdb_byte *sizes;
1161     } v2;
1162   } section_pool;
1163 };
1164
1165 /* Data for one DWP file.  */
1166
1167 struct dwp_file
1168 {
1169   /* Name of the file.  */
1170   const char *name;
1171
1172   /* File format version.  */
1173   int version;
1174
1175   /* The bfd.  */
1176   bfd *dbfd;
1177
1178   /* Section info for this file.  */
1179   struct dwp_sections sections;
1180
1181   /* Table of CUs in the file.  */
1182   const struct dwp_hash_table *cus;
1183
1184   /* Table of TUs in the file.  */
1185   const struct dwp_hash_table *tus;
1186
1187   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1188   htab_t loaded_cus;
1189   htab_t loaded_tus;
1190
1191   /* Table to map ELF section numbers to their sections.
1192      This is only needed for the DWP V1 file format.  */
1193   unsigned int num_sections;
1194   asection **elf_sections;
1195 };
1196
1197 /* This represents a '.dwz' file.  */
1198
1199 struct dwz_file
1200 {
1201   /* A dwz file can only contain a few sections.  */
1202   struct dwarf2_section_info abbrev;
1203   struct dwarf2_section_info info;
1204   struct dwarf2_section_info str;
1205   struct dwarf2_section_info line;
1206   struct dwarf2_section_info macro;
1207   struct dwarf2_section_info gdb_index;
1208   struct dwarf2_section_info debug_names;
1209
1210   /* The dwz's BFD.  */
1211   bfd *dwz_bfd;
1212 };
1213
1214 /* Struct used to pass misc. parameters to read_die_and_children, et
1215    al.  which are used for both .debug_info and .debug_types dies.
1216    All parameters here are unchanging for the life of the call.  This
1217    struct exists to abstract away the constant parameters of die reading.  */
1218
1219 struct die_reader_specs
1220 {
1221   /* The bfd of die_section.  */
1222   bfd* abfd;
1223
1224   /* The CU of the DIE we are parsing.  */
1225   struct dwarf2_cu *cu;
1226
1227   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1228   struct dwo_file *dwo_file;
1229
1230   /* The section the die comes from.
1231      This is either .debug_info or .debug_types, or the .dwo variants.  */
1232   struct dwarf2_section_info *die_section;
1233
1234   /* die_section->buffer.  */
1235   const gdb_byte *buffer;
1236
1237   /* The end of the buffer.  */
1238   const gdb_byte *buffer_end;
1239
1240   /* The value of the DW_AT_comp_dir attribute.  */
1241   const char *comp_dir;
1242 };
1243
1244 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1245 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1246                                       const gdb_byte *info_ptr,
1247                                       struct die_info *comp_unit_die,
1248                                       int has_children,
1249                                       void *data);
1250
1251 /* A 1-based directory index.  This is a strong typedef to prevent
1252    accidentally using a directory index as a 0-based index into an
1253    array/vector.  */
1254 enum class dir_index : unsigned int {};
1255
1256 /* Likewise, a 1-based file name index.  */
1257 enum class file_name_index : unsigned int {};
1258
1259 struct file_entry
1260 {
1261   file_entry () = default;
1262
1263   file_entry (const char *name_, dir_index d_index_,
1264               unsigned int mod_time_, unsigned int length_)
1265     : name (name_),
1266       d_index (d_index_),
1267       mod_time (mod_time_),
1268       length (length_)
1269   {}
1270
1271   /* Return the include directory at D_INDEX stored in LH.  Returns
1272      NULL if D_INDEX is out of bounds.  */
1273   const char *include_dir (const line_header *lh) const;
1274
1275   /* The file name.  Note this is an observing pointer.  The memory is
1276      owned by debug_line_buffer.  */
1277   const char *name {};
1278
1279   /* The directory index (1-based).  */
1280   dir_index d_index {};
1281
1282   unsigned int mod_time {};
1283
1284   unsigned int length {};
1285
1286   /* True if referenced by the Line Number Program.  */
1287   bool included_p {};
1288
1289   /* The associated symbol table, if any.  */
1290   struct symtab *symtab {};
1291 };
1292
1293 /* The line number information for a compilation unit (found in the
1294    .debug_line section) begins with a "statement program header",
1295    which contains the following information.  */
1296 struct line_header
1297 {
1298   line_header ()
1299     : offset_in_dwz {}
1300   {}
1301
1302   /* Add an entry to the include directory table.  */
1303   void add_include_dir (const char *include_dir);
1304
1305   /* Add an entry to the file name table.  */
1306   void add_file_name (const char *name, dir_index d_index,
1307                       unsigned int mod_time, unsigned int length);
1308
1309   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1310      is out of bounds.  */
1311   const char *include_dir_at (dir_index index) const
1312   {
1313     /* Convert directory index number (1-based) to vector index
1314        (0-based).  */
1315     size_t vec_index = to_underlying (index) - 1;
1316
1317     if (vec_index >= include_dirs.size ())
1318       return NULL;
1319     return include_dirs[vec_index];
1320   }
1321
1322   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1323      is out of bounds.  */
1324   file_entry *file_name_at (file_name_index index)
1325   {
1326     /* Convert file name index number (1-based) to vector index
1327        (0-based).  */
1328     size_t vec_index = to_underlying (index) - 1;
1329
1330     if (vec_index >= file_names.size ())
1331       return NULL;
1332     return &file_names[vec_index];
1333   }
1334
1335   /* Const version of the above.  */
1336   const file_entry *file_name_at (unsigned int index) const
1337   {
1338     if (index >= file_names.size ())
1339       return NULL;
1340     return &file_names[index];
1341   }
1342
1343   /* Offset of line number information in .debug_line section.  */
1344   sect_offset sect_off {};
1345
1346   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1347   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1348
1349   unsigned int total_length {};
1350   unsigned short version {};
1351   unsigned int header_length {};
1352   unsigned char minimum_instruction_length {};
1353   unsigned char maximum_ops_per_instruction {};
1354   unsigned char default_is_stmt {};
1355   int line_base {};
1356   unsigned char line_range {};
1357   unsigned char opcode_base {};
1358
1359   /* standard_opcode_lengths[i] is the number of operands for the
1360      standard opcode whose value is i.  This means that
1361      standard_opcode_lengths[0] is unused, and the last meaningful
1362      element is standard_opcode_lengths[opcode_base - 1].  */
1363   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1364
1365   /* The include_directories table.  Note these are observing
1366      pointers.  The memory is owned by debug_line_buffer.  */
1367   std::vector<const char *> include_dirs;
1368
1369   /* The file_names table.  */
1370   std::vector<file_entry> file_names;
1371
1372   /* The start and end of the statement program following this
1373      header.  These point into dwarf2_per_objfile->line_buffer.  */
1374   const gdb_byte *statement_program_start {}, *statement_program_end {};
1375 };
1376
1377 typedef std::unique_ptr<line_header> line_header_up;
1378
1379 const char *
1380 file_entry::include_dir (const line_header *lh) const
1381 {
1382   return lh->include_dir_at (d_index);
1383 }
1384
1385 /* When we construct a partial symbol table entry we only
1386    need this much information.  */
1387 struct partial_die_info
1388   {
1389     /* Offset of this DIE.  */
1390     sect_offset sect_off;
1391
1392     /* DWARF-2 tag for this DIE.  */
1393     ENUM_BITFIELD(dwarf_tag) tag : 16;
1394
1395     /* Assorted flags describing the data found in this DIE.  */
1396     unsigned int has_children : 1;
1397     unsigned int is_external : 1;
1398     unsigned int is_declaration : 1;
1399     unsigned int has_type : 1;
1400     unsigned int has_specification : 1;
1401     unsigned int has_pc_info : 1;
1402     unsigned int may_be_inlined : 1;
1403
1404     /* This DIE has been marked DW_AT_main_subprogram.  */
1405     unsigned int main_subprogram : 1;
1406
1407     /* Flag set if the SCOPE field of this structure has been
1408        computed.  */
1409     unsigned int scope_set : 1;
1410
1411     /* Flag set if the DIE has a byte_size attribute.  */
1412     unsigned int has_byte_size : 1;
1413
1414     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1415     unsigned int has_const_value : 1;
1416
1417     /* Flag set if any of the DIE's children are template arguments.  */
1418     unsigned int has_template_arguments : 1;
1419
1420     /* Flag set if fixup_partial_die has been called on this die.  */
1421     unsigned int fixup_called : 1;
1422
1423     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1424     unsigned int is_dwz : 1;
1425
1426     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1427     unsigned int spec_is_dwz : 1;
1428
1429     /* The name of this DIE.  Normally the value of DW_AT_name, but
1430        sometimes a default name for unnamed DIEs.  */
1431     const char *name;
1432
1433     /* The linkage name, if present.  */
1434     const char *linkage_name;
1435
1436     /* The scope to prepend to our children.  This is generally
1437        allocated on the comp_unit_obstack, so will disappear
1438        when this compilation unit leaves the cache.  */
1439     const char *scope;
1440
1441     /* Some data associated with the partial DIE.  The tag determines
1442        which field is live.  */
1443     union
1444     {
1445       /* The location description associated with this DIE, if any.  */
1446       struct dwarf_block *locdesc;
1447       /* The offset of an import, for DW_TAG_imported_unit.  */
1448       sect_offset sect_off;
1449     } d;
1450
1451     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1452     CORE_ADDR lowpc;
1453     CORE_ADDR highpc;
1454
1455     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1456        DW_AT_sibling, if any.  */
1457     /* NOTE: This member isn't strictly necessary, read_partial_die could
1458        return DW_AT_sibling values to its caller load_partial_dies.  */
1459     const gdb_byte *sibling;
1460
1461     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1462        DW_AT_specification (or DW_AT_abstract_origin or
1463        DW_AT_extension).  */
1464     sect_offset spec_offset;
1465
1466     /* Pointers to this DIE's parent, first child, and next sibling,
1467        if any.  */
1468     struct partial_die_info *die_parent, *die_child, *die_sibling;
1469   };
1470
1471 /* This data structure holds the information of an abbrev.  */
1472 struct abbrev_info
1473   {
1474     unsigned int number;        /* number identifying abbrev */
1475     enum dwarf_tag tag;         /* dwarf tag */
1476     unsigned short has_children;                /* boolean */
1477     unsigned short num_attrs;   /* number of attributes */
1478     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1479     struct abbrev_info *next;   /* next in chain */
1480   };
1481
1482 struct attr_abbrev
1483   {
1484     ENUM_BITFIELD(dwarf_attribute) name : 16;
1485     ENUM_BITFIELD(dwarf_form) form : 16;
1486
1487     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1488     LONGEST implicit_const;
1489   };
1490
1491 /* Size of abbrev_table.abbrev_hash_table.  */
1492 #define ABBREV_HASH_SIZE 121
1493
1494 /* Top level data structure to contain an abbreviation table.  */
1495
1496 struct abbrev_table
1497 {
1498   /* Where the abbrev table came from.
1499      This is used as a sanity check when the table is used.  */
1500   sect_offset sect_off;
1501
1502   /* Storage for the abbrev table.  */
1503   struct obstack abbrev_obstack;
1504
1505   /* Hash table of abbrevs.
1506      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1507      It could be statically allocated, but the previous code didn't so we
1508      don't either.  */
1509   struct abbrev_info **abbrevs;
1510 };
1511
1512 /* Attributes have a name and a value.  */
1513 struct attribute
1514   {
1515     ENUM_BITFIELD(dwarf_attribute) name : 16;
1516     ENUM_BITFIELD(dwarf_form) form : 15;
1517
1518     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1519        field should be in u.str (existing only for DW_STRING) but it is kept
1520        here for better struct attribute alignment.  */
1521     unsigned int string_is_canonical : 1;
1522
1523     union
1524       {
1525         const char *str;
1526         struct dwarf_block *blk;
1527         ULONGEST unsnd;
1528         LONGEST snd;
1529         CORE_ADDR addr;
1530         ULONGEST signature;
1531       }
1532     u;
1533   };
1534
1535 /* This data structure holds a complete die structure.  */
1536 struct die_info
1537   {
1538     /* DWARF-2 tag for this DIE.  */
1539     ENUM_BITFIELD(dwarf_tag) tag : 16;
1540
1541     /* Number of attributes */
1542     unsigned char num_attrs;
1543
1544     /* True if we're presently building the full type name for the
1545        type derived from this DIE.  */
1546     unsigned char building_fullname : 1;
1547
1548     /* True if this die is in process.  PR 16581.  */
1549     unsigned char in_process : 1;
1550
1551     /* Abbrev number */
1552     unsigned int abbrev;
1553
1554     /* Offset in .debug_info or .debug_types section.  */
1555     sect_offset sect_off;
1556
1557     /* The dies in a compilation unit form an n-ary tree.  PARENT
1558        points to this die's parent; CHILD points to the first child of
1559        this node; and all the children of a given node are chained
1560        together via their SIBLING fields.  */
1561     struct die_info *child;     /* Its first child, if any.  */
1562     struct die_info *sibling;   /* Its next sibling, if any.  */
1563     struct die_info *parent;    /* Its parent, if any.  */
1564
1565     /* An array of attributes, with NUM_ATTRS elements.  There may be
1566        zero, but it's not common and zero-sized arrays are not
1567        sufficiently portable C.  */
1568     struct attribute attrs[1];
1569   };
1570
1571 /* Get at parts of an attribute structure.  */
1572
1573 #define DW_STRING(attr)    ((attr)->u.str)
1574 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1575 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1576 #define DW_BLOCK(attr)     ((attr)->u.blk)
1577 #define DW_SND(attr)       ((attr)->u.snd)
1578 #define DW_ADDR(attr)      ((attr)->u.addr)
1579 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1580
1581 /* Blocks are a bunch of untyped bytes.  */
1582 struct dwarf_block
1583   {
1584     size_t size;
1585
1586     /* Valid only if SIZE is not zero.  */
1587     const gdb_byte *data;
1588   };
1589
1590 #ifndef ATTR_ALLOC_CHUNK
1591 #define ATTR_ALLOC_CHUNK 4
1592 #endif
1593
1594 /* Allocate fields for structs, unions and enums in this size.  */
1595 #ifndef DW_FIELD_ALLOC_CHUNK
1596 #define DW_FIELD_ALLOC_CHUNK 4
1597 #endif
1598
1599 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1600    but this would require a corresponding change in unpack_field_as_long
1601    and friends.  */
1602 static int bits_per_byte = 8;
1603
1604 struct nextfield
1605 {
1606   struct nextfield *next;
1607   int accessibility;
1608   int virtuality;
1609   struct field field;
1610 };
1611
1612 struct nextfnfield
1613 {
1614   struct nextfnfield *next;
1615   struct fn_field fnfield;
1616 };
1617
1618 struct fnfieldlist
1619 {
1620   const char *name;
1621   int length;
1622   struct nextfnfield *head;
1623 };
1624
1625 struct decl_field_list
1626 {
1627   struct decl_field field;
1628   struct decl_field_list *next;
1629 };
1630
1631 /* The routines that read and process dies for a C struct or C++ class
1632    pass lists of data member fields and lists of member function fields
1633    in an instance of a field_info structure, as defined below.  */
1634 struct field_info
1635   {
1636     /* List of data member and baseclasses fields.  */
1637     struct nextfield *fields, *baseclasses;
1638
1639     /* Number of fields (including baseclasses).  */
1640     int nfields;
1641
1642     /* Number of baseclasses.  */
1643     int nbaseclasses;
1644
1645     /* Set if the accesibility of one of the fields is not public.  */
1646     int non_public_fields;
1647
1648     /* Member function fieldlist array, contains name of possibly overloaded
1649        member function, number of overloaded member functions and a pointer
1650        to the head of the member function field chain.  */
1651     struct fnfieldlist *fnfieldlists;
1652
1653     /* Number of entries in the fnfieldlists array.  */
1654     int nfnfields;
1655
1656     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1657        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1658     struct decl_field_list *typedef_field_list;
1659     unsigned typedef_field_list_count;
1660
1661     /* Nested types defined by this class and the number of elements in this
1662        list.  */
1663     struct decl_field_list *nested_types_list;
1664     unsigned nested_types_list_count;
1665   };
1666
1667 /* One item on the queue of compilation units to read in full symbols
1668    for.  */
1669 struct dwarf2_queue_item
1670 {
1671   struct dwarf2_per_cu_data *per_cu;
1672   enum language pretend_language;
1673   struct dwarf2_queue_item *next;
1674 };
1675
1676 /* The current queue.  */
1677 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1678
1679 /* Loaded secondary compilation units are kept in memory until they
1680    have not been referenced for the processing of this many
1681    compilation units.  Set this to zero to disable caching.  Cache
1682    sizes of up to at least twenty will improve startup time for
1683    typical inter-CU-reference binaries, at an obvious memory cost.  */
1684 static int dwarf_max_cache_age = 5;
1685 static void
1686 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1687                           struct cmd_list_element *c, const char *value)
1688 {
1689   fprintf_filtered (file, _("The upper bound on the age of cached "
1690                             "DWARF compilation units is %s.\n"),
1691                     value);
1692 }
1693 \f
1694 /* local function prototypes */
1695
1696 static const char *get_section_name (const struct dwarf2_section_info *);
1697
1698 static const char *get_section_file_name (const struct dwarf2_section_info *);
1699
1700 static void dwarf2_find_base_address (struct die_info *die,
1701                                       struct dwarf2_cu *cu);
1702
1703 static struct partial_symtab *create_partial_symtab
1704   (struct dwarf2_per_cu_data *per_cu, const char *name);
1705
1706 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1707                                         const gdb_byte *info_ptr,
1708                                         struct die_info *type_unit_die,
1709                                         int has_children, void *data);
1710
1711 static void dwarf2_build_psymtabs_hard (struct objfile *);
1712
1713 static void scan_partial_symbols (struct partial_die_info *,
1714                                   CORE_ADDR *, CORE_ADDR *,
1715                                   int, struct dwarf2_cu *);
1716
1717 static void add_partial_symbol (struct partial_die_info *,
1718                                 struct dwarf2_cu *);
1719
1720 static void add_partial_namespace (struct partial_die_info *pdi,
1721                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1722                                    int set_addrmap, struct dwarf2_cu *cu);
1723
1724 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1725                                 CORE_ADDR *highpc, int set_addrmap,
1726                                 struct dwarf2_cu *cu);
1727
1728 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1729                                      struct dwarf2_cu *cu);
1730
1731 static void add_partial_subprogram (struct partial_die_info *pdi,
1732                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1733                                     int need_pc, struct dwarf2_cu *cu);
1734
1735 static void dwarf2_read_symtab (struct partial_symtab *,
1736                                 struct objfile *);
1737
1738 static void psymtab_to_symtab_1 (struct partial_symtab *);
1739
1740 static struct abbrev_info *abbrev_table_lookup_abbrev
1741   (const struct abbrev_table *, unsigned int);
1742
1743 static struct abbrev_table *abbrev_table_read_table
1744   (struct dwarf2_section_info *, sect_offset);
1745
1746 static void abbrev_table_free (struct abbrev_table *);
1747
1748 static void abbrev_table_free_cleanup (void *);
1749
1750 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1751                                  struct dwarf2_section_info *);
1752
1753 static void dwarf2_free_abbrev_table (void *);
1754
1755 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1756
1757 static struct partial_die_info *load_partial_dies
1758   (const struct die_reader_specs *, const gdb_byte *, int);
1759
1760 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1761                                          struct partial_die_info *,
1762                                          struct abbrev_info *,
1763                                          unsigned int,
1764                                          const gdb_byte *);
1765
1766 static struct partial_die_info *find_partial_die (sect_offset, int,
1767                                                   struct dwarf2_cu *);
1768
1769 static void fixup_partial_die (struct partial_die_info *,
1770                                struct dwarf2_cu *);
1771
1772 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1773                                        struct attribute *, struct attr_abbrev *,
1774                                        const gdb_byte *);
1775
1776 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1777
1778 static int read_1_signed_byte (bfd *, const gdb_byte *);
1779
1780 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1781
1782 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1783
1784 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1785
1786 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1787                                unsigned int *);
1788
1789 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1790
1791 static LONGEST read_checked_initial_length_and_offset
1792   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1793    unsigned int *, unsigned int *);
1794
1795 static LONGEST read_offset (bfd *, const gdb_byte *,
1796                             const struct comp_unit_head *,
1797                             unsigned int *);
1798
1799 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1800
1801 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1802                                        sect_offset);
1803
1804 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1805
1806 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1807
1808 static const char *read_indirect_string (bfd *, const gdb_byte *,
1809                                          const struct comp_unit_head *,
1810                                          unsigned int *);
1811
1812 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1813                                               const struct comp_unit_head *,
1814                                               unsigned int *);
1815
1816 static const char *read_indirect_string_at_offset (bfd *abfd,
1817                                                    LONGEST str_offset);
1818
1819 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1820
1821 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1822
1823 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1824                                               const gdb_byte *,
1825                                               unsigned int *);
1826
1827 static const char *read_str_index (const struct die_reader_specs *reader,
1828                                    ULONGEST str_index);
1829
1830 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1831
1832 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1833                                       struct dwarf2_cu *);
1834
1835 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1836                                                 unsigned int);
1837
1838 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1839                                        struct dwarf2_cu *cu);
1840
1841 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1842                                struct dwarf2_cu *cu);
1843
1844 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1845
1846 static struct die_info *die_specification (struct die_info *die,
1847                                            struct dwarf2_cu **);
1848
1849 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1850                                                 struct dwarf2_cu *cu);
1851
1852 static void dwarf_decode_lines (struct line_header *, const char *,
1853                                 struct dwarf2_cu *, struct partial_symtab *,
1854                                 CORE_ADDR, int decode_mapping);
1855
1856 static void dwarf2_start_subfile (const char *, const char *);
1857
1858 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1859                                                     const char *, const char *,
1860                                                     CORE_ADDR);
1861
1862 static struct symbol *new_symbol (struct die_info *, struct type *,
1863                                   struct dwarf2_cu *);
1864
1865 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1866                                        struct dwarf2_cu *, struct symbol *);
1867
1868 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1869                                 struct dwarf2_cu *);
1870
1871 static void dwarf2_const_value_attr (const struct attribute *attr,
1872                                      struct type *type,
1873                                      const char *name,
1874                                      struct obstack *obstack,
1875                                      struct dwarf2_cu *cu, LONGEST *value,
1876                                      const gdb_byte **bytes,
1877                                      struct dwarf2_locexpr_baton **baton);
1878
1879 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1880
1881 static int need_gnat_info (struct dwarf2_cu *);
1882
1883 static struct type *die_descriptive_type (struct die_info *,
1884                                           struct dwarf2_cu *);
1885
1886 static void set_descriptive_type (struct type *, struct die_info *,
1887                                   struct dwarf2_cu *);
1888
1889 static struct type *die_containing_type (struct die_info *,
1890                                          struct dwarf2_cu *);
1891
1892 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1893                                      struct dwarf2_cu *);
1894
1895 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1896
1897 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1898
1899 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1900
1901 static char *typename_concat (struct obstack *obs, const char *prefix,
1902                               const char *suffix, int physname,
1903                               struct dwarf2_cu *cu);
1904
1905 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1906
1907 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1908
1909 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1910
1911 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1912
1913 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1914
1915 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1916
1917 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1918                                struct dwarf2_cu *, struct partial_symtab *);
1919
1920 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1921    values.  Keep the items ordered with increasing constraints compliance.  */
1922 enum pc_bounds_kind
1923 {
1924   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1925   PC_BOUNDS_NOT_PRESENT,
1926
1927   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1928      were present but they do not form a valid range of PC addresses.  */
1929   PC_BOUNDS_INVALID,
1930
1931   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1932   PC_BOUNDS_RANGES,
1933
1934   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1935   PC_BOUNDS_HIGH_LOW,
1936 };
1937
1938 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1939                                                  CORE_ADDR *, CORE_ADDR *,
1940                                                  struct dwarf2_cu *,
1941                                                  struct partial_symtab *);
1942
1943 static void get_scope_pc_bounds (struct die_info *,
1944                                  CORE_ADDR *, CORE_ADDR *,
1945                                  struct dwarf2_cu *);
1946
1947 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1948                                         CORE_ADDR, struct dwarf2_cu *);
1949
1950 static void dwarf2_add_field (struct field_info *, struct die_info *,
1951                               struct dwarf2_cu *);
1952
1953 static void dwarf2_attach_fields_to_type (struct field_info *,
1954                                           struct type *, struct dwarf2_cu *);
1955
1956 static void dwarf2_add_member_fn (struct field_info *,
1957                                   struct die_info *, struct type *,
1958                                   struct dwarf2_cu *);
1959
1960 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1961                                              struct type *,
1962                                              struct dwarf2_cu *);
1963
1964 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1965
1966 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1967
1968 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1969
1970 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1971
1972 static struct using_direct **using_directives (enum language);
1973
1974 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1975
1976 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1977
1978 static struct type *read_module_type (struct die_info *die,
1979                                       struct dwarf2_cu *cu);
1980
1981 static const char *namespace_name (struct die_info *die,
1982                                    int *is_anonymous, struct dwarf2_cu *);
1983
1984 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1985
1986 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1987
1988 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1989                                                        struct dwarf2_cu *);
1990
1991 static struct die_info *read_die_and_siblings_1
1992   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1993    struct die_info *);
1994
1995 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1996                                                const gdb_byte *info_ptr,
1997                                                const gdb_byte **new_info_ptr,
1998                                                struct die_info *parent);
1999
2000 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2001                                         struct die_info **, const gdb_byte *,
2002                                         int *, int);
2003
2004 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2005                                       struct die_info **, const gdb_byte *,
2006                                       int *);
2007
2008 static void process_die (struct die_info *, struct dwarf2_cu *);
2009
2010 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2011                                              struct obstack *);
2012
2013 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2014
2015 static const char *dwarf2_full_name (const char *name,
2016                                      struct die_info *die,
2017                                      struct dwarf2_cu *cu);
2018
2019 static const char *dwarf2_physname (const char *name, struct die_info *die,
2020                                     struct dwarf2_cu *cu);
2021
2022 static struct die_info *dwarf2_extension (struct die_info *die,
2023                                           struct dwarf2_cu **);
2024
2025 static const char *dwarf_tag_name (unsigned int);
2026
2027 static const char *dwarf_attr_name (unsigned int);
2028
2029 static const char *dwarf_form_name (unsigned int);
2030
2031 static const char *dwarf_bool_name (unsigned int);
2032
2033 static const char *dwarf_type_encoding_name (unsigned int);
2034
2035 static struct die_info *sibling_die (struct die_info *);
2036
2037 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2038
2039 static void dump_die_for_error (struct die_info *);
2040
2041 static void dump_die_1 (struct ui_file *, int level, int max_level,
2042                         struct die_info *);
2043
2044 /*static*/ void dump_die (struct die_info *, int max_level);
2045
2046 static void store_in_ref_table (struct die_info *,
2047                                 struct dwarf2_cu *);
2048
2049 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2050
2051 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2052
2053 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2054                                                const struct attribute *,
2055                                                struct dwarf2_cu **);
2056
2057 static struct die_info *follow_die_ref (struct die_info *,
2058                                         const struct attribute *,
2059                                         struct dwarf2_cu **);
2060
2061 static struct die_info *follow_die_sig (struct die_info *,
2062                                         const struct attribute *,
2063                                         struct dwarf2_cu **);
2064
2065 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2066                                          struct dwarf2_cu *);
2067
2068 static struct type *get_DW_AT_signature_type (struct die_info *,
2069                                               const struct attribute *,
2070                                               struct dwarf2_cu *);
2071
2072 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2073
2074 static void read_signatured_type (struct signatured_type *);
2075
2076 static int attr_to_dynamic_prop (const struct attribute *attr,
2077                                  struct die_info *die, struct dwarf2_cu *cu,
2078                                  struct dynamic_prop *prop);
2079
2080 /* memory allocation interface */
2081
2082 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2083
2084 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2085
2086 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2087
2088 static int attr_form_is_block (const struct attribute *);
2089
2090 static int attr_form_is_section_offset (const struct attribute *);
2091
2092 static int attr_form_is_constant (const struct attribute *);
2093
2094 static int attr_form_is_ref (const struct attribute *);
2095
2096 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2097                                    struct dwarf2_loclist_baton *baton,
2098                                    const struct attribute *attr);
2099
2100 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2101                                          struct symbol *sym,
2102                                          struct dwarf2_cu *cu,
2103                                          int is_block);
2104
2105 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2106                                      const gdb_byte *info_ptr,
2107                                      struct abbrev_info *abbrev);
2108
2109 static void free_stack_comp_unit (void *);
2110
2111 static hashval_t partial_die_hash (const void *item);
2112
2113 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2114
2115 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2116   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2117
2118 static void init_one_comp_unit (struct dwarf2_cu *cu,
2119                                 struct dwarf2_per_cu_data *per_cu);
2120
2121 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2122                                    struct die_info *comp_unit_die,
2123                                    enum language pretend_language);
2124
2125 static void free_heap_comp_unit (void *);
2126
2127 static void free_cached_comp_units (void *);
2128
2129 static void age_cached_comp_units (void);
2130
2131 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2132
2133 static struct type *set_die_type (struct die_info *, struct type *,
2134                                   struct dwarf2_cu *);
2135
2136 static void create_all_comp_units (struct objfile *);
2137
2138 static int create_all_type_units (struct objfile *);
2139
2140 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2141                                  enum language);
2142
2143 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2144                                     enum language);
2145
2146 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2147                                     enum language);
2148
2149 static void dwarf2_add_dependence (struct dwarf2_cu *,
2150                                    struct dwarf2_per_cu_data *);
2151
2152 static void dwarf2_mark (struct dwarf2_cu *);
2153
2154 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2155
2156 static struct type *get_die_type_at_offset (sect_offset,
2157                                             struct dwarf2_per_cu_data *);
2158
2159 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2160
2161 static void dwarf2_release_queue (void *dummy);
2162
2163 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2164                              enum language pretend_language);
2165
2166 static void process_queue (void);
2167
2168 /* The return type of find_file_and_directory.  Note, the enclosed
2169    string pointers are only valid while this object is valid.  */
2170
2171 struct file_and_directory
2172 {
2173   /* The filename.  This is never NULL.  */
2174   const char *name;
2175
2176   /* The compilation directory.  NULL if not known.  If we needed to
2177      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2178      points directly to the DW_AT_comp_dir string attribute owned by
2179      the obstack that owns the DIE.  */
2180   const char *comp_dir;
2181
2182   /* If we needed to build a new string for comp_dir, this is what
2183      owns the storage.  */
2184   std::string comp_dir_storage;
2185 };
2186
2187 static file_and_directory find_file_and_directory (struct die_info *die,
2188                                                    struct dwarf2_cu *cu);
2189
2190 static char *file_full_name (int file, struct line_header *lh,
2191                              const char *comp_dir);
2192
2193 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2194 enum class rcuh_kind { COMPILE, TYPE };
2195
2196 static const gdb_byte *read_and_check_comp_unit_head
2197   (struct comp_unit_head *header,
2198    struct dwarf2_section_info *section,
2199    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2200    rcuh_kind section_kind);
2201
2202 static void init_cutu_and_read_dies
2203   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2204    int use_existing_cu, int keep,
2205    die_reader_func_ftype *die_reader_func, void *data);
2206
2207 static void init_cutu_and_read_dies_simple
2208   (struct dwarf2_per_cu_data *this_cu,
2209    die_reader_func_ftype *die_reader_func, void *data);
2210
2211 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2212
2213 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2214
2215 static struct dwo_unit *lookup_dwo_unit_in_dwp
2216   (struct dwp_file *dwp_file, const char *comp_dir,
2217    ULONGEST signature, int is_debug_types);
2218
2219 static struct dwp_file *get_dwp_file (void);
2220
2221 static struct dwo_unit *lookup_dwo_comp_unit
2222   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2223
2224 static struct dwo_unit *lookup_dwo_type_unit
2225   (struct signatured_type *, const char *, const char *);
2226
2227 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2228
2229 static void free_dwo_file_cleanup (void *);
2230
2231 static void process_cu_includes (void);
2232
2233 static void check_producer (struct dwarf2_cu *cu);
2234
2235 static void free_line_header_voidp (void *arg);
2236 \f
2237 /* Various complaints about symbol reading that don't abort the process.  */
2238
2239 static void
2240 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2241 {
2242   complaint (&symfile_complaints,
2243              _("statement list doesn't fit in .debug_line section"));
2244 }
2245
2246 static void
2247 dwarf2_debug_line_missing_file_complaint (void)
2248 {
2249   complaint (&symfile_complaints,
2250              _(".debug_line section has line data without a file"));
2251 }
2252
2253 static void
2254 dwarf2_debug_line_missing_end_sequence_complaint (void)
2255 {
2256   complaint (&symfile_complaints,
2257              _(".debug_line section has line "
2258                "program sequence without an end"));
2259 }
2260
2261 static void
2262 dwarf2_complex_location_expr_complaint (void)
2263 {
2264   complaint (&symfile_complaints, _("location expression too complex"));
2265 }
2266
2267 static void
2268 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2269                                               int arg3)
2270 {
2271   complaint (&symfile_complaints,
2272              _("const value length mismatch for '%s', got %d, expected %d"),
2273              arg1, arg2, arg3);
2274 }
2275
2276 static void
2277 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2278 {
2279   complaint (&symfile_complaints,
2280              _("debug info runs off end of %s section"
2281                " [in module %s]"),
2282              get_section_name (section),
2283              get_section_file_name (section));
2284 }
2285
2286 static void
2287 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2288 {
2289   complaint (&symfile_complaints,
2290              _("macro debug info contains a "
2291                "malformed macro definition:\n`%s'"),
2292              arg1);
2293 }
2294
2295 static void
2296 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2297 {
2298   complaint (&symfile_complaints,
2299              _("invalid attribute class or form for '%s' in '%s'"),
2300              arg1, arg2);
2301 }
2302
2303 /* Hash function for line_header_hash.  */
2304
2305 static hashval_t
2306 line_header_hash (const struct line_header *ofs)
2307 {
2308   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2309 }
2310
2311 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2312
2313 static hashval_t
2314 line_header_hash_voidp (const void *item)
2315 {
2316   const struct line_header *ofs = (const struct line_header *) item;
2317
2318   return line_header_hash (ofs);
2319 }
2320
2321 /* Equality function for line_header_hash.  */
2322
2323 static int
2324 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2325 {
2326   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2327   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2328
2329   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2330           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2331 }
2332
2333 \f
2334
2335 /* Read the given attribute value as an address, taking the attribute's
2336    form into account.  */
2337
2338 static CORE_ADDR
2339 attr_value_as_address (struct attribute *attr)
2340 {
2341   CORE_ADDR addr;
2342
2343   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2344     {
2345       /* Aside from a few clearly defined exceptions, attributes that
2346          contain an address must always be in DW_FORM_addr form.
2347          Unfortunately, some compilers happen to be violating this
2348          requirement by encoding addresses using other forms, such
2349          as DW_FORM_data4 for example.  For those broken compilers,
2350          we try to do our best, without any guarantee of success,
2351          to interpret the address correctly.  It would also be nice
2352          to generate a complaint, but that would require us to maintain
2353          a list of legitimate cases where a non-address form is allowed,
2354          as well as update callers to pass in at least the CU's DWARF
2355          version.  This is more overhead than what we're willing to
2356          expand for a pretty rare case.  */
2357       addr = DW_UNSND (attr);
2358     }
2359   else
2360     addr = DW_ADDR (attr);
2361
2362   return addr;
2363 }
2364
2365 /* The suffix for an index file.  */
2366 #define INDEX4_SUFFIX ".gdb-index"
2367 #define INDEX5_SUFFIX ".debug_names"
2368 #define DEBUG_STR_SUFFIX ".debug_str"
2369
2370 /* See declaration.  */
2371
2372 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2373                                         const dwarf2_debug_sections *names)
2374   : objfile (objfile_)
2375 {
2376   if (names == NULL)
2377     names = &dwarf2_elf_names;
2378
2379   bfd *obfd = objfile->obfd;
2380
2381   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2382     locate_sections (obfd, sec, *names);
2383 }
2384
2385 dwarf2_per_objfile::~dwarf2_per_objfile ()
2386 {
2387   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2388   free_cached_comp_units ();
2389
2390   if (quick_file_names_table)
2391     htab_delete (quick_file_names_table);
2392
2393   if (line_header_hash)
2394     htab_delete (line_header_hash);
2395
2396   /* Everything else should be on the objfile obstack.  */
2397 }
2398
2399 /* See declaration.  */
2400
2401 void
2402 dwarf2_per_objfile::free_cached_comp_units ()
2403 {
2404   dwarf2_per_cu_data *per_cu = read_in_chain;
2405   dwarf2_per_cu_data **last_chain = &read_in_chain;
2406   while (per_cu != NULL)
2407     {
2408       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2409
2410       free_heap_comp_unit (per_cu->cu);
2411       *last_chain = next_cu;
2412       per_cu = next_cu;
2413     }
2414 }
2415
2416 /* Try to locate the sections we need for DWARF 2 debugging
2417    information and return true if we have enough to do something.
2418    NAMES points to the dwarf2 section names, or is NULL if the standard
2419    ELF names are used.  */
2420
2421 int
2422 dwarf2_has_info (struct objfile *objfile,
2423                  const struct dwarf2_debug_sections *names)
2424 {
2425   if (objfile->flags & OBJF_READNEVER)
2426     return 0;
2427
2428   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2429                         objfile_data (objfile, dwarf2_objfile_data_key));
2430   if (!dwarf2_per_objfile)
2431     {
2432       /* Initialize per-objfile state.  */
2433       struct dwarf2_per_objfile *data
2434         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2435
2436       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2437       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2438     }
2439   return (!dwarf2_per_objfile->info.is_virtual
2440           && dwarf2_per_objfile->info.s.section != NULL
2441           && !dwarf2_per_objfile->abbrev.is_virtual
2442           && dwarf2_per_objfile->abbrev.s.section != NULL);
2443 }
2444
2445 /* Return the containing section of virtual section SECTION.  */
2446
2447 static struct dwarf2_section_info *
2448 get_containing_section (const struct dwarf2_section_info *section)
2449 {
2450   gdb_assert (section->is_virtual);
2451   return section->s.containing_section;
2452 }
2453
2454 /* Return the bfd owner of SECTION.  */
2455
2456 static struct bfd *
2457 get_section_bfd_owner (const struct dwarf2_section_info *section)
2458 {
2459   if (section->is_virtual)
2460     {
2461       section = get_containing_section (section);
2462       gdb_assert (!section->is_virtual);
2463     }
2464   return section->s.section->owner;
2465 }
2466
2467 /* Return the bfd section of SECTION.
2468    Returns NULL if the section is not present.  */
2469
2470 static asection *
2471 get_section_bfd_section (const struct dwarf2_section_info *section)
2472 {
2473   if (section->is_virtual)
2474     {
2475       section = get_containing_section (section);
2476       gdb_assert (!section->is_virtual);
2477     }
2478   return section->s.section;
2479 }
2480
2481 /* Return the name of SECTION.  */
2482
2483 static const char *
2484 get_section_name (const struct dwarf2_section_info *section)
2485 {
2486   asection *sectp = get_section_bfd_section (section);
2487
2488   gdb_assert (sectp != NULL);
2489   return bfd_section_name (get_section_bfd_owner (section), sectp);
2490 }
2491
2492 /* Return the name of the file SECTION is in.  */
2493
2494 static const char *
2495 get_section_file_name (const struct dwarf2_section_info *section)
2496 {
2497   bfd *abfd = get_section_bfd_owner (section);
2498
2499   return bfd_get_filename (abfd);
2500 }
2501
2502 /* Return the id of SECTION.
2503    Returns 0 if SECTION doesn't exist.  */
2504
2505 static int
2506 get_section_id (const struct dwarf2_section_info *section)
2507 {
2508   asection *sectp = get_section_bfd_section (section);
2509
2510   if (sectp == NULL)
2511     return 0;
2512   return sectp->id;
2513 }
2514
2515 /* Return the flags of SECTION.
2516    SECTION (or containing section if this is a virtual section) must exist.  */
2517
2518 static int
2519 get_section_flags (const struct dwarf2_section_info *section)
2520 {
2521   asection *sectp = get_section_bfd_section (section);
2522
2523   gdb_assert (sectp != NULL);
2524   return bfd_get_section_flags (sectp->owner, sectp);
2525 }
2526
2527 /* When loading sections, we look either for uncompressed section or for
2528    compressed section names.  */
2529
2530 static int
2531 section_is_p (const char *section_name,
2532               const struct dwarf2_section_names *names)
2533 {
2534   if (names->normal != NULL
2535       && strcmp (section_name, names->normal) == 0)
2536     return 1;
2537   if (names->compressed != NULL
2538       && strcmp (section_name, names->compressed) == 0)
2539     return 1;
2540   return 0;
2541 }
2542
2543 /* See declaration.  */
2544
2545 void
2546 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2547                                      const dwarf2_debug_sections &names)
2548 {
2549   flagword aflag = bfd_get_section_flags (abfd, sectp);
2550
2551   if ((aflag & SEC_HAS_CONTENTS) == 0)
2552     {
2553     }
2554   else if (section_is_p (sectp->name, &names.info))
2555     {
2556       this->info.s.section = sectp;
2557       this->info.size = bfd_get_section_size (sectp);
2558     }
2559   else if (section_is_p (sectp->name, &names.abbrev))
2560     {
2561       this->abbrev.s.section = sectp;
2562       this->abbrev.size = bfd_get_section_size (sectp);
2563     }
2564   else if (section_is_p (sectp->name, &names.line))
2565     {
2566       this->line.s.section = sectp;
2567       this->line.size = bfd_get_section_size (sectp);
2568     }
2569   else if (section_is_p (sectp->name, &names.loc))
2570     {
2571       this->loc.s.section = sectp;
2572       this->loc.size = bfd_get_section_size (sectp);
2573     }
2574   else if (section_is_p (sectp->name, &names.loclists))
2575     {
2576       this->loclists.s.section = sectp;
2577       this->loclists.size = bfd_get_section_size (sectp);
2578     }
2579   else if (section_is_p (sectp->name, &names.macinfo))
2580     {
2581       this->macinfo.s.section = sectp;
2582       this->macinfo.size = bfd_get_section_size (sectp);
2583     }
2584   else if (section_is_p (sectp->name, &names.macro))
2585     {
2586       this->macro.s.section = sectp;
2587       this->macro.size = bfd_get_section_size (sectp);
2588     }
2589   else if (section_is_p (sectp->name, &names.str))
2590     {
2591       this->str.s.section = sectp;
2592       this->str.size = bfd_get_section_size (sectp);
2593     }
2594   else if (section_is_p (sectp->name, &names.line_str))
2595     {
2596       this->line_str.s.section = sectp;
2597       this->line_str.size = bfd_get_section_size (sectp);
2598     }
2599   else if (section_is_p (sectp->name, &names.addr))
2600     {
2601       this->addr.s.section = sectp;
2602       this->addr.size = bfd_get_section_size (sectp);
2603     }
2604   else if (section_is_p (sectp->name, &names.frame))
2605     {
2606       this->frame.s.section = sectp;
2607       this->frame.size = bfd_get_section_size (sectp);
2608     }
2609   else if (section_is_p (sectp->name, &names.eh_frame))
2610     {
2611       this->eh_frame.s.section = sectp;
2612       this->eh_frame.size = bfd_get_section_size (sectp);
2613     }
2614   else if (section_is_p (sectp->name, &names.ranges))
2615     {
2616       this->ranges.s.section = sectp;
2617       this->ranges.size = bfd_get_section_size (sectp);
2618     }
2619   else if (section_is_p (sectp->name, &names.rnglists))
2620     {
2621       this->rnglists.s.section = sectp;
2622       this->rnglists.size = bfd_get_section_size (sectp);
2623     }
2624   else if (section_is_p (sectp->name, &names.types))
2625     {
2626       struct dwarf2_section_info type_section;
2627
2628       memset (&type_section, 0, sizeof (type_section));
2629       type_section.s.section = sectp;
2630       type_section.size = bfd_get_section_size (sectp);
2631
2632       VEC_safe_push (dwarf2_section_info_def, this->types,
2633                      &type_section);
2634     }
2635   else if (section_is_p (sectp->name, &names.gdb_index))
2636     {
2637       this->gdb_index.s.section = sectp;
2638       this->gdb_index.size = bfd_get_section_size (sectp);
2639     }
2640   else if (section_is_p (sectp->name, &names.debug_names))
2641     {
2642       this->debug_names.s.section = sectp;
2643       this->debug_names.size = bfd_get_section_size (sectp);
2644     }
2645   else if (section_is_p (sectp->name, &names.debug_aranges))
2646     {
2647       this->debug_aranges.s.section = sectp;
2648       this->debug_aranges.size = bfd_get_section_size (sectp);
2649     }
2650
2651   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2652       && bfd_section_vma (abfd, sectp) == 0)
2653     this->has_section_at_zero = true;
2654 }
2655
2656 /* A helper function that decides whether a section is empty,
2657    or not present.  */
2658
2659 static int
2660 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2661 {
2662   if (section->is_virtual)
2663     return section->size == 0;
2664   return section->s.section == NULL || section->size == 0;
2665 }
2666
2667 /* Read the contents of the section INFO.
2668    OBJFILE is the main object file, but not necessarily the file where
2669    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2670    of the DWO file.
2671    If the section is compressed, uncompress it before returning.  */
2672
2673 static void
2674 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2675 {
2676   asection *sectp;
2677   bfd *abfd;
2678   gdb_byte *buf, *retbuf;
2679
2680   if (info->readin)
2681     return;
2682   info->buffer = NULL;
2683   info->readin = 1;
2684
2685   if (dwarf2_section_empty_p (info))
2686     return;
2687
2688   sectp = get_section_bfd_section (info);
2689
2690   /* If this is a virtual section we need to read in the real one first.  */
2691   if (info->is_virtual)
2692     {
2693       struct dwarf2_section_info *containing_section =
2694         get_containing_section (info);
2695
2696       gdb_assert (sectp != NULL);
2697       if ((sectp->flags & SEC_RELOC) != 0)
2698         {
2699           error (_("Dwarf Error: DWP format V2 with relocations is not"
2700                    " supported in section %s [in module %s]"),
2701                  get_section_name (info), get_section_file_name (info));
2702         }
2703       dwarf2_read_section (objfile, containing_section);
2704       /* Other code should have already caught virtual sections that don't
2705          fit.  */
2706       gdb_assert (info->virtual_offset + info->size
2707                   <= containing_section->size);
2708       /* If the real section is empty or there was a problem reading the
2709          section we shouldn't get here.  */
2710       gdb_assert (containing_section->buffer != NULL);
2711       info->buffer = containing_section->buffer + info->virtual_offset;
2712       return;
2713     }
2714
2715   /* If the section has relocations, we must read it ourselves.
2716      Otherwise we attach it to the BFD.  */
2717   if ((sectp->flags & SEC_RELOC) == 0)
2718     {
2719       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2720       return;
2721     }
2722
2723   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2724   info->buffer = buf;
2725
2726   /* When debugging .o files, we may need to apply relocations; see
2727      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2728      We never compress sections in .o files, so we only need to
2729      try this when the section is not compressed.  */
2730   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2731   if (retbuf != NULL)
2732     {
2733       info->buffer = retbuf;
2734       return;
2735     }
2736
2737   abfd = get_section_bfd_owner (info);
2738   gdb_assert (abfd != NULL);
2739
2740   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2741       || bfd_bread (buf, info->size, abfd) != info->size)
2742     {
2743       error (_("Dwarf Error: Can't read DWARF data"
2744                " in section %s [in module %s]"),
2745              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2746     }
2747 }
2748
2749 /* A helper function that returns the size of a section in a safe way.
2750    If you are positive that the section has been read before using the
2751    size, then it is safe to refer to the dwarf2_section_info object's
2752    "size" field directly.  In other cases, you must call this
2753    function, because for compressed sections the size field is not set
2754    correctly until the section has been read.  */
2755
2756 static bfd_size_type
2757 dwarf2_section_size (struct objfile *objfile,
2758                      struct dwarf2_section_info *info)
2759 {
2760   if (!info->readin)
2761     dwarf2_read_section (objfile, info);
2762   return info->size;
2763 }
2764
2765 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2766    SECTION_NAME.  */
2767
2768 void
2769 dwarf2_get_section_info (struct objfile *objfile,
2770                          enum dwarf2_section_enum sect,
2771                          asection **sectp, const gdb_byte **bufp,
2772                          bfd_size_type *sizep)
2773 {
2774   struct dwarf2_per_objfile *data
2775     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2776                                                   dwarf2_objfile_data_key);
2777   struct dwarf2_section_info *info;
2778
2779   /* We may see an objfile without any DWARF, in which case we just
2780      return nothing.  */
2781   if (data == NULL)
2782     {
2783       *sectp = NULL;
2784       *bufp = NULL;
2785       *sizep = 0;
2786       return;
2787     }
2788   switch (sect)
2789     {
2790     case DWARF2_DEBUG_FRAME:
2791       info = &data->frame;
2792       break;
2793     case DWARF2_EH_FRAME:
2794       info = &data->eh_frame;
2795       break;
2796     default:
2797       gdb_assert_not_reached ("unexpected section");
2798     }
2799
2800   dwarf2_read_section (objfile, info);
2801
2802   *sectp = get_section_bfd_section (info);
2803   *bufp = info->buffer;
2804   *sizep = info->size;
2805 }
2806
2807 /* A helper function to find the sections for a .dwz file.  */
2808
2809 static void
2810 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2811 {
2812   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2813
2814   /* Note that we only support the standard ELF names, because .dwz
2815      is ELF-only (at the time of writing).  */
2816   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2817     {
2818       dwz_file->abbrev.s.section = sectp;
2819       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2820     }
2821   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2822     {
2823       dwz_file->info.s.section = sectp;
2824       dwz_file->info.size = bfd_get_section_size (sectp);
2825     }
2826   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2827     {
2828       dwz_file->str.s.section = sectp;
2829       dwz_file->str.size = bfd_get_section_size (sectp);
2830     }
2831   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2832     {
2833       dwz_file->line.s.section = sectp;
2834       dwz_file->line.size = bfd_get_section_size (sectp);
2835     }
2836   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2837     {
2838       dwz_file->macro.s.section = sectp;
2839       dwz_file->macro.size = bfd_get_section_size (sectp);
2840     }
2841   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2842     {
2843       dwz_file->gdb_index.s.section = sectp;
2844       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2845     }
2846   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2847     {
2848       dwz_file->debug_names.s.section = sectp;
2849       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2850     }
2851 }
2852
2853 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2854    there is no .gnu_debugaltlink section in the file.  Error if there
2855    is such a section but the file cannot be found.  */
2856
2857 static struct dwz_file *
2858 dwarf2_get_dwz_file (void)
2859 {
2860   const char *filename;
2861   struct dwz_file *result;
2862   bfd_size_type buildid_len_arg;
2863   size_t buildid_len;
2864   bfd_byte *buildid;
2865
2866   if (dwarf2_per_objfile->dwz_file != NULL)
2867     return dwarf2_per_objfile->dwz_file;
2868
2869   bfd_set_error (bfd_error_no_error);
2870   gdb::unique_xmalloc_ptr<char> data
2871     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2872                                   &buildid_len_arg, &buildid));
2873   if (data == NULL)
2874     {
2875       if (bfd_get_error () == bfd_error_no_error)
2876         return NULL;
2877       error (_("could not read '.gnu_debugaltlink' section: %s"),
2878              bfd_errmsg (bfd_get_error ()));
2879     }
2880
2881   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2882
2883   buildid_len = (size_t) buildid_len_arg;
2884
2885   filename = data.get ();
2886
2887   std::string abs_storage;
2888   if (!IS_ABSOLUTE_PATH (filename))
2889     {
2890       gdb::unique_xmalloc_ptr<char> abs
2891         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2892
2893       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2894       filename = abs_storage.c_str ();
2895     }
2896
2897   /* First try the file name given in the section.  If that doesn't
2898      work, try to use the build-id instead.  */
2899   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2900   if (dwz_bfd != NULL)
2901     {
2902       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2903         dwz_bfd.release ();
2904     }
2905
2906   if (dwz_bfd == NULL)
2907     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2908
2909   if (dwz_bfd == NULL)
2910     error (_("could not find '.gnu_debugaltlink' file for %s"),
2911            objfile_name (dwarf2_per_objfile->objfile));
2912
2913   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2914                            struct dwz_file);
2915   result->dwz_bfd = dwz_bfd.release ();
2916
2917   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2918
2919   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2920   dwarf2_per_objfile->dwz_file = result;
2921   return result;
2922 }
2923 \f
2924 /* DWARF quick_symbols_functions support.  */
2925
2926 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2927    unique line tables, so we maintain a separate table of all .debug_line
2928    derived entries to support the sharing.
2929    All the quick functions need is the list of file names.  We discard the
2930    line_header when we're done and don't need to record it here.  */
2931 struct quick_file_names
2932 {
2933   /* The data used to construct the hash key.  */
2934   struct stmt_list_hash hash;
2935
2936   /* The number of entries in file_names, real_names.  */
2937   unsigned int num_file_names;
2938
2939   /* The file names from the line table, after being run through
2940      file_full_name.  */
2941   const char **file_names;
2942
2943   /* The file names from the line table after being run through
2944      gdb_realpath.  These are computed lazily.  */
2945   const char **real_names;
2946 };
2947
2948 /* When using the index (and thus not using psymtabs), each CU has an
2949    object of this type.  This is used to hold information needed by
2950    the various "quick" methods.  */
2951 struct dwarf2_per_cu_quick_data
2952 {
2953   /* The file table.  This can be NULL if there was no file table
2954      or it's currently not read in.
2955      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2956   struct quick_file_names *file_names;
2957
2958   /* The corresponding symbol table.  This is NULL if symbols for this
2959      CU have not yet been read.  */
2960   struct compunit_symtab *compunit_symtab;
2961
2962   /* A temporary mark bit used when iterating over all CUs in
2963      expand_symtabs_matching.  */
2964   unsigned int mark : 1;
2965
2966   /* True if we've tried to read the file table and found there isn't one.
2967      There will be no point in trying to read it again next time.  */
2968   unsigned int no_file_data : 1;
2969 };
2970
2971 /* Utility hash function for a stmt_list_hash.  */
2972
2973 static hashval_t
2974 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2975 {
2976   hashval_t v = 0;
2977
2978   if (stmt_list_hash->dwo_unit != NULL)
2979     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2980   v += to_underlying (stmt_list_hash->line_sect_off);
2981   return v;
2982 }
2983
2984 /* Utility equality function for a stmt_list_hash.  */
2985
2986 static int
2987 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2988                     const struct stmt_list_hash *rhs)
2989 {
2990   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2991     return 0;
2992   if (lhs->dwo_unit != NULL
2993       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2994     return 0;
2995
2996   return lhs->line_sect_off == rhs->line_sect_off;
2997 }
2998
2999 /* Hash function for a quick_file_names.  */
3000
3001 static hashval_t
3002 hash_file_name_entry (const void *e)
3003 {
3004   const struct quick_file_names *file_data
3005     = (const struct quick_file_names *) e;
3006
3007   return hash_stmt_list_entry (&file_data->hash);
3008 }
3009
3010 /* Equality function for a quick_file_names.  */
3011
3012 static int
3013 eq_file_name_entry (const void *a, const void *b)
3014 {
3015   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3016   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3017
3018   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3019 }
3020
3021 /* Delete function for a quick_file_names.  */
3022
3023 static void
3024 delete_file_name_entry (void *e)
3025 {
3026   struct quick_file_names *file_data = (struct quick_file_names *) e;
3027   int i;
3028
3029   for (i = 0; i < file_data->num_file_names; ++i)
3030     {
3031       xfree ((void*) file_data->file_names[i]);
3032       if (file_data->real_names)
3033         xfree ((void*) file_data->real_names[i]);
3034     }
3035
3036   /* The space for the struct itself lives on objfile_obstack,
3037      so we don't free it here.  */
3038 }
3039
3040 /* Create a quick_file_names hash table.  */
3041
3042 static htab_t
3043 create_quick_file_names_table (unsigned int nr_initial_entries)
3044 {
3045   return htab_create_alloc (nr_initial_entries,
3046                             hash_file_name_entry, eq_file_name_entry,
3047                             delete_file_name_entry, xcalloc, xfree);
3048 }
3049
3050 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3051    have to be created afterwards.  You should call age_cached_comp_units after
3052    processing PER_CU->CU.  dw2_setup must have been already called.  */
3053
3054 static void
3055 load_cu (struct dwarf2_per_cu_data *per_cu)
3056 {
3057   if (per_cu->is_debug_types)
3058     load_full_type_unit (per_cu);
3059   else
3060     load_full_comp_unit (per_cu, language_minimal);
3061
3062   if (per_cu->cu == NULL)
3063     return;  /* Dummy CU.  */
3064
3065   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3066 }
3067
3068 /* Read in the symbols for PER_CU.  */
3069
3070 static void
3071 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3072 {
3073   struct cleanup *back_to;
3074
3075   /* Skip type_unit_groups, reading the type units they contain
3076      is handled elsewhere.  */
3077   if (IS_TYPE_UNIT_GROUP (per_cu))
3078     return;
3079
3080   back_to = make_cleanup (dwarf2_release_queue, NULL);
3081
3082   if (dwarf2_per_objfile->using_index
3083       ? per_cu->v.quick->compunit_symtab == NULL
3084       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3085     {
3086       queue_comp_unit (per_cu, language_minimal);
3087       load_cu (per_cu);
3088
3089       /* If we just loaded a CU from a DWO, and we're working with an index
3090          that may badly handle TUs, load all the TUs in that DWO as well.
3091          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3092       if (!per_cu->is_debug_types
3093           && per_cu->cu != NULL
3094           && per_cu->cu->dwo_unit != NULL
3095           && dwarf2_per_objfile->index_table != NULL
3096           && dwarf2_per_objfile->index_table->version <= 7
3097           /* DWP files aren't supported yet.  */
3098           && get_dwp_file () == NULL)
3099         queue_and_load_all_dwo_tus (per_cu);
3100     }
3101
3102   process_queue ();
3103
3104   /* Age the cache, releasing compilation units that have not
3105      been used recently.  */
3106   age_cached_comp_units ();
3107
3108   do_cleanups (back_to);
3109 }
3110
3111 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3112    the objfile from which this CU came.  Returns the resulting symbol
3113    table.  */
3114
3115 static struct compunit_symtab *
3116 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3117 {
3118   gdb_assert (dwarf2_per_objfile->using_index);
3119   if (!per_cu->v.quick->compunit_symtab)
3120     {
3121       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
3122       scoped_restore decrementer = increment_reading_symtab ();
3123       dw2_do_instantiate_symtab (per_cu);
3124       process_cu_includes ();
3125       do_cleanups (back_to);
3126     }
3127
3128   return per_cu->v.quick->compunit_symtab;
3129 }
3130
3131 /* Return the CU/TU given its index.
3132
3133    This is intended for loops like:
3134
3135    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3136                     + dwarf2_per_objfile->n_type_units); ++i)
3137      {
3138        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3139
3140        ...;
3141      }
3142 */
3143
3144 static struct dwarf2_per_cu_data *
3145 dw2_get_cutu (int index)
3146 {
3147   if (index >= dwarf2_per_objfile->n_comp_units)
3148     {
3149       index -= dwarf2_per_objfile->n_comp_units;
3150       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3151       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3152     }
3153
3154   return dwarf2_per_objfile->all_comp_units[index];
3155 }
3156
3157 /* Return the CU given its index.
3158    This differs from dw2_get_cutu in that it's for when you know INDEX
3159    refers to a CU.  */
3160
3161 static struct dwarf2_per_cu_data *
3162 dw2_get_cu (int index)
3163 {
3164   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3165
3166   return dwarf2_per_objfile->all_comp_units[index];
3167 }
3168
3169 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3170    objfile_obstack, and constructed with the specified field
3171    values.  */
3172
3173 static dwarf2_per_cu_data *
3174 create_cu_from_index_list (struct objfile *objfile,
3175                           struct dwarf2_section_info *section,
3176                           int is_dwz,
3177                           sect_offset sect_off, ULONGEST length)
3178 {
3179   dwarf2_per_cu_data *the_cu
3180     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3181                      struct dwarf2_per_cu_data);
3182   the_cu->sect_off = sect_off;
3183   the_cu->length = length;
3184   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3185   the_cu->section = section;
3186   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3187                                    struct dwarf2_per_cu_quick_data);
3188   the_cu->is_dwz = is_dwz;
3189   return the_cu;
3190 }
3191
3192 /* A helper for create_cus_from_index that handles a given list of
3193    CUs.  */
3194
3195 static void
3196 create_cus_from_index_list (struct objfile *objfile,
3197                             const gdb_byte *cu_list, offset_type n_elements,
3198                             struct dwarf2_section_info *section,
3199                             int is_dwz,
3200                             int base_offset)
3201 {
3202   offset_type i;
3203
3204   for (i = 0; i < n_elements; i += 2)
3205     {
3206       gdb_static_assert (sizeof (ULONGEST) >= 8);
3207
3208       sect_offset sect_off
3209         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3210       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3211       cu_list += 2 * 8;
3212
3213       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3214         = create_cu_from_index_list (objfile, section, is_dwz, sect_off, length);
3215     }
3216 }
3217
3218 /* Read the CU list from the mapped index, and use it to create all
3219    the CU objects for this objfile.  */
3220
3221 static void
3222 create_cus_from_index (struct objfile *objfile,
3223                        const gdb_byte *cu_list, offset_type cu_list_elements,
3224                        const gdb_byte *dwz_list, offset_type dwz_elements)
3225 {
3226   struct dwz_file *dwz;
3227
3228   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3229   dwarf2_per_objfile->all_comp_units =
3230     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3231                dwarf2_per_objfile->n_comp_units);
3232
3233   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3234                               &dwarf2_per_objfile->info, 0, 0);
3235
3236   if (dwz_elements == 0)
3237     return;
3238
3239   dwz = dwarf2_get_dwz_file ();
3240   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3241                               cu_list_elements / 2);
3242 }
3243
3244 /* Create the signatured type hash table from the index.  */
3245
3246 static void
3247 create_signatured_type_table_from_index (struct objfile *objfile,
3248                                          struct dwarf2_section_info *section,
3249                                          const gdb_byte *bytes,
3250                                          offset_type elements)
3251 {
3252   offset_type i;
3253   htab_t sig_types_hash;
3254
3255   dwarf2_per_objfile->n_type_units
3256     = dwarf2_per_objfile->n_allocated_type_units
3257     = elements / 3;
3258   dwarf2_per_objfile->all_type_units =
3259     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3260
3261   sig_types_hash = allocate_signatured_type_table (objfile);
3262
3263   for (i = 0; i < elements; i += 3)
3264     {
3265       struct signatured_type *sig_type;
3266       ULONGEST signature;
3267       void **slot;
3268       cu_offset type_offset_in_tu;
3269
3270       gdb_static_assert (sizeof (ULONGEST) >= 8);
3271       sect_offset sect_off
3272         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3273       type_offset_in_tu
3274         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3275                                                 BFD_ENDIAN_LITTLE);
3276       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3277       bytes += 3 * 8;
3278
3279       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3280                                  struct signatured_type);
3281       sig_type->signature = signature;
3282       sig_type->type_offset_in_tu = type_offset_in_tu;
3283       sig_type->per_cu.is_debug_types = 1;
3284       sig_type->per_cu.section = section;
3285       sig_type->per_cu.sect_off = sect_off;
3286       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3287       sig_type->per_cu.v.quick
3288         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3289                           struct dwarf2_per_cu_quick_data);
3290
3291       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3292       *slot = sig_type;
3293
3294       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3295     }
3296
3297   dwarf2_per_objfile->signatured_types = sig_types_hash;
3298 }
3299
3300 /* Create the signatured type hash table from .debug_names.  */
3301
3302 static void
3303 create_signatured_type_table_from_debug_names
3304   (struct objfile *objfile,
3305    const mapped_debug_names &map,
3306    struct dwarf2_section_info *section,
3307    struct dwarf2_section_info *abbrev_section)
3308 {
3309   dwarf2_read_section (objfile, section);
3310   dwarf2_read_section (objfile, abbrev_section);
3311
3312   dwarf2_per_objfile->n_type_units
3313     = dwarf2_per_objfile->n_allocated_type_units
3314     = map.tu_count;
3315   dwarf2_per_objfile->all_type_units
3316     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3317
3318   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3319
3320   for (uint32_t i = 0; i < map.tu_count; ++i)
3321     {
3322       struct signatured_type *sig_type;
3323       ULONGEST signature;
3324       void **slot;
3325       cu_offset type_offset_in_tu;
3326
3327       sect_offset sect_off
3328         = (sect_offset) (extract_unsigned_integer
3329                          (map.tu_table_reordered + i * map.offset_size,
3330                           map.offset_size,
3331                           map.dwarf5_byte_order));
3332
3333       comp_unit_head cu_header;
3334       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
3335                                      section->buffer + to_underlying (sect_off),
3336                                      rcuh_kind::TYPE);
3337
3338       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3339                                  struct signatured_type);
3340       sig_type->signature = cu_header.signature;
3341       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3342       sig_type->per_cu.is_debug_types = 1;
3343       sig_type->per_cu.section = section;
3344       sig_type->per_cu.sect_off = sect_off;
3345       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3346       sig_type->per_cu.v.quick
3347         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3348                           struct dwarf2_per_cu_quick_data);
3349
3350       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3351       *slot = sig_type;
3352
3353       dwarf2_per_objfile->all_type_units[i] = sig_type;
3354     }
3355
3356   dwarf2_per_objfile->signatured_types = sig_types_hash;
3357 }
3358
3359 /* Read the address map data from the mapped index, and use it to
3360    populate the objfile's psymtabs_addrmap.  */
3361
3362 static void
3363 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3364 {
3365   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3366   const gdb_byte *iter, *end;
3367   struct addrmap *mutable_map;
3368   CORE_ADDR baseaddr;
3369
3370   auto_obstack temp_obstack;
3371
3372   mutable_map = addrmap_create_mutable (&temp_obstack);
3373
3374   iter = index->address_table.data ();
3375   end = iter + index->address_table.size ();
3376
3377   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3378
3379   while (iter < end)
3380     {
3381       ULONGEST hi, lo, cu_index;
3382       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3383       iter += 8;
3384       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3385       iter += 8;
3386       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3387       iter += 4;
3388
3389       if (lo > hi)
3390         {
3391           complaint (&symfile_complaints,
3392                      _(".gdb_index address table has invalid range (%s - %s)"),
3393                      hex_string (lo), hex_string (hi));
3394           continue;
3395         }
3396
3397       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3398         {
3399           complaint (&symfile_complaints,
3400                      _(".gdb_index address table has invalid CU number %u"),
3401                      (unsigned) cu_index);
3402           continue;
3403         }
3404
3405       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3406       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3407       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3408     }
3409
3410   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3411                                                     &objfile->objfile_obstack);
3412 }
3413
3414 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3415    populate the objfile's psymtabs_addrmap.  */
3416
3417 static void
3418 create_addrmap_from_aranges (struct objfile *objfile,
3419                              struct dwarf2_section_info *section)
3420 {
3421   bfd *abfd = objfile->obfd;
3422   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3423   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3424                                        SECT_OFF_TEXT (objfile));
3425
3426   auto_obstack temp_obstack;
3427   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3428
3429   std::unordered_map<sect_offset,
3430                      dwarf2_per_cu_data *,
3431                      gdb::hash_enum<sect_offset>>
3432     debug_info_offset_to_per_cu;
3433   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3434     {
3435       dwarf2_per_cu_data *per_cu = dw2_get_cutu (cui);
3436       const auto insertpair
3437         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3438       if (!insertpair.second)
3439         {
3440           warning (_("Section .debug_aranges in %s has duplicate "
3441                      "debug_info_offset %u, ignoring .debug_aranges."),
3442                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3443           return;
3444         }
3445     }
3446
3447   dwarf2_read_section (objfile, section);
3448
3449   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3450
3451   const gdb_byte *addr = section->buffer;
3452
3453   while (addr < section->buffer + section->size)
3454     {
3455       const gdb_byte *const entry_addr = addr;
3456       unsigned int bytes_read;
3457
3458       const LONGEST entry_length = read_initial_length (abfd, addr,
3459                                                         &bytes_read);
3460       addr += bytes_read;
3461
3462       const gdb_byte *const entry_end = addr + entry_length;
3463       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3464       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3465       if (addr + entry_length > section->buffer + section->size)
3466         {
3467           warning (_("Section .debug_aranges in %s entry at offset %zu "
3468                      "length %s exceeds section length %s, "
3469                      "ignoring .debug_aranges."),
3470                    objfile_name (objfile), entry_addr - section->buffer,
3471                    plongest (bytes_read + entry_length),
3472                    pulongest (section->size));
3473           return;
3474         }
3475
3476       /* The version number.  */
3477       const uint16_t version = read_2_bytes (abfd, addr);
3478       addr += 2;
3479       if (version != 2)
3480         {
3481           warning (_("Section .debug_aranges in %s entry at offset %zu "
3482                      "has unsupported version %d, ignoring .debug_aranges."),
3483                    objfile_name (objfile), entry_addr - section->buffer,
3484                    version);
3485           return;
3486         }
3487
3488       const uint64_t debug_info_offset
3489         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3490       addr += offset_size;
3491       const auto per_cu_it
3492         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3493       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3494         {
3495           warning (_("Section .debug_aranges in %s entry at offset %zu "
3496                      "debug_info_offset %s does not exists, "
3497                      "ignoring .debug_aranges."),
3498                    objfile_name (objfile), entry_addr - section->buffer,
3499                    pulongest (debug_info_offset));
3500           return;
3501         }
3502       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3503
3504       const uint8_t address_size = *addr++;
3505       if (address_size < 1 || address_size > 8)
3506         {
3507           warning (_("Section .debug_aranges in %s entry at offset %zu "
3508                      "address_size %u is invalid, ignoring .debug_aranges."),
3509                    objfile_name (objfile), entry_addr - section->buffer,
3510                    address_size);
3511           return;
3512         }
3513
3514       const uint8_t segment_selector_size = *addr++;
3515       if (segment_selector_size != 0)
3516         {
3517           warning (_("Section .debug_aranges in %s entry at offset %zu "
3518                      "segment_selector_size %u is not supported, "
3519                      "ignoring .debug_aranges."),
3520                    objfile_name (objfile), entry_addr - section->buffer,
3521                    segment_selector_size);
3522           return;
3523         }
3524
3525       /* Must pad to an alignment boundary that is twice the address
3526          size.  It is undocumented by the DWARF standard but GCC does
3527          use it.  */
3528       for (size_t padding = ((-(addr - section->buffer))
3529                              & (2 * address_size - 1));
3530            padding > 0; padding--)
3531         if (*addr++ != 0)
3532           {
3533             warning (_("Section .debug_aranges in %s entry at offset %zu "
3534                        "padding is not zero, ignoring .debug_aranges."),
3535                      objfile_name (objfile), entry_addr - section->buffer);
3536             return;
3537           }
3538
3539       for (;;)
3540         {
3541           if (addr + 2 * address_size > entry_end)
3542             {
3543               warning (_("Section .debug_aranges in %s entry at offset %zu "
3544                          "address list is not properly terminated, "
3545                          "ignoring .debug_aranges."),
3546                        objfile_name (objfile), entry_addr - section->buffer);
3547               return;
3548             }
3549           ULONGEST start = extract_unsigned_integer (addr, address_size,
3550                                                      dwarf5_byte_order);
3551           addr += address_size;
3552           ULONGEST length = extract_unsigned_integer (addr, address_size,
3553                                                       dwarf5_byte_order);
3554           addr += address_size;
3555           if (start == 0 && length == 0)
3556             break;
3557           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3558             {
3559               /* Symbol was eliminated due to a COMDAT group.  */
3560               continue;
3561             }
3562           ULONGEST end = start + length;
3563           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3564           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3565           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3566         }
3567     }
3568
3569   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3570                                                     &objfile->objfile_obstack);
3571 }
3572
3573 /* The hash function for strings in the mapped index.  This is the same as
3574    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3575    implementation.  This is necessary because the hash function is tied to the
3576    format of the mapped index file.  The hash values do not have to match with
3577    SYMBOL_HASH_NEXT.
3578    
3579    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3580
3581 static hashval_t
3582 mapped_index_string_hash (int index_version, const void *p)
3583 {
3584   const unsigned char *str = (const unsigned char *) p;
3585   hashval_t r = 0;
3586   unsigned char c;
3587
3588   while ((c = *str++) != 0)
3589     {
3590       if (index_version >= 5)
3591         c = tolower (c);
3592       r = r * 67 + c - 113;
3593     }
3594
3595   return r;
3596 }
3597
3598 /* Find a slot in the mapped index INDEX for the object named NAME.
3599    If NAME is found, set *VEC_OUT to point to the CU vector in the
3600    constant pool and return true.  If NAME cannot be found, return
3601    false.  */
3602
3603 static bool
3604 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3605                           offset_type **vec_out)
3606 {
3607   offset_type hash;
3608   offset_type slot, step;
3609   int (*cmp) (const char *, const char *);
3610
3611   gdb::unique_xmalloc_ptr<char> without_params;
3612   if (current_language->la_language == language_cplus
3613       || current_language->la_language == language_fortran
3614       || current_language->la_language == language_d)
3615     {
3616       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3617          not contain any.  */
3618
3619       if (strchr (name, '(') != NULL)
3620         {
3621           without_params = cp_remove_params (name);
3622
3623           if (without_params != NULL)
3624             name = without_params.get ();
3625         }
3626     }
3627
3628   /* Index version 4 did not support case insensitive searches.  But the
3629      indices for case insensitive languages are built in lowercase, therefore
3630      simulate our NAME being searched is also lowercased.  */
3631   hash = mapped_index_string_hash ((index->version == 4
3632                                     && case_sensitivity == case_sensitive_off
3633                                     ? 5 : index->version),
3634                                    name);
3635
3636   slot = hash & (index->symbol_table.size () - 1);
3637   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3638   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3639
3640   for (;;)
3641     {
3642       const char *str;
3643
3644       const auto &bucket = index->symbol_table[slot];
3645       if (bucket.name == 0 && bucket.vec == 0)
3646         return false;
3647
3648       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3649       if (!cmp (name, str))
3650         {
3651           *vec_out = (offset_type *) (index->constant_pool
3652                                       + MAYBE_SWAP (bucket.vec));
3653           return true;
3654         }
3655
3656       slot = (slot + step) & (index->symbol_table.size () - 1);
3657     }
3658 }
3659
3660 /* A helper function that reads the .gdb_index from SECTION and fills
3661    in MAP.  FILENAME is the name of the file containing the section;
3662    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3663    ok to use deprecated sections.
3664
3665    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3666    out parameters that are filled in with information about the CU and
3667    TU lists in the section.
3668
3669    Returns 1 if all went well, 0 otherwise.  */
3670
3671 static int
3672 read_index_from_section (struct objfile *objfile,
3673                          const char *filename,
3674                          int deprecated_ok,
3675                          struct dwarf2_section_info *section,
3676                          struct mapped_index *map,
3677                          const gdb_byte **cu_list,
3678                          offset_type *cu_list_elements,
3679                          const gdb_byte **types_list,
3680                          offset_type *types_list_elements)
3681 {
3682   const gdb_byte *addr;
3683   offset_type version;
3684   offset_type *metadata;
3685   int i;
3686
3687   if (dwarf2_section_empty_p (section))
3688     return 0;
3689
3690   /* Older elfutils strip versions could keep the section in the main
3691      executable while splitting it for the separate debug info file.  */
3692   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3693     return 0;
3694
3695   dwarf2_read_section (objfile, section);
3696
3697   addr = section->buffer;
3698   /* Version check.  */
3699   version = MAYBE_SWAP (*(offset_type *) addr);
3700   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3701      causes the index to behave very poorly for certain requests.  Version 3
3702      contained incomplete addrmap.  So, it seems better to just ignore such
3703      indices.  */
3704   if (version < 4)
3705     {
3706       static int warning_printed = 0;
3707       if (!warning_printed)
3708         {
3709           warning (_("Skipping obsolete .gdb_index section in %s."),
3710                    filename);
3711           warning_printed = 1;
3712         }
3713       return 0;
3714     }
3715   /* Index version 4 uses a different hash function than index version
3716      5 and later.
3717
3718      Versions earlier than 6 did not emit psymbols for inlined
3719      functions.  Using these files will cause GDB not to be able to
3720      set breakpoints on inlined functions by name, so we ignore these
3721      indices unless the user has done
3722      "set use-deprecated-index-sections on".  */
3723   if (version < 6 && !deprecated_ok)
3724     {
3725       static int warning_printed = 0;
3726       if (!warning_printed)
3727         {
3728           warning (_("\
3729 Skipping deprecated .gdb_index section in %s.\n\
3730 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3731 to use the section anyway."),
3732                    filename);
3733           warning_printed = 1;
3734         }
3735       return 0;
3736     }
3737   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3738      of the TU (for symbols coming from TUs),
3739      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3740      Plus gold-generated indices can have duplicate entries for global symbols,
3741      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3742      These are just performance bugs, and we can't distinguish gdb-generated
3743      indices from gold-generated ones, so issue no warning here.  */
3744
3745   /* Indexes with higher version than the one supported by GDB may be no
3746      longer backward compatible.  */
3747   if (version > 8)
3748     return 0;
3749
3750   map->version = version;
3751   map->total_size = section->size;
3752
3753   metadata = (offset_type *) (addr + sizeof (offset_type));
3754
3755   i = 0;
3756   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3757   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3758                        / 8);
3759   ++i;
3760
3761   *types_list = addr + MAYBE_SWAP (metadata[i]);
3762   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3763                            - MAYBE_SWAP (metadata[i]))
3764                           / 8);
3765   ++i;
3766
3767   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3768   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3769   map->address_table
3770     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3771   ++i;
3772
3773   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3774   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3775   map->symbol_table
3776     = gdb::array_view<mapped_index::symbol_table_slot>
3777        ((mapped_index::symbol_table_slot *) symbol_table,
3778         (mapped_index::symbol_table_slot *) symbol_table_end);
3779
3780   ++i;
3781   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3782
3783   return 1;
3784 }
3785
3786 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3787    elements of all the CUs and return 1.  Otherwise, return 0.  */
3788
3789 static int
3790 dwarf2_read_index (struct objfile *objfile)
3791 {
3792   struct mapped_index local_map, *map;
3793   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3794   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3795   struct dwz_file *dwz;
3796
3797   if (!read_index_from_section (objfile, objfile_name (objfile),
3798                                 use_deprecated_index_sections,
3799                                 &dwarf2_per_objfile->gdb_index, &local_map,
3800                                 &cu_list, &cu_list_elements,
3801                                 &types_list, &types_list_elements))
3802     return 0;
3803
3804   /* Don't use the index if it's empty.  */
3805   if (local_map.symbol_table.empty ())
3806     return 0;
3807
3808   /* If there is a .dwz file, read it so we can get its CU list as
3809      well.  */
3810   dwz = dwarf2_get_dwz_file ();
3811   if (dwz != NULL)
3812     {
3813       struct mapped_index dwz_map;
3814       const gdb_byte *dwz_types_ignore;
3815       offset_type dwz_types_elements_ignore;
3816
3817       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3818                                     1,
3819                                     &dwz->gdb_index, &dwz_map,
3820                                     &dwz_list, &dwz_list_elements,
3821                                     &dwz_types_ignore,
3822                                     &dwz_types_elements_ignore))
3823         {
3824           warning (_("could not read '.gdb_index' section from %s; skipping"),
3825                    bfd_get_filename (dwz->dwz_bfd));
3826           return 0;
3827         }
3828     }
3829
3830   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3831                          dwz_list_elements);
3832
3833   if (types_list_elements)
3834     {
3835       struct dwarf2_section_info *section;
3836
3837       /* We can only handle a single .debug_types when we have an
3838          index.  */
3839       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3840         return 0;
3841
3842       section = VEC_index (dwarf2_section_info_def,
3843                            dwarf2_per_objfile->types, 0);
3844
3845       create_signatured_type_table_from_index (objfile, section, types_list,
3846                                                types_list_elements);
3847     }
3848
3849   create_addrmap_from_index (objfile, &local_map);
3850
3851   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3852   map = new (map) mapped_index ();
3853   *map = local_map;
3854
3855   dwarf2_per_objfile->index_table = map;
3856   dwarf2_per_objfile->using_index = 1;
3857   dwarf2_per_objfile->quick_file_names_table =
3858     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3859
3860   return 1;
3861 }
3862
3863 /* A helper for the "quick" functions which sets the global
3864    dwarf2_per_objfile according to OBJFILE.  */
3865
3866 static void
3867 dw2_setup (struct objfile *objfile)
3868 {
3869   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3870                         objfile_data (objfile, dwarf2_objfile_data_key));
3871   gdb_assert (dwarf2_per_objfile);
3872 }
3873
3874 /* die_reader_func for dw2_get_file_names.  */
3875
3876 static void
3877 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3878                            const gdb_byte *info_ptr,
3879                            struct die_info *comp_unit_die,
3880                            int has_children,
3881                            void *data)
3882 {
3883   struct dwarf2_cu *cu = reader->cu;
3884   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3885   struct objfile *objfile = dwarf2_per_objfile->objfile;
3886   struct dwarf2_per_cu_data *lh_cu;
3887   struct attribute *attr;
3888   int i;
3889   void **slot;
3890   struct quick_file_names *qfn;
3891
3892   gdb_assert (! this_cu->is_debug_types);
3893
3894   /* Our callers never want to match partial units -- instead they
3895      will match the enclosing full CU.  */
3896   if (comp_unit_die->tag == DW_TAG_partial_unit)
3897     {
3898       this_cu->v.quick->no_file_data = 1;
3899       return;
3900     }
3901
3902   lh_cu = this_cu;
3903   slot = NULL;
3904
3905   line_header_up lh;
3906   sect_offset line_offset {};
3907
3908   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3909   if (attr)
3910     {
3911       struct quick_file_names find_entry;
3912
3913       line_offset = (sect_offset) DW_UNSND (attr);
3914
3915       /* We may have already read in this line header (TU line header sharing).
3916          If we have we're done.  */
3917       find_entry.hash.dwo_unit = cu->dwo_unit;
3918       find_entry.hash.line_sect_off = line_offset;
3919       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3920                              &find_entry, INSERT);
3921       if (*slot != NULL)
3922         {
3923           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3924           return;
3925         }
3926
3927       lh = dwarf_decode_line_header (line_offset, cu);
3928     }
3929   if (lh == NULL)
3930     {
3931       lh_cu->v.quick->no_file_data = 1;
3932       return;
3933     }
3934
3935   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3936   qfn->hash.dwo_unit = cu->dwo_unit;
3937   qfn->hash.line_sect_off = line_offset;
3938   gdb_assert (slot != NULL);
3939   *slot = qfn;
3940
3941   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3942
3943   qfn->num_file_names = lh->file_names.size ();
3944   qfn->file_names =
3945     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3946   for (i = 0; i < lh->file_names.size (); ++i)
3947     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3948   qfn->real_names = NULL;
3949
3950   lh_cu->v.quick->file_names = qfn;
3951 }
3952
3953 /* A helper for the "quick" functions which attempts to read the line
3954    table for THIS_CU.  */
3955
3956 static struct quick_file_names *
3957 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3958 {
3959   /* This should never be called for TUs.  */
3960   gdb_assert (! this_cu->is_debug_types);
3961   /* Nor type unit groups.  */
3962   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3963
3964   if (this_cu->v.quick->file_names != NULL)
3965     return this_cu->v.quick->file_names;
3966   /* If we know there is no line data, no point in looking again.  */
3967   if (this_cu->v.quick->no_file_data)
3968     return NULL;
3969
3970   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3971
3972   if (this_cu->v.quick->no_file_data)
3973     return NULL;
3974   return this_cu->v.quick->file_names;
3975 }
3976
3977 /* A helper for the "quick" functions which computes and caches the
3978    real path for a given file name from the line table.  */
3979
3980 static const char *
3981 dw2_get_real_path (struct objfile *objfile,
3982                    struct quick_file_names *qfn, int index)
3983 {
3984   if (qfn->real_names == NULL)
3985     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3986                                       qfn->num_file_names, const char *);
3987
3988   if (qfn->real_names[index] == NULL)
3989     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3990
3991   return qfn->real_names[index];
3992 }
3993
3994 static struct symtab *
3995 dw2_find_last_source_symtab (struct objfile *objfile)
3996 {
3997   struct compunit_symtab *cust;
3998   int index;
3999
4000   dw2_setup (objfile);
4001   index = dwarf2_per_objfile->n_comp_units - 1;
4002   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
4003   if (cust == NULL)
4004     return NULL;
4005   return compunit_primary_filetab (cust);
4006 }
4007
4008 /* Traversal function for dw2_forget_cached_source_info.  */
4009
4010 static int
4011 dw2_free_cached_file_names (void **slot, void *info)
4012 {
4013   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4014
4015   if (file_data->real_names)
4016     {
4017       int i;
4018
4019       for (i = 0; i < file_data->num_file_names; ++i)
4020         {
4021           xfree ((void*) file_data->real_names[i]);
4022           file_data->real_names[i] = NULL;
4023         }
4024     }
4025
4026   return 1;
4027 }
4028
4029 static void
4030 dw2_forget_cached_source_info (struct objfile *objfile)
4031 {
4032   dw2_setup (objfile);
4033
4034   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4035                           dw2_free_cached_file_names, NULL);
4036 }
4037
4038 /* Helper function for dw2_map_symtabs_matching_filename that expands
4039    the symtabs and calls the iterator.  */
4040
4041 static int
4042 dw2_map_expand_apply (struct objfile *objfile,
4043                       struct dwarf2_per_cu_data *per_cu,
4044                       const char *name, const char *real_path,
4045                       gdb::function_view<bool (symtab *)> callback)
4046 {
4047   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4048
4049   /* Don't visit already-expanded CUs.  */
4050   if (per_cu->v.quick->compunit_symtab)
4051     return 0;
4052
4053   /* This may expand more than one symtab, and we want to iterate over
4054      all of them.  */
4055   dw2_instantiate_symtab (per_cu);
4056
4057   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4058                                     last_made, callback);
4059 }
4060
4061 /* Implementation of the map_symtabs_matching_filename method.  */
4062
4063 static bool
4064 dw2_map_symtabs_matching_filename
4065   (struct objfile *objfile, const char *name, const char *real_path,
4066    gdb::function_view<bool (symtab *)> callback)
4067 {
4068   int i;
4069   const char *name_basename = lbasename (name);
4070
4071   dw2_setup (objfile);
4072
4073   /* The rule is CUs specify all the files, including those used by
4074      any TU, so there's no need to scan TUs here.  */
4075
4076   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4077     {
4078       int j;
4079       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4080       struct quick_file_names *file_data;
4081
4082       /* We only need to look at symtabs not already expanded.  */
4083       if (per_cu->v.quick->compunit_symtab)
4084         continue;
4085
4086       file_data = dw2_get_file_names (per_cu);
4087       if (file_data == NULL)
4088         continue;
4089
4090       for (j = 0; j < file_data->num_file_names; ++j)
4091         {
4092           const char *this_name = file_data->file_names[j];
4093           const char *this_real_name;
4094
4095           if (compare_filenames_for_search (this_name, name))
4096             {
4097               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4098                                         callback))
4099                 return true;
4100               continue;
4101             }
4102
4103           /* Before we invoke realpath, which can get expensive when many
4104              files are involved, do a quick comparison of the basenames.  */
4105           if (! basenames_may_differ
4106               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4107             continue;
4108
4109           this_real_name = dw2_get_real_path (objfile, file_data, j);
4110           if (compare_filenames_for_search (this_real_name, name))
4111             {
4112               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4113                                         callback))
4114                 return true;
4115               continue;
4116             }
4117
4118           if (real_path != NULL)
4119             {
4120               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4121               gdb_assert (IS_ABSOLUTE_PATH (name));
4122               if (this_real_name != NULL
4123                   && FILENAME_CMP (real_path, this_real_name) == 0)
4124                 {
4125                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4126                                             callback))
4127                     return true;
4128                   continue;
4129                 }
4130             }
4131         }
4132     }
4133
4134   return false;
4135 }
4136
4137 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4138
4139 struct dw2_symtab_iterator
4140 {
4141   /* The internalized form of .gdb_index.  */
4142   struct mapped_index *index;
4143   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4144   int want_specific_block;
4145   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4146      Unused if !WANT_SPECIFIC_BLOCK.  */
4147   int block_index;
4148   /* The kind of symbol we're looking for.  */
4149   domain_enum domain;
4150   /* The list of CUs from the index entry of the symbol,
4151      or NULL if not found.  */
4152   offset_type *vec;
4153   /* The next element in VEC to look at.  */
4154   int next;
4155   /* The number of elements in VEC, or zero if there is no match.  */
4156   int length;
4157   /* Have we seen a global version of the symbol?
4158      If so we can ignore all further global instances.
4159      This is to work around gold/15646, inefficient gold-generated
4160      indices.  */
4161   int global_seen;
4162 };
4163
4164 /* Initialize the index symtab iterator ITER.
4165    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4166    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4167
4168 static void
4169 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4170                       struct mapped_index *index,
4171                       int want_specific_block,
4172                       int block_index,
4173                       domain_enum domain,
4174                       const char *name)
4175 {
4176   iter->index = index;
4177   iter->want_specific_block = want_specific_block;
4178   iter->block_index = block_index;
4179   iter->domain = domain;
4180   iter->next = 0;
4181   iter->global_seen = 0;
4182
4183   if (find_slot_in_mapped_hash (index, name, &iter->vec))
4184     iter->length = MAYBE_SWAP (*iter->vec);
4185   else
4186     {
4187       iter->vec = NULL;
4188       iter->length = 0;
4189     }
4190 }
4191
4192 /* Return the next matching CU or NULL if there are no more.  */
4193
4194 static struct dwarf2_per_cu_data *
4195 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4196 {
4197   for ( ; iter->next < iter->length; ++iter->next)
4198     {
4199       offset_type cu_index_and_attrs =
4200         MAYBE_SWAP (iter->vec[iter->next + 1]);
4201       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4202       struct dwarf2_per_cu_data *per_cu;
4203       int want_static = iter->block_index != GLOBAL_BLOCK;
4204       /* This value is only valid for index versions >= 7.  */
4205       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4206       gdb_index_symbol_kind symbol_kind =
4207         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4208       /* Only check the symbol attributes if they're present.
4209          Indices prior to version 7 don't record them,
4210          and indices >= 7 may elide them for certain symbols
4211          (gold does this).  */
4212       int attrs_valid =
4213         (iter->index->version >= 7
4214          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4215
4216       /* Don't crash on bad data.  */
4217       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4218                        + dwarf2_per_objfile->n_type_units))
4219         {
4220           complaint (&symfile_complaints,
4221                      _(".gdb_index entry has bad CU index"
4222                        " [in module %s]"),
4223                      objfile_name (dwarf2_per_objfile->objfile));
4224           continue;
4225         }
4226
4227       per_cu = dw2_get_cutu (cu_index);
4228
4229       /* Skip if already read in.  */
4230       if (per_cu->v.quick->compunit_symtab)
4231         continue;
4232
4233       /* Check static vs global.  */
4234       if (attrs_valid)
4235         {
4236           if (iter->want_specific_block
4237               && want_static != is_static)
4238             continue;
4239           /* Work around gold/15646.  */
4240           if (!is_static && iter->global_seen)
4241             continue;
4242           if (!is_static)
4243             iter->global_seen = 1;
4244         }
4245
4246       /* Only check the symbol's kind if it has one.  */
4247       if (attrs_valid)
4248         {
4249           switch (iter->domain)
4250             {
4251             case VAR_DOMAIN:
4252               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4253                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4254                   /* Some types are also in VAR_DOMAIN.  */
4255                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4256                 continue;
4257               break;
4258             case STRUCT_DOMAIN:
4259               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4260                 continue;
4261               break;
4262             case LABEL_DOMAIN:
4263               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4264                 continue;
4265               break;
4266             default:
4267               break;
4268             }
4269         }
4270
4271       ++iter->next;
4272       return per_cu;
4273     }
4274
4275   return NULL;
4276 }
4277
4278 static struct compunit_symtab *
4279 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4280                    const char *name, domain_enum domain)
4281 {
4282   struct compunit_symtab *stab_best = NULL;
4283   struct mapped_index *index;
4284
4285   dw2_setup (objfile);
4286
4287   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4288
4289   index = dwarf2_per_objfile->index_table;
4290
4291   /* index is NULL if OBJF_READNOW.  */
4292   if (index)
4293     {
4294       struct dw2_symtab_iterator iter;
4295       struct dwarf2_per_cu_data *per_cu;
4296
4297       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
4298
4299       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4300         {
4301           struct symbol *sym, *with_opaque = NULL;
4302           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4303           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4304           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4305
4306           sym = block_find_symbol (block, name, domain,
4307                                    block_find_non_opaque_type_preferred,
4308                                    &with_opaque);
4309
4310           /* Some caution must be observed with overloaded functions
4311              and methods, since the index will not contain any overload
4312              information (but NAME might contain it).  */
4313
4314           if (sym != NULL
4315               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4316             return stab;
4317           if (with_opaque != NULL
4318               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4319             stab_best = stab;
4320
4321           /* Keep looking through other CUs.  */
4322         }
4323     }
4324
4325   return stab_best;
4326 }
4327
4328 static void
4329 dw2_print_stats (struct objfile *objfile)
4330 {
4331   int i, total, count;
4332
4333   dw2_setup (objfile);
4334   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4335   count = 0;
4336   for (i = 0; i < total; ++i)
4337     {
4338       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4339
4340       if (!per_cu->v.quick->compunit_symtab)
4341         ++count;
4342     }
4343   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4344   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4345 }
4346
4347 /* This dumps minimal information about the index.
4348    It is called via "mt print objfiles".
4349    One use is to verify .gdb_index has been loaded by the
4350    gdb.dwarf2/gdb-index.exp testcase.  */
4351
4352 static void
4353 dw2_dump (struct objfile *objfile)
4354 {
4355   dw2_setup (objfile);
4356   gdb_assert (dwarf2_per_objfile->using_index);
4357   printf_filtered (".gdb_index:");
4358   if (dwarf2_per_objfile->index_table != NULL)
4359     {
4360       printf_filtered (" version %d\n",
4361                        dwarf2_per_objfile->index_table->version);
4362     }
4363   else
4364     printf_filtered (" faked for \"readnow\"\n");
4365   printf_filtered ("\n");
4366 }
4367
4368 static void
4369 dw2_relocate (struct objfile *objfile,
4370               const struct section_offsets *new_offsets,
4371               const struct section_offsets *delta)
4372 {
4373   /* There's nothing to relocate here.  */
4374 }
4375
4376 static void
4377 dw2_expand_symtabs_for_function (struct objfile *objfile,
4378                                  const char *func_name)
4379 {
4380   struct mapped_index *index;
4381
4382   dw2_setup (objfile);
4383
4384   index = dwarf2_per_objfile->index_table;
4385
4386   /* index is NULL if OBJF_READNOW.  */
4387   if (index)
4388     {
4389       struct dw2_symtab_iterator iter;
4390       struct dwarf2_per_cu_data *per_cu;
4391
4392       /* Note: It doesn't matter what we pass for block_index here.  */
4393       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4394                             func_name);
4395
4396       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4397         dw2_instantiate_symtab (per_cu);
4398     }
4399 }
4400
4401 static void
4402 dw2_expand_all_symtabs (struct objfile *objfile)
4403 {
4404   int i;
4405
4406   dw2_setup (objfile);
4407
4408   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4409                    + dwarf2_per_objfile->n_type_units); ++i)
4410     {
4411       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4412
4413       dw2_instantiate_symtab (per_cu);
4414     }
4415 }
4416
4417 static void
4418 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4419                                   const char *fullname)
4420 {
4421   int i;
4422
4423   dw2_setup (objfile);
4424
4425   /* We don't need to consider type units here.
4426      This is only called for examining code, e.g. expand_line_sal.
4427      There can be an order of magnitude (or more) more type units
4428      than comp units, and we avoid them if we can.  */
4429
4430   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4431     {
4432       int j;
4433       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4434       struct quick_file_names *file_data;
4435
4436       /* We only need to look at symtabs not already expanded.  */
4437       if (per_cu->v.quick->compunit_symtab)
4438         continue;
4439
4440       file_data = dw2_get_file_names (per_cu);
4441       if (file_data == NULL)
4442         continue;
4443
4444       for (j = 0; j < file_data->num_file_names; ++j)
4445         {
4446           const char *this_fullname = file_data->file_names[j];
4447
4448           if (filename_cmp (this_fullname, fullname) == 0)
4449             {
4450               dw2_instantiate_symtab (per_cu);
4451               break;
4452             }
4453         }
4454     }
4455 }
4456
4457 static void
4458 dw2_map_matching_symbols (struct objfile *objfile,
4459                           const char * name, domain_enum domain,
4460                           int global,
4461                           int (*callback) (struct block *,
4462                                            struct symbol *, void *),
4463                           void *data, symbol_name_match_type match,
4464                           symbol_compare_ftype *ordered_compare)
4465 {
4466   /* Currently unimplemented; used for Ada.  The function can be called if the
4467      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4468      does not look for non-Ada symbols this function should just return.  */
4469 }
4470
4471 /* Symbol name matcher for .gdb_index names.
4472
4473    Symbol names in .gdb_index have a few particularities:
4474
4475    - There's no indication of which is the language of each symbol.
4476
4477      Since each language has its own symbol name matching algorithm,
4478      and we don't know which language is the right one, we must match
4479      each symbol against all languages.  This would be a potential
4480      performance problem if it were not mitigated by the
4481      mapped_index::name_components lookup table, which significantly
4482      reduces the number of times we need to call into this matcher,
4483      making it a non-issue.
4484
4485    - Symbol names in the index have no overload (parameter)
4486      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4487      appear as "foo" in the index, for example.
4488
4489      This means that the lookup names passed to the symbol name
4490      matcher functions must have no parameter information either
4491      because (e.g.) symbol search name "foo" does not match
4492      lookup-name "foo(int)" [while swapping search name for lookup
4493      name would match].
4494 */
4495 class gdb_index_symbol_name_matcher
4496 {
4497 public:
4498   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4499   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4500
4501   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4502      Returns true if any matcher matches.  */
4503   bool matches (const char *symbol_name);
4504
4505 private:
4506   /* A reference to the lookup name we're matching against.  */
4507   const lookup_name_info &m_lookup_name;
4508
4509   /* A vector holding all the different symbol name matchers, for all
4510      languages.  */
4511   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4512 };
4513
4514 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4515   (const lookup_name_info &lookup_name)
4516     : m_lookup_name (lookup_name)
4517 {
4518   /* Prepare the vector of comparison functions upfront, to avoid
4519      doing the same work for each symbol.  Care is taken to avoid
4520      matching with the same matcher more than once if/when multiple
4521      languages use the same matcher function.  */
4522   auto &matchers = m_symbol_name_matcher_funcs;
4523   matchers.reserve (nr_languages);
4524
4525   matchers.push_back (default_symbol_name_matcher);
4526
4527   for (int i = 0; i < nr_languages; i++)
4528     {
4529       const language_defn *lang = language_def ((enum language) i);
4530       if (lang->la_get_symbol_name_matcher != NULL)
4531         {
4532           symbol_name_matcher_ftype *name_matcher
4533             = lang->la_get_symbol_name_matcher (m_lookup_name);
4534
4535           /* Don't insert the same comparison routine more than once.
4536              Note that we do this linear walk instead of a cheaper
4537              sorted insert, or use a std::set or something like that,
4538              because relative order of function addresses is not
4539              stable.  This is not a problem in practice because the
4540              number of supported languages is low, and the cost here
4541              is tiny compared to the number of searches we'll do
4542              afterwards using this object.  */
4543           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4544               == matchers.end ())
4545             matchers.push_back (name_matcher);
4546         }
4547     }
4548 }
4549
4550 bool
4551 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4552 {
4553   for (auto matches_name : m_symbol_name_matcher_funcs)
4554     if (matches_name (symbol_name, m_lookup_name, NULL))
4555       return true;
4556
4557   return false;
4558 }
4559
4560 /* Starting from a search name, return the string that finds the upper
4561    bound of all strings that start with SEARCH_NAME in a sorted name
4562    list.  Returns the empty string to indicate that the upper bound is
4563    the end of the list.  */
4564
4565 static std::string
4566 make_sort_after_prefix_name (const char *search_name)
4567 {
4568   /* When looking to complete "func", we find the upper bound of all
4569      symbols that start with "func" by looking for where we'd insert
4570      the closest string that would follow "func" in lexicographical
4571      order.  Usually, that's "func"-with-last-character-incremented,
4572      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4573      will be UTF-8 multi-byte sequences, but we can't be certain.
4574      Especially mind the 0xff character, which is a valid character in
4575      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4576      rule out compilers allowing it in identifiers.  Note that
4577      conveniently, strcmp/strcasecmp are specified to compare
4578      characters interpreted as unsigned char.  So what we do is treat
4579      the whole string as a base 256 number composed of a sequence of
4580      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4581      to 0, and carries 1 to the following more-significant position.
4582      If the very first character in SEARCH_NAME ends up incremented
4583      and carries/overflows, then the upper bound is the end of the
4584      list.  The string after the empty string is also the empty
4585      string.
4586
4587      Some examples of this operation:
4588
4589        SEARCH_NAME  => "+1" RESULT
4590
4591        "abc"              => "abd"
4592        "ab\xff"           => "ac"
4593        "\xff" "a" "\xff"  => "\xff" "b"
4594        "\xff"             => ""
4595        "\xff\xff"         => ""
4596        ""                 => ""
4597
4598      Then, with these symbols for example:
4599
4600       func
4601       func1
4602       fund
4603
4604      completing "func" looks for symbols between "func" and
4605      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4606      which finds "func" and "func1", but not "fund".
4607
4608      And with:
4609
4610       funcÿ     (Latin1 'ÿ' [0xff])
4611       funcÿ1
4612       fund
4613
4614      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4615      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4616
4617      And with:
4618
4619       ÿÿ        (Latin1 'ÿ' [0xff])
4620       ÿÿ1
4621
4622      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4623      the end of the list.
4624   */
4625   std::string after = search_name;
4626   while (!after.empty () && (unsigned char) after.back () == 0xff)
4627     after.pop_back ();
4628   if (!after.empty ())
4629     after.back () = (unsigned char) after.back () + 1;
4630   return after;
4631 }
4632
4633 /* See declaration.  */
4634
4635 std::pair<std::vector<name_component>::const_iterator,
4636           std::vector<name_component>::const_iterator>
4637 mapped_index_base::find_name_components_bounds
4638   (const lookup_name_info &lookup_name_without_params) const
4639 {
4640   auto *name_cmp
4641     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4642
4643   const char *cplus
4644     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4645
4646   /* Comparison function object for lower_bound that matches against a
4647      given symbol name.  */
4648   auto lookup_compare_lower = [&] (const name_component &elem,
4649                                    const char *name)
4650     {
4651       const char *elem_qualified = this->symbol_name_at (elem.idx);
4652       const char *elem_name = elem_qualified + elem.name_offset;
4653       return name_cmp (elem_name, name) < 0;
4654     };
4655
4656   /* Comparison function object for upper_bound that matches against a
4657      given symbol name.  */
4658   auto lookup_compare_upper = [&] (const char *name,
4659                                    const name_component &elem)
4660     {
4661       const char *elem_qualified = this->symbol_name_at (elem.idx);
4662       const char *elem_name = elem_qualified + elem.name_offset;
4663       return name_cmp (name, elem_name) < 0;
4664     };
4665
4666   auto begin = this->name_components.begin ();
4667   auto end = this->name_components.end ();
4668
4669   /* Find the lower bound.  */
4670   auto lower = [&] ()
4671     {
4672       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4673         return begin;
4674       else
4675         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4676     } ();
4677
4678   /* Find the upper bound.  */
4679   auto upper = [&] ()
4680     {
4681       if (lookup_name_without_params.completion_mode ())
4682         {
4683           /* In completion mode, we want UPPER to point past all
4684              symbols names that have the same prefix.  I.e., with
4685              these symbols, and completing "func":
4686
4687               function        << lower bound
4688               function1
4689               other_function  << upper bound
4690
4691              We find the upper bound by looking for the insertion
4692              point of "func"-with-last-character-incremented,
4693              i.e. "fund".  */
4694           std::string after = make_sort_after_prefix_name (cplus);
4695           if (after.empty ())
4696             return end;
4697           return std::lower_bound (lower, end, after.c_str (),
4698                                    lookup_compare_lower);
4699         }
4700       else
4701         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4702     } ();
4703
4704   return {lower, upper};
4705 }
4706
4707 /* See declaration.  */
4708
4709 void
4710 mapped_index_base::build_name_components ()
4711 {
4712   if (!this->name_components.empty ())
4713     return;
4714
4715   this->name_components_casing = case_sensitivity;
4716   auto *name_cmp
4717     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4718
4719   /* The code below only knows how to break apart components of C++
4720      symbol names (and other languages that use '::' as
4721      namespace/module separator).  If we add support for wild matching
4722      to some language that uses some other operator (E.g., Ada, Go and
4723      D use '.'), then we'll need to try splitting the symbol name
4724      according to that language too.  Note that Ada does support wild
4725      matching, but doesn't currently support .gdb_index.  */
4726   auto count = this->symbol_name_count ();
4727   for (offset_type idx = 0; idx < count; idx++)
4728     {
4729       if (this->symbol_name_slot_invalid (idx))
4730         continue;
4731
4732       const char *name = this->symbol_name_at (idx);
4733
4734       /* Add each name component to the name component table.  */
4735       unsigned int previous_len = 0;
4736       for (unsigned int current_len = cp_find_first_component (name);
4737            name[current_len] != '\0';
4738            current_len += cp_find_first_component (name + current_len))
4739         {
4740           gdb_assert (name[current_len] == ':');
4741           this->name_components.push_back ({previous_len, idx});
4742           /* Skip the '::'.  */
4743           current_len += 2;
4744           previous_len = current_len;
4745         }
4746       this->name_components.push_back ({previous_len, idx});
4747     }
4748
4749   /* Sort name_components elements by name.  */
4750   auto name_comp_compare = [&] (const name_component &left,
4751                                 const name_component &right)
4752     {
4753       const char *left_qualified = this->symbol_name_at (left.idx);
4754       const char *right_qualified = this->symbol_name_at (right.idx);
4755
4756       const char *left_name = left_qualified + left.name_offset;
4757       const char *right_name = right_qualified + right.name_offset;
4758
4759       return name_cmp (left_name, right_name) < 0;
4760     };
4761
4762   std::sort (this->name_components.begin (),
4763              this->name_components.end (),
4764              name_comp_compare);
4765 }
4766
4767 /* Helper for dw2_expand_symtabs_matching that works with a
4768    mapped_index_base instead of the containing objfile.  This is split
4769    to a separate function in order to be able to unit test the
4770    name_components matching using a mock mapped_index_base.  For each
4771    symbol name that matches, calls MATCH_CALLBACK, passing it the
4772    symbol's index in the mapped_index_base symbol table.  */
4773
4774 static void
4775 dw2_expand_symtabs_matching_symbol
4776   (mapped_index_base &index,
4777    const lookup_name_info &lookup_name_in,
4778    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4779    enum search_domain kind,
4780    gdb::function_view<void (offset_type)> match_callback)
4781 {
4782   lookup_name_info lookup_name_without_params
4783     = lookup_name_in.make_ignore_params ();
4784   gdb_index_symbol_name_matcher lookup_name_matcher
4785     (lookup_name_without_params);
4786
4787   /* Build the symbol name component sorted vector, if we haven't
4788      yet.  */
4789   index.build_name_components ();
4790
4791   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4792
4793   /* Now for each symbol name in range, check to see if we have a name
4794      match, and if so, call the MATCH_CALLBACK callback.  */
4795
4796   /* The same symbol may appear more than once in the range though.
4797      E.g., if we're looking for symbols that complete "w", and we have
4798      a symbol named "w1::w2", we'll find the two name components for
4799      that same symbol in the range.  To be sure we only call the
4800      callback once per symbol, we first collect the symbol name
4801      indexes that matched in a temporary vector and ignore
4802      duplicates.  */
4803   std::vector<offset_type> matches;
4804   matches.reserve (std::distance (bounds.first, bounds.second));
4805
4806   for (; bounds.first != bounds.second; ++bounds.first)
4807     {
4808       const char *qualified = index.symbol_name_at (bounds.first->idx);
4809
4810       if (!lookup_name_matcher.matches (qualified)
4811           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4812         continue;
4813
4814       matches.push_back (bounds.first->idx);
4815     }
4816
4817   std::sort (matches.begin (), matches.end ());
4818
4819   /* Finally call the callback, once per match.  */
4820   ULONGEST prev = -1;
4821   for (offset_type idx : matches)
4822     {
4823       if (prev != idx)
4824         {
4825           match_callback (idx);
4826           prev = idx;
4827         }
4828     }
4829
4830   /* Above we use a type wider than idx's for 'prev', since 0 and
4831      (offset_type)-1 are both possible values.  */
4832   static_assert (sizeof (prev) > sizeof (offset_type), "");
4833 }
4834
4835 #if GDB_SELF_TEST
4836
4837 namespace selftests { namespace dw2_expand_symtabs_matching {
4838
4839 /* A mock .gdb_index/.debug_names-like name index table, enough to
4840    exercise dw2_expand_symtabs_matching_symbol, which works with the
4841    mapped_index_base interface.  Builds an index from the symbol list
4842    passed as parameter to the constructor.  */
4843 class mock_mapped_index : public mapped_index_base
4844 {
4845 public:
4846   mock_mapped_index (gdb::array_view<const char *> symbols)
4847     : m_symbol_table (symbols)
4848   {}
4849
4850   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4851
4852   /* Return the number of names in the symbol table.  */
4853   virtual size_t symbol_name_count () const
4854   {
4855     return m_symbol_table.size ();
4856   }
4857
4858   /* Get the name of the symbol at IDX in the symbol table.  */
4859   virtual const char *symbol_name_at (offset_type idx) const
4860   {
4861     return m_symbol_table[idx];
4862   }
4863
4864 private:
4865   gdb::array_view<const char *> m_symbol_table;
4866 };
4867
4868 /* Convenience function that converts a NULL pointer to a "<null>"
4869    string, to pass to print routines.  */
4870
4871 static const char *
4872 string_or_null (const char *str)
4873 {
4874   return str != NULL ? str : "<null>";
4875 }
4876
4877 /* Check if a lookup_name_info built from
4878    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4879    index.  EXPECTED_LIST is the list of expected matches, in expected
4880    matching order.  If no match expected, then an empty list is
4881    specified.  Returns true on success.  On failure prints a warning
4882    indicating the file:line that failed, and returns false.  */
4883
4884 static bool
4885 check_match (const char *file, int line,
4886              mock_mapped_index &mock_index,
4887              const char *name, symbol_name_match_type match_type,
4888              bool completion_mode,
4889              std::initializer_list<const char *> expected_list)
4890 {
4891   lookup_name_info lookup_name (name, match_type, completion_mode);
4892
4893   bool matched = true;
4894
4895   auto mismatch = [&] (const char *expected_str,
4896                        const char *got)
4897   {
4898     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4899                "expected=\"%s\", got=\"%s\"\n"),
4900              file, line,
4901              (match_type == symbol_name_match_type::FULL
4902               ? "FULL" : "WILD"),
4903              name, string_or_null (expected_str), string_or_null (got));
4904     matched = false;
4905   };
4906
4907   auto expected_it = expected_list.begin ();
4908   auto expected_end = expected_list.end ();
4909
4910   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4911                                       NULL, ALL_DOMAIN,
4912                                       [&] (offset_type idx)
4913   {
4914     const char *matched_name = mock_index.symbol_name_at (idx);
4915     const char *expected_str
4916       = expected_it == expected_end ? NULL : *expected_it++;
4917
4918     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4919       mismatch (expected_str, matched_name);
4920   });
4921
4922   const char *expected_str
4923   = expected_it == expected_end ? NULL : *expected_it++;
4924   if (expected_str != NULL)
4925     mismatch (expected_str, NULL);
4926
4927   return matched;
4928 }
4929
4930 /* The symbols added to the mock mapped_index for testing (in
4931    canonical form).  */
4932 static const char *test_symbols[] = {
4933   "function",
4934   "std::bar",
4935   "std::zfunction",
4936   "std::zfunction2",
4937   "w1::w2",
4938   "ns::foo<char*>",
4939   "ns::foo<int>",
4940   "ns::foo<long>",
4941   "ns2::tmpl<int>::foo2",
4942   "(anonymous namespace)::A::B::C",
4943
4944   /* These are used to check that the increment-last-char in the
4945      matching algorithm for completion doesn't match "t1_fund" when
4946      completing "t1_func".  */
4947   "t1_func",
4948   "t1_func1",
4949   "t1_fund",
4950   "t1_fund1",
4951
4952   /* A UTF-8 name with multi-byte sequences to make sure that
4953      cp-name-parser understands this as a single identifier ("função"
4954      is "function" in PT).  */
4955   u8"u8função",
4956
4957   /* \377 (0xff) is Latin1 'ÿ'.  */
4958   "yfunc\377",
4959
4960   /* \377 (0xff) is Latin1 'ÿ'.  */
4961   "\377",
4962   "\377\377123",
4963
4964   /* A name with all sorts of complications.  Starts with "z" to make
4965      it easier for the completion tests below.  */
4966 #define Z_SYM_NAME \
4967   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4968     "::tuple<(anonymous namespace)::ui*, " \
4969     "std::default_delete<(anonymous namespace)::ui>, void>"
4970
4971   Z_SYM_NAME
4972 };
4973
4974 /* Returns true if the mapped_index_base::find_name_component_bounds
4975    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4976    in completion mode.  */
4977
4978 static bool
4979 check_find_bounds_finds (mapped_index_base &index,
4980                          const char *search_name,
4981                          gdb::array_view<const char *> expected_syms)
4982 {
4983   lookup_name_info lookup_name (search_name,
4984                                 symbol_name_match_type::FULL, true);
4985
4986   auto bounds = index.find_name_components_bounds (lookup_name);
4987
4988   size_t distance = std::distance (bounds.first, bounds.second);
4989   if (distance != expected_syms.size ())
4990     return false;
4991
4992   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4993     {
4994       auto nc_elem = bounds.first + exp_elem;
4995       const char *qualified = index.symbol_name_at (nc_elem->idx);
4996       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4997         return false;
4998     }
4999
5000   return true;
5001 }
5002
5003 /* Test the lower-level mapped_index::find_name_component_bounds
5004    method.  */
5005
5006 static void
5007 test_mapped_index_find_name_component_bounds ()
5008 {
5009   mock_mapped_index mock_index (test_symbols);
5010
5011   mock_index.build_name_components ();
5012
5013   /* Test the lower-level mapped_index::find_name_component_bounds
5014      method in completion mode.  */
5015   {
5016     static const char *expected_syms[] = {
5017       "t1_func",
5018       "t1_func1",
5019     };
5020
5021     SELF_CHECK (check_find_bounds_finds (mock_index,
5022                                          "t1_func", expected_syms));
5023   }
5024
5025   /* Check that the increment-last-char in the name matching algorithm
5026      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5027   {
5028     static const char *expected_syms1[] = {
5029       "\377",
5030       "\377\377123",
5031     };
5032     SELF_CHECK (check_find_bounds_finds (mock_index,
5033                                          "\377", expected_syms1));
5034
5035     static const char *expected_syms2[] = {
5036       "\377\377123",
5037     };
5038     SELF_CHECK (check_find_bounds_finds (mock_index,
5039                                          "\377\377", expected_syms2));
5040   }
5041 }
5042
5043 /* Test dw2_expand_symtabs_matching_symbol.  */
5044
5045 static void
5046 test_dw2_expand_symtabs_matching_symbol ()
5047 {
5048   mock_mapped_index mock_index (test_symbols);
5049
5050   /* We let all tests run until the end even if some fails, for debug
5051      convenience.  */
5052   bool any_mismatch = false;
5053
5054   /* Create the expected symbols list (an initializer_list).  Needed
5055      because lists have commas, and we need to pass them to CHECK,
5056      which is a macro.  */
5057 #define EXPECT(...) { __VA_ARGS__ }
5058
5059   /* Wrapper for check_match that passes down the current
5060      __FILE__/__LINE__.  */
5061 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5062   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5063                                 mock_index,                             \
5064                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5065                                 EXPECTED_LIST)
5066
5067   /* Identity checks.  */
5068   for (const char *sym : test_symbols)
5069     {
5070       /* Should be able to match all existing symbols.  */
5071       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5072                    EXPECT (sym));
5073
5074       /* Should be able to match all existing symbols with
5075          parameters.  */
5076       std::string with_params = std::string (sym) + "(int)";
5077       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5078                    EXPECT (sym));
5079
5080       /* Should be able to match all existing symbols with
5081          parameters and qualifiers.  */
5082       with_params = std::string (sym) + " ( int ) const";
5083       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5084                    EXPECT (sym));
5085
5086       /* This should really find sym, but cp-name-parser.y doesn't
5087          know about lvalue/rvalue qualifiers yet.  */
5088       with_params = std::string (sym) + " ( int ) &&";
5089       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5090                    {});
5091     }
5092
5093   /* Check that the name matching algorithm for completion doesn't get
5094      confused with Latin1 'ÿ' / 0xff.  */
5095   {
5096     static const char str[] = "\377";
5097     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5098                  EXPECT ("\377", "\377\377123"));
5099   }
5100
5101   /* Check that the increment-last-char in the matching algorithm for
5102      completion doesn't match "t1_fund" when completing "t1_func".  */
5103   {
5104     static const char str[] = "t1_func";
5105     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5106                  EXPECT ("t1_func", "t1_func1"));
5107   }
5108
5109   /* Check that completion mode works at each prefix of the expected
5110      symbol name.  */
5111   {
5112     static const char str[] = "function(int)";
5113     size_t len = strlen (str);
5114     std::string lookup;
5115
5116     for (size_t i = 1; i < len; i++)
5117       {
5118         lookup.assign (str, i);
5119         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5120                      EXPECT ("function"));
5121       }
5122   }
5123
5124   /* While "w" is a prefix of both components, the match function
5125      should still only be called once.  */
5126   {
5127     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5128                  EXPECT ("w1::w2"));
5129     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5130                  EXPECT ("w1::w2"));
5131   }
5132
5133   /* Same, with a "complicated" symbol.  */
5134   {
5135     static const char str[] = Z_SYM_NAME;
5136     size_t len = strlen (str);
5137     std::string lookup;
5138
5139     for (size_t i = 1; i < len; i++)
5140       {
5141         lookup.assign (str, i);
5142         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5143                      EXPECT (Z_SYM_NAME));
5144       }
5145   }
5146
5147   /* In FULL mode, an incomplete symbol doesn't match.  */
5148   {
5149     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5150                  {});
5151   }
5152
5153   /* A complete symbol with parameters matches any overload, since the
5154      index has no overload info.  */
5155   {
5156     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5157                  EXPECT ("std::zfunction", "std::zfunction2"));
5158     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5159                  EXPECT ("std::zfunction", "std::zfunction2"));
5160     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5161                  EXPECT ("std::zfunction", "std::zfunction2"));
5162   }
5163
5164   /* Check that whitespace is ignored appropriately.  A symbol with a
5165      template argument list. */
5166   {
5167     static const char expected[] = "ns::foo<int>";
5168     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5169                  EXPECT (expected));
5170     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5171                  EXPECT (expected));
5172   }
5173
5174   /* Check that whitespace is ignored appropriately.  A symbol with a
5175      template argument list that includes a pointer.  */
5176   {
5177     static const char expected[] = "ns::foo<char*>";
5178     /* Try both completion and non-completion modes.  */
5179     static const bool completion_mode[2] = {false, true};
5180     for (size_t i = 0; i < 2; i++)
5181       {
5182         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5183                      completion_mode[i], EXPECT (expected));
5184         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5185                      completion_mode[i], EXPECT (expected));
5186
5187         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5188                      completion_mode[i], EXPECT (expected));
5189         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5190                      completion_mode[i], EXPECT (expected));
5191       }
5192   }
5193
5194   {
5195     /* Check method qualifiers are ignored.  */
5196     static const char expected[] = "ns::foo<char*>";
5197     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5198                  symbol_name_match_type::FULL, true, EXPECT (expected));
5199     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5200                  symbol_name_match_type::FULL, true, EXPECT (expected));
5201     CHECK_MATCH ("foo < char * >  ( int ) const",
5202                  symbol_name_match_type::WILD, true, EXPECT (expected));
5203     CHECK_MATCH ("foo < char * >  ( int ) &&",
5204                  symbol_name_match_type::WILD, true, EXPECT (expected));
5205   }
5206
5207   /* Test lookup names that don't match anything.  */
5208   {
5209     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5210                  {});
5211
5212     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5213                  {});
5214   }
5215
5216   /* Some wild matching tests, exercising "(anonymous namespace)",
5217      which should not be confused with a parameter list.  */
5218   {
5219     static const char *syms[] = {
5220       "A::B::C",
5221       "B::C",
5222       "C",
5223       "A :: B :: C ( int )",
5224       "B :: C ( int )",
5225       "C ( int )",
5226     };
5227
5228     for (const char *s : syms)
5229       {
5230         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5231                      EXPECT ("(anonymous namespace)::A::B::C"));
5232       }
5233   }
5234
5235   {
5236     static const char expected[] = "ns2::tmpl<int>::foo2";
5237     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5238                  EXPECT (expected));
5239     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5240                  EXPECT (expected));
5241   }
5242
5243   SELF_CHECK (!any_mismatch);
5244
5245 #undef EXPECT
5246 #undef CHECK_MATCH
5247 }
5248
5249 static void
5250 run_test ()
5251 {
5252   test_mapped_index_find_name_component_bounds ();
5253   test_dw2_expand_symtabs_matching_symbol ();
5254 }
5255
5256 }} // namespace selftests::dw2_expand_symtabs_matching
5257
5258 #endif /* GDB_SELF_TEST */
5259
5260 /* If FILE_MATCHER is NULL or if PER_CU has
5261    dwarf2_per_cu_quick_data::MARK set (see
5262    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5263    EXPANSION_NOTIFY on it.  */
5264
5265 static void
5266 dw2_expand_symtabs_matching_one
5267   (struct dwarf2_per_cu_data *per_cu,
5268    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5269    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5270 {
5271   if (file_matcher == NULL || per_cu->v.quick->mark)
5272     {
5273       bool symtab_was_null
5274         = (per_cu->v.quick->compunit_symtab == NULL);
5275
5276       dw2_instantiate_symtab (per_cu);
5277
5278       if (expansion_notify != NULL
5279           && symtab_was_null
5280           && per_cu->v.quick->compunit_symtab != NULL)
5281         expansion_notify (per_cu->v.quick->compunit_symtab);
5282     }
5283 }
5284
5285 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5286    matched, to expand corresponding CUs that were marked.  IDX is the
5287    index of the symbol name that matched.  */
5288
5289 static void
5290 dw2_expand_marked_cus
5291   (mapped_index &index, offset_type idx,
5292    struct objfile *objfile,
5293    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5294    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5295    search_domain kind)
5296 {
5297   offset_type *vec, vec_len, vec_idx;
5298   bool global_seen = false;
5299
5300   vec = (offset_type *) (index.constant_pool
5301                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5302   vec_len = MAYBE_SWAP (vec[0]);
5303   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5304     {
5305       struct dwarf2_per_cu_data *per_cu;
5306       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5307       /* This value is only valid for index versions >= 7.  */
5308       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5309       gdb_index_symbol_kind symbol_kind =
5310         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5311       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5312       /* Only check the symbol attributes if they're present.
5313          Indices prior to version 7 don't record them,
5314          and indices >= 7 may elide them for certain symbols
5315          (gold does this).  */
5316       int attrs_valid =
5317         (index.version >= 7
5318          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5319
5320       /* Work around gold/15646.  */
5321       if (attrs_valid)
5322         {
5323           if (!is_static && global_seen)
5324             continue;
5325           if (!is_static)
5326             global_seen = true;
5327         }
5328
5329       /* Only check the symbol's kind if it has one.  */
5330       if (attrs_valid)
5331         {
5332           switch (kind)
5333             {
5334             case VARIABLES_DOMAIN:
5335               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5336                 continue;
5337               break;
5338             case FUNCTIONS_DOMAIN:
5339               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5340                 continue;
5341               break;
5342             case TYPES_DOMAIN:
5343               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5344                 continue;
5345               break;
5346             default:
5347               break;
5348             }
5349         }
5350
5351       /* Don't crash on bad data.  */
5352       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5353                        + dwarf2_per_objfile->n_type_units))
5354         {
5355           complaint (&symfile_complaints,
5356                      _(".gdb_index entry has bad CU index"
5357                        " [in module %s]"), objfile_name (objfile));
5358           continue;
5359         }
5360
5361       per_cu = dw2_get_cutu (cu_index);
5362       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5363                                        expansion_notify);
5364     }
5365 }
5366
5367 /* If FILE_MATCHER is non-NULL, set all the
5368    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5369    that match FILE_MATCHER.  */
5370
5371 static void
5372 dw_expand_symtabs_matching_file_matcher
5373   (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5374 {
5375   if (file_matcher == NULL)
5376     return;
5377
5378   objfile *const objfile = dwarf2_per_objfile->objfile;
5379
5380   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5381                                             htab_eq_pointer,
5382                                             NULL, xcalloc, xfree));
5383   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5384                                                 htab_eq_pointer,
5385                                                 NULL, xcalloc, xfree));
5386
5387   /* The rule is CUs specify all the files, including those used by
5388      any TU, so there's no need to scan TUs here.  */
5389
5390   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5391     {
5392       int j;
5393       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5394       struct quick_file_names *file_data;
5395       void **slot;
5396
5397       QUIT;
5398
5399       per_cu->v.quick->mark = 0;
5400
5401       /* We only need to look at symtabs not already expanded.  */
5402       if (per_cu->v.quick->compunit_symtab)
5403         continue;
5404
5405       file_data = dw2_get_file_names (per_cu);
5406       if (file_data == NULL)
5407         continue;
5408
5409       if (htab_find (visited_not_found.get (), file_data) != NULL)
5410         continue;
5411       else if (htab_find (visited_found.get (), file_data) != NULL)
5412         {
5413           per_cu->v.quick->mark = 1;
5414           continue;
5415         }
5416
5417       for (j = 0; j < file_data->num_file_names; ++j)
5418         {
5419           const char *this_real_name;
5420
5421           if (file_matcher (file_data->file_names[j], false))
5422             {
5423               per_cu->v.quick->mark = 1;
5424               break;
5425             }
5426
5427           /* Before we invoke realpath, which can get expensive when many
5428              files are involved, do a quick comparison of the basenames.  */
5429           if (!basenames_may_differ
5430               && !file_matcher (lbasename (file_data->file_names[j]),
5431                                 true))
5432             continue;
5433
5434           this_real_name = dw2_get_real_path (objfile, file_data, j);
5435           if (file_matcher (this_real_name, false))
5436             {
5437               per_cu->v.quick->mark = 1;
5438               break;
5439             }
5440         }
5441
5442       slot = htab_find_slot (per_cu->v.quick->mark
5443                              ? visited_found.get ()
5444                              : visited_not_found.get (),
5445                              file_data, INSERT);
5446       *slot = file_data;
5447     }
5448 }
5449
5450 static void
5451 dw2_expand_symtabs_matching
5452   (struct objfile *objfile,
5453    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5454    const lookup_name_info &lookup_name,
5455    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5456    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5457    enum search_domain kind)
5458 {
5459   dw2_setup (objfile);
5460
5461   /* index_table is NULL if OBJF_READNOW.  */
5462   if (!dwarf2_per_objfile->index_table)
5463     return;
5464
5465   dw_expand_symtabs_matching_file_matcher (file_matcher);
5466
5467   mapped_index &index = *dwarf2_per_objfile->index_table;
5468
5469   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5470                                       symbol_matcher,
5471                                       kind, [&] (offset_type idx)
5472     {
5473       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5474                              expansion_notify, kind);
5475     });
5476 }
5477
5478 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5479    symtab.  */
5480
5481 static struct compunit_symtab *
5482 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5483                                           CORE_ADDR pc)
5484 {
5485   int i;
5486
5487   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5488       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5489     return cust;
5490
5491   if (cust->includes == NULL)
5492     return NULL;
5493
5494   for (i = 0; cust->includes[i]; ++i)
5495     {
5496       struct compunit_symtab *s = cust->includes[i];
5497
5498       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5499       if (s != NULL)
5500         return s;
5501     }
5502
5503   return NULL;
5504 }
5505
5506 static struct compunit_symtab *
5507 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5508                                   struct bound_minimal_symbol msymbol,
5509                                   CORE_ADDR pc,
5510                                   struct obj_section *section,
5511                                   int warn_if_readin)
5512 {
5513   struct dwarf2_per_cu_data *data;
5514   struct compunit_symtab *result;
5515
5516   dw2_setup (objfile);
5517
5518   if (!objfile->psymtabs_addrmap)
5519     return NULL;
5520
5521   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5522                                                      pc);
5523   if (!data)
5524     return NULL;
5525
5526   if (warn_if_readin && data->v.quick->compunit_symtab)
5527     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5528              paddress (get_objfile_arch (objfile), pc));
5529
5530   result
5531     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5532                                                 pc);
5533   gdb_assert (result != NULL);
5534   return result;
5535 }
5536
5537 static void
5538 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5539                           void *data, int need_fullname)
5540 {
5541   dw2_setup (objfile);
5542
5543   if (!dwarf2_per_objfile->filenames_cache)
5544     {
5545       dwarf2_per_objfile->filenames_cache.emplace ();
5546
5547       htab_up visited (htab_create_alloc (10,
5548                                           htab_hash_pointer, htab_eq_pointer,
5549                                           NULL, xcalloc, xfree));
5550
5551       /* The rule is CUs specify all the files, including those used
5552          by any TU, so there's no need to scan TUs here.  We can
5553          ignore file names coming from already-expanded CUs.  */
5554
5555       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5556         {
5557           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5558
5559           if (per_cu->v.quick->compunit_symtab)
5560             {
5561               void **slot = htab_find_slot (visited.get (),
5562                                             per_cu->v.quick->file_names,
5563                                             INSERT);
5564
5565               *slot = per_cu->v.quick->file_names;
5566             }
5567         }
5568
5569       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5570         {
5571           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5572           struct quick_file_names *file_data;
5573           void **slot;
5574
5575           /* We only need to look at symtabs not already expanded.  */
5576           if (per_cu->v.quick->compunit_symtab)
5577             continue;
5578
5579           file_data = dw2_get_file_names (per_cu);
5580           if (file_data == NULL)
5581             continue;
5582
5583           slot = htab_find_slot (visited.get (), file_data, INSERT);
5584           if (*slot)
5585             {
5586               /* Already visited.  */
5587               continue;
5588             }
5589           *slot = file_data;
5590
5591           for (int j = 0; j < file_data->num_file_names; ++j)
5592             {
5593               const char *filename = file_data->file_names[j];
5594               dwarf2_per_objfile->filenames_cache->seen (filename);
5595             }
5596         }
5597     }
5598
5599   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5600     {
5601       gdb::unique_xmalloc_ptr<char> this_real_name;
5602
5603       if (need_fullname)
5604         this_real_name = gdb_realpath (filename);
5605       (*fun) (filename, this_real_name.get (), data);
5606     });
5607 }
5608
5609 static int
5610 dw2_has_symbols (struct objfile *objfile)
5611 {
5612   return 1;
5613 }
5614
5615 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5616 {
5617   dw2_has_symbols,
5618   dw2_find_last_source_symtab,
5619   dw2_forget_cached_source_info,
5620   dw2_map_symtabs_matching_filename,
5621   dw2_lookup_symbol,
5622   dw2_print_stats,
5623   dw2_dump,
5624   dw2_relocate,
5625   dw2_expand_symtabs_for_function,
5626   dw2_expand_all_symtabs,
5627   dw2_expand_symtabs_with_fullname,
5628   dw2_map_matching_symbols,
5629   dw2_expand_symtabs_matching,
5630   dw2_find_pc_sect_compunit_symtab,
5631   NULL,
5632   dw2_map_symbol_filenames
5633 };
5634
5635 /* DWARF-5 debug_names reader.  */
5636
5637 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5638 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5639
5640 /* A helper function that reads the .debug_names section in SECTION
5641    and fills in MAP.  FILENAME is the name of the file containing the
5642    section; it is used for error reporting.
5643
5644    Returns true if all went well, false otherwise.  */
5645
5646 static bool
5647 read_debug_names_from_section (struct objfile *objfile,
5648                                const char *filename,
5649                                struct dwarf2_section_info *section,
5650                                mapped_debug_names &map)
5651 {
5652   if (dwarf2_section_empty_p (section))
5653     return false;
5654
5655   /* Older elfutils strip versions could keep the section in the main
5656      executable while splitting it for the separate debug info file.  */
5657   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5658     return false;
5659
5660   dwarf2_read_section (objfile, section);
5661
5662   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5663
5664   const gdb_byte *addr = section->buffer;
5665
5666   bfd *const abfd = get_section_bfd_owner (section);
5667
5668   unsigned int bytes_read;
5669   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5670   addr += bytes_read;
5671
5672   map.dwarf5_is_dwarf64 = bytes_read != 4;
5673   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5674   if (bytes_read + length != section->size)
5675     {
5676       /* There may be multiple per-CU indices.  */
5677       warning (_("Section .debug_names in %s length %s does not match "
5678                  "section length %s, ignoring .debug_names."),
5679                filename, plongest (bytes_read + length),
5680                pulongest (section->size));
5681       return false;
5682     }
5683
5684   /* The version number.  */
5685   uint16_t version = read_2_bytes (abfd, addr);
5686   addr += 2;
5687   if (version != 5)
5688     {
5689       warning (_("Section .debug_names in %s has unsupported version %d, "
5690                  "ignoring .debug_names."),
5691                filename, version);
5692       return false;
5693     }
5694
5695   /* Padding.  */
5696   uint16_t padding = read_2_bytes (abfd, addr);
5697   addr += 2;
5698   if (padding != 0)
5699     {
5700       warning (_("Section .debug_names in %s has unsupported padding %d, "
5701                  "ignoring .debug_names."),
5702                filename, padding);
5703       return false;
5704     }
5705
5706   /* comp_unit_count - The number of CUs in the CU list.  */
5707   map.cu_count = read_4_bytes (abfd, addr);
5708   addr += 4;
5709
5710   /* local_type_unit_count - The number of TUs in the local TU
5711      list.  */
5712   map.tu_count = read_4_bytes (abfd, addr);
5713   addr += 4;
5714
5715   /* foreign_type_unit_count - The number of TUs in the foreign TU
5716      list.  */
5717   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5718   addr += 4;
5719   if (foreign_tu_count != 0)
5720     {
5721       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5722                  "ignoring .debug_names."),
5723                filename, static_cast<unsigned long> (foreign_tu_count));
5724       return false;
5725     }
5726
5727   /* bucket_count - The number of hash buckets in the hash lookup
5728      table.  */
5729   map.bucket_count = read_4_bytes (abfd, addr);
5730   addr += 4;
5731
5732   /* name_count - The number of unique names in the index.  */
5733   map.name_count = read_4_bytes (abfd, addr);
5734   addr += 4;
5735
5736   /* abbrev_table_size - The size in bytes of the abbreviations
5737      table.  */
5738   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5739   addr += 4;
5740
5741   /* augmentation_string_size - The size in bytes of the augmentation
5742      string.  This value is rounded up to a multiple of 4.  */
5743   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5744   addr += 4;
5745   map.augmentation_is_gdb = ((augmentation_string_size
5746                               == sizeof (dwarf5_augmentation))
5747                              && memcmp (addr, dwarf5_augmentation,
5748                                         sizeof (dwarf5_augmentation)) == 0);
5749   augmentation_string_size += (-augmentation_string_size) & 3;
5750   addr += augmentation_string_size;
5751
5752   /* List of CUs */
5753   map.cu_table_reordered = addr;
5754   addr += map.cu_count * map.offset_size;
5755
5756   /* List of Local TUs */
5757   map.tu_table_reordered = addr;
5758   addr += map.tu_count * map.offset_size;
5759
5760   /* Hash Lookup Table */
5761   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5762   addr += map.bucket_count * 4;
5763   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5764   addr += map.name_count * 4;
5765
5766   /* Name Table */
5767   map.name_table_string_offs_reordered = addr;
5768   addr += map.name_count * map.offset_size;
5769   map.name_table_entry_offs_reordered = addr;
5770   addr += map.name_count * map.offset_size;
5771
5772   const gdb_byte *abbrev_table_start = addr;
5773   for (;;)
5774     {
5775       unsigned int bytes_read;
5776       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5777       addr += bytes_read;
5778       if (index_num == 0)
5779         break;
5780
5781       const auto insertpair
5782         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5783       if (!insertpair.second)
5784         {
5785           warning (_("Section .debug_names in %s has duplicate index %s, "
5786                      "ignoring .debug_names."),
5787                    filename, pulongest (index_num));
5788           return false;
5789         }
5790       mapped_debug_names::index_val &indexval = insertpair.first->second;
5791       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5792       addr += bytes_read;
5793
5794       for (;;)
5795         {
5796           mapped_debug_names::index_val::attr attr;
5797           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5798           addr += bytes_read;
5799           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5800           addr += bytes_read;
5801           if (attr.form == DW_FORM_implicit_const)
5802             {
5803               attr.implicit_const = read_signed_leb128 (abfd, addr,
5804                                                         &bytes_read);
5805               addr += bytes_read;
5806             }
5807           if (attr.dw_idx == 0 && attr.form == 0)
5808             break;
5809           indexval.attr_vec.push_back (std::move (attr));
5810         }
5811     }
5812   if (addr != abbrev_table_start + abbrev_table_size)
5813     {
5814       warning (_("Section .debug_names in %s has abbreviation_table "
5815                  "of size %zu vs. written as %u, ignoring .debug_names."),
5816                filename, addr - abbrev_table_start, abbrev_table_size);
5817       return false;
5818     }
5819   map.entry_pool = addr;
5820
5821   return true;
5822 }
5823
5824 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5825    list.  */
5826
5827 static void
5828 create_cus_from_debug_names_list (struct objfile *objfile,
5829                                   const mapped_debug_names &map,
5830                                   dwarf2_section_info &section,
5831                                   bool is_dwz, int base_offset)
5832 {
5833   sect_offset sect_off_prev;
5834   for (uint32_t i = 0; i <= map.cu_count; ++i)
5835     {
5836       sect_offset sect_off_next;
5837       if (i < map.cu_count)
5838         {
5839           sect_off_next
5840             = (sect_offset) (extract_unsigned_integer
5841                              (map.cu_table_reordered + i * map.offset_size,
5842                               map.offset_size,
5843                               map.dwarf5_byte_order));
5844         }
5845       else
5846         sect_off_next = (sect_offset) section.size;
5847       if (i >= 1)
5848         {
5849           const ULONGEST length = sect_off_next - sect_off_prev;
5850           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5851             = create_cu_from_index_list (objfile, &section, is_dwz,
5852                                          sect_off_prev, length);
5853         }
5854       sect_off_prev = sect_off_next;
5855     }
5856 }
5857
5858 /* Read the CU list from the mapped index, and use it to create all
5859    the CU objects for this objfile.  */
5860
5861 static void
5862 create_cus_from_debug_names (struct objfile *objfile,
5863                              const mapped_debug_names &map,
5864                              const mapped_debug_names &dwz_map)
5865 {
5866
5867   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5868   dwarf2_per_objfile->all_comp_units
5869     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5870                  dwarf2_per_objfile->n_comp_units);
5871
5872   create_cus_from_debug_names_list (objfile, map, dwarf2_per_objfile->info,
5873                                     false /* is_dwz */,
5874                                     0 /* base_offset */);
5875
5876   if (dwz_map.cu_count == 0)
5877     return;
5878
5879   dwz_file *dwz = dwarf2_get_dwz_file ();
5880   create_cus_from_debug_names_list (objfile, dwz_map, dwz->info,
5881                                     true /* is_dwz */,
5882                                     map.cu_count /* base_offset */);
5883 }
5884
5885 /* Read .debug_names.  If everything went ok, initialize the "quick"
5886    elements of all the CUs and return true.  Otherwise, return false.  */
5887
5888 static bool
5889 dwarf2_read_debug_names (struct objfile *objfile)
5890 {
5891   mapped_debug_names local_map, dwz_map;
5892
5893   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5894                                       &dwarf2_per_objfile->debug_names,
5895                                       local_map))
5896     return false;
5897
5898   /* Don't use the index if it's empty.  */
5899   if (local_map.name_count == 0)
5900     return false;
5901
5902   /* If there is a .dwz file, read it so we can get its CU list as
5903      well.  */
5904   dwz_file *dwz = dwarf2_get_dwz_file ();
5905   if (dwz != NULL)
5906     {
5907       if (!read_debug_names_from_section (objfile,
5908                                           bfd_get_filename (dwz->dwz_bfd),
5909                                           &dwz->debug_names, dwz_map))
5910         {
5911           warning (_("could not read '.debug_names' section from %s; skipping"),
5912                    bfd_get_filename (dwz->dwz_bfd));
5913           return false;
5914         }
5915     }
5916
5917   create_cus_from_debug_names (objfile, local_map, dwz_map);
5918
5919   if (local_map.tu_count != 0)
5920     {
5921       /* We can only handle a single .debug_types when we have an
5922          index.  */
5923       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5924         return false;
5925
5926       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5927                                                 dwarf2_per_objfile->types, 0);
5928
5929       create_signatured_type_table_from_debug_names
5930         (objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5931     }
5932
5933   create_addrmap_from_aranges (objfile, &dwarf2_per_objfile->debug_aranges);
5934
5935   dwarf2_per_objfile->debug_names_table.reset (new mapped_debug_names);
5936   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5937   dwarf2_per_objfile->using_index = 1;
5938   dwarf2_per_objfile->quick_file_names_table =
5939     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5940
5941   return true;
5942 }
5943
5944 /* Symbol name hashing function as specified by DWARF-5.  */
5945
5946 static uint32_t
5947 dwarf5_djb_hash (const char *str_)
5948 {
5949   const unsigned char *str = (const unsigned char *) str_;
5950
5951   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
5952      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
5953
5954   uint32_t hash = 5381;
5955   while (int c = *str++)
5956     hash = hash * 33 + tolower (c);
5957   return hash;
5958 }
5959
5960 /* Type used to manage iterating over all CUs looking for a symbol for
5961    .debug_names.  */
5962
5963 class dw2_debug_names_iterator
5964 {
5965 public:
5966   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5967      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5968   dw2_debug_names_iterator (const mapped_debug_names &map,
5969                             bool want_specific_block,
5970                             block_enum block_index, domain_enum domain,
5971                             const char *name)
5972     : m_map (map), m_want_specific_block (want_specific_block),
5973       m_block_index (block_index), m_domain (domain),
5974       m_addr (find_vec_in_debug_names (map, name))
5975   {}
5976
5977   dw2_debug_names_iterator (const mapped_debug_names &map,
5978                             search_domain search, uint32_t namei)
5979     : m_map (map),
5980       m_search (search),
5981       m_addr (find_vec_in_debug_names (map, namei))
5982   {}
5983
5984   /* Return the next matching CU or NULL if there are no more.  */
5985   dwarf2_per_cu_data *next ();
5986
5987 private:
5988   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5989                                                   const char *name);
5990   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5991                                                   uint32_t namei);
5992
5993   /* The internalized form of .debug_names.  */
5994   const mapped_debug_names &m_map;
5995
5996   /* If true, only look for symbols that match BLOCK_INDEX.  */
5997   const bool m_want_specific_block = false;
5998
5999   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6000      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6001      value.  */
6002   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6003
6004   /* The kind of symbol we're looking for.  */
6005   const domain_enum m_domain = UNDEF_DOMAIN;
6006   const search_domain m_search = ALL_DOMAIN;
6007
6008   /* The list of CUs from the index entry of the symbol, or NULL if
6009      not found.  */
6010   const gdb_byte *m_addr;
6011 };
6012
6013 const char *
6014 mapped_debug_names::namei_to_name (uint32_t namei) const
6015 {
6016   const ULONGEST namei_string_offs
6017     = extract_unsigned_integer ((name_table_string_offs_reordered
6018                                  + namei * offset_size),
6019                                 offset_size,
6020                                 dwarf5_byte_order);
6021   return read_indirect_string_at_offset
6022     (dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6023 }
6024
6025 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6026    found, return pointer to its pool data.  If NAME cannot be found,
6027    return NULL.  */
6028
6029 const gdb_byte *
6030 dw2_debug_names_iterator::find_vec_in_debug_names
6031   (const mapped_debug_names &map, const char *name)
6032 {
6033   int (*cmp) (const char *, const char *);
6034
6035   if (current_language->la_language == language_cplus
6036       || current_language->la_language == language_fortran
6037       || current_language->la_language == language_d)
6038     {
6039       /* NAME is already canonical.  Drop any qualifiers as
6040          .debug_names does not contain any.  */
6041
6042       if (strchr (name, '(') != NULL)
6043         {
6044           gdb::unique_xmalloc_ptr<char> without_params
6045             = cp_remove_params (name);
6046
6047           if (without_params != NULL)
6048             {
6049               name = without_params.get();
6050             }
6051         }
6052     }
6053
6054   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6055
6056   const uint32_t full_hash = dwarf5_djb_hash (name);
6057   uint32_t namei
6058     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6059                                 (map.bucket_table_reordered
6060                                  + (full_hash % map.bucket_count)), 4,
6061                                 map.dwarf5_byte_order);
6062   if (namei == 0)
6063     return NULL;
6064   --namei;
6065   if (namei >= map.name_count)
6066     {
6067       complaint (&symfile_complaints,
6068                  _("Wrong .debug_names with name index %u but name_count=%u "
6069                    "[in module %s]"),
6070                  namei, map.name_count,
6071                  objfile_name (dwarf2_per_objfile->objfile));
6072       return NULL;
6073     }
6074
6075   for (;;)
6076     {
6077       const uint32_t namei_full_hash
6078         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6079                                     (map.hash_table_reordered + namei), 4,
6080                                     map.dwarf5_byte_order);
6081       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6082         return NULL;
6083
6084       if (full_hash == namei_full_hash)
6085         {
6086           const char *const namei_string = map.namei_to_name (namei);
6087
6088 #if 0 /* An expensive sanity check.  */
6089           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6090             {
6091               complaint (&symfile_complaints,
6092                          _("Wrong .debug_names hash for string at index %u "
6093                            "[in module %s]"),
6094                          namei, objfile_name (dwarf2_per_objfile->objfile));
6095               return NULL;
6096             }
6097 #endif
6098
6099           if (cmp (namei_string, name) == 0)
6100             {
6101               const ULONGEST namei_entry_offs
6102                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6103                                              + namei * map.offset_size),
6104                                             map.offset_size, map.dwarf5_byte_order);
6105               return map.entry_pool + namei_entry_offs;
6106             }
6107         }
6108
6109       ++namei;
6110       if (namei >= map.name_count)
6111         return NULL;
6112     }
6113 }
6114
6115 const gdb_byte *
6116 dw2_debug_names_iterator::find_vec_in_debug_names
6117   (const mapped_debug_names &map, uint32_t namei)
6118 {
6119   if (namei >= map.name_count)
6120     {
6121       complaint (&symfile_complaints,
6122                  _("Wrong .debug_names with name index %u but name_count=%u "
6123                    "[in module %s]"),
6124                  namei, map.name_count,
6125                  objfile_name (dwarf2_per_objfile->objfile));
6126       return NULL;
6127     }
6128
6129   const ULONGEST namei_entry_offs
6130     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6131                                  + namei * map.offset_size),
6132                                 map.offset_size, map.dwarf5_byte_order);
6133   return map.entry_pool + namei_entry_offs;
6134 }
6135
6136 /* See dw2_debug_names_iterator.  */
6137
6138 dwarf2_per_cu_data *
6139 dw2_debug_names_iterator::next ()
6140 {
6141   if (m_addr == NULL)
6142     return NULL;
6143
6144   bfd *const abfd = dwarf2_per_objfile->objfile->obfd;
6145
6146  again:
6147
6148   unsigned int bytes_read;
6149   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6150   m_addr += bytes_read;
6151   if (abbrev == 0)
6152     return NULL;
6153
6154   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6155   if (indexval_it == m_map.abbrev_map.cend ())
6156     {
6157       complaint (&symfile_complaints,
6158                  _("Wrong .debug_names undefined abbrev code %s "
6159                    "[in module %s]"),
6160                  pulongest (abbrev), objfile_name (dwarf2_per_objfile->objfile));
6161       return NULL;
6162     }
6163   const mapped_debug_names::index_val &indexval = indexval_it->second;
6164   bool have_is_static = false;
6165   bool is_static;
6166   dwarf2_per_cu_data *per_cu = NULL;
6167   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6168     {
6169       ULONGEST ull;
6170       switch (attr.form)
6171         {
6172         case DW_FORM_implicit_const:
6173           ull = attr.implicit_const;
6174           break;
6175         case DW_FORM_flag_present:
6176           ull = 1;
6177           break;
6178         case DW_FORM_udata:
6179           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6180           m_addr += bytes_read;
6181           break;
6182         default:
6183           complaint (&symfile_complaints,
6184                      _("Unsupported .debug_names form %s [in module %s]"),
6185                      dwarf_form_name (attr.form),
6186                      objfile_name (dwarf2_per_objfile->objfile));
6187           return NULL;
6188         }
6189       switch (attr.dw_idx)
6190         {
6191         case DW_IDX_compile_unit:
6192           /* Don't crash on bad data.  */
6193           if (ull >= dwarf2_per_objfile->n_comp_units)
6194             {
6195               complaint (&symfile_complaints,
6196                          _(".debug_names entry has bad CU index %s"
6197                            " [in module %s]"),
6198                          pulongest (ull),
6199                          objfile_name (dwarf2_per_objfile->objfile));
6200               continue;
6201             }
6202           per_cu = dw2_get_cutu (ull);
6203           break;
6204         case DW_IDX_type_unit:
6205           /* Don't crash on bad data.  */
6206           if (ull >= dwarf2_per_objfile->n_type_units)
6207             {
6208               complaint (&symfile_complaints,
6209                          _(".debug_names entry has bad TU index %s"
6210                            " [in module %s]"),
6211                          pulongest (ull),
6212                          objfile_name (dwarf2_per_objfile->objfile));
6213               continue;
6214             }
6215           per_cu = dw2_get_cutu (dwarf2_per_objfile->n_comp_units + ull);
6216           break;
6217         case DW_IDX_GNU_internal:
6218           if (!m_map.augmentation_is_gdb)
6219             break;
6220           have_is_static = true;
6221           is_static = true;
6222           break;
6223         case DW_IDX_GNU_external:
6224           if (!m_map.augmentation_is_gdb)
6225             break;
6226           have_is_static = true;
6227           is_static = false;
6228           break;
6229         }
6230     }
6231
6232   /* Skip if already read in.  */
6233   if (per_cu->v.quick->compunit_symtab)
6234     goto again;
6235
6236   /* Check static vs global.  */
6237   if (have_is_static)
6238     {
6239       const bool want_static = m_block_index != GLOBAL_BLOCK;
6240       if (m_want_specific_block && want_static != is_static)
6241         goto again;
6242     }
6243
6244   /* Match dw2_symtab_iter_next, symbol_kind
6245      and debug_names::psymbol_tag.  */
6246   switch (m_domain)
6247     {
6248     case VAR_DOMAIN:
6249       switch (indexval.dwarf_tag)
6250         {
6251         case DW_TAG_variable:
6252         case DW_TAG_subprogram:
6253         /* Some types are also in VAR_DOMAIN.  */
6254         case DW_TAG_typedef:
6255         case DW_TAG_structure_type:
6256           break;
6257         default:
6258           goto again;
6259         }
6260       break;
6261     case STRUCT_DOMAIN:
6262       switch (indexval.dwarf_tag)
6263         {
6264         case DW_TAG_typedef:
6265         case DW_TAG_structure_type:
6266           break;
6267         default:
6268           goto again;
6269         }
6270       break;
6271     case LABEL_DOMAIN:
6272       switch (indexval.dwarf_tag)
6273         {
6274         case 0:
6275         case DW_TAG_variable:
6276           break;
6277         default:
6278           goto again;
6279         }
6280       break;
6281     default:
6282       break;
6283     }
6284
6285   /* Match dw2_expand_symtabs_matching, symbol_kind and
6286      debug_names::psymbol_tag.  */
6287   switch (m_search)
6288     {
6289     case VARIABLES_DOMAIN:
6290       switch (indexval.dwarf_tag)
6291         {
6292         case DW_TAG_variable:
6293           break;
6294         default:
6295           goto again;
6296         }
6297       break;
6298     case FUNCTIONS_DOMAIN:
6299       switch (indexval.dwarf_tag)
6300         {
6301         case DW_TAG_subprogram:
6302           break;
6303         default:
6304           goto again;
6305         }
6306       break;
6307     case TYPES_DOMAIN:
6308       switch (indexval.dwarf_tag)
6309         {
6310         case DW_TAG_typedef:
6311         case DW_TAG_structure_type:
6312           break;
6313         default:
6314           goto again;
6315         }
6316       break;
6317     default:
6318       break;
6319     }
6320
6321   return per_cu;
6322 }
6323
6324 static struct compunit_symtab *
6325 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6326                                const char *name, domain_enum domain)
6327 {
6328   const block_enum block_index = static_cast<block_enum> (block_index_int);
6329   dw2_setup (objfile);
6330
6331   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6332   if (!mapp)
6333     {
6334       /* index is NULL if OBJF_READNOW.  */
6335       return NULL;
6336     }
6337   const auto &map = *mapp;
6338
6339   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6340                                  block_index, domain, name);
6341
6342   struct compunit_symtab *stab_best = NULL;
6343   struct dwarf2_per_cu_data *per_cu;
6344   while ((per_cu = iter.next ()) != NULL)
6345     {
6346       struct symbol *sym, *with_opaque = NULL;
6347       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6348       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6349       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6350
6351       sym = block_find_symbol (block, name, domain,
6352                                block_find_non_opaque_type_preferred,
6353                                &with_opaque);
6354
6355       /* Some caution must be observed with overloaded functions and
6356          methods, since the index will not contain any overload
6357          information (but NAME might contain it).  */
6358
6359       if (sym != NULL
6360           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6361         return stab;
6362       if (with_opaque != NULL
6363           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6364         stab_best = stab;
6365
6366       /* Keep looking through other CUs.  */
6367     }
6368
6369   return stab_best;
6370 }
6371
6372 /* This dumps minimal information about .debug_names.  It is called
6373    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6374    uses this to verify that .debug_names has been loaded.  */
6375
6376 static void
6377 dw2_debug_names_dump (struct objfile *objfile)
6378 {
6379   dw2_setup (objfile);
6380   gdb_assert (dwarf2_per_objfile->using_index);
6381   printf_filtered (".debug_names:");
6382   if (dwarf2_per_objfile->debug_names_table)
6383     printf_filtered (" exists\n");
6384   else
6385     printf_filtered (" faked for \"readnow\"\n");
6386   printf_filtered ("\n");
6387 }
6388
6389 static void
6390 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6391                                              const char *func_name)
6392 {
6393   dw2_setup (objfile);
6394
6395   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6396   if (dwarf2_per_objfile->debug_names_table)
6397     {
6398       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6399
6400       /* Note: It doesn't matter what we pass for block_index here.  */
6401       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6402                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6403
6404       struct dwarf2_per_cu_data *per_cu;
6405       while ((per_cu = iter.next ()) != NULL)
6406         dw2_instantiate_symtab (per_cu);
6407     }
6408 }
6409
6410 static void
6411 dw2_debug_names_expand_symtabs_matching
6412   (struct objfile *objfile,
6413    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6414    const lookup_name_info &lookup_name,
6415    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6416    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6417    enum search_domain kind)
6418 {
6419   dw2_setup (objfile);
6420
6421   /* debug_names_table is NULL if OBJF_READNOW.  */
6422   if (!dwarf2_per_objfile->debug_names_table)
6423     return;
6424
6425   dw_expand_symtabs_matching_file_matcher (file_matcher);
6426
6427   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6428
6429   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6430                                       symbol_matcher,
6431                                       kind, [&] (offset_type namei)
6432     {
6433       /* The name was matched, now expand corresponding CUs that were
6434          marked.  */
6435       dw2_debug_names_iterator iter (map, kind, namei);
6436
6437       struct dwarf2_per_cu_data *per_cu;
6438       while ((per_cu = iter.next ()) != NULL)
6439         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6440                                          expansion_notify);
6441     });
6442 }
6443
6444 const struct quick_symbol_functions dwarf2_debug_names_functions =
6445 {
6446   dw2_has_symbols,
6447   dw2_find_last_source_symtab,
6448   dw2_forget_cached_source_info,
6449   dw2_map_symtabs_matching_filename,
6450   dw2_debug_names_lookup_symbol,
6451   dw2_print_stats,
6452   dw2_debug_names_dump,
6453   dw2_relocate,
6454   dw2_debug_names_expand_symtabs_for_function,
6455   dw2_expand_all_symtabs,
6456   dw2_expand_symtabs_with_fullname,
6457   dw2_map_matching_symbols,
6458   dw2_debug_names_expand_symtabs_matching,
6459   dw2_find_pc_sect_compunit_symtab,
6460   NULL,
6461   dw2_map_symbol_filenames
6462 };
6463
6464 /* See symfile.h.  */
6465
6466 bool
6467 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6468 {
6469   /* If we're about to read full symbols, don't bother with the
6470      indices.  In this case we also don't care if some other debug
6471      format is making psymtabs, because they are all about to be
6472      expanded anyway.  */
6473   if ((objfile->flags & OBJF_READNOW))
6474     {
6475       int i;
6476
6477       dwarf2_per_objfile->using_index = 1;
6478       create_all_comp_units (objfile);
6479       create_all_type_units (objfile);
6480       dwarf2_per_objfile->quick_file_names_table =
6481         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6482
6483       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6484                        + dwarf2_per_objfile->n_type_units); ++i)
6485         {
6486           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6487
6488           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6489                                             struct dwarf2_per_cu_quick_data);
6490         }
6491
6492       /* Return 1 so that gdb sees the "quick" functions.  However,
6493          these functions will be no-ops because we will have expanded
6494          all symtabs.  */
6495       *index_kind = dw_index_kind::GDB_INDEX;
6496       return true;
6497     }
6498
6499   if (dwarf2_read_debug_names (objfile))
6500     {
6501       *index_kind = dw_index_kind::DEBUG_NAMES;
6502       return true;
6503     }
6504
6505   if (dwarf2_read_index (objfile))
6506     {
6507       *index_kind = dw_index_kind::GDB_INDEX;
6508       return true;
6509     }
6510
6511   return false;
6512 }
6513
6514 \f
6515
6516 /* Build a partial symbol table.  */
6517
6518 void
6519 dwarf2_build_psymtabs (struct objfile *objfile)
6520 {
6521
6522   if (objfile->global_psymbols.capacity () == 0
6523       && objfile->static_psymbols.capacity () == 0)
6524     init_psymbol_list (objfile, 1024);
6525
6526   TRY
6527     {
6528       /* This isn't really ideal: all the data we allocate on the
6529          objfile's obstack is still uselessly kept around.  However,
6530          freeing it seems unsafe.  */
6531       psymtab_discarder psymtabs (objfile);
6532       dwarf2_build_psymtabs_hard (objfile);
6533       psymtabs.keep ();
6534     }
6535   CATCH (except, RETURN_MASK_ERROR)
6536     {
6537       exception_print (gdb_stderr, except);
6538     }
6539   END_CATCH
6540 }
6541
6542 /* Return the total length of the CU described by HEADER.  */
6543
6544 static unsigned int
6545 get_cu_length (const struct comp_unit_head *header)
6546 {
6547   return header->initial_length_size + header->length;
6548 }
6549
6550 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6551
6552 static inline bool
6553 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6554 {
6555   sect_offset bottom = cu_header->sect_off;
6556   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6557
6558   return sect_off >= bottom && sect_off < top;
6559 }
6560
6561 /* Find the base address of the compilation unit for range lists and
6562    location lists.  It will normally be specified by DW_AT_low_pc.
6563    In DWARF-3 draft 4, the base address could be overridden by
6564    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6565    compilation units with discontinuous ranges.  */
6566
6567 static void
6568 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6569 {
6570   struct attribute *attr;
6571
6572   cu->base_known = 0;
6573   cu->base_address = 0;
6574
6575   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6576   if (attr)
6577     {
6578       cu->base_address = attr_value_as_address (attr);
6579       cu->base_known = 1;
6580     }
6581   else
6582     {
6583       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6584       if (attr)
6585         {
6586           cu->base_address = attr_value_as_address (attr);
6587           cu->base_known = 1;
6588         }
6589     }
6590 }
6591
6592 /* Read in the comp unit header information from the debug_info at info_ptr.
6593    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6594    NOTE: This leaves members offset, first_die_offset to be filled in
6595    by the caller.  */
6596
6597 static const gdb_byte *
6598 read_comp_unit_head (struct comp_unit_head *cu_header,
6599                      const gdb_byte *info_ptr,
6600                      struct dwarf2_section_info *section,
6601                      rcuh_kind section_kind)
6602 {
6603   int signed_addr;
6604   unsigned int bytes_read;
6605   const char *filename = get_section_file_name (section);
6606   bfd *abfd = get_section_bfd_owner (section);
6607
6608   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6609   cu_header->initial_length_size = bytes_read;
6610   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6611   info_ptr += bytes_read;
6612   cu_header->version = read_2_bytes (abfd, info_ptr);
6613   info_ptr += 2;
6614   if (cu_header->version < 5)
6615     switch (section_kind)
6616       {
6617       case rcuh_kind::COMPILE:
6618         cu_header->unit_type = DW_UT_compile;
6619         break;
6620       case rcuh_kind::TYPE:
6621         cu_header->unit_type = DW_UT_type;
6622         break;
6623       default:
6624         internal_error (__FILE__, __LINE__,
6625                         _("read_comp_unit_head: invalid section_kind"));
6626       }
6627   else
6628     {
6629       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6630                                                  (read_1_byte (abfd, info_ptr));
6631       info_ptr += 1;
6632       switch (cu_header->unit_type)
6633         {
6634         case DW_UT_compile:
6635           if (section_kind != rcuh_kind::COMPILE)
6636             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6637                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6638                    filename);
6639           break;
6640         case DW_UT_type:
6641           section_kind = rcuh_kind::TYPE;
6642           break;
6643         default:
6644           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6645                  "(is %d, should be %d or %d) [in module %s]"),
6646                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6647         }
6648
6649       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6650       info_ptr += 1;
6651     }
6652   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6653                                                           cu_header,
6654                                                           &bytes_read);
6655   info_ptr += bytes_read;
6656   if (cu_header->version < 5)
6657     {
6658       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6659       info_ptr += 1;
6660     }
6661   signed_addr = bfd_get_sign_extend_vma (abfd);
6662   if (signed_addr < 0)
6663     internal_error (__FILE__, __LINE__,
6664                     _("read_comp_unit_head: dwarf from non elf file"));
6665   cu_header->signed_addr_p = signed_addr;
6666
6667   if (section_kind == rcuh_kind::TYPE)
6668     {
6669       LONGEST type_offset;
6670
6671       cu_header->signature = read_8_bytes (abfd, info_ptr);
6672       info_ptr += 8;
6673
6674       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6675       info_ptr += bytes_read;
6676       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6677       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6678         error (_("Dwarf Error: Too big type_offset in compilation unit "
6679                "header (is %s) [in module %s]"), plongest (type_offset),
6680                filename);
6681     }
6682
6683   return info_ptr;
6684 }
6685
6686 /* Helper function that returns the proper abbrev section for
6687    THIS_CU.  */
6688
6689 static struct dwarf2_section_info *
6690 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6691 {
6692   struct dwarf2_section_info *abbrev;
6693
6694   if (this_cu->is_dwz)
6695     abbrev = &dwarf2_get_dwz_file ()->abbrev;
6696   else
6697     abbrev = &dwarf2_per_objfile->abbrev;
6698
6699   return abbrev;
6700 }
6701
6702 /* Subroutine of read_and_check_comp_unit_head and
6703    read_and_check_type_unit_head to simplify them.
6704    Perform various error checking on the header.  */
6705
6706 static void
6707 error_check_comp_unit_head (struct comp_unit_head *header,
6708                             struct dwarf2_section_info *section,
6709                             struct dwarf2_section_info *abbrev_section)
6710 {
6711   const char *filename = get_section_file_name (section);
6712
6713   if (header->version < 2 || header->version > 5)
6714     error (_("Dwarf Error: wrong version in compilation unit header "
6715            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6716            filename);
6717
6718   if (to_underlying (header->abbrev_sect_off)
6719       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6720     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6721            "(offset 0x%x + 6) [in module %s]"),
6722            to_underlying (header->abbrev_sect_off),
6723            to_underlying (header->sect_off),
6724            filename);
6725
6726   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6727      avoid potential 32-bit overflow.  */
6728   if (((ULONGEST) header->sect_off + get_cu_length (header))
6729       > section->size)
6730     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6731            "(offset 0x%x + 0) [in module %s]"),
6732            header->length, to_underlying (header->sect_off),
6733            filename);
6734 }
6735
6736 /* Read in a CU/TU header and perform some basic error checking.
6737    The contents of the header are stored in HEADER.
6738    The result is a pointer to the start of the first DIE.  */
6739
6740 static const gdb_byte *
6741 read_and_check_comp_unit_head (struct comp_unit_head *header,
6742                                struct dwarf2_section_info *section,
6743                                struct dwarf2_section_info *abbrev_section,
6744                                const gdb_byte *info_ptr,
6745                                rcuh_kind section_kind)
6746 {
6747   const gdb_byte *beg_of_comp_unit = info_ptr;
6748
6749   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6750
6751   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6752
6753   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6754
6755   error_check_comp_unit_head (header, section, abbrev_section);
6756
6757   return info_ptr;
6758 }
6759
6760 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6761
6762 static sect_offset
6763 read_abbrev_offset (struct dwarf2_section_info *section,
6764                     sect_offset sect_off)
6765 {
6766   bfd *abfd = get_section_bfd_owner (section);
6767   const gdb_byte *info_ptr;
6768   unsigned int initial_length_size, offset_size;
6769   uint16_t version;
6770
6771   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6772   info_ptr = section->buffer + to_underlying (sect_off);
6773   read_initial_length (abfd, info_ptr, &initial_length_size);
6774   offset_size = initial_length_size == 4 ? 4 : 8;
6775   info_ptr += initial_length_size;
6776
6777   version = read_2_bytes (abfd, info_ptr);
6778   info_ptr += 2;
6779   if (version >= 5)
6780     {
6781       /* Skip unit type and address size.  */
6782       info_ptr += 2;
6783     }
6784
6785   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6786 }
6787
6788 /* Allocate a new partial symtab for file named NAME and mark this new
6789    partial symtab as being an include of PST.  */
6790
6791 static void
6792 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6793                                struct objfile *objfile)
6794 {
6795   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6796
6797   if (!IS_ABSOLUTE_PATH (subpst->filename))
6798     {
6799       /* It shares objfile->objfile_obstack.  */
6800       subpst->dirname = pst->dirname;
6801     }
6802
6803   subpst->textlow = 0;
6804   subpst->texthigh = 0;
6805
6806   subpst->dependencies
6807     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6808   subpst->dependencies[0] = pst;
6809   subpst->number_of_dependencies = 1;
6810
6811   subpst->globals_offset = 0;
6812   subpst->n_global_syms = 0;
6813   subpst->statics_offset = 0;
6814   subpst->n_static_syms = 0;
6815   subpst->compunit_symtab = NULL;
6816   subpst->read_symtab = pst->read_symtab;
6817   subpst->readin = 0;
6818
6819   /* No private part is necessary for include psymtabs.  This property
6820      can be used to differentiate between such include psymtabs and
6821      the regular ones.  */
6822   subpst->read_symtab_private = NULL;
6823 }
6824
6825 /* Read the Line Number Program data and extract the list of files
6826    included by the source file represented by PST.  Build an include
6827    partial symtab for each of these included files.  */
6828
6829 static void
6830 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6831                                struct die_info *die,
6832                                struct partial_symtab *pst)
6833 {
6834   line_header_up lh;
6835   struct attribute *attr;
6836
6837   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6838   if (attr)
6839     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6840   if (lh == NULL)
6841     return;  /* No linetable, so no includes.  */
6842
6843   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6844   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6845 }
6846
6847 static hashval_t
6848 hash_signatured_type (const void *item)
6849 {
6850   const struct signatured_type *sig_type
6851     = (const struct signatured_type *) item;
6852
6853   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6854   return sig_type->signature;
6855 }
6856
6857 static int
6858 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6859 {
6860   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6861   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6862
6863   return lhs->signature == rhs->signature;
6864 }
6865
6866 /* Allocate a hash table for signatured types.  */
6867
6868 static htab_t
6869 allocate_signatured_type_table (struct objfile *objfile)
6870 {
6871   return htab_create_alloc_ex (41,
6872                                hash_signatured_type,
6873                                eq_signatured_type,
6874                                NULL,
6875                                &objfile->objfile_obstack,
6876                                hashtab_obstack_allocate,
6877                                dummy_obstack_deallocate);
6878 }
6879
6880 /* A helper function to add a signatured type CU to a table.  */
6881
6882 static int
6883 add_signatured_type_cu_to_table (void **slot, void *datum)
6884 {
6885   struct signatured_type *sigt = (struct signatured_type *) *slot;
6886   struct signatured_type ***datap = (struct signatured_type ***) datum;
6887
6888   **datap = sigt;
6889   ++*datap;
6890
6891   return 1;
6892 }
6893
6894 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6895    and fill them into TYPES_HTAB.  It will process only type units,
6896    therefore DW_UT_type.  */
6897
6898 static void
6899 create_debug_type_hash_table (struct dwo_file *dwo_file,
6900                               dwarf2_section_info *section, htab_t &types_htab,
6901                               rcuh_kind section_kind)
6902 {
6903   struct objfile *objfile = dwarf2_per_objfile->objfile;
6904   struct dwarf2_section_info *abbrev_section;
6905   bfd *abfd;
6906   const gdb_byte *info_ptr, *end_ptr;
6907
6908   abbrev_section = (dwo_file != NULL
6909                     ? &dwo_file->sections.abbrev
6910                     : &dwarf2_per_objfile->abbrev);
6911
6912   if (dwarf_read_debug)
6913     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6914                         get_section_name (section),
6915                         get_section_file_name (abbrev_section));
6916
6917   dwarf2_read_section (objfile, section);
6918   info_ptr = section->buffer;
6919
6920   if (info_ptr == NULL)
6921     return;
6922
6923   /* We can't set abfd until now because the section may be empty or
6924      not present, in which case the bfd is unknown.  */
6925   abfd = get_section_bfd_owner (section);
6926
6927   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6928      because we don't need to read any dies: the signature is in the
6929      header.  */
6930
6931   end_ptr = info_ptr + section->size;
6932   while (info_ptr < end_ptr)
6933     {
6934       struct signatured_type *sig_type;
6935       struct dwo_unit *dwo_tu;
6936       void **slot;
6937       const gdb_byte *ptr = info_ptr;
6938       struct comp_unit_head header;
6939       unsigned int length;
6940
6941       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6942
6943       /* Initialize it due to a false compiler warning.  */
6944       header.signature = -1;
6945       header.type_cu_offset_in_tu = (cu_offset) -1;
6946
6947       /* We need to read the type's signature in order to build the hash
6948          table, but we don't need anything else just yet.  */
6949
6950       ptr = read_and_check_comp_unit_head (&header, section,
6951                                            abbrev_section, ptr, section_kind);
6952
6953       length = get_cu_length (&header);
6954
6955       /* Skip dummy type units.  */
6956       if (ptr >= info_ptr + length
6957           || peek_abbrev_code (abfd, ptr) == 0
6958           || header.unit_type != DW_UT_type)
6959         {
6960           info_ptr += length;
6961           continue;
6962         }
6963
6964       if (types_htab == NULL)
6965         {
6966           if (dwo_file)
6967             types_htab = allocate_dwo_unit_table (objfile);
6968           else
6969             types_htab = allocate_signatured_type_table (objfile);
6970         }
6971
6972       if (dwo_file)
6973         {
6974           sig_type = NULL;
6975           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6976                                    struct dwo_unit);
6977           dwo_tu->dwo_file = dwo_file;
6978           dwo_tu->signature = header.signature;
6979           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6980           dwo_tu->section = section;
6981           dwo_tu->sect_off = sect_off;
6982           dwo_tu->length = length;
6983         }
6984       else
6985         {
6986           /* N.B.: type_offset is not usable if this type uses a DWO file.
6987              The real type_offset is in the DWO file.  */
6988           dwo_tu = NULL;
6989           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6990                                      struct signatured_type);
6991           sig_type->signature = header.signature;
6992           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6993           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6994           sig_type->per_cu.is_debug_types = 1;
6995           sig_type->per_cu.section = section;
6996           sig_type->per_cu.sect_off = sect_off;
6997           sig_type->per_cu.length = length;
6998         }
6999
7000       slot = htab_find_slot (types_htab,
7001                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7002                              INSERT);
7003       gdb_assert (slot != NULL);
7004       if (*slot != NULL)
7005         {
7006           sect_offset dup_sect_off;
7007
7008           if (dwo_file)
7009             {
7010               const struct dwo_unit *dup_tu
7011                 = (const struct dwo_unit *) *slot;
7012
7013               dup_sect_off = dup_tu->sect_off;
7014             }
7015           else
7016             {
7017               const struct signatured_type *dup_tu
7018                 = (const struct signatured_type *) *slot;
7019
7020               dup_sect_off = dup_tu->per_cu.sect_off;
7021             }
7022
7023           complaint (&symfile_complaints,
7024                      _("debug type entry at offset 0x%x is duplicate to"
7025                        " the entry at offset 0x%x, signature %s"),
7026                      to_underlying (sect_off), to_underlying (dup_sect_off),
7027                      hex_string (header.signature));
7028         }
7029       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7030
7031       if (dwarf_read_debug > 1)
7032         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7033                             to_underlying (sect_off),
7034                             hex_string (header.signature));
7035
7036       info_ptr += length;
7037     }
7038 }
7039
7040 /* Create the hash table of all entries in the .debug_types
7041    (or .debug_types.dwo) section(s).
7042    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7043    otherwise it is NULL.
7044
7045    The result is a pointer to the hash table or NULL if there are no types.
7046
7047    Note: This function processes DWO files only, not DWP files.  */
7048
7049 static void
7050 create_debug_types_hash_table (struct dwo_file *dwo_file,
7051                                VEC (dwarf2_section_info_def) *types,
7052                                htab_t &types_htab)
7053 {
7054   int ix;
7055   struct dwarf2_section_info *section;
7056
7057   if (VEC_empty (dwarf2_section_info_def, types))
7058     return;
7059
7060   for (ix = 0;
7061        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7062        ++ix)
7063     create_debug_type_hash_table (dwo_file, section, types_htab,
7064                                   rcuh_kind::TYPE);
7065 }
7066
7067 /* Create the hash table of all entries in the .debug_types section,
7068    and initialize all_type_units.
7069    The result is zero if there is an error (e.g. missing .debug_types section),
7070    otherwise non-zero.  */
7071
7072 static int
7073 create_all_type_units (struct objfile *objfile)
7074 {
7075   htab_t types_htab = NULL;
7076   struct signatured_type **iter;
7077
7078   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
7079                                 rcuh_kind::COMPILE);
7080   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
7081   if (types_htab == NULL)
7082     {
7083       dwarf2_per_objfile->signatured_types = NULL;
7084       return 0;
7085     }
7086
7087   dwarf2_per_objfile->signatured_types = types_htab;
7088
7089   dwarf2_per_objfile->n_type_units
7090     = dwarf2_per_objfile->n_allocated_type_units
7091     = htab_elements (types_htab);
7092   dwarf2_per_objfile->all_type_units =
7093     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7094   iter = &dwarf2_per_objfile->all_type_units[0];
7095   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7096   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7097               == dwarf2_per_objfile->n_type_units);
7098
7099   return 1;
7100 }
7101
7102 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7103    If SLOT is non-NULL, it is the entry to use in the hash table.
7104    Otherwise we find one.  */
7105
7106 static struct signatured_type *
7107 add_type_unit (ULONGEST sig, void **slot)
7108 {
7109   struct objfile *objfile = dwarf2_per_objfile->objfile;
7110   int n_type_units = dwarf2_per_objfile->n_type_units;
7111   struct signatured_type *sig_type;
7112
7113   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7114   ++n_type_units;
7115   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7116     {
7117       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7118         dwarf2_per_objfile->n_allocated_type_units = 1;
7119       dwarf2_per_objfile->n_allocated_type_units *= 2;
7120       dwarf2_per_objfile->all_type_units
7121         = XRESIZEVEC (struct signatured_type *,
7122                       dwarf2_per_objfile->all_type_units,
7123                       dwarf2_per_objfile->n_allocated_type_units);
7124       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7125     }
7126   dwarf2_per_objfile->n_type_units = n_type_units;
7127
7128   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7129                              struct signatured_type);
7130   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7131   sig_type->signature = sig;
7132   sig_type->per_cu.is_debug_types = 1;
7133   if (dwarf2_per_objfile->using_index)
7134     {
7135       sig_type->per_cu.v.quick =
7136         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7137                         struct dwarf2_per_cu_quick_data);
7138     }
7139
7140   if (slot == NULL)
7141     {
7142       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7143                              sig_type, INSERT);
7144     }
7145   gdb_assert (*slot == NULL);
7146   *slot = sig_type;
7147   /* The rest of sig_type must be filled in by the caller.  */
7148   return sig_type;
7149 }
7150
7151 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7152    Fill in SIG_ENTRY with DWO_ENTRY.  */
7153
7154 static void
7155 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
7156                                   struct signatured_type *sig_entry,
7157                                   struct dwo_unit *dwo_entry)
7158 {
7159   /* Make sure we're not clobbering something we don't expect to.  */
7160   gdb_assert (! sig_entry->per_cu.queued);
7161   gdb_assert (sig_entry->per_cu.cu == NULL);
7162   if (dwarf2_per_objfile->using_index)
7163     {
7164       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7165       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7166     }
7167   else
7168       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7169   gdb_assert (sig_entry->signature == dwo_entry->signature);
7170   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7171   gdb_assert (sig_entry->type_unit_group == NULL);
7172   gdb_assert (sig_entry->dwo_unit == NULL);
7173
7174   sig_entry->per_cu.section = dwo_entry->section;
7175   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7176   sig_entry->per_cu.length = dwo_entry->length;
7177   sig_entry->per_cu.reading_dwo_directly = 1;
7178   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7179   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7180   sig_entry->dwo_unit = dwo_entry;
7181 }
7182
7183 /* Subroutine of lookup_signatured_type.
7184    If we haven't read the TU yet, create the signatured_type data structure
7185    for a TU to be read in directly from a DWO file, bypassing the stub.
7186    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7187    using .gdb_index, then when reading a CU we want to stay in the DWO file
7188    containing that CU.  Otherwise we could end up reading several other DWO
7189    files (due to comdat folding) to process the transitive closure of all the
7190    mentioned TUs, and that can be slow.  The current DWO file will have every
7191    type signature that it needs.
7192    We only do this for .gdb_index because in the psymtab case we already have
7193    to read all the DWOs to build the type unit groups.  */
7194
7195 static struct signatured_type *
7196 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7197 {
7198   struct objfile *objfile = dwarf2_per_objfile->objfile;
7199   struct dwo_file *dwo_file;
7200   struct dwo_unit find_dwo_entry, *dwo_entry;
7201   struct signatured_type find_sig_entry, *sig_entry;
7202   void **slot;
7203
7204   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7205
7206   /* If TU skeletons have been removed then we may not have read in any
7207      TUs yet.  */
7208   if (dwarf2_per_objfile->signatured_types == NULL)
7209     {
7210       dwarf2_per_objfile->signatured_types
7211         = allocate_signatured_type_table (objfile);
7212     }
7213
7214   /* We only ever need to read in one copy of a signatured type.
7215      Use the global signatured_types array to do our own comdat-folding
7216      of types.  If this is the first time we're reading this TU, and
7217      the TU has an entry in .gdb_index, replace the recorded data from
7218      .gdb_index with this TU.  */
7219
7220   find_sig_entry.signature = sig;
7221   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7222                          &find_sig_entry, INSERT);
7223   sig_entry = (struct signatured_type *) *slot;
7224
7225   /* We can get here with the TU already read, *or* in the process of being
7226      read.  Don't reassign the global entry to point to this DWO if that's
7227      the case.  Also note that if the TU is already being read, it may not
7228      have come from a DWO, the program may be a mix of Fission-compiled
7229      code and non-Fission-compiled code.  */
7230
7231   /* Have we already tried to read this TU?
7232      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7233      needn't exist in the global table yet).  */
7234   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7235     return sig_entry;
7236
7237   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7238      dwo_unit of the TU itself.  */
7239   dwo_file = cu->dwo_unit->dwo_file;
7240
7241   /* Ok, this is the first time we're reading this TU.  */
7242   if (dwo_file->tus == NULL)
7243     return NULL;
7244   find_dwo_entry.signature = sig;
7245   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7246   if (dwo_entry == NULL)
7247     return NULL;
7248
7249   /* If the global table doesn't have an entry for this TU, add one.  */
7250   if (sig_entry == NULL)
7251     sig_entry = add_type_unit (sig, slot);
7252
7253   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7254   sig_entry->per_cu.tu_read = 1;
7255   return sig_entry;
7256 }
7257
7258 /* Subroutine of lookup_signatured_type.
7259    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7260    then try the DWP file.  If the TU stub (skeleton) has been removed then
7261    it won't be in .gdb_index.  */
7262
7263 static struct signatured_type *
7264 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7265 {
7266   struct objfile *objfile = dwarf2_per_objfile->objfile;
7267   struct dwp_file *dwp_file = get_dwp_file ();
7268   struct dwo_unit *dwo_entry;
7269   struct signatured_type find_sig_entry, *sig_entry;
7270   void **slot;
7271
7272   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7273   gdb_assert (dwp_file != NULL);
7274
7275   /* If TU skeletons have been removed then we may not have read in any
7276      TUs yet.  */
7277   if (dwarf2_per_objfile->signatured_types == NULL)
7278     {
7279       dwarf2_per_objfile->signatured_types
7280         = allocate_signatured_type_table (objfile);
7281     }
7282
7283   find_sig_entry.signature = sig;
7284   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7285                          &find_sig_entry, INSERT);
7286   sig_entry = (struct signatured_type *) *slot;
7287
7288   /* Have we already tried to read this TU?
7289      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7290      needn't exist in the global table yet).  */
7291   if (sig_entry != NULL)
7292     return sig_entry;
7293
7294   if (dwp_file->tus == NULL)
7295     return NULL;
7296   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
7297                                       sig, 1 /* is_debug_types */);
7298   if (dwo_entry == NULL)
7299     return NULL;
7300
7301   sig_entry = add_type_unit (sig, slot);
7302   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7303
7304   return sig_entry;
7305 }
7306
7307 /* Lookup a signature based type for DW_FORM_ref_sig8.
7308    Returns NULL if signature SIG is not present in the table.
7309    It is up to the caller to complain about this.  */
7310
7311 static struct signatured_type *
7312 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7313 {
7314   if (cu->dwo_unit
7315       && dwarf2_per_objfile->using_index)
7316     {
7317       /* We're in a DWO/DWP file, and we're using .gdb_index.
7318          These cases require special processing.  */
7319       if (get_dwp_file () == NULL)
7320         return lookup_dwo_signatured_type (cu, sig);
7321       else
7322         return lookup_dwp_signatured_type (cu, sig);
7323     }
7324   else
7325     {
7326       struct signatured_type find_entry, *entry;
7327
7328       if (dwarf2_per_objfile->signatured_types == NULL)
7329         return NULL;
7330       find_entry.signature = sig;
7331       entry = ((struct signatured_type *)
7332                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7333       return entry;
7334     }
7335 }
7336 \f
7337 /* Low level DIE reading support.  */
7338
7339 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7340
7341 static void
7342 init_cu_die_reader (struct die_reader_specs *reader,
7343                     struct dwarf2_cu *cu,
7344                     struct dwarf2_section_info *section,
7345                     struct dwo_file *dwo_file)
7346 {
7347   gdb_assert (section->readin && section->buffer != NULL);
7348   reader->abfd = get_section_bfd_owner (section);
7349   reader->cu = cu;
7350   reader->dwo_file = dwo_file;
7351   reader->die_section = section;
7352   reader->buffer = section->buffer;
7353   reader->buffer_end = section->buffer + section->size;
7354   reader->comp_dir = NULL;
7355 }
7356
7357 /* Subroutine of init_cutu_and_read_dies to simplify it.
7358    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7359    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7360    already.
7361
7362    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7363    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7364    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7365    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7366    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7367    STUB_COMP_DIR may be non-NULL.
7368    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7369    are filled in with the info of the DIE from the DWO file.
7370    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
7371    provided an abbrev table to use.
7372    The result is non-zero if a valid (non-dummy) DIE was found.  */
7373
7374 static int
7375 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7376                         struct dwo_unit *dwo_unit,
7377                         int abbrev_table_provided,
7378                         struct die_info *stub_comp_unit_die,
7379                         const char *stub_comp_dir,
7380                         struct die_reader_specs *result_reader,
7381                         const gdb_byte **result_info_ptr,
7382                         struct die_info **result_comp_unit_die,
7383                         int *result_has_children)
7384 {
7385   struct objfile *objfile = dwarf2_per_objfile->objfile;
7386   struct dwarf2_cu *cu = this_cu->cu;
7387   struct dwarf2_section_info *section;
7388   bfd *abfd;
7389   const gdb_byte *begin_info_ptr, *info_ptr;
7390   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7391   int i,num_extra_attrs;
7392   struct dwarf2_section_info *dwo_abbrev_section;
7393   struct attribute *attr;
7394   struct die_info *comp_unit_die;
7395
7396   /* At most one of these may be provided.  */
7397   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7398
7399   /* These attributes aren't processed until later:
7400      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7401      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7402      referenced later.  However, these attributes are found in the stub
7403      which we won't have later.  In order to not impose this complication
7404      on the rest of the code, we read them here and copy them to the
7405      DWO CU/TU die.  */
7406
7407   stmt_list = NULL;
7408   low_pc = NULL;
7409   high_pc = NULL;
7410   ranges = NULL;
7411   comp_dir = NULL;
7412
7413   if (stub_comp_unit_die != NULL)
7414     {
7415       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7416          DWO file.  */
7417       if (! this_cu->is_debug_types)
7418         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7419       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7420       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7421       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7422       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7423
7424       /* There should be a DW_AT_addr_base attribute here (if needed).
7425          We need the value before we can process DW_FORM_GNU_addr_index.  */
7426       cu->addr_base = 0;
7427       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7428       if (attr)
7429         cu->addr_base = DW_UNSND (attr);
7430
7431       /* There should be a DW_AT_ranges_base attribute here (if needed).
7432          We need the value before we can process DW_AT_ranges.  */
7433       cu->ranges_base = 0;
7434       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7435       if (attr)
7436         cu->ranges_base = DW_UNSND (attr);
7437     }
7438   else if (stub_comp_dir != NULL)
7439     {
7440       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7441       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7442       comp_dir->name = DW_AT_comp_dir;
7443       comp_dir->form = DW_FORM_string;
7444       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7445       DW_STRING (comp_dir) = stub_comp_dir;
7446     }
7447
7448   /* Set up for reading the DWO CU/TU.  */
7449   cu->dwo_unit = dwo_unit;
7450   section = dwo_unit->section;
7451   dwarf2_read_section (objfile, section);
7452   abfd = get_section_bfd_owner (section);
7453   begin_info_ptr = info_ptr = (section->buffer
7454                                + to_underlying (dwo_unit->sect_off));
7455   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7456   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
7457
7458   if (this_cu->is_debug_types)
7459     {
7460       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7461
7462       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7463                                                 dwo_abbrev_section,
7464                                                 info_ptr, rcuh_kind::TYPE);
7465       /* This is not an assert because it can be caused by bad debug info.  */
7466       if (sig_type->signature != cu->header.signature)
7467         {
7468           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7469                    " TU at offset 0x%x [in module %s]"),
7470                  hex_string (sig_type->signature),
7471                  hex_string (cu->header.signature),
7472                  to_underlying (dwo_unit->sect_off),
7473                  bfd_get_filename (abfd));
7474         }
7475       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7476       /* For DWOs coming from DWP files, we don't know the CU length
7477          nor the type's offset in the TU until now.  */
7478       dwo_unit->length = get_cu_length (&cu->header);
7479       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7480
7481       /* Establish the type offset that can be used to lookup the type.
7482          For DWO files, we don't know it until now.  */
7483       sig_type->type_offset_in_section
7484         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7485     }
7486   else
7487     {
7488       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7489                                                 dwo_abbrev_section,
7490                                                 info_ptr, rcuh_kind::COMPILE);
7491       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7492       /* For DWOs coming from DWP files, we don't know the CU length
7493          until now.  */
7494       dwo_unit->length = get_cu_length (&cu->header);
7495     }
7496
7497   /* Replace the CU's original abbrev table with the DWO's.
7498      Reminder: We can't read the abbrev table until we've read the header.  */
7499   if (abbrev_table_provided)
7500     {
7501       /* Don't free the provided abbrev table, the caller of
7502          init_cutu_and_read_dies owns it.  */
7503       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7504       /* Ensure the DWO abbrev table gets freed.  */
7505       make_cleanup (dwarf2_free_abbrev_table, cu);
7506     }
7507   else
7508     {
7509       dwarf2_free_abbrev_table (cu);
7510       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7511       /* Leave any existing abbrev table cleanup as is.  */
7512     }
7513
7514   /* Read in the die, but leave space to copy over the attributes
7515      from the stub.  This has the benefit of simplifying the rest of
7516      the code - all the work to maintain the illusion of a single
7517      DW_TAG_{compile,type}_unit DIE is done here.  */
7518   num_extra_attrs = ((stmt_list != NULL)
7519                      + (low_pc != NULL)
7520                      + (high_pc != NULL)
7521                      + (ranges != NULL)
7522                      + (comp_dir != NULL));
7523   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7524                               result_has_children, num_extra_attrs);
7525
7526   /* Copy over the attributes from the stub to the DIE we just read in.  */
7527   comp_unit_die = *result_comp_unit_die;
7528   i = comp_unit_die->num_attrs;
7529   if (stmt_list != NULL)
7530     comp_unit_die->attrs[i++] = *stmt_list;
7531   if (low_pc != NULL)
7532     comp_unit_die->attrs[i++] = *low_pc;
7533   if (high_pc != NULL)
7534     comp_unit_die->attrs[i++] = *high_pc;
7535   if (ranges != NULL)
7536     comp_unit_die->attrs[i++] = *ranges;
7537   if (comp_dir != NULL)
7538     comp_unit_die->attrs[i++] = *comp_dir;
7539   comp_unit_die->num_attrs += num_extra_attrs;
7540
7541   if (dwarf_die_debug)
7542     {
7543       fprintf_unfiltered (gdb_stdlog,
7544                           "Read die from %s@0x%x of %s:\n",
7545                           get_section_name (section),
7546                           (unsigned) (begin_info_ptr - section->buffer),
7547                           bfd_get_filename (abfd));
7548       dump_die (comp_unit_die, dwarf_die_debug);
7549     }
7550
7551   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7552      TUs by skipping the stub and going directly to the entry in the DWO file.
7553      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7554      to get it via circuitous means.  Blech.  */
7555   if (comp_dir != NULL)
7556     result_reader->comp_dir = DW_STRING (comp_dir);
7557
7558   /* Skip dummy compilation units.  */
7559   if (info_ptr >= begin_info_ptr + dwo_unit->length
7560       || peek_abbrev_code (abfd, info_ptr) == 0)
7561     return 0;
7562
7563   *result_info_ptr = info_ptr;
7564   return 1;
7565 }
7566
7567 /* Subroutine of init_cutu_and_read_dies to simplify it.
7568    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7569    Returns NULL if the specified DWO unit cannot be found.  */
7570
7571 static struct dwo_unit *
7572 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7573                  struct die_info *comp_unit_die)
7574 {
7575   struct dwarf2_cu *cu = this_cu->cu;
7576   ULONGEST signature;
7577   struct dwo_unit *dwo_unit;
7578   const char *comp_dir, *dwo_name;
7579
7580   gdb_assert (cu != NULL);
7581
7582   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7583   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7584   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7585
7586   if (this_cu->is_debug_types)
7587     {
7588       struct signatured_type *sig_type;
7589
7590       /* Since this_cu is the first member of struct signatured_type,
7591          we can go from a pointer to one to a pointer to the other.  */
7592       sig_type = (struct signatured_type *) this_cu;
7593       signature = sig_type->signature;
7594       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7595     }
7596   else
7597     {
7598       struct attribute *attr;
7599
7600       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7601       if (! attr)
7602         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7603                  " [in module %s]"),
7604                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7605       signature = DW_UNSND (attr);
7606       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7607                                        signature);
7608     }
7609
7610   return dwo_unit;
7611 }
7612
7613 /* Subroutine of init_cutu_and_read_dies to simplify it.
7614    See it for a description of the parameters.
7615    Read a TU directly from a DWO file, bypassing the stub.
7616
7617    Note: This function could be a little bit simpler if we shared cleanups
7618    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7619    to do, so we keep this function self-contained.  Or we could move this
7620    into our caller, but it's complex enough already.  */
7621
7622 static void
7623 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7624                            int use_existing_cu, int keep,
7625                            die_reader_func_ftype *die_reader_func,
7626                            void *data)
7627 {
7628   struct dwarf2_cu *cu;
7629   struct signatured_type *sig_type;
7630   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7631   struct die_reader_specs reader;
7632   const gdb_byte *info_ptr;
7633   struct die_info *comp_unit_die;
7634   int has_children;
7635
7636   /* Verify we can do the following downcast, and that we have the
7637      data we need.  */
7638   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7639   sig_type = (struct signatured_type *) this_cu;
7640   gdb_assert (sig_type->dwo_unit != NULL);
7641
7642   cleanups = make_cleanup (null_cleanup, NULL);
7643
7644   if (use_existing_cu && this_cu->cu != NULL)
7645     {
7646       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7647       cu = this_cu->cu;
7648       /* There's no need to do the rereading_dwo_cu handling that
7649          init_cutu_and_read_dies does since we don't read the stub.  */
7650     }
7651   else
7652     {
7653       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7654       gdb_assert (this_cu->cu == NULL);
7655       cu = XNEW (struct dwarf2_cu);
7656       init_one_comp_unit (cu, this_cu);
7657       /* If an error occurs while loading, release our storage.  */
7658       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7659     }
7660
7661   /* A future optimization, if needed, would be to use an existing
7662      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7663      could share abbrev tables.  */
7664
7665   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7666                               0 /* abbrev_table_provided */,
7667                               NULL /* stub_comp_unit_die */,
7668                               sig_type->dwo_unit->dwo_file->comp_dir,
7669                               &reader, &info_ptr,
7670                               &comp_unit_die, &has_children) == 0)
7671     {
7672       /* Dummy die.  */
7673       do_cleanups (cleanups);
7674       return;
7675     }
7676
7677   /* All the "real" work is done here.  */
7678   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7679
7680   /* This duplicates the code in init_cutu_and_read_dies,
7681      but the alternative is making the latter more complex.
7682      This function is only for the special case of using DWO files directly:
7683      no point in overly complicating the general case just to handle this.  */
7684   if (free_cu_cleanup != NULL)
7685     {
7686       if (keep)
7687         {
7688           /* We've successfully allocated this compilation unit.  Let our
7689              caller clean it up when finished with it.  */
7690           discard_cleanups (free_cu_cleanup);
7691
7692           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7693              So we have to manually free the abbrev table.  */
7694           dwarf2_free_abbrev_table (cu);
7695
7696           /* Link this CU into read_in_chain.  */
7697           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7698           dwarf2_per_objfile->read_in_chain = this_cu;
7699         }
7700       else
7701         do_cleanups (free_cu_cleanup);
7702     }
7703
7704   do_cleanups (cleanups);
7705 }
7706
7707 /* Initialize a CU (or TU) and read its DIEs.
7708    If the CU defers to a DWO file, read the DWO file as well.
7709
7710    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7711    Otherwise the table specified in the comp unit header is read in and used.
7712    This is an optimization for when we already have the abbrev table.
7713
7714    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7715    Otherwise, a new CU is allocated with xmalloc.
7716
7717    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7718    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7719
7720    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7721    linker) then DIE_READER_FUNC will not get called.  */
7722
7723 static void
7724 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7725                          struct abbrev_table *abbrev_table,
7726                          int use_existing_cu, int keep,
7727                          die_reader_func_ftype *die_reader_func,
7728                          void *data)
7729 {
7730   struct objfile *objfile = dwarf2_per_objfile->objfile;
7731   struct dwarf2_section_info *section = this_cu->section;
7732   bfd *abfd = get_section_bfd_owner (section);
7733   struct dwarf2_cu *cu;
7734   const gdb_byte *begin_info_ptr, *info_ptr;
7735   struct die_reader_specs reader;
7736   struct die_info *comp_unit_die;
7737   int has_children;
7738   struct attribute *attr;
7739   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7740   struct signatured_type *sig_type = NULL;
7741   struct dwarf2_section_info *abbrev_section;
7742   /* Non-zero if CU currently points to a DWO file and we need to
7743      reread it.  When this happens we need to reread the skeleton die
7744      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7745   int rereading_dwo_cu = 0;
7746
7747   if (dwarf_die_debug)
7748     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7749                         this_cu->is_debug_types ? "type" : "comp",
7750                         to_underlying (this_cu->sect_off));
7751
7752   if (use_existing_cu)
7753     gdb_assert (keep);
7754
7755   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7756      file (instead of going through the stub), short-circuit all of this.  */
7757   if (this_cu->reading_dwo_directly)
7758     {
7759       /* Narrow down the scope of possibilities to have to understand.  */
7760       gdb_assert (this_cu->is_debug_types);
7761       gdb_assert (abbrev_table == NULL);
7762       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7763                                  die_reader_func, data);
7764       return;
7765     }
7766
7767   cleanups = make_cleanup (null_cleanup, NULL);
7768
7769   /* This is cheap if the section is already read in.  */
7770   dwarf2_read_section (objfile, section);
7771
7772   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7773
7774   abbrev_section = get_abbrev_section_for_cu (this_cu);
7775
7776   if (use_existing_cu && this_cu->cu != NULL)
7777     {
7778       cu = this_cu->cu;
7779       /* If this CU is from a DWO file we need to start over, we need to
7780          refetch the attributes from the skeleton CU.
7781          This could be optimized by retrieving those attributes from when we
7782          were here the first time: the previous comp_unit_die was stored in
7783          comp_unit_obstack.  But there's no data yet that we need this
7784          optimization.  */
7785       if (cu->dwo_unit != NULL)
7786         rereading_dwo_cu = 1;
7787     }
7788   else
7789     {
7790       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7791       gdb_assert (this_cu->cu == NULL);
7792       cu = XNEW (struct dwarf2_cu);
7793       init_one_comp_unit (cu, this_cu);
7794       /* If an error occurs while loading, release our storage.  */
7795       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7796     }
7797
7798   /* Get the header.  */
7799   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7800     {
7801       /* We already have the header, there's no need to read it in again.  */
7802       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7803     }
7804   else
7805     {
7806       if (this_cu->is_debug_types)
7807         {
7808           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7809                                                     abbrev_section, info_ptr,
7810                                                     rcuh_kind::TYPE);
7811
7812           /* Since per_cu is the first member of struct signatured_type,
7813              we can go from a pointer to one to a pointer to the other.  */
7814           sig_type = (struct signatured_type *) this_cu;
7815           gdb_assert (sig_type->signature == cu->header.signature);
7816           gdb_assert (sig_type->type_offset_in_tu
7817                       == cu->header.type_cu_offset_in_tu);
7818           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7819
7820           /* LENGTH has not been set yet for type units if we're
7821              using .gdb_index.  */
7822           this_cu->length = get_cu_length (&cu->header);
7823
7824           /* Establish the type offset that can be used to lookup the type.  */
7825           sig_type->type_offset_in_section =
7826             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7827
7828           this_cu->dwarf_version = cu->header.version;
7829         }
7830       else
7831         {
7832           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7833                                                     abbrev_section,
7834                                                     info_ptr,
7835                                                     rcuh_kind::COMPILE);
7836
7837           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7838           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7839           this_cu->dwarf_version = cu->header.version;
7840         }
7841     }
7842
7843   /* Skip dummy compilation units.  */
7844   if (info_ptr >= begin_info_ptr + this_cu->length
7845       || peek_abbrev_code (abfd, info_ptr) == 0)
7846     {
7847       do_cleanups (cleanups);
7848       return;
7849     }
7850
7851   /* If we don't have them yet, read the abbrevs for this compilation unit.
7852      And if we need to read them now, make sure they're freed when we're
7853      done.  Note that it's important that if the CU had an abbrev table
7854      on entry we don't free it when we're done: Somewhere up the call stack
7855      it may be in use.  */
7856   if (abbrev_table != NULL)
7857     {
7858       gdb_assert (cu->abbrev_table == NULL);
7859       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7860       cu->abbrev_table = abbrev_table;
7861     }
7862   else if (cu->abbrev_table == NULL)
7863     {
7864       dwarf2_read_abbrevs (cu, abbrev_section);
7865       make_cleanup (dwarf2_free_abbrev_table, cu);
7866     }
7867   else if (rereading_dwo_cu)
7868     {
7869       dwarf2_free_abbrev_table (cu);
7870       dwarf2_read_abbrevs (cu, abbrev_section);
7871     }
7872
7873   /* Read the top level CU/TU die.  */
7874   init_cu_die_reader (&reader, cu, section, NULL);
7875   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7876
7877   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7878      from the DWO file.
7879      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7880      DWO CU, that this test will fail (the attribute will not be present).  */
7881   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7882   if (attr)
7883     {
7884       struct dwo_unit *dwo_unit;
7885       struct die_info *dwo_comp_unit_die;
7886
7887       if (has_children)
7888         {
7889           complaint (&symfile_complaints,
7890                      _("compilation unit with DW_AT_GNU_dwo_name"
7891                        " has children (offset 0x%x) [in module %s]"),
7892                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7893         }
7894       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7895       if (dwo_unit != NULL)
7896         {
7897           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7898                                       abbrev_table != NULL,
7899                                       comp_unit_die, NULL,
7900                                       &reader, &info_ptr,
7901                                       &dwo_comp_unit_die, &has_children) == 0)
7902             {
7903               /* Dummy die.  */
7904               do_cleanups (cleanups);
7905               return;
7906             }
7907           comp_unit_die = dwo_comp_unit_die;
7908         }
7909       else
7910         {
7911           /* Yikes, we couldn't find the rest of the DIE, we only have
7912              the stub.  A complaint has already been logged.  There's
7913              not much more we can do except pass on the stub DIE to
7914              die_reader_func.  We don't want to throw an error on bad
7915              debug info.  */
7916         }
7917     }
7918
7919   /* All of the above is setup for this call.  Yikes.  */
7920   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7921
7922   /* Done, clean up.  */
7923   if (free_cu_cleanup != NULL)
7924     {
7925       if (keep)
7926         {
7927           /* We've successfully allocated this compilation unit.  Let our
7928              caller clean it up when finished with it.  */
7929           discard_cleanups (free_cu_cleanup);
7930
7931           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7932              So we have to manually free the abbrev table.  */
7933           dwarf2_free_abbrev_table (cu);
7934
7935           /* Link this CU into read_in_chain.  */
7936           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7937           dwarf2_per_objfile->read_in_chain = this_cu;
7938         }
7939       else
7940         do_cleanups (free_cu_cleanup);
7941     }
7942
7943   do_cleanups (cleanups);
7944 }
7945
7946 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7947    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7948    to have already done the lookup to find the DWO file).
7949
7950    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7951    THIS_CU->is_debug_types, but nothing else.
7952
7953    We fill in THIS_CU->length.
7954
7955    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7956    linker) then DIE_READER_FUNC will not get called.
7957
7958    THIS_CU->cu is always freed when done.
7959    This is done in order to not leave THIS_CU->cu in a state where we have
7960    to care whether it refers to the "main" CU or the DWO CU.  */
7961
7962 static void
7963 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7964                                    struct dwo_file *dwo_file,
7965                                    die_reader_func_ftype *die_reader_func,
7966                                    void *data)
7967 {
7968   struct objfile *objfile = dwarf2_per_objfile->objfile;
7969   struct dwarf2_section_info *section = this_cu->section;
7970   bfd *abfd = get_section_bfd_owner (section);
7971   struct dwarf2_section_info *abbrev_section;
7972   struct dwarf2_cu cu;
7973   const gdb_byte *begin_info_ptr, *info_ptr;
7974   struct die_reader_specs reader;
7975   struct cleanup *cleanups;
7976   struct die_info *comp_unit_die;
7977   int has_children;
7978
7979   if (dwarf_die_debug)
7980     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7981                         this_cu->is_debug_types ? "type" : "comp",
7982                         to_underlying (this_cu->sect_off));
7983
7984   gdb_assert (this_cu->cu == NULL);
7985
7986   abbrev_section = (dwo_file != NULL
7987                     ? &dwo_file->sections.abbrev
7988                     : get_abbrev_section_for_cu (this_cu));
7989
7990   /* This is cheap if the section is already read in.  */
7991   dwarf2_read_section (objfile, section);
7992
7993   init_one_comp_unit (&cu, this_cu);
7994
7995   cleanups = make_cleanup (free_stack_comp_unit, &cu);
7996
7997   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7998   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
7999                                             abbrev_section, info_ptr,
8000                                             (this_cu->is_debug_types
8001                                              ? rcuh_kind::TYPE
8002                                              : rcuh_kind::COMPILE));
8003
8004   this_cu->length = get_cu_length (&cu.header);
8005
8006   /* Skip dummy compilation units.  */
8007   if (info_ptr >= begin_info_ptr + this_cu->length
8008       || peek_abbrev_code (abfd, info_ptr) == 0)
8009     {
8010       do_cleanups (cleanups);
8011       return;
8012     }
8013
8014   dwarf2_read_abbrevs (&cu, abbrev_section);
8015   make_cleanup (dwarf2_free_abbrev_table, &cu);
8016
8017   init_cu_die_reader (&reader, &cu, section, dwo_file);
8018   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8019
8020   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8021
8022   do_cleanups (cleanups);
8023 }
8024
8025 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8026    does not lookup the specified DWO file.
8027    This cannot be used to read DWO files.
8028
8029    THIS_CU->cu is always freed when done.
8030    This is done in order to not leave THIS_CU->cu in a state where we have
8031    to care whether it refers to the "main" CU or the DWO CU.
8032    We can revisit this if the data shows there's a performance issue.  */
8033
8034 static void
8035 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8036                                 die_reader_func_ftype *die_reader_func,
8037                                 void *data)
8038 {
8039   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8040 }
8041 \f
8042 /* Type Unit Groups.
8043
8044    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8045    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8046    so that all types coming from the same compilation (.o file) are grouped
8047    together.  A future step could be to put the types in the same symtab as
8048    the CU the types ultimately came from.  */
8049
8050 static hashval_t
8051 hash_type_unit_group (const void *item)
8052 {
8053   const struct type_unit_group *tu_group
8054     = (const struct type_unit_group *) item;
8055
8056   return hash_stmt_list_entry (&tu_group->hash);
8057 }
8058
8059 static int
8060 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8061 {
8062   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8063   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8064
8065   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8066 }
8067
8068 /* Allocate a hash table for type unit groups.  */
8069
8070 static htab_t
8071 allocate_type_unit_groups_table (void)
8072 {
8073   return htab_create_alloc_ex (3,
8074                                hash_type_unit_group,
8075                                eq_type_unit_group,
8076                                NULL,
8077                                &dwarf2_per_objfile->objfile->objfile_obstack,
8078                                hashtab_obstack_allocate,
8079                                dummy_obstack_deallocate);
8080 }
8081
8082 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8083    partial symtabs.  We combine several TUs per psymtab to not let the size
8084    of any one psymtab grow too big.  */
8085 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8086 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8087
8088 /* Helper routine for get_type_unit_group.
8089    Create the type_unit_group object used to hold one or more TUs.  */
8090
8091 static struct type_unit_group *
8092 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8093 {
8094   struct objfile *objfile = dwarf2_per_objfile->objfile;
8095   struct dwarf2_per_cu_data *per_cu;
8096   struct type_unit_group *tu_group;
8097
8098   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8099                              struct type_unit_group);
8100   per_cu = &tu_group->per_cu;
8101   per_cu->dwarf2_per_objfile = cu->dwarf2_per_objfile;
8102
8103   if (dwarf2_per_objfile->using_index)
8104     {
8105       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8106                                         struct dwarf2_per_cu_quick_data);
8107     }
8108   else
8109     {
8110       unsigned int line_offset = to_underlying (line_offset_struct);
8111       struct partial_symtab *pst;
8112       char *name;
8113
8114       /* Give the symtab a useful name for debug purposes.  */
8115       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8116         name = xstrprintf ("<type_units_%d>",
8117                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8118       else
8119         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8120
8121       pst = create_partial_symtab (per_cu, name);
8122       pst->anonymous = 1;
8123
8124       xfree (name);
8125     }
8126
8127   tu_group->hash.dwo_unit = cu->dwo_unit;
8128   tu_group->hash.line_sect_off = line_offset_struct;
8129
8130   return tu_group;
8131 }
8132
8133 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8134    STMT_LIST is a DW_AT_stmt_list attribute.  */
8135
8136 static struct type_unit_group *
8137 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8138 {
8139   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8140   struct type_unit_group *tu_group;
8141   void **slot;
8142   unsigned int line_offset;
8143   struct type_unit_group type_unit_group_for_lookup;
8144
8145   if (dwarf2_per_objfile->type_unit_groups == NULL)
8146     {
8147       dwarf2_per_objfile->type_unit_groups =
8148         allocate_type_unit_groups_table ();
8149     }
8150
8151   /* Do we need to create a new group, or can we use an existing one?  */
8152
8153   if (stmt_list)
8154     {
8155       line_offset = DW_UNSND (stmt_list);
8156       ++tu_stats->nr_symtab_sharers;
8157     }
8158   else
8159     {
8160       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8161          We can do various things here like create one group per TU or
8162          spread them over multiple groups to split up the expansion work.
8163          To avoid worst case scenarios (too many groups or too large groups)
8164          we, umm, group them in bunches.  */
8165       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8166                      | (tu_stats->nr_stmt_less_type_units
8167                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8168       ++tu_stats->nr_stmt_less_type_units;
8169     }
8170
8171   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8172   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8173   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8174                          &type_unit_group_for_lookup, INSERT);
8175   if (*slot != NULL)
8176     {
8177       tu_group = (struct type_unit_group *) *slot;
8178       gdb_assert (tu_group != NULL);
8179     }
8180   else
8181     {
8182       sect_offset line_offset_struct = (sect_offset) line_offset;
8183       tu_group = create_type_unit_group (cu, line_offset_struct);
8184       *slot = tu_group;
8185       ++tu_stats->nr_symtabs;
8186     }
8187
8188   return tu_group;
8189 }
8190 \f
8191 /* Partial symbol tables.  */
8192
8193 /* Create a psymtab named NAME and assign it to PER_CU.
8194
8195    The caller must fill in the following details:
8196    dirname, textlow, texthigh.  */
8197
8198 static struct partial_symtab *
8199 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8200 {
8201   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8202   struct partial_symtab *pst;
8203
8204   pst = start_psymtab_common (objfile, name, 0,
8205                               objfile->global_psymbols,
8206                               objfile->static_psymbols);
8207
8208   pst->psymtabs_addrmap_supported = 1;
8209
8210   /* This is the glue that links PST into GDB's symbol API.  */
8211   pst->read_symtab_private = per_cu;
8212   pst->read_symtab = dwarf2_read_symtab;
8213   per_cu->v.psymtab = pst;
8214
8215   return pst;
8216 }
8217
8218 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8219    type.  */
8220
8221 struct process_psymtab_comp_unit_data
8222 {
8223   /* True if we are reading a DW_TAG_partial_unit.  */
8224
8225   int want_partial_unit;
8226
8227   /* The "pretend" language that is used if the CU doesn't declare a
8228      language.  */
8229
8230   enum language pretend_language;
8231 };
8232
8233 /* die_reader_func for process_psymtab_comp_unit.  */
8234
8235 static void
8236 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8237                                   const gdb_byte *info_ptr,
8238                                   struct die_info *comp_unit_die,
8239                                   int has_children,
8240                                   void *data)
8241 {
8242   struct dwarf2_cu *cu = reader->cu;
8243   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
8244   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8245   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8246   CORE_ADDR baseaddr;
8247   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8248   struct partial_symtab *pst;
8249   enum pc_bounds_kind cu_bounds_kind;
8250   const char *filename;
8251   struct process_psymtab_comp_unit_data *info
8252     = (struct process_psymtab_comp_unit_data *) data;
8253
8254   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8255     return;
8256
8257   gdb_assert (! per_cu->is_debug_types);
8258
8259   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8260
8261   cu->list_in_scope = &file_symbols;
8262
8263   /* Allocate a new partial symbol table structure.  */
8264   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8265   if (filename == NULL)
8266     filename = "";
8267
8268   pst = create_partial_symtab (per_cu, filename);
8269
8270   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8271   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8272
8273   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8274
8275   dwarf2_find_base_address (comp_unit_die, cu);
8276
8277   /* Possibly set the default values of LOWPC and HIGHPC from
8278      `DW_AT_ranges'.  */
8279   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8280                                          &best_highpc, cu, pst);
8281   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8282     /* Store the contiguous range if it is not empty; it can be empty for
8283        CUs with no code.  */
8284     addrmap_set_empty (objfile->psymtabs_addrmap,
8285                        gdbarch_adjust_dwarf2_addr (gdbarch,
8286                                                    best_lowpc + baseaddr),
8287                        gdbarch_adjust_dwarf2_addr (gdbarch,
8288                                                    best_highpc + baseaddr) - 1,
8289                        pst);
8290
8291   /* Check if comp unit has_children.
8292      If so, read the rest of the partial symbols from this comp unit.
8293      If not, there's no more debug_info for this comp unit.  */
8294   if (has_children)
8295     {
8296       struct partial_die_info *first_die;
8297       CORE_ADDR lowpc, highpc;
8298
8299       lowpc = ((CORE_ADDR) -1);
8300       highpc = ((CORE_ADDR) 0);
8301
8302       first_die = load_partial_dies (reader, info_ptr, 1);
8303
8304       scan_partial_symbols (first_die, &lowpc, &highpc,
8305                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8306
8307       /* If we didn't find a lowpc, set it to highpc to avoid
8308          complaints from `maint check'.  */
8309       if (lowpc == ((CORE_ADDR) -1))
8310         lowpc = highpc;
8311
8312       /* If the compilation unit didn't have an explicit address range,
8313          then use the information extracted from its child dies.  */
8314       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8315         {
8316           best_lowpc = lowpc;
8317           best_highpc = highpc;
8318         }
8319     }
8320   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8321   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8322
8323   end_psymtab_common (objfile, pst);
8324
8325   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8326     {
8327       int i;
8328       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8329       struct dwarf2_per_cu_data *iter;
8330
8331       /* Fill in 'dependencies' here; we fill in 'users' in a
8332          post-pass.  */
8333       pst->number_of_dependencies = len;
8334       pst->dependencies =
8335         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8336       for (i = 0;
8337            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8338                         i, iter);
8339            ++i)
8340         pst->dependencies[i] = iter->v.psymtab;
8341
8342       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8343     }
8344
8345   /* Get the list of files included in the current compilation unit,
8346      and build a psymtab for each of them.  */
8347   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8348
8349   if (dwarf_read_debug)
8350     {
8351       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8352
8353       fprintf_unfiltered (gdb_stdlog,
8354                           "Psymtab for %s unit @0x%x: %s - %s"
8355                           ", %d global, %d static syms\n",
8356                           per_cu->is_debug_types ? "type" : "comp",
8357                           to_underlying (per_cu->sect_off),
8358                           paddress (gdbarch, pst->textlow),
8359                           paddress (gdbarch, pst->texthigh),
8360                           pst->n_global_syms, pst->n_static_syms);
8361     }
8362 }
8363
8364 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8365    Process compilation unit THIS_CU for a psymtab.  */
8366
8367 static void
8368 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8369                            int want_partial_unit,
8370                            enum language pretend_language)
8371 {
8372   /* If this compilation unit was already read in, free the
8373      cached copy in order to read it in again.  This is
8374      necessary because we skipped some symbols when we first
8375      read in the compilation unit (see load_partial_dies).
8376      This problem could be avoided, but the benefit is unclear.  */
8377   if (this_cu->cu != NULL)
8378     free_one_cached_comp_unit (this_cu);
8379
8380   if (this_cu->is_debug_types)
8381     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8382                              NULL);
8383   else
8384     {
8385       process_psymtab_comp_unit_data info;
8386       info.want_partial_unit = want_partial_unit;
8387       info.pretend_language = pretend_language;
8388       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8389                                process_psymtab_comp_unit_reader, &info);
8390     }
8391
8392   /* Age out any secondary CUs.  */
8393   age_cached_comp_units ();
8394 }
8395
8396 /* Reader function for build_type_psymtabs.  */
8397
8398 static void
8399 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8400                             const gdb_byte *info_ptr,
8401                             struct die_info *type_unit_die,
8402                             int has_children,
8403                             void *data)
8404 {
8405   struct objfile *objfile = dwarf2_per_objfile->objfile;
8406   struct dwarf2_cu *cu = reader->cu;
8407   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8408   struct signatured_type *sig_type;
8409   struct type_unit_group *tu_group;
8410   struct attribute *attr;
8411   struct partial_die_info *first_die;
8412   CORE_ADDR lowpc, highpc;
8413   struct partial_symtab *pst;
8414
8415   gdb_assert (data == NULL);
8416   gdb_assert (per_cu->is_debug_types);
8417   sig_type = (struct signatured_type *) per_cu;
8418
8419   if (! has_children)
8420     return;
8421
8422   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8423   tu_group = get_type_unit_group (cu, attr);
8424
8425   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8426
8427   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8428   cu->list_in_scope = &file_symbols;
8429   pst = create_partial_symtab (per_cu, "");
8430   pst->anonymous = 1;
8431
8432   first_die = load_partial_dies (reader, info_ptr, 1);
8433
8434   lowpc = (CORE_ADDR) -1;
8435   highpc = (CORE_ADDR) 0;
8436   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8437
8438   end_psymtab_common (objfile, pst);
8439 }
8440
8441 /* Struct used to sort TUs by their abbreviation table offset.  */
8442
8443 struct tu_abbrev_offset
8444 {
8445   struct signatured_type *sig_type;
8446   sect_offset abbrev_offset;
8447 };
8448
8449 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8450
8451 static int
8452 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8453 {
8454   const struct tu_abbrev_offset * const *a
8455     = (const struct tu_abbrev_offset * const*) ap;
8456   const struct tu_abbrev_offset * const *b
8457     = (const struct tu_abbrev_offset * const*) bp;
8458   sect_offset aoff = (*a)->abbrev_offset;
8459   sect_offset boff = (*b)->abbrev_offset;
8460
8461   return (aoff > boff) - (aoff < boff);
8462 }
8463
8464 /* Efficiently read all the type units.
8465    This does the bulk of the work for build_type_psymtabs.
8466
8467    The efficiency is because we sort TUs by the abbrev table they use and
8468    only read each abbrev table once.  In one program there are 200K TUs
8469    sharing 8K abbrev tables.
8470
8471    The main purpose of this function is to support building the
8472    dwarf2_per_objfile->type_unit_groups table.
8473    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8474    can collapse the search space by grouping them by stmt_list.
8475    The savings can be significant, in the same program from above the 200K TUs
8476    share 8K stmt_list tables.
8477
8478    FUNC is expected to call get_type_unit_group, which will create the
8479    struct type_unit_group if necessary and add it to
8480    dwarf2_per_objfile->type_unit_groups.  */
8481
8482 static void
8483 build_type_psymtabs_1 (void)
8484 {
8485   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8486   struct cleanup *cleanups;
8487   struct abbrev_table *abbrev_table;
8488   sect_offset abbrev_offset;
8489   struct tu_abbrev_offset *sorted_by_abbrev;
8490   int i;
8491
8492   /* It's up to the caller to not call us multiple times.  */
8493   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8494
8495   if (dwarf2_per_objfile->n_type_units == 0)
8496     return;
8497
8498   /* TUs typically share abbrev tables, and there can be way more TUs than
8499      abbrev tables.  Sort by abbrev table to reduce the number of times we
8500      read each abbrev table in.
8501      Alternatives are to punt or to maintain a cache of abbrev tables.
8502      This is simpler and efficient enough for now.
8503
8504      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8505      symtab to use).  Typically TUs with the same abbrev offset have the same
8506      stmt_list value too so in practice this should work well.
8507
8508      The basic algorithm here is:
8509
8510       sort TUs by abbrev table
8511       for each TU with same abbrev table:
8512         read abbrev table if first user
8513         read TU top level DIE
8514           [IWBN if DWO skeletons had DW_AT_stmt_list]
8515         call FUNC  */
8516
8517   if (dwarf_read_debug)
8518     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8519
8520   /* Sort in a separate table to maintain the order of all_type_units
8521      for .gdb_index: TU indices directly index all_type_units.  */
8522   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8523                               dwarf2_per_objfile->n_type_units);
8524   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8525     {
8526       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8527
8528       sorted_by_abbrev[i].sig_type = sig_type;
8529       sorted_by_abbrev[i].abbrev_offset =
8530         read_abbrev_offset (sig_type->per_cu.section,
8531                             sig_type->per_cu.sect_off);
8532     }
8533   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8534   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8535          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8536
8537   abbrev_offset = (sect_offset) ~(unsigned) 0;
8538   abbrev_table = NULL;
8539   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
8540
8541   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8542     {
8543       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8544
8545       /* Switch to the next abbrev table if necessary.  */
8546       if (abbrev_table == NULL
8547           || tu->abbrev_offset != abbrev_offset)
8548         {
8549           if (abbrev_table != NULL)
8550             {
8551               abbrev_table_free (abbrev_table);
8552               /* Reset to NULL in case abbrev_table_read_table throws
8553                  an error: abbrev_table_free_cleanup will get called.  */
8554               abbrev_table = NULL;
8555             }
8556           abbrev_offset = tu->abbrev_offset;
8557           abbrev_table =
8558             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
8559                                      abbrev_offset);
8560           ++tu_stats->nr_uniq_abbrev_tables;
8561         }
8562
8563       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
8564                                build_type_psymtabs_reader, NULL);
8565     }
8566
8567   do_cleanups (cleanups);
8568 }
8569
8570 /* Print collected type unit statistics.  */
8571
8572 static void
8573 print_tu_stats (void)
8574 {
8575   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8576
8577   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8578   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8579                       dwarf2_per_objfile->n_type_units);
8580   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8581                       tu_stats->nr_uniq_abbrev_tables);
8582   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8583                       tu_stats->nr_symtabs);
8584   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8585                       tu_stats->nr_symtab_sharers);
8586   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8587                       tu_stats->nr_stmt_less_type_units);
8588   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8589                       tu_stats->nr_all_type_units_reallocs);
8590 }
8591
8592 /* Traversal function for build_type_psymtabs.  */
8593
8594 static int
8595 build_type_psymtab_dependencies (void **slot, void *info)
8596 {
8597   struct objfile *objfile = dwarf2_per_objfile->objfile;
8598   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8599   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8600   struct partial_symtab *pst = per_cu->v.psymtab;
8601   int len = VEC_length (sig_type_ptr, tu_group->tus);
8602   struct signatured_type *iter;
8603   int i;
8604
8605   gdb_assert (len > 0);
8606   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8607
8608   pst->number_of_dependencies = len;
8609   pst->dependencies =
8610     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8611   for (i = 0;
8612        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8613        ++i)
8614     {
8615       gdb_assert (iter->per_cu.is_debug_types);
8616       pst->dependencies[i] = iter->per_cu.v.psymtab;
8617       iter->type_unit_group = tu_group;
8618     }
8619
8620   VEC_free (sig_type_ptr, tu_group->tus);
8621
8622   return 1;
8623 }
8624
8625 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8626    Build partial symbol tables for the .debug_types comp-units.  */
8627
8628 static void
8629 build_type_psymtabs (struct objfile *objfile)
8630 {
8631   if (! create_all_type_units (objfile))
8632     return;
8633
8634   build_type_psymtabs_1 ();
8635 }
8636
8637 /* Traversal function for process_skeletonless_type_unit.
8638    Read a TU in a DWO file and build partial symbols for it.  */
8639
8640 static int
8641 process_skeletonless_type_unit (void **slot, void *info)
8642 {
8643   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8644   struct objfile *objfile = (struct objfile *) info;
8645   struct signatured_type find_entry, *entry;
8646
8647   /* If this TU doesn't exist in the global table, add it and read it in.  */
8648
8649   if (dwarf2_per_objfile->signatured_types == NULL)
8650     {
8651       dwarf2_per_objfile->signatured_types
8652         = allocate_signatured_type_table (objfile);
8653     }
8654
8655   find_entry.signature = dwo_unit->signature;
8656   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8657                          INSERT);
8658   /* If we've already seen this type there's nothing to do.  What's happening
8659      is we're doing our own version of comdat-folding here.  */
8660   if (*slot != NULL)
8661     return 1;
8662
8663   /* This does the job that create_all_type_units would have done for
8664      this TU.  */
8665   entry = add_type_unit (dwo_unit->signature, slot);
8666   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
8667   *slot = entry;
8668
8669   /* This does the job that build_type_psymtabs_1 would have done.  */
8670   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8671                            build_type_psymtabs_reader, NULL);
8672
8673   return 1;
8674 }
8675
8676 /* Traversal function for process_skeletonless_type_units.  */
8677
8678 static int
8679 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8680 {
8681   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8682
8683   if (dwo_file->tus != NULL)
8684     {
8685       htab_traverse_noresize (dwo_file->tus,
8686                               process_skeletonless_type_unit, info);
8687     }
8688
8689   return 1;
8690 }
8691
8692 /* Scan all TUs of DWO files, verifying we've processed them.
8693    This is needed in case a TU was emitted without its skeleton.
8694    Note: This can't be done until we know what all the DWO files are.  */
8695
8696 static void
8697 process_skeletonless_type_units (struct objfile *objfile)
8698 {
8699   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8700   if (get_dwp_file () == NULL
8701       && dwarf2_per_objfile->dwo_files != NULL)
8702     {
8703       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8704                               process_dwo_file_for_skeletonless_type_units,
8705                               objfile);
8706     }
8707 }
8708
8709 /* Compute the 'user' field for each psymtab in OBJFILE.  */
8710
8711 static void
8712 set_partial_user (struct objfile *objfile)
8713 {
8714   int i;
8715
8716   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8717     {
8718       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8719       struct partial_symtab *pst = per_cu->v.psymtab;
8720       int j;
8721
8722       if (pst == NULL)
8723         continue;
8724
8725       for (j = 0; j < pst->number_of_dependencies; ++j)
8726         {
8727           /* Set the 'user' field only if it is not already set.  */
8728           if (pst->dependencies[j]->user == NULL)
8729             pst->dependencies[j]->user = pst;
8730         }
8731     }
8732 }
8733
8734 /* Build the partial symbol table by doing a quick pass through the
8735    .debug_info and .debug_abbrev sections.  */
8736
8737 static void
8738 dwarf2_build_psymtabs_hard (struct objfile *objfile)
8739 {
8740   struct cleanup *back_to;
8741   int i;
8742
8743   if (dwarf_read_debug)
8744     {
8745       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8746                           objfile_name (objfile));
8747     }
8748
8749   dwarf2_per_objfile->reading_partial_symbols = 1;
8750
8751   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8752
8753   /* Any cached compilation units will be linked by the per-objfile
8754      read_in_chain.  Make sure to free them when we're done.  */
8755   back_to = make_cleanup (free_cached_comp_units, NULL);
8756
8757   build_type_psymtabs (objfile);
8758
8759   create_all_comp_units (objfile);
8760
8761   /* Create a temporary address map on a temporary obstack.  We later
8762      copy this to the final obstack.  */
8763   auto_obstack temp_obstack;
8764
8765   scoped_restore save_psymtabs_addrmap
8766     = make_scoped_restore (&objfile->psymtabs_addrmap,
8767                            addrmap_create_mutable (&temp_obstack));
8768
8769   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8770     {
8771       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8772
8773       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8774     }
8775
8776   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8777   process_skeletonless_type_units (objfile);
8778
8779   /* Now that all TUs have been processed we can fill in the dependencies.  */
8780   if (dwarf2_per_objfile->type_unit_groups != NULL)
8781     {
8782       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8783                               build_type_psymtab_dependencies, NULL);
8784     }
8785
8786   if (dwarf_read_debug)
8787     print_tu_stats ();
8788
8789   set_partial_user (objfile);
8790
8791   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8792                                                     &objfile->objfile_obstack);
8793   /* At this point we want to keep the address map.  */
8794   save_psymtabs_addrmap.release ();
8795
8796   do_cleanups (back_to);
8797
8798   if (dwarf_read_debug)
8799     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8800                         objfile_name (objfile));
8801 }
8802
8803 /* die_reader_func for load_partial_comp_unit.  */
8804
8805 static void
8806 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8807                                const gdb_byte *info_ptr,
8808                                struct die_info *comp_unit_die,
8809                                int has_children,
8810                                void *data)
8811 {
8812   struct dwarf2_cu *cu = reader->cu;
8813
8814   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8815
8816   /* Check if comp unit has_children.
8817      If so, read the rest of the partial symbols from this comp unit.
8818      If not, there's no more debug_info for this comp unit.  */
8819   if (has_children)
8820     load_partial_dies (reader, info_ptr, 0);
8821 }
8822
8823 /* Load the partial DIEs for a secondary CU into memory.
8824    This is also used when rereading a primary CU with load_all_dies.  */
8825
8826 static void
8827 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8828 {
8829   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8830                            load_partial_comp_unit_reader, NULL);
8831 }
8832
8833 static void
8834 read_comp_units_from_section (struct objfile *objfile,
8835                               struct dwarf2_section_info *section,
8836                               struct dwarf2_section_info *abbrev_section,
8837                               unsigned int is_dwz,
8838                               int *n_allocated,
8839                               int *n_comp_units,
8840                               struct dwarf2_per_cu_data ***all_comp_units)
8841 {
8842   const gdb_byte *info_ptr;
8843
8844   if (dwarf_read_debug)
8845     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8846                         get_section_name (section),
8847                         get_section_file_name (section));
8848
8849   dwarf2_read_section (objfile, section);
8850
8851   info_ptr = section->buffer;
8852
8853   while (info_ptr < section->buffer + section->size)
8854     {
8855       struct dwarf2_per_cu_data *this_cu;
8856
8857       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8858
8859       comp_unit_head cu_header;
8860       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
8861                                      info_ptr, rcuh_kind::COMPILE);
8862
8863       /* Save the compilation unit for later lookup.  */
8864       if (cu_header.unit_type != DW_UT_type)
8865         {
8866           this_cu = XOBNEW (&objfile->objfile_obstack,
8867                             struct dwarf2_per_cu_data);
8868           memset (this_cu, 0, sizeof (*this_cu));
8869         }
8870       else
8871         {
8872           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8873                                   struct signatured_type);
8874           memset (sig_type, 0, sizeof (*sig_type));
8875           sig_type->signature = cu_header.signature;
8876           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8877           this_cu = &sig_type->per_cu;
8878         }
8879       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8880       this_cu->sect_off = sect_off;
8881       this_cu->length = cu_header.length + cu_header.initial_length_size;
8882       this_cu->is_dwz = is_dwz;
8883       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8884       this_cu->section = section;
8885
8886       if (*n_comp_units == *n_allocated)
8887         {
8888           *n_allocated *= 2;
8889           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8890                                         *all_comp_units, *n_allocated);
8891         }
8892       (*all_comp_units)[*n_comp_units] = this_cu;
8893       ++*n_comp_units;
8894
8895       info_ptr = info_ptr + this_cu->length;
8896     }
8897 }
8898
8899 /* Create a list of all compilation units in OBJFILE.
8900    This is only done for -readnow and building partial symtabs.  */
8901
8902 static void
8903 create_all_comp_units (struct objfile *objfile)
8904 {
8905   int n_allocated;
8906   int n_comp_units;
8907   struct dwarf2_per_cu_data **all_comp_units;
8908   struct dwz_file *dwz;
8909
8910   n_comp_units = 0;
8911   n_allocated = 10;
8912   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8913
8914   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
8915                                 &dwarf2_per_objfile->abbrev, 0,
8916                                 &n_allocated, &n_comp_units, &all_comp_units);
8917
8918   dwz = dwarf2_get_dwz_file ();
8919   if (dwz != NULL)
8920     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
8921                                   &n_allocated, &n_comp_units,
8922                                   &all_comp_units);
8923
8924   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8925                                                   struct dwarf2_per_cu_data *,
8926                                                   n_comp_units);
8927   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8928           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8929   xfree (all_comp_units);
8930   dwarf2_per_objfile->n_comp_units = n_comp_units;
8931 }
8932
8933 /* Process all loaded DIEs for compilation unit CU, starting at
8934    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8935    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8936    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8937    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8938
8939 static void
8940 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8941                       CORE_ADDR *highpc, int set_addrmap,
8942                       struct dwarf2_cu *cu)
8943 {
8944   struct partial_die_info *pdi;
8945
8946   /* Now, march along the PDI's, descending into ones which have
8947      interesting children but skipping the children of the other ones,
8948      until we reach the end of the compilation unit.  */
8949
8950   pdi = first_die;
8951
8952   while (pdi != NULL)
8953     {
8954       fixup_partial_die (pdi, cu);
8955
8956       /* Anonymous namespaces or modules have no name but have interesting
8957          children, so we need to look at them.  Ditto for anonymous
8958          enums.  */
8959
8960       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8961           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8962           || pdi->tag == DW_TAG_imported_unit)
8963         {
8964           switch (pdi->tag)
8965             {
8966             case DW_TAG_subprogram:
8967               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8968               break;
8969             case DW_TAG_constant:
8970             case DW_TAG_variable:
8971             case DW_TAG_typedef:
8972             case DW_TAG_union_type:
8973               if (!pdi->is_declaration)
8974                 {
8975                   add_partial_symbol (pdi, cu);
8976                 }
8977               break;
8978             case DW_TAG_class_type:
8979             case DW_TAG_interface_type:
8980             case DW_TAG_structure_type:
8981               if (!pdi->is_declaration)
8982                 {
8983                   add_partial_symbol (pdi, cu);
8984                 }
8985               if (cu->language == language_rust && pdi->has_children)
8986                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8987                                       set_addrmap, cu);
8988               break;
8989             case DW_TAG_enumeration_type:
8990               if (!pdi->is_declaration)
8991                 add_partial_enumeration (pdi, cu);
8992               break;
8993             case DW_TAG_base_type:
8994             case DW_TAG_subrange_type:
8995               /* File scope base type definitions are added to the partial
8996                  symbol table.  */
8997               add_partial_symbol (pdi, cu);
8998               break;
8999             case DW_TAG_namespace:
9000               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9001               break;
9002             case DW_TAG_module:
9003               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9004               break;
9005             case DW_TAG_imported_unit:
9006               {
9007                 struct dwarf2_per_cu_data *per_cu;
9008
9009                 /* For now we don't handle imported units in type units.  */
9010                 if (cu->per_cu->is_debug_types)
9011                   {
9012                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9013                              " supported in type units [in module %s]"),
9014                            objfile_name (cu->dwarf2_per_objfile->objfile));
9015                   }
9016
9017                 per_cu = dwarf2_find_containing_comp_unit
9018                            (pdi->d.sect_off, pdi->is_dwz,
9019                             cu->dwarf2_per_objfile->objfile);
9020
9021                 /* Go read the partial unit, if needed.  */
9022                 if (per_cu->v.psymtab == NULL)
9023                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9024
9025                 VEC_safe_push (dwarf2_per_cu_ptr,
9026                                cu->per_cu->imported_symtabs, per_cu);
9027               }
9028               break;
9029             case DW_TAG_imported_declaration:
9030               add_partial_symbol (pdi, cu);
9031               break;
9032             default:
9033               break;
9034             }
9035         }
9036
9037       /* If the die has a sibling, skip to the sibling.  */
9038
9039       pdi = pdi->die_sibling;
9040     }
9041 }
9042
9043 /* Functions used to compute the fully scoped name of a partial DIE.
9044
9045    Normally, this is simple.  For C++, the parent DIE's fully scoped
9046    name is concatenated with "::" and the partial DIE's name.
9047    Enumerators are an exception; they use the scope of their parent
9048    enumeration type, i.e. the name of the enumeration type is not
9049    prepended to the enumerator.
9050
9051    There are two complexities.  One is DW_AT_specification; in this
9052    case "parent" means the parent of the target of the specification,
9053    instead of the direct parent of the DIE.  The other is compilers
9054    which do not emit DW_TAG_namespace; in this case we try to guess
9055    the fully qualified name of structure types from their members'
9056    linkage names.  This must be done using the DIE's children rather
9057    than the children of any DW_AT_specification target.  We only need
9058    to do this for structures at the top level, i.e. if the target of
9059    any DW_AT_specification (if any; otherwise the DIE itself) does not
9060    have a parent.  */
9061
9062 /* Compute the scope prefix associated with PDI's parent, in
9063    compilation unit CU.  The result will be allocated on CU's
9064    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9065    field.  NULL is returned if no prefix is necessary.  */
9066 static const char *
9067 partial_die_parent_scope (struct partial_die_info *pdi,
9068                           struct dwarf2_cu *cu)
9069 {
9070   const char *grandparent_scope;
9071   struct partial_die_info *parent, *real_pdi;
9072
9073   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9074      then this means the parent of the specification DIE.  */
9075
9076   real_pdi = pdi;
9077   while (real_pdi->has_specification)
9078     real_pdi = find_partial_die (real_pdi->spec_offset,
9079                                  real_pdi->spec_is_dwz, cu);
9080
9081   parent = real_pdi->die_parent;
9082   if (parent == NULL)
9083     return NULL;
9084
9085   if (parent->scope_set)
9086     return parent->scope;
9087
9088   fixup_partial_die (parent, cu);
9089
9090   grandparent_scope = partial_die_parent_scope (parent, cu);
9091
9092   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9093      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9094      Work around this problem here.  */
9095   if (cu->language == language_cplus
9096       && parent->tag == DW_TAG_namespace
9097       && strcmp (parent->name, "::") == 0
9098       && grandparent_scope == NULL)
9099     {
9100       parent->scope = NULL;
9101       parent->scope_set = 1;
9102       return NULL;
9103     }
9104
9105   if (pdi->tag == DW_TAG_enumerator)
9106     /* Enumerators should not get the name of the enumeration as a prefix.  */
9107     parent->scope = grandparent_scope;
9108   else if (parent->tag == DW_TAG_namespace
9109       || parent->tag == DW_TAG_module
9110       || parent->tag == DW_TAG_structure_type
9111       || parent->tag == DW_TAG_class_type
9112       || parent->tag == DW_TAG_interface_type
9113       || parent->tag == DW_TAG_union_type
9114       || parent->tag == DW_TAG_enumeration_type)
9115     {
9116       if (grandparent_scope == NULL)
9117         parent->scope = parent->name;
9118       else
9119         parent->scope = typename_concat (&cu->comp_unit_obstack,
9120                                          grandparent_scope,
9121                                          parent->name, 0, cu);
9122     }
9123   else
9124     {
9125       /* FIXME drow/2004-04-01: What should we be doing with
9126          function-local names?  For partial symbols, we should probably be
9127          ignoring them.  */
9128       complaint (&symfile_complaints,
9129                  _("unhandled containing DIE tag %d for DIE at %d"),
9130                  parent->tag, to_underlying (pdi->sect_off));
9131       parent->scope = grandparent_scope;
9132     }
9133
9134   parent->scope_set = 1;
9135   return parent->scope;
9136 }
9137
9138 /* Return the fully scoped name associated with PDI, from compilation unit
9139    CU.  The result will be allocated with malloc.  */
9140
9141 static char *
9142 partial_die_full_name (struct partial_die_info *pdi,
9143                        struct dwarf2_cu *cu)
9144 {
9145   const char *parent_scope;
9146
9147   /* If this is a template instantiation, we can not work out the
9148      template arguments from partial DIEs.  So, unfortunately, we have
9149      to go through the full DIEs.  At least any work we do building
9150      types here will be reused if full symbols are loaded later.  */
9151   if (pdi->has_template_arguments)
9152     {
9153       fixup_partial_die (pdi, cu);
9154
9155       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9156         {
9157           struct die_info *die;
9158           struct attribute attr;
9159           struct dwarf2_cu *ref_cu = cu;
9160
9161           /* DW_FORM_ref_addr is using section offset.  */
9162           attr.name = (enum dwarf_attribute) 0;
9163           attr.form = DW_FORM_ref_addr;
9164           attr.u.unsnd = to_underlying (pdi->sect_off);
9165           die = follow_die_ref (NULL, &attr, &ref_cu);
9166
9167           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9168         }
9169     }
9170
9171   parent_scope = partial_die_parent_scope (pdi, cu);
9172   if (parent_scope == NULL)
9173     return NULL;
9174   else
9175     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9176 }
9177
9178 static void
9179 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9180 {
9181   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
9182   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9183   CORE_ADDR addr = 0;
9184   const char *actual_name = NULL;
9185   CORE_ADDR baseaddr;
9186   char *built_actual_name;
9187
9188   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9189
9190   built_actual_name = partial_die_full_name (pdi, cu);
9191   if (built_actual_name != NULL)
9192     actual_name = built_actual_name;
9193
9194   if (actual_name == NULL)
9195     actual_name = pdi->name;
9196
9197   switch (pdi->tag)
9198     {
9199     case DW_TAG_subprogram:
9200       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9201       if (pdi->is_external || cu->language == language_ada)
9202         {
9203           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9204              of the global scope.  But in Ada, we want to be able to access
9205              nested procedures globally.  So all Ada subprograms are stored
9206              in the global scope.  */
9207           add_psymbol_to_list (actual_name, strlen (actual_name),
9208                                built_actual_name != NULL,
9209                                VAR_DOMAIN, LOC_BLOCK,
9210                                &objfile->global_psymbols,
9211                                addr, cu->language, objfile);
9212         }
9213       else
9214         {
9215           add_psymbol_to_list (actual_name, strlen (actual_name),
9216                                built_actual_name != NULL,
9217                                VAR_DOMAIN, LOC_BLOCK,
9218                                &objfile->static_psymbols,
9219                                addr, cu->language, objfile);
9220         }
9221
9222       if (pdi->main_subprogram && actual_name != NULL)
9223         set_objfile_main_name (objfile, actual_name, cu->language);
9224       break;
9225     case DW_TAG_constant:
9226       {
9227         std::vector<partial_symbol *> *list;
9228
9229         if (pdi->is_external)
9230           list = &objfile->global_psymbols;
9231         else
9232           list = &objfile->static_psymbols;
9233         add_psymbol_to_list (actual_name, strlen (actual_name),
9234                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9235                              list, 0, cu->language, objfile);
9236       }
9237       break;
9238     case DW_TAG_variable:
9239       if (pdi->d.locdesc)
9240         addr = decode_locdesc (pdi->d.locdesc, cu);
9241
9242       if (pdi->d.locdesc
9243           && addr == 0
9244           && !dwarf2_per_objfile->has_section_at_zero)
9245         {
9246           /* A global or static variable may also have been stripped
9247              out by the linker if unused, in which case its address
9248              will be nullified; do not add such variables into partial
9249              symbol table then.  */
9250         }
9251       else if (pdi->is_external)
9252         {
9253           /* Global Variable.
9254              Don't enter into the minimal symbol tables as there is
9255              a minimal symbol table entry from the ELF symbols already.
9256              Enter into partial symbol table if it has a location
9257              descriptor or a type.
9258              If the location descriptor is missing, new_symbol will create
9259              a LOC_UNRESOLVED symbol, the address of the variable will then
9260              be determined from the minimal symbol table whenever the variable
9261              is referenced.
9262              The address for the partial symbol table entry is not
9263              used by GDB, but it comes in handy for debugging partial symbol
9264              table building.  */
9265
9266           if (pdi->d.locdesc || pdi->has_type)
9267             add_psymbol_to_list (actual_name, strlen (actual_name),
9268                                  built_actual_name != NULL,
9269                                  VAR_DOMAIN, LOC_STATIC,
9270                                  &objfile->global_psymbols,
9271                                  addr + baseaddr,
9272                                  cu->language, objfile);
9273         }
9274       else
9275         {
9276           int has_loc = pdi->d.locdesc != NULL;
9277
9278           /* Static Variable.  Skip symbols whose value we cannot know (those
9279              without location descriptors or constant values).  */
9280           if (!has_loc && !pdi->has_const_value)
9281             {
9282               xfree (built_actual_name);
9283               return;
9284             }
9285
9286           add_psymbol_to_list (actual_name, strlen (actual_name),
9287                                built_actual_name != NULL,
9288                                VAR_DOMAIN, LOC_STATIC,
9289                                &objfile->static_psymbols,
9290                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9291                                cu->language, objfile);
9292         }
9293       break;
9294     case DW_TAG_typedef:
9295     case DW_TAG_base_type:
9296     case DW_TAG_subrange_type:
9297       add_psymbol_to_list (actual_name, strlen (actual_name),
9298                            built_actual_name != NULL,
9299                            VAR_DOMAIN, LOC_TYPEDEF,
9300                            &objfile->static_psymbols,
9301                            0, cu->language, objfile);
9302       break;
9303     case DW_TAG_imported_declaration:
9304     case DW_TAG_namespace:
9305       add_psymbol_to_list (actual_name, strlen (actual_name),
9306                            built_actual_name != NULL,
9307                            VAR_DOMAIN, LOC_TYPEDEF,
9308                            &objfile->global_psymbols,
9309                            0, cu->language, objfile);
9310       break;
9311     case DW_TAG_module:
9312       add_psymbol_to_list (actual_name, strlen (actual_name),
9313                            built_actual_name != NULL,
9314                            MODULE_DOMAIN, LOC_TYPEDEF,
9315                            &objfile->global_psymbols,
9316                            0, cu->language, objfile);
9317       break;
9318     case DW_TAG_class_type:
9319     case DW_TAG_interface_type:
9320     case DW_TAG_structure_type:
9321     case DW_TAG_union_type:
9322     case DW_TAG_enumeration_type:
9323       /* Skip external references.  The DWARF standard says in the section
9324          about "Structure, Union, and Class Type Entries": "An incomplete
9325          structure, union or class type is represented by a structure,
9326          union or class entry that does not have a byte size attribute
9327          and that has a DW_AT_declaration attribute."  */
9328       if (!pdi->has_byte_size && pdi->is_declaration)
9329         {
9330           xfree (built_actual_name);
9331           return;
9332         }
9333
9334       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9335          static vs. global.  */
9336       add_psymbol_to_list (actual_name, strlen (actual_name),
9337                            built_actual_name != NULL,
9338                            STRUCT_DOMAIN, LOC_TYPEDEF,
9339                            cu->language == language_cplus
9340                            ? &objfile->global_psymbols
9341                            : &objfile->static_psymbols,
9342                            0, cu->language, objfile);
9343
9344       break;
9345     case DW_TAG_enumerator:
9346       add_psymbol_to_list (actual_name, strlen (actual_name),
9347                            built_actual_name != NULL,
9348                            VAR_DOMAIN, LOC_CONST,
9349                            cu->language == language_cplus
9350                            ? &objfile->global_psymbols
9351                            : &objfile->static_psymbols,
9352                            0, cu->language, objfile);
9353       break;
9354     default:
9355       break;
9356     }
9357
9358   xfree (built_actual_name);
9359 }
9360
9361 /* Read a partial die corresponding to a namespace; also, add a symbol
9362    corresponding to that namespace to the symbol table.  NAMESPACE is
9363    the name of the enclosing namespace.  */
9364
9365 static void
9366 add_partial_namespace (struct partial_die_info *pdi,
9367                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9368                        int set_addrmap, struct dwarf2_cu *cu)
9369 {
9370   /* Add a symbol for the namespace.  */
9371
9372   add_partial_symbol (pdi, cu);
9373
9374   /* Now scan partial symbols in that namespace.  */
9375
9376   if (pdi->has_children)
9377     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9378 }
9379
9380 /* Read a partial die corresponding to a Fortran module.  */
9381
9382 static void
9383 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9384                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9385 {
9386   /* Add a symbol for the namespace.  */
9387
9388   add_partial_symbol (pdi, cu);
9389
9390   /* Now scan partial symbols in that module.  */
9391
9392   if (pdi->has_children)
9393     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9394 }
9395
9396 /* Read a partial die corresponding to a subprogram and create a partial
9397    symbol for that subprogram.  When the CU language allows it, this
9398    routine also defines a partial symbol for each nested subprogram
9399    that this subprogram contains.  If SET_ADDRMAP is true, record the
9400    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
9401    and highest PC values found in PDI.
9402
9403    PDI may also be a lexical block, in which case we simply search
9404    recursively for subprograms defined inside that lexical block.
9405    Again, this is only performed when the CU language allows this
9406    type of definitions.  */
9407
9408 static void
9409 add_partial_subprogram (struct partial_die_info *pdi,
9410                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9411                         int set_addrmap, struct dwarf2_cu *cu)
9412 {
9413   if (pdi->tag == DW_TAG_subprogram)
9414     {
9415       if (pdi->has_pc_info)
9416         {
9417           if (pdi->lowpc < *lowpc)
9418             *lowpc = pdi->lowpc;
9419           if (pdi->highpc > *highpc)
9420             *highpc = pdi->highpc;
9421           if (set_addrmap)
9422             {
9423               struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
9424               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9425               CORE_ADDR baseaddr;
9426               CORE_ADDR highpc;
9427               CORE_ADDR lowpc;
9428
9429               baseaddr = ANOFFSET (objfile->section_offsets,
9430                                    SECT_OFF_TEXT (objfile));
9431               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9432                                                   pdi->lowpc + baseaddr);
9433               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9434                                                    pdi->highpc + baseaddr);
9435               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9436                                  cu->per_cu->v.psymtab);
9437             }
9438         }
9439
9440       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9441         {
9442           if (!pdi->is_declaration)
9443             /* Ignore subprogram DIEs that do not have a name, they are
9444                illegal.  Do not emit a complaint at this point, we will
9445                do so when we convert this psymtab into a symtab.  */
9446             if (pdi->name)
9447               add_partial_symbol (pdi, cu);
9448         }
9449     }
9450
9451   if (! pdi->has_children)
9452     return;
9453
9454   if (cu->language == language_ada)
9455     {
9456       pdi = pdi->die_child;
9457       while (pdi != NULL)
9458         {
9459           fixup_partial_die (pdi, cu);
9460           if (pdi->tag == DW_TAG_subprogram
9461               || pdi->tag == DW_TAG_lexical_block)
9462             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9463           pdi = pdi->die_sibling;
9464         }
9465     }
9466 }
9467
9468 /* Read a partial die corresponding to an enumeration type.  */
9469
9470 static void
9471 add_partial_enumeration (struct partial_die_info *enum_pdi,
9472                          struct dwarf2_cu *cu)
9473 {
9474   struct partial_die_info *pdi;
9475
9476   if (enum_pdi->name != NULL)
9477     add_partial_symbol (enum_pdi, cu);
9478
9479   pdi = enum_pdi->die_child;
9480   while (pdi)
9481     {
9482       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9483         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9484       else
9485         add_partial_symbol (pdi, cu);
9486       pdi = pdi->die_sibling;
9487     }
9488 }
9489
9490 /* Return the initial uleb128 in the die at INFO_PTR.  */
9491
9492 static unsigned int
9493 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9494 {
9495   unsigned int bytes_read;
9496
9497   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9498 }
9499
9500 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
9501    Return the corresponding abbrev, or NULL if the number is zero (indicating
9502    an empty DIE).  In either case *BYTES_READ will be set to the length of
9503    the initial number.  */
9504
9505 static struct abbrev_info *
9506 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
9507                  struct dwarf2_cu *cu)
9508 {
9509   bfd *abfd = cu->dwarf2_per_objfile->objfile->obfd;
9510   unsigned int abbrev_number;
9511   struct abbrev_info *abbrev;
9512
9513   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9514
9515   if (abbrev_number == 0)
9516     return NULL;
9517
9518   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
9519   if (!abbrev)
9520     {
9521       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9522                " at offset 0x%x [in module %s]"),
9523              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9524              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9525     }
9526
9527   return abbrev;
9528 }
9529
9530 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9531    Returns a pointer to the end of a series of DIEs, terminated by an empty
9532    DIE.  Any children of the skipped DIEs will also be skipped.  */
9533
9534 static const gdb_byte *
9535 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9536 {
9537   struct dwarf2_cu *cu = reader->cu;
9538   struct abbrev_info *abbrev;
9539   unsigned int bytes_read;
9540
9541   while (1)
9542     {
9543       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
9544       if (abbrev == NULL)
9545         return info_ptr + bytes_read;
9546       else
9547         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9548     }
9549 }
9550
9551 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9552    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9553    abbrev corresponding to that skipped uleb128 should be passed in
9554    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9555    children.  */
9556
9557 static const gdb_byte *
9558 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9559               struct abbrev_info *abbrev)
9560 {
9561   unsigned int bytes_read;
9562   struct attribute attr;
9563   bfd *abfd = reader->abfd;
9564   struct dwarf2_cu *cu = reader->cu;
9565   const gdb_byte *buffer = reader->buffer;
9566   const gdb_byte *buffer_end = reader->buffer_end;
9567   unsigned int form, i;
9568
9569   for (i = 0; i < abbrev->num_attrs; i++)
9570     {
9571       /* The only abbrev we care about is DW_AT_sibling.  */
9572       if (abbrev->attrs[i].name == DW_AT_sibling)
9573         {
9574           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9575           if (attr.form == DW_FORM_ref_addr)
9576             complaint (&symfile_complaints,
9577                        _("ignoring absolute DW_AT_sibling"));
9578           else
9579             {
9580               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9581               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9582
9583               if (sibling_ptr < info_ptr)
9584                 complaint (&symfile_complaints,
9585                            _("DW_AT_sibling points backwards"));
9586               else if (sibling_ptr > reader->buffer_end)
9587                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9588               else
9589                 return sibling_ptr;
9590             }
9591         }
9592
9593       /* If it isn't DW_AT_sibling, skip this attribute.  */
9594       form = abbrev->attrs[i].form;
9595     skip_attribute:
9596       switch (form)
9597         {
9598         case DW_FORM_ref_addr:
9599           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9600              and later it is offset sized.  */
9601           if (cu->header.version == 2)
9602             info_ptr += cu->header.addr_size;
9603           else
9604             info_ptr += cu->header.offset_size;
9605           break;
9606         case DW_FORM_GNU_ref_alt:
9607           info_ptr += cu->header.offset_size;
9608           break;
9609         case DW_FORM_addr:
9610           info_ptr += cu->header.addr_size;
9611           break;
9612         case DW_FORM_data1:
9613         case DW_FORM_ref1:
9614         case DW_FORM_flag:
9615           info_ptr += 1;
9616           break;
9617         case DW_FORM_flag_present:
9618         case DW_FORM_implicit_const:
9619           break;
9620         case DW_FORM_data2:
9621         case DW_FORM_ref2:
9622           info_ptr += 2;
9623           break;
9624         case DW_FORM_data4:
9625         case DW_FORM_ref4:
9626           info_ptr += 4;
9627           break;
9628         case DW_FORM_data8:
9629         case DW_FORM_ref8:
9630         case DW_FORM_ref_sig8:
9631           info_ptr += 8;
9632           break;
9633         case DW_FORM_data16:
9634           info_ptr += 16;
9635           break;
9636         case DW_FORM_string:
9637           read_direct_string (abfd, info_ptr, &bytes_read);
9638           info_ptr += bytes_read;
9639           break;
9640         case DW_FORM_sec_offset:
9641         case DW_FORM_strp:
9642         case DW_FORM_GNU_strp_alt:
9643           info_ptr += cu->header.offset_size;
9644           break;
9645         case DW_FORM_exprloc:
9646         case DW_FORM_block:
9647           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9648           info_ptr += bytes_read;
9649           break;
9650         case DW_FORM_block1:
9651           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9652           break;
9653         case DW_FORM_block2:
9654           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9655           break;
9656         case DW_FORM_block4:
9657           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9658           break;
9659         case DW_FORM_sdata:
9660         case DW_FORM_udata:
9661         case DW_FORM_ref_udata:
9662         case DW_FORM_GNU_addr_index:
9663         case DW_FORM_GNU_str_index:
9664           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9665           break;
9666         case DW_FORM_indirect:
9667           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9668           info_ptr += bytes_read;
9669           /* We need to continue parsing from here, so just go back to
9670              the top.  */
9671           goto skip_attribute;
9672
9673         default:
9674           error (_("Dwarf Error: Cannot handle %s "
9675                    "in DWARF reader [in module %s]"),
9676                  dwarf_form_name (form),
9677                  bfd_get_filename (abfd));
9678         }
9679     }
9680
9681   if (abbrev->has_children)
9682     return skip_children (reader, info_ptr);
9683   else
9684     return info_ptr;
9685 }
9686
9687 /* Locate ORIG_PDI's sibling.
9688    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9689
9690 static const gdb_byte *
9691 locate_pdi_sibling (const struct die_reader_specs *reader,
9692                     struct partial_die_info *orig_pdi,
9693                     const gdb_byte *info_ptr)
9694 {
9695   /* Do we know the sibling already?  */
9696
9697   if (orig_pdi->sibling)
9698     return orig_pdi->sibling;
9699
9700   /* Are there any children to deal with?  */
9701
9702   if (!orig_pdi->has_children)
9703     return info_ptr;
9704
9705   /* Skip the children the long way.  */
9706
9707   return skip_children (reader, info_ptr);
9708 }
9709
9710 /* Expand this partial symbol table into a full symbol table.  SELF is
9711    not NULL.  */
9712
9713 static void
9714 dwarf2_read_symtab (struct partial_symtab *self,
9715                     struct objfile *objfile)
9716 {
9717   if (self->readin)
9718     {
9719       warning (_("bug: psymtab for %s is already read in."),
9720                self->filename);
9721     }
9722   else
9723     {
9724       if (info_verbose)
9725         {
9726           printf_filtered (_("Reading in symbols for %s..."),
9727                            self->filename);
9728           gdb_flush (gdb_stdout);
9729         }
9730
9731       /* Restore our global data.  */
9732       dwarf2_per_objfile
9733         = (struct dwarf2_per_objfile *) objfile_data (objfile,
9734                                                       dwarf2_objfile_data_key);
9735
9736       /* If this psymtab is constructed from a debug-only objfile, the
9737          has_section_at_zero flag will not necessarily be correct.  We
9738          can get the correct value for this flag by looking at the data
9739          associated with the (presumably stripped) associated objfile.  */
9740       if (objfile->separate_debug_objfile_backlink)
9741         {
9742           struct dwarf2_per_objfile *dpo_backlink
9743             = ((struct dwarf2_per_objfile *)
9744                objfile_data (objfile->separate_debug_objfile_backlink,
9745                              dwarf2_objfile_data_key));
9746
9747           dwarf2_per_objfile->has_section_at_zero
9748             = dpo_backlink->has_section_at_zero;
9749         }
9750
9751       dwarf2_per_objfile->reading_partial_symbols = 0;
9752
9753       psymtab_to_symtab_1 (self);
9754
9755       /* Finish up the debug error message.  */
9756       if (info_verbose)
9757         printf_filtered (_("done.\n"));
9758     }
9759
9760   process_cu_includes ();
9761 }
9762 \f
9763 /* Reading in full CUs.  */
9764
9765 /* Add PER_CU to the queue.  */
9766
9767 static void
9768 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9769                  enum language pretend_language)
9770 {
9771   struct dwarf2_queue_item *item;
9772
9773   per_cu->queued = 1;
9774   item = XNEW (struct dwarf2_queue_item);
9775   item->per_cu = per_cu;
9776   item->pretend_language = pretend_language;
9777   item->next = NULL;
9778
9779   if (dwarf2_queue == NULL)
9780     dwarf2_queue = item;
9781   else
9782     dwarf2_queue_tail->next = item;
9783
9784   dwarf2_queue_tail = item;
9785 }
9786
9787 /* If PER_CU is not yet queued, add it to the queue.
9788    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9789    dependency.
9790    The result is non-zero if PER_CU was queued, otherwise the result is zero
9791    meaning either PER_CU is already queued or it is already loaded.
9792
9793    N.B. There is an invariant here that if a CU is queued then it is loaded.
9794    The caller is required to load PER_CU if we return non-zero.  */
9795
9796 static int
9797 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9798                        struct dwarf2_per_cu_data *per_cu,
9799                        enum language pretend_language)
9800 {
9801   /* We may arrive here during partial symbol reading, if we need full
9802      DIEs to process an unusual case (e.g. template arguments).  Do
9803      not queue PER_CU, just tell our caller to load its DIEs.  */
9804   if (dwarf2_per_objfile->reading_partial_symbols)
9805     {
9806       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9807         return 1;
9808       return 0;
9809     }
9810
9811   /* Mark the dependence relation so that we don't flush PER_CU
9812      too early.  */
9813   if (dependent_cu != NULL)
9814     dwarf2_add_dependence (dependent_cu, per_cu);
9815
9816   /* If it's already on the queue, we have nothing to do.  */
9817   if (per_cu->queued)
9818     return 0;
9819
9820   /* If the compilation unit is already loaded, just mark it as
9821      used.  */
9822   if (per_cu->cu != NULL)
9823     {
9824       per_cu->cu->last_used = 0;
9825       return 0;
9826     }
9827
9828   /* Add it to the queue.  */
9829   queue_comp_unit (per_cu, pretend_language);
9830
9831   return 1;
9832 }
9833
9834 /* Process the queue.  */
9835
9836 static void
9837 process_queue (void)
9838 {
9839   struct dwarf2_queue_item *item, *next_item;
9840
9841   if (dwarf_read_debug)
9842     {
9843       fprintf_unfiltered (gdb_stdlog,
9844                           "Expanding one or more symtabs of objfile %s ...\n",
9845                           objfile_name (dwarf2_per_objfile->objfile));
9846     }
9847
9848   /* The queue starts out with one item, but following a DIE reference
9849      may load a new CU, adding it to the end of the queue.  */
9850   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9851     {
9852       if ((dwarf2_per_objfile->using_index
9853            ? !item->per_cu->v.quick->compunit_symtab
9854            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9855           /* Skip dummy CUs.  */
9856           && item->per_cu->cu != NULL)
9857         {
9858           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9859           unsigned int debug_print_threshold;
9860           char buf[100];
9861
9862           if (per_cu->is_debug_types)
9863             {
9864               struct signatured_type *sig_type =
9865                 (struct signatured_type *) per_cu;
9866
9867               sprintf (buf, "TU %s at offset 0x%x",
9868                        hex_string (sig_type->signature),
9869                        to_underlying (per_cu->sect_off));
9870               /* There can be 100s of TUs.
9871                  Only print them in verbose mode.  */
9872               debug_print_threshold = 2;
9873             }
9874           else
9875             {
9876               sprintf (buf, "CU at offset 0x%x",
9877                        to_underlying (per_cu->sect_off));
9878               debug_print_threshold = 1;
9879             }
9880
9881           if (dwarf_read_debug >= debug_print_threshold)
9882             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9883
9884           if (per_cu->is_debug_types)
9885             process_full_type_unit (per_cu, item->pretend_language);
9886           else
9887             process_full_comp_unit (per_cu, item->pretend_language);
9888
9889           if (dwarf_read_debug >= debug_print_threshold)
9890             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9891         }
9892
9893       item->per_cu->queued = 0;
9894       next_item = item->next;
9895       xfree (item);
9896     }
9897
9898   dwarf2_queue_tail = NULL;
9899
9900   if (dwarf_read_debug)
9901     {
9902       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9903                           objfile_name (dwarf2_per_objfile->objfile));
9904     }
9905 }
9906
9907 /* Free all allocated queue entries.  This function only releases anything if
9908    an error was thrown; if the queue was processed then it would have been
9909    freed as we went along.  */
9910
9911 static void
9912 dwarf2_release_queue (void *dummy)
9913 {
9914   struct dwarf2_queue_item *item, *last;
9915
9916   item = dwarf2_queue;
9917   while (item)
9918     {
9919       /* Anything still marked queued is likely to be in an
9920          inconsistent state, so discard it.  */
9921       if (item->per_cu->queued)
9922         {
9923           if (item->per_cu->cu != NULL)
9924             free_one_cached_comp_unit (item->per_cu);
9925           item->per_cu->queued = 0;
9926         }
9927
9928       last = item;
9929       item = item->next;
9930       xfree (last);
9931     }
9932
9933   dwarf2_queue = dwarf2_queue_tail = NULL;
9934 }
9935
9936 /* Read in full symbols for PST, and anything it depends on.  */
9937
9938 static void
9939 psymtab_to_symtab_1 (struct partial_symtab *pst)
9940 {
9941   struct dwarf2_per_cu_data *per_cu;
9942   int i;
9943
9944   if (pst->readin)
9945     return;
9946
9947   for (i = 0; i < pst->number_of_dependencies; i++)
9948     if (!pst->dependencies[i]->readin
9949         && pst->dependencies[i]->user == NULL)
9950       {
9951         /* Inform about additional files that need to be read in.  */
9952         if (info_verbose)
9953           {
9954             /* FIXME: i18n: Need to make this a single string.  */
9955             fputs_filtered (" ", gdb_stdout);
9956             wrap_here ("");
9957             fputs_filtered ("and ", gdb_stdout);
9958             wrap_here ("");
9959             printf_filtered ("%s...", pst->dependencies[i]->filename);
9960             wrap_here ("");     /* Flush output.  */
9961             gdb_flush (gdb_stdout);
9962           }
9963         psymtab_to_symtab_1 (pst->dependencies[i]);
9964       }
9965
9966   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9967
9968   if (per_cu == NULL)
9969     {
9970       /* It's an include file, no symbols to read for it.
9971          Everything is in the parent symtab.  */
9972       pst->readin = 1;
9973       return;
9974     }
9975
9976   dw2_do_instantiate_symtab (per_cu);
9977 }
9978
9979 /* Trivial hash function for die_info: the hash value of a DIE
9980    is its offset in .debug_info for this objfile.  */
9981
9982 static hashval_t
9983 die_hash (const void *item)
9984 {
9985   const struct die_info *die = (const struct die_info *) item;
9986
9987   return to_underlying (die->sect_off);
9988 }
9989
9990 /* Trivial comparison function for die_info structures: two DIEs
9991    are equal if they have the same offset.  */
9992
9993 static int
9994 die_eq (const void *item_lhs, const void *item_rhs)
9995 {
9996   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9997   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9998
9999   return die_lhs->sect_off == die_rhs->sect_off;
10000 }
10001
10002 /* die_reader_func for load_full_comp_unit.
10003    This is identical to read_signatured_type_reader,
10004    but is kept separate for now.  */
10005
10006 static void
10007 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10008                             const gdb_byte *info_ptr,
10009                             struct die_info *comp_unit_die,
10010                             int has_children,
10011                             void *data)
10012 {
10013   struct dwarf2_cu *cu = reader->cu;
10014   enum language *language_ptr = (enum language *) data;
10015
10016   gdb_assert (cu->die_hash == NULL);
10017   cu->die_hash =
10018     htab_create_alloc_ex (cu->header.length / 12,
10019                           die_hash,
10020                           die_eq,
10021                           NULL,
10022                           &cu->comp_unit_obstack,
10023                           hashtab_obstack_allocate,
10024                           dummy_obstack_deallocate);
10025
10026   if (has_children)
10027     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10028                                                   &info_ptr, comp_unit_die);
10029   cu->dies = comp_unit_die;
10030   /* comp_unit_die is not stored in die_hash, no need.  */
10031
10032   /* We try not to read any attributes in this function, because not
10033      all CUs needed for references have been loaded yet, and symbol
10034      table processing isn't initialized.  But we have to set the CU language,
10035      or we won't be able to build types correctly.
10036      Similarly, if we do not read the producer, we can not apply
10037      producer-specific interpretation.  */
10038   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10039 }
10040
10041 /* Load the DIEs associated with PER_CU into memory.  */
10042
10043 static void
10044 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10045                      enum language pretend_language)
10046 {
10047   gdb_assert (! this_cu->is_debug_types);
10048
10049   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10050                            load_full_comp_unit_reader, &pretend_language);
10051 }
10052
10053 /* Add a DIE to the delayed physname list.  */
10054
10055 static void
10056 add_to_method_list (struct type *type, int fnfield_index, int index,
10057                     const char *name, struct die_info *die,
10058                     struct dwarf2_cu *cu)
10059 {
10060   struct delayed_method_info mi;
10061   mi.type = type;
10062   mi.fnfield_index = fnfield_index;
10063   mi.index = index;
10064   mi.name = name;
10065   mi.die = die;
10066   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10067 }
10068
10069 /* A cleanup for freeing the delayed method list.  */
10070
10071 static void
10072 free_delayed_list (void *ptr)
10073 {
10074   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10075   if (cu->method_list != NULL)
10076     {
10077       VEC_free (delayed_method_info, cu->method_list);
10078       cu->method_list = NULL;
10079     }
10080 }
10081
10082 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10083    "const" / "volatile".  If so, decrements LEN by the length of the
10084    modifier and return true.  Otherwise return false.  */
10085
10086 template<size_t N>
10087 static bool
10088 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10089 {
10090   size_t mod_len = sizeof (mod) - 1;
10091   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10092     {
10093       len -= mod_len;
10094       return true;
10095     }
10096   return false;
10097 }
10098
10099 /* Compute the physnames of any methods on the CU's method list.
10100
10101    The computation of method physnames is delayed in order to avoid the
10102    (bad) condition that one of the method's formal parameters is of an as yet
10103    incomplete type.  */
10104
10105 static void
10106 compute_delayed_physnames (struct dwarf2_cu *cu)
10107 {
10108   int i;
10109   struct delayed_method_info *mi;
10110
10111   /* Only C++ delays computing physnames.  */
10112   if (VEC_empty (delayed_method_info, cu->method_list))
10113     return;
10114   gdb_assert (cu->language == language_cplus);
10115
10116   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10117     {
10118       const char *physname;
10119       struct fn_fieldlist *fn_flp
10120         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10121       physname = dwarf2_physname (mi->name, mi->die, cu);
10122       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10123         = physname ? physname : "";
10124
10125       /* Since there's no tag to indicate whether a method is a
10126          const/volatile overload, extract that information out of the
10127          demangled name.  */
10128       if (physname != NULL)
10129         {
10130           size_t len = strlen (physname);
10131
10132           while (1)
10133             {
10134               if (physname[len] == ')') /* shortcut */
10135                 break;
10136               else if (check_modifier (physname, len, " const"))
10137                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10138               else if (check_modifier (physname, len, " volatile"))
10139                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10140               else
10141                 break;
10142             }
10143         }
10144     }
10145 }
10146
10147 /* Go objects should be embedded in a DW_TAG_module DIE,
10148    and it's not clear if/how imported objects will appear.
10149    To keep Go support simple until that's worked out,
10150    go back through what we've read and create something usable.
10151    We could do this while processing each DIE, and feels kinda cleaner,
10152    but that way is more invasive.
10153    This is to, for example, allow the user to type "p var" or "b main"
10154    without having to specify the package name, and allow lookups
10155    of module.object to work in contexts that use the expression
10156    parser.  */
10157
10158 static void
10159 fixup_go_packaging (struct dwarf2_cu *cu)
10160 {
10161   char *package_name = NULL;
10162   struct pending *list;
10163   int i;
10164
10165   for (list = global_symbols; list != NULL; list = list->next)
10166     {
10167       for (i = 0; i < list->nsyms; ++i)
10168         {
10169           struct symbol *sym = list->symbol[i];
10170
10171           if (SYMBOL_LANGUAGE (sym) == language_go
10172               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10173             {
10174               char *this_package_name = go_symbol_package_name (sym);
10175
10176               if (this_package_name == NULL)
10177                 continue;
10178               if (package_name == NULL)
10179                 package_name = this_package_name;
10180               else
10181                 {
10182                   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
10183                   if (strcmp (package_name, this_package_name) != 0)
10184                     complaint (&symfile_complaints,
10185                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10186                                (symbol_symtab (sym) != NULL
10187                                 ? symtab_to_filename_for_display
10188                                     (symbol_symtab (sym))
10189                                 : objfile_name (objfile)),
10190                                this_package_name, package_name);
10191                   xfree (this_package_name);
10192                 }
10193             }
10194         }
10195     }
10196
10197   if (package_name != NULL)
10198     {
10199       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
10200       const char *saved_package_name
10201         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10202                                         package_name,
10203                                         strlen (package_name));
10204       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10205                                      saved_package_name);
10206       struct symbol *sym;
10207
10208       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10209
10210       sym = allocate_symbol (objfile);
10211       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10212       SYMBOL_SET_NAMES (sym, saved_package_name,
10213                         strlen (saved_package_name), 0, objfile);
10214       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10215          e.g., "main" finds the "main" module and not C's main().  */
10216       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10217       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10218       SYMBOL_TYPE (sym) = type;
10219
10220       add_symbol_to_list (sym, &global_symbols);
10221
10222       xfree (package_name);
10223     }
10224 }
10225
10226 /* Return the symtab for PER_CU.  This works properly regardless of
10227    whether we're using the index or psymtabs.  */
10228
10229 static struct compunit_symtab *
10230 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10231 {
10232   return (dwarf2_per_objfile->using_index
10233           ? per_cu->v.quick->compunit_symtab
10234           : per_cu->v.psymtab->compunit_symtab);
10235 }
10236
10237 /* A helper function for computing the list of all symbol tables
10238    included by PER_CU.  */
10239
10240 static void
10241 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10242                                 htab_t all_children, htab_t all_type_symtabs,
10243                                 struct dwarf2_per_cu_data *per_cu,
10244                                 struct compunit_symtab *immediate_parent)
10245 {
10246   void **slot;
10247   int ix;
10248   struct compunit_symtab *cust;
10249   struct dwarf2_per_cu_data *iter;
10250
10251   slot = htab_find_slot (all_children, per_cu, INSERT);
10252   if (*slot != NULL)
10253     {
10254       /* This inclusion and its children have been processed.  */
10255       return;
10256     }
10257
10258   *slot = per_cu;
10259   /* Only add a CU if it has a symbol table.  */
10260   cust = get_compunit_symtab (per_cu);
10261   if (cust != NULL)
10262     {
10263       /* If this is a type unit only add its symbol table if we haven't
10264          seen it yet (type unit per_cu's can share symtabs).  */
10265       if (per_cu->is_debug_types)
10266         {
10267           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10268           if (*slot == NULL)
10269             {
10270               *slot = cust;
10271               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10272               if (cust->user == NULL)
10273                 cust->user = immediate_parent;
10274             }
10275         }
10276       else
10277         {
10278           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10279           if (cust->user == NULL)
10280             cust->user = immediate_parent;
10281         }
10282     }
10283
10284   for (ix = 0;
10285        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10286        ++ix)
10287     {
10288       recursively_compute_inclusions (result, all_children,
10289                                       all_type_symtabs, iter, cust);
10290     }
10291 }
10292
10293 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10294    PER_CU.  */
10295
10296 static void
10297 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10298 {
10299   gdb_assert (! per_cu->is_debug_types);
10300
10301   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10302     {
10303       int ix, len;
10304       struct dwarf2_per_cu_data *per_cu_iter;
10305       struct compunit_symtab *compunit_symtab_iter;
10306       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10307       htab_t all_children, all_type_symtabs;
10308       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10309
10310       /* If we don't have a symtab, we can just skip this case.  */
10311       if (cust == NULL)
10312         return;
10313
10314       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10315                                         NULL, xcalloc, xfree);
10316       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10317                                             NULL, xcalloc, xfree);
10318
10319       for (ix = 0;
10320            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10321                         ix, per_cu_iter);
10322            ++ix)
10323         {
10324           recursively_compute_inclusions (&result_symtabs, all_children,
10325                                           all_type_symtabs, per_cu_iter,
10326                                           cust);
10327         }
10328
10329       /* Now we have a transitive closure of all the included symtabs.  */
10330       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10331       cust->includes
10332         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
10333                      struct compunit_symtab *, len + 1);
10334       for (ix = 0;
10335            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10336                         compunit_symtab_iter);
10337            ++ix)
10338         cust->includes[ix] = compunit_symtab_iter;
10339       cust->includes[len] = NULL;
10340
10341       VEC_free (compunit_symtab_ptr, result_symtabs);
10342       htab_delete (all_children);
10343       htab_delete (all_type_symtabs);
10344     }
10345 }
10346
10347 /* Compute the 'includes' field for the symtabs of all the CUs we just
10348    read.  */
10349
10350 static void
10351 process_cu_includes (void)
10352 {
10353   int ix;
10354   struct dwarf2_per_cu_data *iter;
10355
10356   for (ix = 0;
10357        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10358                     ix, iter);
10359        ++ix)
10360     {
10361       if (! iter->is_debug_types)
10362         compute_compunit_symtab_includes (iter);
10363     }
10364
10365   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10366 }
10367
10368 /* Generate full symbol information for PER_CU, whose DIEs have
10369    already been loaded into memory.  */
10370
10371 static void
10372 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10373                         enum language pretend_language)
10374 {
10375   struct dwarf2_cu *cu = per_cu->cu;
10376   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
10377   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10378   CORE_ADDR lowpc, highpc;
10379   struct compunit_symtab *cust;
10380   struct cleanup *delayed_list_cleanup;
10381   CORE_ADDR baseaddr;
10382   struct block *static_block;
10383   CORE_ADDR addr;
10384
10385   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10386
10387   buildsym_init ();
10388   scoped_free_pendings free_pending;
10389   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10390
10391   cu->list_in_scope = &file_symbols;
10392
10393   cu->language = pretend_language;
10394   cu->language_defn = language_def (cu->language);
10395
10396   /* Do line number decoding in read_file_scope () */
10397   process_die (cu->dies, cu);
10398
10399   /* For now fudge the Go package.  */
10400   if (cu->language == language_go)
10401     fixup_go_packaging (cu);
10402
10403   /* Now that we have processed all the DIEs in the CU, all the types 
10404      should be complete, and it should now be safe to compute all of the
10405      physnames.  */
10406   compute_delayed_physnames (cu);
10407   do_cleanups (delayed_list_cleanup);
10408
10409   /* Some compilers don't define a DW_AT_high_pc attribute for the
10410      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10411      it, by scanning the DIE's below the compilation unit.  */
10412   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10413
10414   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10415   static_block = end_symtab_get_static_block (addr, 0, 1);
10416
10417   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10418      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10419      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10420      addrmap to help ensure it has an accurate map of pc values belonging to
10421      this comp unit.  */
10422   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10423
10424   cust = end_symtab_from_static_block (static_block,
10425                                        SECT_OFF_TEXT (objfile), 0);
10426
10427   if (cust != NULL)
10428     {
10429       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10430
10431       /* Set symtab language to language from DW_AT_language.  If the
10432          compilation is from a C file generated by language preprocessors, do
10433          not set the language if it was already deduced by start_subfile.  */
10434       if (!(cu->language == language_c
10435             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10436         COMPUNIT_FILETABS (cust)->language = cu->language;
10437
10438       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10439          produce DW_AT_location with location lists but it can be possibly
10440          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10441          there were bugs in prologue debug info, fixed later in GCC-4.5
10442          by "unwind info for epilogues" patch (which is not directly related).
10443
10444          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10445          needed, it would be wrong due to missing DW_AT_producer there.
10446
10447          Still one can confuse GDB by using non-standard GCC compilation
10448          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10449          */ 
10450       if (cu->has_loclist && gcc_4_minor >= 5)
10451         cust->locations_valid = 1;
10452
10453       if (gcc_4_minor >= 5)
10454         cust->epilogue_unwind_valid = 1;
10455
10456       cust->call_site_htab = cu->call_site_htab;
10457     }
10458
10459   if (dwarf2_per_objfile->using_index)
10460     per_cu->v.quick->compunit_symtab = cust;
10461   else
10462     {
10463       struct partial_symtab *pst = per_cu->v.psymtab;
10464       pst->compunit_symtab = cust;
10465       pst->readin = 1;
10466     }
10467
10468   /* Push it for inclusion processing later.  */
10469   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10470 }
10471
10472 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10473    already been loaded into memory.  */
10474
10475 static void
10476 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10477                         enum language pretend_language)
10478 {
10479   struct dwarf2_cu *cu = per_cu->cu;
10480   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
10481   struct compunit_symtab *cust;
10482   struct cleanup *delayed_list_cleanup;
10483   struct signatured_type *sig_type;
10484
10485   gdb_assert (per_cu->is_debug_types);
10486   sig_type = (struct signatured_type *) per_cu;
10487
10488   buildsym_init ();
10489   scoped_free_pendings free_pending;
10490   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10491
10492   cu->list_in_scope = &file_symbols;
10493
10494   cu->language = pretend_language;
10495   cu->language_defn = language_def (cu->language);
10496
10497   /* The symbol tables are set up in read_type_unit_scope.  */
10498   process_die (cu->dies, cu);
10499
10500   /* For now fudge the Go package.  */
10501   if (cu->language == language_go)
10502     fixup_go_packaging (cu);
10503
10504   /* Now that we have processed all the DIEs in the CU, all the types 
10505      should be complete, and it should now be safe to compute all of the
10506      physnames.  */
10507   compute_delayed_physnames (cu);
10508   do_cleanups (delayed_list_cleanup);
10509
10510   /* TUs share symbol tables.
10511      If this is the first TU to use this symtab, complete the construction
10512      of it with end_expandable_symtab.  Otherwise, complete the addition of
10513      this TU's symbols to the existing symtab.  */
10514   if (sig_type->type_unit_group->compunit_symtab == NULL)
10515     {
10516       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10517       sig_type->type_unit_group->compunit_symtab = cust;
10518
10519       if (cust != NULL)
10520         {
10521           /* Set symtab language to language from DW_AT_language.  If the
10522              compilation is from a C file generated by language preprocessors,
10523              do not set the language if it was already deduced by
10524              start_subfile.  */
10525           if (!(cu->language == language_c
10526                 && COMPUNIT_FILETABS (cust)->language != language_c))
10527             COMPUNIT_FILETABS (cust)->language = cu->language;
10528         }
10529     }
10530   else
10531     {
10532       augment_type_symtab ();
10533       cust = sig_type->type_unit_group->compunit_symtab;
10534     }
10535
10536   if (dwarf2_per_objfile->using_index)
10537     per_cu->v.quick->compunit_symtab = cust;
10538   else
10539     {
10540       struct partial_symtab *pst = per_cu->v.psymtab;
10541       pst->compunit_symtab = cust;
10542       pst->readin = 1;
10543     }
10544 }
10545
10546 /* Process an imported unit DIE.  */
10547
10548 static void
10549 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10550 {
10551   struct attribute *attr;
10552
10553   /* For now we don't handle imported units in type units.  */
10554   if (cu->per_cu->is_debug_types)
10555     {
10556       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10557                " supported in type units [in module %s]"),
10558              objfile_name (cu->dwarf2_per_objfile->objfile));
10559     }
10560
10561   attr = dwarf2_attr (die, DW_AT_import, cu);
10562   if (attr != NULL)
10563     {
10564       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10565       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10566       dwarf2_per_cu_data *per_cu
10567         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10568                                             cu->dwarf2_per_objfile->objfile);
10569
10570       /* If necessary, add it to the queue and load its DIEs.  */
10571       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10572         load_full_comp_unit (per_cu, cu->language);
10573
10574       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10575                      per_cu);
10576     }
10577 }
10578
10579 /* RAII object that represents a process_die scope: i.e.,
10580    starts/finishes processing a DIE.  */
10581 class process_die_scope
10582 {
10583 public:
10584   process_die_scope (die_info *die, dwarf2_cu *cu)
10585     : m_die (die), m_cu (cu)
10586   {
10587     /* We should only be processing DIEs not already in process.  */
10588     gdb_assert (!m_die->in_process);
10589     m_die->in_process = true;
10590   }
10591
10592   ~process_die_scope ()
10593   {
10594     m_die->in_process = false;
10595
10596     /* If we're done processing the DIE for the CU that owns the line
10597        header, we don't need the line header anymore.  */
10598     if (m_cu->line_header_die_owner == m_die)
10599       {
10600         delete m_cu->line_header;
10601         m_cu->line_header = NULL;
10602         m_cu->line_header_die_owner = NULL;
10603       }
10604   }
10605
10606 private:
10607   die_info *m_die;
10608   dwarf2_cu *m_cu;
10609 };
10610
10611 /* Process a die and its children.  */
10612
10613 static void
10614 process_die (struct die_info *die, struct dwarf2_cu *cu)
10615 {
10616   process_die_scope scope (die, cu);
10617
10618   switch (die->tag)
10619     {
10620     case DW_TAG_padding:
10621       break;
10622     case DW_TAG_compile_unit:
10623     case DW_TAG_partial_unit:
10624       read_file_scope (die, cu);
10625       break;
10626     case DW_TAG_type_unit:
10627       read_type_unit_scope (die, cu);
10628       break;
10629     case DW_TAG_subprogram:
10630     case DW_TAG_inlined_subroutine:
10631       read_func_scope (die, cu);
10632       break;
10633     case DW_TAG_lexical_block:
10634     case DW_TAG_try_block:
10635     case DW_TAG_catch_block:
10636       read_lexical_block_scope (die, cu);
10637       break;
10638     case DW_TAG_call_site:
10639     case DW_TAG_GNU_call_site:
10640       read_call_site_scope (die, cu);
10641       break;
10642     case DW_TAG_class_type:
10643     case DW_TAG_interface_type:
10644     case DW_TAG_structure_type:
10645     case DW_TAG_union_type:
10646       process_structure_scope (die, cu);
10647       break;
10648     case DW_TAG_enumeration_type:
10649       process_enumeration_scope (die, cu);
10650       break;
10651
10652     /* These dies have a type, but processing them does not create
10653        a symbol or recurse to process the children.  Therefore we can
10654        read them on-demand through read_type_die.  */
10655     case DW_TAG_subroutine_type:
10656     case DW_TAG_set_type:
10657     case DW_TAG_array_type:
10658     case DW_TAG_pointer_type:
10659     case DW_TAG_ptr_to_member_type:
10660     case DW_TAG_reference_type:
10661     case DW_TAG_rvalue_reference_type:
10662     case DW_TAG_string_type:
10663       break;
10664
10665     case DW_TAG_base_type:
10666     case DW_TAG_subrange_type:
10667     case DW_TAG_typedef:
10668       /* Add a typedef symbol for the type definition, if it has a
10669          DW_AT_name.  */
10670       new_symbol (die, read_type_die (die, cu), cu);
10671       break;
10672     case DW_TAG_common_block:
10673       read_common_block (die, cu);
10674       break;
10675     case DW_TAG_common_inclusion:
10676       break;
10677     case DW_TAG_namespace:
10678       cu->processing_has_namespace_info = 1;
10679       read_namespace (die, cu);
10680       break;
10681     case DW_TAG_module:
10682       cu->processing_has_namespace_info = 1;
10683       read_module (die, cu);
10684       break;
10685     case DW_TAG_imported_declaration:
10686       cu->processing_has_namespace_info = 1;
10687       if (read_namespace_alias (die, cu))
10688         break;
10689       /* The declaration is not a global namespace alias: fall through.  */
10690     case DW_TAG_imported_module:
10691       cu->processing_has_namespace_info = 1;
10692       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10693                                  || cu->language != language_fortran))
10694         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10695                    dwarf_tag_name (die->tag));
10696       read_import_statement (die, cu);
10697       break;
10698
10699     case DW_TAG_imported_unit:
10700       process_imported_unit_die (die, cu);
10701       break;
10702
10703     case DW_TAG_variable:
10704       read_variable (die, cu);
10705       break;
10706
10707     default:
10708       new_symbol (die, NULL, cu);
10709       break;
10710     }
10711 }
10712 \f
10713 /* DWARF name computation.  */
10714
10715 /* A helper function for dwarf2_compute_name which determines whether DIE
10716    needs to have the name of the scope prepended to the name listed in the
10717    die.  */
10718
10719 static int
10720 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10721 {
10722   struct attribute *attr;
10723
10724   switch (die->tag)
10725     {
10726     case DW_TAG_namespace:
10727     case DW_TAG_typedef:
10728     case DW_TAG_class_type:
10729     case DW_TAG_interface_type:
10730     case DW_TAG_structure_type:
10731     case DW_TAG_union_type:
10732     case DW_TAG_enumeration_type:
10733     case DW_TAG_enumerator:
10734     case DW_TAG_subprogram:
10735     case DW_TAG_inlined_subroutine:
10736     case DW_TAG_member:
10737     case DW_TAG_imported_declaration:
10738       return 1;
10739
10740     case DW_TAG_variable:
10741     case DW_TAG_constant:
10742       /* We only need to prefix "globally" visible variables.  These include
10743          any variable marked with DW_AT_external or any variable that
10744          lives in a namespace.  [Variables in anonymous namespaces
10745          require prefixing, but they are not DW_AT_external.]  */
10746
10747       if (dwarf2_attr (die, DW_AT_specification, cu))
10748         {
10749           struct dwarf2_cu *spec_cu = cu;
10750
10751           return die_needs_namespace (die_specification (die, &spec_cu),
10752                                       spec_cu);
10753         }
10754
10755       attr = dwarf2_attr (die, DW_AT_external, cu);
10756       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10757           && die->parent->tag != DW_TAG_module)
10758         return 0;
10759       /* A variable in a lexical block of some kind does not need a
10760          namespace, even though in C++ such variables may be external
10761          and have a mangled name.  */
10762       if (die->parent->tag ==  DW_TAG_lexical_block
10763           || die->parent->tag ==  DW_TAG_try_block
10764           || die->parent->tag ==  DW_TAG_catch_block
10765           || die->parent->tag == DW_TAG_subprogram)
10766         return 0;
10767       return 1;
10768
10769     default:
10770       return 0;
10771     }
10772 }
10773
10774 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10775    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10776    defined for the given DIE.  */
10777
10778 static struct attribute *
10779 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10780 {
10781   struct attribute *attr;
10782
10783   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10784   if (attr == NULL)
10785     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10786
10787   return attr;
10788 }
10789
10790 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10791    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10792    defined for the given DIE.  */
10793
10794 static const char *
10795 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10796 {
10797   const char *linkage_name;
10798
10799   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10800   if (linkage_name == NULL)
10801     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10802
10803   return linkage_name;
10804 }
10805
10806 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10807    compute the physname for the object, which include a method's:
10808    - formal parameters (C++),
10809    - receiver type (Go),
10810
10811    The term "physname" is a bit confusing.
10812    For C++, for example, it is the demangled name.
10813    For Go, for example, it's the mangled name.
10814
10815    For Ada, return the DIE's linkage name rather than the fully qualified
10816    name.  PHYSNAME is ignored..
10817
10818    The result is allocated on the objfile_obstack and canonicalized.  */
10819
10820 static const char *
10821 dwarf2_compute_name (const char *name,
10822                      struct die_info *die, struct dwarf2_cu *cu,
10823                      int physname)
10824 {
10825   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
10826
10827   if (name == NULL)
10828     name = dwarf2_name (die, cu);
10829
10830   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10831      but otherwise compute it by typename_concat inside GDB.
10832      FIXME: Actually this is not really true, or at least not always true.
10833      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10834      Fortran names because there is no mangling standard.  So new_symbol_full
10835      will set the demangled name to the result of dwarf2_full_name, and it is
10836      the demangled name that GDB uses if it exists.  */
10837   if (cu->language == language_ada
10838       || (cu->language == language_fortran && physname))
10839     {
10840       /* For Ada unit, we prefer the linkage name over the name, as
10841          the former contains the exported name, which the user expects
10842          to be able to reference.  Ideally, we want the user to be able
10843          to reference this entity using either natural or linkage name,
10844          but we haven't started looking at this enhancement yet.  */
10845       const char *linkage_name = dw2_linkage_name (die, cu);
10846
10847       if (linkage_name != NULL)
10848         return linkage_name;
10849     }
10850
10851   /* These are the only languages we know how to qualify names in.  */
10852   if (name != NULL
10853       && (cu->language == language_cplus
10854           || cu->language == language_fortran || cu->language == language_d
10855           || cu->language == language_rust))
10856     {
10857       if (die_needs_namespace (die, cu))
10858         {
10859           const char *prefix;
10860           const char *canonical_name = NULL;
10861
10862           string_file buf;
10863
10864           prefix = determine_prefix (die, cu);
10865           if (*prefix != '\0')
10866             {
10867               char *prefixed_name = typename_concat (NULL, prefix, name,
10868                                                      physname, cu);
10869
10870               buf.puts (prefixed_name);
10871               xfree (prefixed_name);
10872             }
10873           else
10874             buf.puts (name);
10875
10876           /* Template parameters may be specified in the DIE's DW_AT_name, or
10877              as children with DW_TAG_template_type_param or
10878              DW_TAG_value_type_param.  If the latter, add them to the name
10879              here.  If the name already has template parameters, then
10880              skip this step; some versions of GCC emit both, and
10881              it is more efficient to use the pre-computed name.
10882
10883              Something to keep in mind about this process: it is very
10884              unlikely, or in some cases downright impossible, to produce
10885              something that will match the mangled name of a function.
10886              If the definition of the function has the same debug info,
10887              we should be able to match up with it anyway.  But fallbacks
10888              using the minimal symbol, for instance to find a method
10889              implemented in a stripped copy of libstdc++, will not work.
10890              If we do not have debug info for the definition, we will have to
10891              match them up some other way.
10892
10893              When we do name matching there is a related problem with function
10894              templates; two instantiated function templates are allowed to
10895              differ only by their return types, which we do not add here.  */
10896
10897           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10898             {
10899               struct attribute *attr;
10900               struct die_info *child;
10901               int first = 1;
10902
10903               die->building_fullname = 1;
10904
10905               for (child = die->child; child != NULL; child = child->sibling)
10906                 {
10907                   struct type *type;
10908                   LONGEST value;
10909                   const gdb_byte *bytes;
10910                   struct dwarf2_locexpr_baton *baton;
10911                   struct value *v;
10912
10913                   if (child->tag != DW_TAG_template_type_param
10914                       && child->tag != DW_TAG_template_value_param)
10915                     continue;
10916
10917                   if (first)
10918                     {
10919                       buf.puts ("<");
10920                       first = 0;
10921                     }
10922                   else
10923                     buf.puts (", ");
10924
10925                   attr = dwarf2_attr (child, DW_AT_type, cu);
10926                   if (attr == NULL)
10927                     {
10928                       complaint (&symfile_complaints,
10929                                  _("template parameter missing DW_AT_type"));
10930                       buf.puts ("UNKNOWN_TYPE");
10931                       continue;
10932                     }
10933                   type = die_type (child, cu);
10934
10935                   if (child->tag == DW_TAG_template_type_param)
10936                     {
10937                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10938                       continue;
10939                     }
10940
10941                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10942                   if (attr == NULL)
10943                     {
10944                       complaint (&symfile_complaints,
10945                                  _("template parameter missing "
10946                                    "DW_AT_const_value"));
10947                       buf.puts ("UNKNOWN_VALUE");
10948                       continue;
10949                     }
10950
10951                   dwarf2_const_value_attr (attr, type, name,
10952                                            &cu->comp_unit_obstack, cu,
10953                                            &value, &bytes, &baton);
10954
10955                   if (TYPE_NOSIGN (type))
10956                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10957                        changed, this can use value_print instead.  */
10958                     c_printchar (value, type, &buf);
10959                   else
10960                     {
10961                       struct value_print_options opts;
10962
10963                       if (baton != NULL)
10964                         v = dwarf2_evaluate_loc_desc (type, NULL,
10965                                                       baton->data,
10966                                                       baton->size,
10967                                                       baton->per_cu);
10968                       else if (bytes != NULL)
10969                         {
10970                           v = allocate_value (type);
10971                           memcpy (value_contents_writeable (v), bytes,
10972                                   TYPE_LENGTH (type));
10973                         }
10974                       else
10975                         v = value_from_longest (type, value);
10976
10977                       /* Specify decimal so that we do not depend on
10978                          the radix.  */
10979                       get_formatted_print_options (&opts, 'd');
10980                       opts.raw = 1;
10981                       value_print (v, &buf, &opts);
10982                       release_value (v);
10983                       value_free (v);
10984                     }
10985                 }
10986
10987               die->building_fullname = 0;
10988
10989               if (!first)
10990                 {
10991                   /* Close the argument list, with a space if necessary
10992                      (nested templates).  */
10993                   if (!buf.empty () && buf.string ().back () == '>')
10994                     buf.puts (" >");
10995                   else
10996                     buf.puts (">");
10997                 }
10998             }
10999
11000           /* For C++ methods, append formal parameter type
11001              information, if PHYSNAME.  */
11002
11003           if (physname && die->tag == DW_TAG_subprogram
11004               && cu->language == language_cplus)
11005             {
11006               struct type *type = read_type_die (die, cu);
11007
11008               c_type_print_args (type, &buf, 1, cu->language,
11009                                  &type_print_raw_options);
11010
11011               if (cu->language == language_cplus)
11012                 {
11013                   /* Assume that an artificial first parameter is
11014                      "this", but do not crash if it is not.  RealView
11015                      marks unnamed (and thus unused) parameters as
11016                      artificial; there is no way to differentiate
11017                      the two cases.  */
11018                   if (TYPE_NFIELDS (type) > 0
11019                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11020                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11021                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11022                                                                         0))))
11023                     buf.puts (" const");
11024                 }
11025             }
11026
11027           const std::string &intermediate_name = buf.string ();
11028
11029           if (cu->language == language_cplus)
11030             canonical_name
11031               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11032                                           &objfile->per_bfd->storage_obstack);
11033
11034           /* If we only computed INTERMEDIATE_NAME, or if
11035              INTERMEDIATE_NAME is already canonical, then we need to
11036              copy it to the appropriate obstack.  */
11037           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11038             name = ((const char *)
11039                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11040                                    intermediate_name.c_str (),
11041                                    intermediate_name.length ()));
11042           else
11043             name = canonical_name;
11044         }
11045     }
11046
11047   return name;
11048 }
11049
11050 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11051    If scope qualifiers are appropriate they will be added.  The result
11052    will be allocated on the storage_obstack, or NULL if the DIE does
11053    not have a name.  NAME may either be from a previous call to
11054    dwarf2_name or NULL.
11055
11056    The output string will be canonicalized (if C++).  */
11057
11058 static const char *
11059 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11060 {
11061   return dwarf2_compute_name (name, die, cu, 0);
11062 }
11063
11064 /* Construct a physname for the given DIE in CU.  NAME may either be
11065    from a previous call to dwarf2_name or NULL.  The result will be
11066    allocated on the objfile_objstack or NULL if the DIE does not have a
11067    name.
11068
11069    The output string will be canonicalized (if C++).  */
11070
11071 static const char *
11072 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11073 {
11074   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
11075   const char *retval, *mangled = NULL, *canon = NULL;
11076   int need_copy = 1;
11077
11078   /* In this case dwarf2_compute_name is just a shortcut not building anything
11079      on its own.  */
11080   if (!die_needs_namespace (die, cu))
11081     return dwarf2_compute_name (name, die, cu, 1);
11082
11083   mangled = dw2_linkage_name (die, cu);
11084
11085   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11086      See https://github.com/rust-lang/rust/issues/32925.  */
11087   if (cu->language == language_rust && mangled != NULL
11088       && strchr (mangled, '{') != NULL)
11089     mangled = NULL;
11090
11091   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11092      has computed.  */
11093   gdb::unique_xmalloc_ptr<char> demangled;
11094   if (mangled != NULL)
11095     {
11096       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11097          type.  It is easier for GDB users to search for such functions as
11098          `name(params)' than `long name(params)'.  In such case the minimal
11099          symbol names do not match the full symbol names but for template
11100          functions there is never a need to look up their definition from their
11101          declaration so the only disadvantage remains the minimal symbol
11102          variant `long name(params)' does not have the proper inferior type.
11103          */
11104
11105       if (cu->language == language_go)
11106         {
11107           /* This is a lie, but we already lie to the caller new_symbol_full.
11108              new_symbol_full assumes we return the mangled name.
11109              This just undoes that lie until things are cleaned up.  */
11110         }
11111       else
11112         {
11113           demangled.reset (gdb_demangle (mangled,
11114                                          (DMGL_PARAMS | DMGL_ANSI
11115                                           | DMGL_RET_DROP)));
11116         }
11117       if (demangled)
11118         canon = demangled.get ();
11119       else
11120         {
11121           canon = mangled;
11122           need_copy = 0;
11123         }
11124     }
11125
11126   if (canon == NULL || check_physname)
11127     {
11128       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11129
11130       if (canon != NULL && strcmp (physname, canon) != 0)
11131         {
11132           /* It may not mean a bug in GDB.  The compiler could also
11133              compute DW_AT_linkage_name incorrectly.  But in such case
11134              GDB would need to be bug-to-bug compatible.  */
11135
11136           complaint (&symfile_complaints,
11137                      _("Computed physname <%s> does not match demangled <%s> "
11138                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11139                      physname, canon, mangled, to_underlying (die->sect_off),
11140                      objfile_name (objfile));
11141
11142           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11143              is available here - over computed PHYSNAME.  It is safer
11144              against both buggy GDB and buggy compilers.  */
11145
11146           retval = canon;
11147         }
11148       else
11149         {
11150           retval = physname;
11151           need_copy = 0;
11152         }
11153     }
11154   else
11155     retval = canon;
11156
11157   if (need_copy)
11158     retval = ((const char *)
11159               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11160                              retval, strlen (retval)));
11161
11162   return retval;
11163 }
11164
11165 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11166    a new symbol for it.
11167
11168    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11169
11170 static int
11171 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11172 {
11173   struct attribute *attr;
11174
11175   /* If the die does not have a name, this is not a namespace
11176      alias.  */
11177   attr = dwarf2_attr (die, DW_AT_name, cu);
11178   if (attr != NULL)
11179     {
11180       int num;
11181       struct die_info *d = die;
11182       struct dwarf2_cu *imported_cu = cu;
11183
11184       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11185          keep inspecting DIEs until we hit the underlying import.  */
11186 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11187       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11188         {
11189           attr = dwarf2_attr (d, DW_AT_import, cu);
11190           if (attr == NULL)
11191             break;
11192
11193           d = follow_die_ref (d, attr, &imported_cu);
11194           if (d->tag != DW_TAG_imported_declaration)
11195             break;
11196         }
11197
11198       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11199         {
11200           complaint (&symfile_complaints,
11201                      _("DIE at 0x%x has too many recursively imported "
11202                        "declarations"), to_underlying (d->sect_off));
11203           return 0;
11204         }
11205
11206       if (attr != NULL)
11207         {
11208           struct type *type;
11209           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11210
11211           type = get_die_type_at_offset (sect_off, cu->per_cu);
11212           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11213             {
11214               /* This declaration is a global namespace alias.  Add
11215                  a symbol for it whose type is the aliased namespace.  */
11216               new_symbol (die, type, cu);
11217               return 1;
11218             }
11219         }
11220     }
11221
11222   return 0;
11223 }
11224
11225 /* Return the using directives repository (global or local?) to use in the
11226    current context for LANGUAGE.
11227
11228    For Ada, imported declarations can materialize renamings, which *may* be
11229    global.  However it is impossible (for now?) in DWARF to distinguish
11230    "external" imported declarations and "static" ones.  As all imported
11231    declarations seem to be static in all other languages, make them all CU-wide
11232    global only in Ada.  */
11233
11234 static struct using_direct **
11235 using_directives (enum language language)
11236 {
11237   if (language == language_ada && context_stack_depth == 0)
11238     return &global_using_directives;
11239   else
11240     return &local_using_directives;
11241 }
11242
11243 /* Read the import statement specified by the given die and record it.  */
11244
11245 static void
11246 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11247 {
11248   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
11249   struct attribute *import_attr;
11250   struct die_info *imported_die, *child_die;
11251   struct dwarf2_cu *imported_cu;
11252   const char *imported_name;
11253   const char *imported_name_prefix;
11254   const char *canonical_name;
11255   const char *import_alias;
11256   const char *imported_declaration = NULL;
11257   const char *import_prefix;
11258   std::vector<const char *> excludes;
11259
11260   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11261   if (import_attr == NULL)
11262     {
11263       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11264                  dwarf_tag_name (die->tag));
11265       return;
11266     }
11267
11268   imported_cu = cu;
11269   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11270   imported_name = dwarf2_name (imported_die, imported_cu);
11271   if (imported_name == NULL)
11272     {
11273       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11274
11275         The import in the following code:
11276         namespace A
11277           {
11278             typedef int B;
11279           }
11280
11281         int main ()
11282           {
11283             using A::B;
11284             B b;
11285             return b;
11286           }
11287
11288         ...
11289          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11290             <52>   DW_AT_decl_file   : 1
11291             <53>   DW_AT_decl_line   : 6
11292             <54>   DW_AT_import      : <0x75>
11293          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11294             <59>   DW_AT_name        : B
11295             <5b>   DW_AT_decl_file   : 1
11296             <5c>   DW_AT_decl_line   : 2
11297             <5d>   DW_AT_type        : <0x6e>
11298         ...
11299          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11300             <76>   DW_AT_byte_size   : 4
11301             <77>   DW_AT_encoding    : 5        (signed)
11302
11303         imports the wrong die ( 0x75 instead of 0x58 ).
11304         This case will be ignored until the gcc bug is fixed.  */
11305       return;
11306     }
11307
11308   /* Figure out the local name after import.  */
11309   import_alias = dwarf2_name (die, cu);
11310
11311   /* Figure out where the statement is being imported to.  */
11312   import_prefix = determine_prefix (die, cu);
11313
11314   /* Figure out what the scope of the imported die is and prepend it
11315      to the name of the imported die.  */
11316   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11317
11318   if (imported_die->tag != DW_TAG_namespace
11319       && imported_die->tag != DW_TAG_module)
11320     {
11321       imported_declaration = imported_name;
11322       canonical_name = imported_name_prefix;
11323     }
11324   else if (strlen (imported_name_prefix) > 0)
11325     canonical_name = obconcat (&objfile->objfile_obstack,
11326                                imported_name_prefix,
11327                                (cu->language == language_d ? "." : "::"),
11328                                imported_name, (char *) NULL);
11329   else
11330     canonical_name = imported_name;
11331
11332   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11333     for (child_die = die->child; child_die && child_die->tag;
11334          child_die = sibling_die (child_die))
11335       {
11336         /* DWARF-4: A Fortran use statement with a “rename list” may be
11337            represented by an imported module entry with an import attribute
11338            referring to the module and owned entries corresponding to those
11339            entities that are renamed as part of being imported.  */
11340
11341         if (child_die->tag != DW_TAG_imported_declaration)
11342           {
11343             complaint (&symfile_complaints,
11344                        _("child DW_TAG_imported_declaration expected "
11345                          "- DIE at 0x%x [in module %s]"),
11346                        to_underlying (child_die->sect_off), objfile_name (objfile));
11347             continue;
11348           }
11349
11350         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11351         if (import_attr == NULL)
11352           {
11353             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11354                        dwarf_tag_name (child_die->tag));
11355             continue;
11356           }
11357
11358         imported_cu = cu;
11359         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11360                                               &imported_cu);
11361         imported_name = dwarf2_name (imported_die, imported_cu);
11362         if (imported_name == NULL)
11363           {
11364             complaint (&symfile_complaints,
11365                        _("child DW_TAG_imported_declaration has unknown "
11366                          "imported name - DIE at 0x%x [in module %s]"),
11367                        to_underlying (child_die->sect_off), objfile_name (objfile));
11368             continue;
11369           }
11370
11371         excludes.push_back (imported_name);
11372
11373         process_die (child_die, cu);
11374       }
11375
11376   add_using_directive (using_directives (cu->language),
11377                        import_prefix,
11378                        canonical_name,
11379                        import_alias,
11380                        imported_declaration,
11381                        excludes,
11382                        0,
11383                        &objfile->objfile_obstack);
11384 }
11385
11386 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11387    types, but gives them a size of zero.  Starting with version 14,
11388    ICC is compatible with GCC.  */
11389
11390 static int
11391 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11392 {
11393   if (!cu->checked_producer)
11394     check_producer (cu);
11395
11396   return cu->producer_is_icc_lt_14;
11397 }
11398
11399 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11400    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11401    this, it was first present in GCC release 4.3.0.  */
11402
11403 static int
11404 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11405 {
11406   if (!cu->checked_producer)
11407     check_producer (cu);
11408
11409   return cu->producer_is_gcc_lt_4_3;
11410 }
11411
11412 static file_and_directory
11413 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11414 {
11415   file_and_directory res;
11416
11417   /* Find the filename.  Do not use dwarf2_name here, since the filename
11418      is not a source language identifier.  */
11419   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11420   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11421
11422   if (res.comp_dir == NULL
11423       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11424       && IS_ABSOLUTE_PATH (res.name))
11425     {
11426       res.comp_dir_storage = ldirname (res.name);
11427       if (!res.comp_dir_storage.empty ())
11428         res.comp_dir = res.comp_dir_storage.c_str ();
11429     }
11430   if (res.comp_dir != NULL)
11431     {
11432       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11433          directory, get rid of it.  */
11434       const char *cp = strchr (res.comp_dir, ':');
11435
11436       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11437         res.comp_dir = cp + 1;
11438     }
11439
11440   if (res.name == NULL)
11441     res.name = "<unknown>";
11442
11443   return res;
11444 }
11445
11446 /* Handle DW_AT_stmt_list for a compilation unit.
11447    DIE is the DW_TAG_compile_unit die for CU.
11448    COMP_DIR is the compilation directory.  LOWPC is passed to
11449    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11450
11451 static void
11452 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11453                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11454 {
11455   struct objfile *objfile = dwarf2_per_objfile->objfile;
11456   struct attribute *attr;
11457   struct line_header line_header_local;
11458   hashval_t line_header_local_hash;
11459   void **slot;
11460   int decode_mapping;
11461
11462   gdb_assert (! cu->per_cu->is_debug_types);
11463
11464   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11465   if (attr == NULL)
11466     return;
11467
11468   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11469
11470   /* The line header hash table is only created if needed (it exists to
11471      prevent redundant reading of the line table for partial_units).
11472      If we're given a partial_unit, we'll need it.  If we're given a
11473      compile_unit, then use the line header hash table if it's already
11474      created, but don't create one just yet.  */
11475
11476   if (dwarf2_per_objfile->line_header_hash == NULL
11477       && die->tag == DW_TAG_partial_unit)
11478     {
11479       dwarf2_per_objfile->line_header_hash
11480         = htab_create_alloc_ex (127, line_header_hash_voidp,
11481                                 line_header_eq_voidp,
11482                                 free_line_header_voidp,
11483                                 &objfile->objfile_obstack,
11484                                 hashtab_obstack_allocate,
11485                                 dummy_obstack_deallocate);
11486     }
11487
11488   line_header_local.sect_off = line_offset;
11489   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11490   line_header_local_hash = line_header_hash (&line_header_local);
11491   if (dwarf2_per_objfile->line_header_hash != NULL)
11492     {
11493       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11494                                        &line_header_local,
11495                                        line_header_local_hash, NO_INSERT);
11496
11497       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11498          is not present in *SLOT (since if there is something in *SLOT then
11499          it will be for a partial_unit).  */
11500       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11501         {
11502           gdb_assert (*slot != NULL);
11503           cu->line_header = (struct line_header *) *slot;
11504           return;
11505         }
11506     }
11507
11508   /* dwarf_decode_line_header does not yet provide sufficient information.
11509      We always have to call also dwarf_decode_lines for it.  */
11510   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11511   if (lh == NULL)
11512     return;
11513
11514   cu->line_header = lh.release ();
11515   cu->line_header_die_owner = die;
11516
11517   if (dwarf2_per_objfile->line_header_hash == NULL)
11518     slot = NULL;
11519   else
11520     {
11521       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11522                                        &line_header_local,
11523                                        line_header_local_hash, INSERT);
11524       gdb_assert (slot != NULL);
11525     }
11526   if (slot != NULL && *slot == NULL)
11527     {
11528       /* This newly decoded line number information unit will be owned
11529          by line_header_hash hash table.  */
11530       *slot = cu->line_header;
11531       cu->line_header_die_owner = NULL;
11532     }
11533   else
11534     {
11535       /* We cannot free any current entry in (*slot) as that struct line_header
11536          may be already used by multiple CUs.  Create only temporary decoded
11537          line_header for this CU - it may happen at most once for each line
11538          number information unit.  And if we're not using line_header_hash
11539          then this is what we want as well.  */
11540       gdb_assert (die->tag != DW_TAG_partial_unit);
11541     }
11542   decode_mapping = (die->tag != DW_TAG_partial_unit);
11543   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11544                       decode_mapping);
11545
11546 }
11547
11548 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11549
11550 static void
11551 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11552 {
11553   struct objfile *objfile = dwarf2_per_objfile->objfile;
11554   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11555   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11556   CORE_ADDR highpc = ((CORE_ADDR) 0);
11557   struct attribute *attr;
11558   struct die_info *child_die;
11559   CORE_ADDR baseaddr;
11560
11561   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11562
11563   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11564
11565   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11566      from finish_block.  */
11567   if (lowpc == ((CORE_ADDR) -1))
11568     lowpc = highpc;
11569   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11570
11571   file_and_directory fnd = find_file_and_directory (die, cu);
11572
11573   prepare_one_comp_unit (cu, die, cu->language);
11574
11575   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11576      standardised yet.  As a workaround for the language detection we fall
11577      back to the DW_AT_producer string.  */
11578   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11579     cu->language = language_opencl;
11580
11581   /* Similar hack for Go.  */
11582   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11583     set_cu_language (DW_LANG_Go, cu);
11584
11585   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11586
11587   /* Decode line number information if present.  We do this before
11588      processing child DIEs, so that the line header table is available
11589      for DW_AT_decl_file.  */
11590   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11591
11592   /* Process all dies in compilation unit.  */
11593   if (die->child != NULL)
11594     {
11595       child_die = die->child;
11596       while (child_die && child_die->tag)
11597         {
11598           process_die (child_die, cu);
11599           child_die = sibling_die (child_die);
11600         }
11601     }
11602
11603   /* Decode macro information, if present.  Dwarf 2 macro information
11604      refers to information in the line number info statement program
11605      header, so we can only read it if we've read the header
11606      successfully.  */
11607   attr = dwarf2_attr (die, DW_AT_macros, cu);
11608   if (attr == NULL)
11609     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11610   if (attr && cu->line_header)
11611     {
11612       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11613         complaint (&symfile_complaints,
11614                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11615
11616       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11617     }
11618   else
11619     {
11620       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11621       if (attr && cu->line_header)
11622         {
11623           unsigned int macro_offset = DW_UNSND (attr);
11624
11625           dwarf_decode_macros (cu, macro_offset, 0);
11626         }
11627     }
11628 }
11629
11630 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11631    Create the set of symtabs used by this TU, or if this TU is sharing
11632    symtabs with another TU and the symtabs have already been created
11633    then restore those symtabs in the line header.
11634    We don't need the pc/line-number mapping for type units.  */
11635
11636 static void
11637 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11638 {
11639   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11640   struct type_unit_group *tu_group;
11641   int first_time;
11642   struct attribute *attr;
11643   unsigned int i;
11644   struct signatured_type *sig_type;
11645
11646   gdb_assert (per_cu->is_debug_types);
11647   sig_type = (struct signatured_type *) per_cu;
11648
11649   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11650
11651   /* If we're using .gdb_index (includes -readnow) then
11652      per_cu->type_unit_group may not have been set up yet.  */
11653   if (sig_type->type_unit_group == NULL)
11654     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11655   tu_group = sig_type->type_unit_group;
11656
11657   /* If we've already processed this stmt_list there's no real need to
11658      do it again, we could fake it and just recreate the part we need
11659      (file name,index -> symtab mapping).  If data shows this optimization
11660      is useful we can do it then.  */
11661   first_time = tu_group->compunit_symtab == NULL;
11662
11663   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11664      debug info.  */
11665   line_header_up lh;
11666   if (attr != NULL)
11667     {
11668       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11669       lh = dwarf_decode_line_header (line_offset, cu);
11670     }
11671   if (lh == NULL)
11672     {
11673       if (first_time)
11674         dwarf2_start_symtab (cu, "", NULL, 0);
11675       else
11676         {
11677           gdb_assert (tu_group->symtabs == NULL);
11678           restart_symtab (tu_group->compunit_symtab, "", 0);
11679         }
11680       return;
11681     }
11682
11683   cu->line_header = lh.release ();
11684   cu->line_header_die_owner = die;
11685
11686   if (first_time)
11687     {
11688       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11689
11690       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11691          still initializing it, and our caller (a few levels up)
11692          process_full_type_unit still needs to know if this is the first
11693          time.  */
11694
11695       tu_group->num_symtabs = cu->line_header->file_names.size ();
11696       tu_group->symtabs = XNEWVEC (struct symtab *,
11697                                    cu->line_header->file_names.size ());
11698
11699       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11700         {
11701           file_entry &fe = cu->line_header->file_names[i];
11702
11703           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11704
11705           if (current_subfile->symtab == NULL)
11706             {
11707               /* NOTE: start_subfile will recognize when it's been
11708                  passed a file it has already seen.  So we can't
11709                  assume there's a simple mapping from
11710                  cu->line_header->file_names to subfiles, plus
11711                  cu->line_header->file_names may contain dups.  */
11712               current_subfile->symtab
11713                 = allocate_symtab (cust, current_subfile->name);
11714             }
11715
11716           fe.symtab = current_subfile->symtab;
11717           tu_group->symtabs[i] = fe.symtab;
11718         }
11719     }
11720   else
11721     {
11722       restart_symtab (tu_group->compunit_symtab, "", 0);
11723
11724       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11725         {
11726           file_entry &fe = cu->line_header->file_names[i];
11727
11728           fe.symtab = tu_group->symtabs[i];
11729         }
11730     }
11731
11732   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11733      so they don't have a "real" (so to speak) symtab anyway.
11734      There is later code that will assign the main symtab to all symbols
11735      that don't have one.  We need to handle the case of a symbol with a
11736      missing symtab (DW_AT_decl_file) anyway.  */
11737 }
11738
11739 /* Process DW_TAG_type_unit.
11740    For TUs we want to skip the first top level sibling if it's not the
11741    actual type being defined by this TU.  In this case the first top
11742    level sibling is there to provide context only.  */
11743
11744 static void
11745 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11746 {
11747   struct die_info *child_die;
11748
11749   prepare_one_comp_unit (cu, die, language_minimal);
11750
11751   /* Initialize (or reinitialize) the machinery for building symtabs.
11752      We do this before processing child DIEs, so that the line header table
11753      is available for DW_AT_decl_file.  */
11754   setup_type_unit_groups (die, cu);
11755
11756   if (die->child != NULL)
11757     {
11758       child_die = die->child;
11759       while (child_die && child_die->tag)
11760         {
11761           process_die (child_die, cu);
11762           child_die = sibling_die (child_die);
11763         }
11764     }
11765 }
11766 \f
11767 /* DWO/DWP files.
11768
11769    http://gcc.gnu.org/wiki/DebugFission
11770    http://gcc.gnu.org/wiki/DebugFissionDWP
11771
11772    To simplify handling of both DWO files ("object" files with the DWARF info)
11773    and DWP files (a file with the DWOs packaged up into one file), we treat
11774    DWP files as having a collection of virtual DWO files.  */
11775
11776 static hashval_t
11777 hash_dwo_file (const void *item)
11778 {
11779   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11780   hashval_t hash;
11781
11782   hash = htab_hash_string (dwo_file->dwo_name);
11783   if (dwo_file->comp_dir != NULL)
11784     hash += htab_hash_string (dwo_file->comp_dir);
11785   return hash;
11786 }
11787
11788 static int
11789 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11790 {
11791   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11792   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11793
11794   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11795     return 0;
11796   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11797     return lhs->comp_dir == rhs->comp_dir;
11798   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11799 }
11800
11801 /* Allocate a hash table for DWO files.  */
11802
11803 static htab_t
11804 allocate_dwo_file_hash_table (void)
11805 {
11806   struct objfile *objfile = dwarf2_per_objfile->objfile;
11807
11808   return htab_create_alloc_ex (41,
11809                                hash_dwo_file,
11810                                eq_dwo_file,
11811                                NULL,
11812                                &objfile->objfile_obstack,
11813                                hashtab_obstack_allocate,
11814                                dummy_obstack_deallocate);
11815 }
11816
11817 /* Lookup DWO file DWO_NAME.  */
11818
11819 static void **
11820 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
11821 {
11822   struct dwo_file find_entry;
11823   void **slot;
11824
11825   if (dwarf2_per_objfile->dwo_files == NULL)
11826     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
11827
11828   memset (&find_entry, 0, sizeof (find_entry));
11829   find_entry.dwo_name = dwo_name;
11830   find_entry.comp_dir = comp_dir;
11831   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11832
11833   return slot;
11834 }
11835
11836 static hashval_t
11837 hash_dwo_unit (const void *item)
11838 {
11839   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11840
11841   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11842   return dwo_unit->signature;
11843 }
11844
11845 static int
11846 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11847 {
11848   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11849   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11850
11851   /* The signature is assumed to be unique within the DWO file.
11852      So while object file CU dwo_id's always have the value zero,
11853      that's OK, assuming each object file DWO file has only one CU,
11854      and that's the rule for now.  */
11855   return lhs->signature == rhs->signature;
11856 }
11857
11858 /* Allocate a hash table for DWO CUs,TUs.
11859    There is one of these tables for each of CUs,TUs for each DWO file.  */
11860
11861 static htab_t
11862 allocate_dwo_unit_table (struct objfile *objfile)
11863 {
11864   /* Start out with a pretty small number.
11865      Generally DWO files contain only one CU and maybe some TUs.  */
11866   return htab_create_alloc_ex (3,
11867                                hash_dwo_unit,
11868                                eq_dwo_unit,
11869                                NULL,
11870                                &objfile->objfile_obstack,
11871                                hashtab_obstack_allocate,
11872                                dummy_obstack_deallocate);
11873 }
11874
11875 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11876
11877 struct create_dwo_cu_data
11878 {
11879   struct dwo_file *dwo_file;
11880   struct dwo_unit dwo_unit;
11881 };
11882
11883 /* die_reader_func for create_dwo_cu.  */
11884
11885 static void
11886 create_dwo_cu_reader (const struct die_reader_specs *reader,
11887                       const gdb_byte *info_ptr,
11888                       struct die_info *comp_unit_die,
11889                       int has_children,
11890                       void *datap)
11891 {
11892   struct dwarf2_cu *cu = reader->cu;
11893   sect_offset sect_off = cu->per_cu->sect_off;
11894   struct dwarf2_section_info *section = cu->per_cu->section;
11895   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11896   struct dwo_file *dwo_file = data->dwo_file;
11897   struct dwo_unit *dwo_unit = &data->dwo_unit;
11898   struct attribute *attr;
11899
11900   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11901   if (attr == NULL)
11902     {
11903       complaint (&symfile_complaints,
11904                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11905                    " its dwo_id [in module %s]"),
11906                  to_underlying (sect_off), dwo_file->dwo_name);
11907       return;
11908     }
11909
11910   dwo_unit->dwo_file = dwo_file;
11911   dwo_unit->signature = DW_UNSND (attr);
11912   dwo_unit->section = section;
11913   dwo_unit->sect_off = sect_off;
11914   dwo_unit->length = cu->per_cu->length;
11915
11916   if (dwarf_read_debug)
11917     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11918                         to_underlying (sect_off),
11919                         hex_string (dwo_unit->signature));
11920 }
11921
11922 /* Create the dwo_units for the CUs in a DWO_FILE.
11923    Note: This function processes DWO files only, not DWP files.  */
11924
11925 static void
11926 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
11927                        htab_t &cus_htab)
11928 {
11929   struct objfile *objfile = dwarf2_per_objfile->objfile;
11930   const gdb_byte *info_ptr, *end_ptr;
11931
11932   dwarf2_read_section (objfile, &section);
11933   info_ptr = section.buffer;
11934
11935   if (info_ptr == NULL)
11936     return;
11937
11938   if (dwarf_read_debug)
11939     {
11940       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11941                           get_section_name (&section),
11942                           get_section_file_name (&section));
11943     }
11944
11945   end_ptr = info_ptr + section.size;
11946   while (info_ptr < end_ptr)
11947     {
11948       struct dwarf2_per_cu_data per_cu;
11949       struct create_dwo_cu_data create_dwo_cu_data;
11950       struct dwo_unit *dwo_unit;
11951       void **slot;
11952       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11953
11954       memset (&create_dwo_cu_data.dwo_unit, 0,
11955               sizeof (create_dwo_cu_data.dwo_unit));
11956       memset (&per_cu, 0, sizeof (per_cu));
11957       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11958       per_cu.is_debug_types = 0;
11959       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11960       per_cu.section = &section;
11961       create_dwo_cu_data.dwo_file = &dwo_file;
11962
11963       init_cutu_and_read_dies_no_follow (
11964           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11965       info_ptr += per_cu.length;
11966
11967       // If the unit could not be parsed, skip it.
11968       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11969         continue;
11970
11971       if (cus_htab == NULL)
11972         cus_htab = allocate_dwo_unit_table (objfile);
11973
11974       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11975       *dwo_unit = create_dwo_cu_data.dwo_unit;
11976       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11977       gdb_assert (slot != NULL);
11978       if (*slot != NULL)
11979         {
11980           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11981           sect_offset dup_sect_off = dup_cu->sect_off;
11982
11983           complaint (&symfile_complaints,
11984                      _("debug cu entry at offset 0x%x is duplicate to"
11985                        " the entry at offset 0x%x, signature %s"),
11986                      to_underlying (sect_off), to_underlying (dup_sect_off),
11987                      hex_string (dwo_unit->signature));
11988         }
11989       *slot = (void *)dwo_unit;
11990     }
11991 }
11992
11993 /* DWP file .debug_{cu,tu}_index section format:
11994    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11995
11996    DWP Version 1:
11997
11998    Both index sections have the same format, and serve to map a 64-bit
11999    signature to a set of section numbers.  Each section begins with a header,
12000    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12001    indexes, and a pool of 32-bit section numbers.  The index sections will be
12002    aligned at 8-byte boundaries in the file.
12003
12004    The index section header consists of:
12005
12006     V, 32 bit version number
12007     -, 32 bits unused
12008     N, 32 bit number of compilation units or type units in the index
12009     M, 32 bit number of slots in the hash table
12010
12011    Numbers are recorded using the byte order of the application binary.
12012
12013    The hash table begins at offset 16 in the section, and consists of an array
12014    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12015    order of the application binary).  Unused slots in the hash table are 0.
12016    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12017
12018    The parallel table begins immediately after the hash table
12019    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12020    array of 32-bit indexes (using the byte order of the application binary),
12021    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12022    table contains a 32-bit index into the pool of section numbers.  For unused
12023    hash table slots, the corresponding entry in the parallel table will be 0.
12024
12025    The pool of section numbers begins immediately following the hash table
12026    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12027    section numbers consists of an array of 32-bit words (using the byte order
12028    of the application binary).  Each item in the array is indexed starting
12029    from 0.  The hash table entry provides the index of the first section
12030    number in the set.  Additional section numbers in the set follow, and the
12031    set is terminated by a 0 entry (section number 0 is not used in ELF).
12032
12033    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12034    section must be the first entry in the set, and the .debug_abbrev.dwo must
12035    be the second entry. Other members of the set may follow in any order.
12036
12037    ---
12038
12039    DWP Version 2:
12040
12041    DWP Version 2 combines all the .debug_info, etc. sections into one,
12042    and the entries in the index tables are now offsets into these sections.
12043    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12044    section.
12045
12046    Index Section Contents:
12047     Header
12048     Hash Table of Signatures   dwp_hash_table.hash_table
12049     Parallel Table of Indices  dwp_hash_table.unit_table
12050     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12051     Table of Section Sizes     dwp_hash_table.v2.sizes
12052
12053    The index section header consists of:
12054
12055     V, 32 bit version number
12056     L, 32 bit number of columns in the table of section offsets
12057     N, 32 bit number of compilation units or type units in the index
12058     M, 32 bit number of slots in the hash table
12059
12060    Numbers are recorded using the byte order of the application binary.
12061
12062    The hash table has the same format as version 1.
12063    The parallel table of indices has the same format as version 1,
12064    except that the entries are origin-1 indices into the table of sections
12065    offsets and the table of section sizes.
12066
12067    The table of offsets begins immediately following the parallel table
12068    (at offset 16 + 12 * M from the beginning of the section).  The table is
12069    a two-dimensional array of 32-bit words (using the byte order of the
12070    application binary), with L columns and N+1 rows, in row-major order.
12071    Each row in the array is indexed starting from 0.  The first row provides
12072    a key to the remaining rows: each column in this row provides an identifier
12073    for a debug section, and the offsets in the same column of subsequent rows
12074    refer to that section.  The section identifiers are:
12075
12076     DW_SECT_INFO         1  .debug_info.dwo
12077     DW_SECT_TYPES        2  .debug_types.dwo
12078     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12079     DW_SECT_LINE         4  .debug_line.dwo
12080     DW_SECT_LOC          5  .debug_loc.dwo
12081     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12082     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12083     DW_SECT_MACRO        8  .debug_macro.dwo
12084
12085    The offsets provided by the CU and TU index sections are the base offsets
12086    for the contributions made by each CU or TU to the corresponding section
12087    in the package file.  Each CU and TU header contains an abbrev_offset
12088    field, used to find the abbreviations table for that CU or TU within the
12089    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12090    be interpreted as relative to the base offset given in the index section.
12091    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12092    should be interpreted as relative to the base offset for .debug_line.dwo,
12093    and offsets into other debug sections obtained from DWARF attributes should
12094    also be interpreted as relative to the corresponding base offset.
12095
12096    The table of sizes begins immediately following the table of offsets.
12097    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12098    with L columns and N rows, in row-major order.  Each row in the array is
12099    indexed starting from 1 (row 0 is shared by the two tables).
12100
12101    ---
12102
12103    Hash table lookup is handled the same in version 1 and 2:
12104
12105    We assume that N and M will not exceed 2^32 - 1.
12106    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12107
12108    Given a 64-bit compilation unit signature or a type signature S, an entry
12109    in the hash table is located as follows:
12110
12111    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12112       the low-order k bits all set to 1.
12113
12114    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12115
12116    3) If the hash table entry at index H matches the signature, use that
12117       entry.  If the hash table entry at index H is unused (all zeroes),
12118       terminate the search: the signature is not present in the table.
12119
12120    4) Let H = (H + H') modulo M. Repeat at Step 3.
12121
12122    Because M > N and H' and M are relatively prime, the search is guaranteed
12123    to stop at an unused slot or find the match.  */
12124
12125 /* Create a hash table to map DWO IDs to their CU/TU entry in
12126    .debug_{info,types}.dwo in DWP_FILE.
12127    Returns NULL if there isn't one.
12128    Note: This function processes DWP files only, not DWO files.  */
12129
12130 static struct dwp_hash_table *
12131 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
12132 {
12133   struct objfile *objfile = dwarf2_per_objfile->objfile;
12134   bfd *dbfd = dwp_file->dbfd;
12135   const gdb_byte *index_ptr, *index_end;
12136   struct dwarf2_section_info *index;
12137   uint32_t version, nr_columns, nr_units, nr_slots;
12138   struct dwp_hash_table *htab;
12139
12140   if (is_debug_types)
12141     index = &dwp_file->sections.tu_index;
12142   else
12143     index = &dwp_file->sections.cu_index;
12144
12145   if (dwarf2_section_empty_p (index))
12146     return NULL;
12147   dwarf2_read_section (objfile, index);
12148
12149   index_ptr = index->buffer;
12150   index_end = index_ptr + index->size;
12151
12152   version = read_4_bytes (dbfd, index_ptr);
12153   index_ptr += 4;
12154   if (version == 2)
12155     nr_columns = read_4_bytes (dbfd, index_ptr);
12156   else
12157     nr_columns = 0;
12158   index_ptr += 4;
12159   nr_units = read_4_bytes (dbfd, index_ptr);
12160   index_ptr += 4;
12161   nr_slots = read_4_bytes (dbfd, index_ptr);
12162   index_ptr += 4;
12163
12164   if (version != 1 && version != 2)
12165     {
12166       error (_("Dwarf Error: unsupported DWP file version (%s)"
12167                " [in module %s]"),
12168              pulongest (version), dwp_file->name);
12169     }
12170   if (nr_slots != (nr_slots & -nr_slots))
12171     {
12172       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12173                " is not power of 2 [in module %s]"),
12174              pulongest (nr_slots), dwp_file->name);
12175     }
12176
12177   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12178   htab->version = version;
12179   htab->nr_columns = nr_columns;
12180   htab->nr_units = nr_units;
12181   htab->nr_slots = nr_slots;
12182   htab->hash_table = index_ptr;
12183   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12184
12185   /* Exit early if the table is empty.  */
12186   if (nr_slots == 0 || nr_units == 0
12187       || (version == 2 && nr_columns == 0))
12188     {
12189       /* All must be zero.  */
12190       if (nr_slots != 0 || nr_units != 0
12191           || (version == 2 && nr_columns != 0))
12192         {
12193           complaint (&symfile_complaints,
12194                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12195                        " all zero [in modules %s]"),
12196                      dwp_file->name);
12197         }
12198       return htab;
12199     }
12200
12201   if (version == 1)
12202     {
12203       htab->section_pool.v1.indices =
12204         htab->unit_table + sizeof (uint32_t) * nr_slots;
12205       /* It's harder to decide whether the section is too small in v1.
12206          V1 is deprecated anyway so we punt.  */
12207     }
12208   else
12209     {
12210       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12211       int *ids = htab->section_pool.v2.section_ids;
12212       /* Reverse map for error checking.  */
12213       int ids_seen[DW_SECT_MAX + 1];
12214       int i;
12215
12216       if (nr_columns < 2)
12217         {
12218           error (_("Dwarf Error: bad DWP hash table, too few columns"
12219                    " in section table [in module %s]"),
12220                  dwp_file->name);
12221         }
12222       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12223         {
12224           error (_("Dwarf Error: bad DWP hash table, too many columns"
12225                    " in section table [in module %s]"),
12226                  dwp_file->name);
12227         }
12228       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12229       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12230       for (i = 0; i < nr_columns; ++i)
12231         {
12232           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12233
12234           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12235             {
12236               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12237                        " in section table [in module %s]"),
12238                      id, dwp_file->name);
12239             }
12240           if (ids_seen[id] != -1)
12241             {
12242               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12243                        " id %d in section table [in module %s]"),
12244                      id, dwp_file->name);
12245             }
12246           ids_seen[id] = i;
12247           ids[i] = id;
12248         }
12249       /* Must have exactly one info or types section.  */
12250       if (((ids_seen[DW_SECT_INFO] != -1)
12251            + (ids_seen[DW_SECT_TYPES] != -1))
12252           != 1)
12253         {
12254           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12255                    " DWO info/types section [in module %s]"),
12256                  dwp_file->name);
12257         }
12258       /* Must have an abbrev section.  */
12259       if (ids_seen[DW_SECT_ABBREV] == -1)
12260         {
12261           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12262                    " section [in module %s]"),
12263                  dwp_file->name);
12264         }
12265       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12266       htab->section_pool.v2.sizes =
12267         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12268                                          * nr_units * nr_columns);
12269       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12270                                           * nr_units * nr_columns))
12271           > index_end)
12272         {
12273           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12274                    " [in module %s]"),
12275                  dwp_file->name);
12276         }
12277     }
12278
12279   return htab;
12280 }
12281
12282 /* Update SECTIONS with the data from SECTP.
12283
12284    This function is like the other "locate" section routines that are
12285    passed to bfd_map_over_sections, but in this context the sections to
12286    read comes from the DWP V1 hash table, not the full ELF section table.
12287
12288    The result is non-zero for success, or zero if an error was found.  */
12289
12290 static int
12291 locate_v1_virtual_dwo_sections (asection *sectp,
12292                                 struct virtual_v1_dwo_sections *sections)
12293 {
12294   const struct dwop_section_names *names = &dwop_section_names;
12295
12296   if (section_is_p (sectp->name, &names->abbrev_dwo))
12297     {
12298       /* There can be only one.  */
12299       if (sections->abbrev.s.section != NULL)
12300         return 0;
12301       sections->abbrev.s.section = sectp;
12302       sections->abbrev.size = bfd_get_section_size (sectp);
12303     }
12304   else if (section_is_p (sectp->name, &names->info_dwo)
12305            || section_is_p (sectp->name, &names->types_dwo))
12306     {
12307       /* There can be only one.  */
12308       if (sections->info_or_types.s.section != NULL)
12309         return 0;
12310       sections->info_or_types.s.section = sectp;
12311       sections->info_or_types.size = bfd_get_section_size (sectp);
12312     }
12313   else if (section_is_p (sectp->name, &names->line_dwo))
12314     {
12315       /* There can be only one.  */
12316       if (sections->line.s.section != NULL)
12317         return 0;
12318       sections->line.s.section = sectp;
12319       sections->line.size = bfd_get_section_size (sectp);
12320     }
12321   else if (section_is_p (sectp->name, &names->loc_dwo))
12322     {
12323       /* There can be only one.  */
12324       if (sections->loc.s.section != NULL)
12325         return 0;
12326       sections->loc.s.section = sectp;
12327       sections->loc.size = bfd_get_section_size (sectp);
12328     }
12329   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12330     {
12331       /* There can be only one.  */
12332       if (sections->macinfo.s.section != NULL)
12333         return 0;
12334       sections->macinfo.s.section = sectp;
12335       sections->macinfo.size = bfd_get_section_size (sectp);
12336     }
12337   else if (section_is_p (sectp->name, &names->macro_dwo))
12338     {
12339       /* There can be only one.  */
12340       if (sections->macro.s.section != NULL)
12341         return 0;
12342       sections->macro.s.section = sectp;
12343       sections->macro.size = bfd_get_section_size (sectp);
12344     }
12345   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12346     {
12347       /* There can be only one.  */
12348       if (sections->str_offsets.s.section != NULL)
12349         return 0;
12350       sections->str_offsets.s.section = sectp;
12351       sections->str_offsets.size = bfd_get_section_size (sectp);
12352     }
12353   else
12354     {
12355       /* No other kind of section is valid.  */
12356       return 0;
12357     }
12358
12359   return 1;
12360 }
12361
12362 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12363    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12364    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12365    This is for DWP version 1 files.  */
12366
12367 static struct dwo_unit *
12368 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
12369                            uint32_t unit_index,
12370                            const char *comp_dir,
12371                            ULONGEST signature, int is_debug_types)
12372 {
12373   struct objfile *objfile = dwarf2_per_objfile->objfile;
12374   const struct dwp_hash_table *dwp_htab =
12375     is_debug_types ? dwp_file->tus : dwp_file->cus;
12376   bfd *dbfd = dwp_file->dbfd;
12377   const char *kind = is_debug_types ? "TU" : "CU";
12378   struct dwo_file *dwo_file;
12379   struct dwo_unit *dwo_unit;
12380   struct virtual_v1_dwo_sections sections;
12381   void **dwo_file_slot;
12382   int i;
12383
12384   gdb_assert (dwp_file->version == 1);
12385
12386   if (dwarf_read_debug)
12387     {
12388       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12389                           kind,
12390                           pulongest (unit_index), hex_string (signature),
12391                           dwp_file->name);
12392     }
12393
12394   /* Fetch the sections of this DWO unit.
12395      Put a limit on the number of sections we look for so that bad data
12396      doesn't cause us to loop forever.  */
12397
12398 #define MAX_NR_V1_DWO_SECTIONS \
12399   (1 /* .debug_info or .debug_types */ \
12400    + 1 /* .debug_abbrev */ \
12401    + 1 /* .debug_line */ \
12402    + 1 /* .debug_loc */ \
12403    + 1 /* .debug_str_offsets */ \
12404    + 1 /* .debug_macro or .debug_macinfo */ \
12405    + 1 /* trailing zero */)
12406
12407   memset (&sections, 0, sizeof (sections));
12408
12409   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12410     {
12411       asection *sectp;
12412       uint32_t section_nr =
12413         read_4_bytes (dbfd,
12414                       dwp_htab->section_pool.v1.indices
12415                       + (unit_index + i) * sizeof (uint32_t));
12416
12417       if (section_nr == 0)
12418         break;
12419       if (section_nr >= dwp_file->num_sections)
12420         {
12421           error (_("Dwarf Error: bad DWP hash table, section number too large"
12422                    " [in module %s]"),
12423                  dwp_file->name);
12424         }
12425
12426       sectp = dwp_file->elf_sections[section_nr];
12427       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12428         {
12429           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12430                    " [in module %s]"),
12431                  dwp_file->name);
12432         }
12433     }
12434
12435   if (i < 2
12436       || dwarf2_section_empty_p (&sections.info_or_types)
12437       || dwarf2_section_empty_p (&sections.abbrev))
12438     {
12439       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12440                " [in module %s]"),
12441              dwp_file->name);
12442     }
12443   if (i == MAX_NR_V1_DWO_SECTIONS)
12444     {
12445       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12446                " [in module %s]"),
12447              dwp_file->name);
12448     }
12449
12450   /* It's easier for the rest of the code if we fake a struct dwo_file and
12451      have dwo_unit "live" in that.  At least for now.
12452
12453      The DWP file can be made up of a random collection of CUs and TUs.
12454      However, for each CU + set of TUs that came from the same original DWO
12455      file, we can combine them back into a virtual DWO file to save space
12456      (fewer struct dwo_file objects to allocate).  Remember that for really
12457      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12458
12459   std::string virtual_dwo_name =
12460     string_printf ("virtual-dwo/%d-%d-%d-%d",
12461                    get_section_id (&sections.abbrev),
12462                    get_section_id (&sections.line),
12463                    get_section_id (&sections.loc),
12464                    get_section_id (&sections.str_offsets));
12465   /* Can we use an existing virtual DWO file?  */
12466   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12467   /* Create one if necessary.  */
12468   if (*dwo_file_slot == NULL)
12469     {
12470       if (dwarf_read_debug)
12471         {
12472           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12473                               virtual_dwo_name.c_str ());
12474         }
12475       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12476       dwo_file->dwo_name
12477         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12478                                         virtual_dwo_name.c_str (),
12479                                         virtual_dwo_name.size ());
12480       dwo_file->comp_dir = comp_dir;
12481       dwo_file->sections.abbrev = sections.abbrev;
12482       dwo_file->sections.line = sections.line;
12483       dwo_file->sections.loc = sections.loc;
12484       dwo_file->sections.macinfo = sections.macinfo;
12485       dwo_file->sections.macro = sections.macro;
12486       dwo_file->sections.str_offsets = sections.str_offsets;
12487       /* The "str" section is global to the entire DWP file.  */
12488       dwo_file->sections.str = dwp_file->sections.str;
12489       /* The info or types section is assigned below to dwo_unit,
12490          there's no need to record it in dwo_file.
12491          Also, we can't simply record type sections in dwo_file because
12492          we record a pointer into the vector in dwo_unit.  As we collect more
12493          types we'll grow the vector and eventually have to reallocate space
12494          for it, invalidating all copies of pointers into the previous
12495          contents.  */
12496       *dwo_file_slot = dwo_file;
12497     }
12498   else
12499     {
12500       if (dwarf_read_debug)
12501         {
12502           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12503                               virtual_dwo_name.c_str ());
12504         }
12505       dwo_file = (struct dwo_file *) *dwo_file_slot;
12506     }
12507
12508   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12509   dwo_unit->dwo_file = dwo_file;
12510   dwo_unit->signature = signature;
12511   dwo_unit->section =
12512     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12513   *dwo_unit->section = sections.info_or_types;
12514   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12515
12516   return dwo_unit;
12517 }
12518
12519 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12520    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12521    piece within that section used by a TU/CU, return a virtual section
12522    of just that piece.  */
12523
12524 static struct dwarf2_section_info
12525 create_dwp_v2_section (struct dwarf2_section_info *section,
12526                        bfd_size_type offset, bfd_size_type size)
12527 {
12528   struct dwarf2_section_info result;
12529   asection *sectp;
12530
12531   gdb_assert (section != NULL);
12532   gdb_assert (!section->is_virtual);
12533
12534   memset (&result, 0, sizeof (result));
12535   result.s.containing_section = section;
12536   result.is_virtual = 1;
12537
12538   if (size == 0)
12539     return result;
12540
12541   sectp = get_section_bfd_section (section);
12542
12543   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12544      bounds of the real section.  This is a pretty-rare event, so just
12545      flag an error (easier) instead of a warning and trying to cope.  */
12546   if (sectp == NULL
12547       || offset + size > bfd_get_section_size (sectp))
12548     {
12549       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12550                " in section %s [in module %s]"),
12551              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12552              objfile_name (dwarf2_per_objfile->objfile));
12553     }
12554
12555   result.virtual_offset = offset;
12556   result.size = size;
12557   return result;
12558 }
12559
12560 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12561    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12562    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12563    This is for DWP version 2 files.  */
12564
12565 static struct dwo_unit *
12566 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
12567                            uint32_t unit_index,
12568                            const char *comp_dir,
12569                            ULONGEST signature, int is_debug_types)
12570 {
12571   struct objfile *objfile = dwarf2_per_objfile->objfile;
12572   const struct dwp_hash_table *dwp_htab =
12573     is_debug_types ? dwp_file->tus : dwp_file->cus;
12574   bfd *dbfd = dwp_file->dbfd;
12575   const char *kind = is_debug_types ? "TU" : "CU";
12576   struct dwo_file *dwo_file;
12577   struct dwo_unit *dwo_unit;
12578   struct virtual_v2_dwo_sections sections;
12579   void **dwo_file_slot;
12580   int i;
12581
12582   gdb_assert (dwp_file->version == 2);
12583
12584   if (dwarf_read_debug)
12585     {
12586       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12587                           kind,
12588                           pulongest (unit_index), hex_string (signature),
12589                           dwp_file->name);
12590     }
12591
12592   /* Fetch the section offsets of this DWO unit.  */
12593
12594   memset (&sections, 0, sizeof (sections));
12595
12596   for (i = 0; i < dwp_htab->nr_columns; ++i)
12597     {
12598       uint32_t offset = read_4_bytes (dbfd,
12599                                       dwp_htab->section_pool.v2.offsets
12600                                       + (((unit_index - 1) * dwp_htab->nr_columns
12601                                           + i)
12602                                          * sizeof (uint32_t)));
12603       uint32_t size = read_4_bytes (dbfd,
12604                                     dwp_htab->section_pool.v2.sizes
12605                                     + (((unit_index - 1) * dwp_htab->nr_columns
12606                                         + i)
12607                                        * sizeof (uint32_t)));
12608
12609       switch (dwp_htab->section_pool.v2.section_ids[i])
12610         {
12611         case DW_SECT_INFO:
12612         case DW_SECT_TYPES:
12613           sections.info_or_types_offset = offset;
12614           sections.info_or_types_size = size;
12615           break;
12616         case DW_SECT_ABBREV:
12617           sections.abbrev_offset = offset;
12618           sections.abbrev_size = size;
12619           break;
12620         case DW_SECT_LINE:
12621           sections.line_offset = offset;
12622           sections.line_size = size;
12623           break;
12624         case DW_SECT_LOC:
12625           sections.loc_offset = offset;
12626           sections.loc_size = size;
12627           break;
12628         case DW_SECT_STR_OFFSETS:
12629           sections.str_offsets_offset = offset;
12630           sections.str_offsets_size = size;
12631           break;
12632         case DW_SECT_MACINFO:
12633           sections.macinfo_offset = offset;
12634           sections.macinfo_size = size;
12635           break;
12636         case DW_SECT_MACRO:
12637           sections.macro_offset = offset;
12638           sections.macro_size = size;
12639           break;
12640         }
12641     }
12642
12643   /* It's easier for the rest of the code if we fake a struct dwo_file and
12644      have dwo_unit "live" in that.  At least for now.
12645
12646      The DWP file can be made up of a random collection of CUs and TUs.
12647      However, for each CU + set of TUs that came from the same original DWO
12648      file, we can combine them back into a virtual DWO file to save space
12649      (fewer struct dwo_file objects to allocate).  Remember that for really
12650      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12651
12652   std::string virtual_dwo_name =
12653     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12654                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12655                    (long) (sections.line_size ? sections.line_offset : 0),
12656                    (long) (sections.loc_size ? sections.loc_offset : 0),
12657                    (long) (sections.str_offsets_size
12658                            ? sections.str_offsets_offset : 0));
12659   /* Can we use an existing virtual DWO file?  */
12660   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12661   /* Create one if necessary.  */
12662   if (*dwo_file_slot == NULL)
12663     {
12664       if (dwarf_read_debug)
12665         {
12666           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12667                               virtual_dwo_name.c_str ());
12668         }
12669       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12670       dwo_file->dwo_name
12671         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12672                                         virtual_dwo_name.c_str (),
12673                                         virtual_dwo_name.size ());
12674       dwo_file->comp_dir = comp_dir;
12675       dwo_file->sections.abbrev =
12676         create_dwp_v2_section (&dwp_file->sections.abbrev,
12677                                sections.abbrev_offset, sections.abbrev_size);
12678       dwo_file->sections.line =
12679         create_dwp_v2_section (&dwp_file->sections.line,
12680                                sections.line_offset, sections.line_size);
12681       dwo_file->sections.loc =
12682         create_dwp_v2_section (&dwp_file->sections.loc,
12683                                sections.loc_offset, sections.loc_size);
12684       dwo_file->sections.macinfo =
12685         create_dwp_v2_section (&dwp_file->sections.macinfo,
12686                                sections.macinfo_offset, sections.macinfo_size);
12687       dwo_file->sections.macro =
12688         create_dwp_v2_section (&dwp_file->sections.macro,
12689                                sections.macro_offset, sections.macro_size);
12690       dwo_file->sections.str_offsets =
12691         create_dwp_v2_section (&dwp_file->sections.str_offsets,
12692                                sections.str_offsets_offset,
12693                                sections.str_offsets_size);
12694       /* The "str" section is global to the entire DWP file.  */
12695       dwo_file->sections.str = dwp_file->sections.str;
12696       /* The info or types section is assigned below to dwo_unit,
12697          there's no need to record it in dwo_file.
12698          Also, we can't simply record type sections in dwo_file because
12699          we record a pointer into the vector in dwo_unit.  As we collect more
12700          types we'll grow the vector and eventually have to reallocate space
12701          for it, invalidating all copies of pointers into the previous
12702          contents.  */
12703       *dwo_file_slot = dwo_file;
12704     }
12705   else
12706     {
12707       if (dwarf_read_debug)
12708         {
12709           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12710                               virtual_dwo_name.c_str ());
12711         }
12712       dwo_file = (struct dwo_file *) *dwo_file_slot;
12713     }
12714
12715   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12716   dwo_unit->dwo_file = dwo_file;
12717   dwo_unit->signature = signature;
12718   dwo_unit->section =
12719     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12720   *dwo_unit->section = create_dwp_v2_section (is_debug_types
12721                                               ? &dwp_file->sections.types
12722                                               : &dwp_file->sections.info,
12723                                               sections.info_or_types_offset,
12724                                               sections.info_or_types_size);
12725   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12726
12727   return dwo_unit;
12728 }
12729
12730 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12731    Returns NULL if the signature isn't found.  */
12732
12733 static struct dwo_unit *
12734 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
12735                         ULONGEST signature, int is_debug_types)
12736 {
12737   const struct dwp_hash_table *dwp_htab =
12738     is_debug_types ? dwp_file->tus : dwp_file->cus;
12739   bfd *dbfd = dwp_file->dbfd;
12740   uint32_t mask = dwp_htab->nr_slots - 1;
12741   uint32_t hash = signature & mask;
12742   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12743   unsigned int i;
12744   void **slot;
12745   struct dwo_unit find_dwo_cu;
12746
12747   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12748   find_dwo_cu.signature = signature;
12749   slot = htab_find_slot (is_debug_types
12750                          ? dwp_file->loaded_tus
12751                          : dwp_file->loaded_cus,
12752                          &find_dwo_cu, INSERT);
12753
12754   if (*slot != NULL)
12755     return (struct dwo_unit *) *slot;
12756
12757   /* Use a for loop so that we don't loop forever on bad debug info.  */
12758   for (i = 0; i < dwp_htab->nr_slots; ++i)
12759     {
12760       ULONGEST signature_in_table;
12761
12762       signature_in_table =
12763         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12764       if (signature_in_table == signature)
12765         {
12766           uint32_t unit_index =
12767             read_4_bytes (dbfd,
12768                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12769
12770           if (dwp_file->version == 1)
12771             {
12772               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
12773                                                  comp_dir, signature,
12774                                                  is_debug_types);
12775             }
12776           else
12777             {
12778               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
12779                                                  comp_dir, signature,
12780                                                  is_debug_types);
12781             }
12782           return (struct dwo_unit *) *slot;
12783         }
12784       if (signature_in_table == 0)
12785         return NULL;
12786       hash = (hash + hash2) & mask;
12787     }
12788
12789   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12790            " [in module %s]"),
12791          dwp_file->name);
12792 }
12793
12794 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12795    Open the file specified by FILE_NAME and hand it off to BFD for
12796    preliminary analysis.  Return a newly initialized bfd *, which
12797    includes a canonicalized copy of FILE_NAME.
12798    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12799    SEARCH_CWD is true if the current directory is to be searched.
12800    It will be searched before debug-file-directory.
12801    If successful, the file is added to the bfd include table of the
12802    objfile's bfd (see gdb_bfd_record_inclusion).
12803    If unable to find/open the file, return NULL.
12804    NOTE: This function is derived from symfile_bfd_open.  */
12805
12806 static gdb_bfd_ref_ptr
12807 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
12808 {
12809   int desc, flags;
12810   char *absolute_name;
12811   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12812      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12813      to debug_file_directory.  */
12814   char *search_path;
12815   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12816
12817   if (search_cwd)
12818     {
12819       if (*debug_file_directory != '\0')
12820         search_path = concat (".", dirname_separator_string,
12821                               debug_file_directory, (char *) NULL);
12822       else
12823         search_path = xstrdup (".");
12824     }
12825   else
12826     search_path = xstrdup (debug_file_directory);
12827
12828   flags = OPF_RETURN_REALPATH;
12829   if (is_dwp)
12830     flags |= OPF_SEARCH_IN_PATH;
12831   desc = openp (search_path, flags, file_name,
12832                 O_RDONLY | O_BINARY, &absolute_name);
12833   xfree (search_path);
12834   if (desc < 0)
12835     return NULL;
12836
12837   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12838   xfree (absolute_name);
12839   if (sym_bfd == NULL)
12840     return NULL;
12841   bfd_set_cacheable (sym_bfd.get (), 1);
12842
12843   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12844     return NULL;
12845
12846   /* Success.  Record the bfd as having been included by the objfile's bfd.
12847      This is important because things like demangled_names_hash lives in the
12848      objfile's per_bfd space and may have references to things like symbol
12849      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12850   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12851
12852   return sym_bfd;
12853 }
12854
12855 /* Try to open DWO file FILE_NAME.
12856    COMP_DIR is the DW_AT_comp_dir attribute.
12857    The result is the bfd handle of the file.
12858    If there is a problem finding or opening the file, return NULL.
12859    Upon success, the canonicalized path of the file is stored in the bfd,
12860    same as symfile_bfd_open.  */
12861
12862 static gdb_bfd_ref_ptr
12863 open_dwo_file (const char *file_name, const char *comp_dir)
12864 {
12865   if (IS_ABSOLUTE_PATH (file_name))
12866     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
12867
12868   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12869
12870   if (comp_dir != NULL)
12871     {
12872       char *path_to_try = concat (comp_dir, SLASH_STRING,
12873                                   file_name, (char *) NULL);
12874
12875       /* NOTE: If comp_dir is a relative path, this will also try the
12876          search path, which seems useful.  */
12877       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
12878                                                 1 /*search_cwd*/));
12879       xfree (path_to_try);
12880       if (abfd != NULL)
12881         return abfd;
12882     }
12883
12884   /* That didn't work, try debug-file-directory, which, despite its name,
12885      is a list of paths.  */
12886
12887   if (*debug_file_directory == '\0')
12888     return NULL;
12889
12890   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
12891 }
12892
12893 /* This function is mapped across the sections and remembers the offset and
12894    size of each of the DWO debugging sections we are interested in.  */
12895
12896 static void
12897 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12898 {
12899   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12900   const struct dwop_section_names *names = &dwop_section_names;
12901
12902   if (section_is_p (sectp->name, &names->abbrev_dwo))
12903     {
12904       dwo_sections->abbrev.s.section = sectp;
12905       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12906     }
12907   else if (section_is_p (sectp->name, &names->info_dwo))
12908     {
12909       dwo_sections->info.s.section = sectp;
12910       dwo_sections->info.size = bfd_get_section_size (sectp);
12911     }
12912   else if (section_is_p (sectp->name, &names->line_dwo))
12913     {
12914       dwo_sections->line.s.section = sectp;
12915       dwo_sections->line.size = bfd_get_section_size (sectp);
12916     }
12917   else if (section_is_p (sectp->name, &names->loc_dwo))
12918     {
12919       dwo_sections->loc.s.section = sectp;
12920       dwo_sections->loc.size = bfd_get_section_size (sectp);
12921     }
12922   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12923     {
12924       dwo_sections->macinfo.s.section = sectp;
12925       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12926     }
12927   else if (section_is_p (sectp->name, &names->macro_dwo))
12928     {
12929       dwo_sections->macro.s.section = sectp;
12930       dwo_sections->macro.size = bfd_get_section_size (sectp);
12931     }
12932   else if (section_is_p (sectp->name, &names->str_dwo))
12933     {
12934       dwo_sections->str.s.section = sectp;
12935       dwo_sections->str.size = bfd_get_section_size (sectp);
12936     }
12937   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12938     {
12939       dwo_sections->str_offsets.s.section = sectp;
12940       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12941     }
12942   else if (section_is_p (sectp->name, &names->types_dwo))
12943     {
12944       struct dwarf2_section_info type_section;
12945
12946       memset (&type_section, 0, sizeof (type_section));
12947       type_section.s.section = sectp;
12948       type_section.size = bfd_get_section_size (sectp);
12949       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12950                      &type_section);
12951     }
12952 }
12953
12954 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12955    by PER_CU.  This is for the non-DWP case.
12956    The result is NULL if DWO_NAME can't be found.  */
12957
12958 static struct dwo_file *
12959 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12960                         const char *dwo_name, const char *comp_dir)
12961 {
12962   struct objfile *objfile = dwarf2_per_objfile->objfile;
12963   struct dwo_file *dwo_file;
12964   struct cleanup *cleanups;
12965
12966   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
12967   if (dbfd == NULL)
12968     {
12969       if (dwarf_read_debug)
12970         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12971       return NULL;
12972     }
12973   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12974   dwo_file->dwo_name = dwo_name;
12975   dwo_file->comp_dir = comp_dir;
12976   dwo_file->dbfd = dbfd.release ();
12977
12978   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
12979
12980   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12981                          &dwo_file->sections);
12982
12983   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
12984
12985   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
12986                                  dwo_file->tus);
12987
12988   discard_cleanups (cleanups);
12989
12990   if (dwarf_read_debug)
12991     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12992
12993   return dwo_file;
12994 }
12995
12996 /* This function is mapped across the sections and remembers the offset and
12997    size of each of the DWP debugging sections common to version 1 and 2 that
12998    we are interested in.  */
12999
13000 static void
13001 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13002                                    void *dwp_file_ptr)
13003 {
13004   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13005   const struct dwop_section_names *names = &dwop_section_names;
13006   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13007
13008   /* Record the ELF section number for later lookup: this is what the
13009      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13010   gdb_assert (elf_section_nr < dwp_file->num_sections);
13011   dwp_file->elf_sections[elf_section_nr] = sectp;
13012
13013   /* Look for specific sections that we need.  */
13014   if (section_is_p (sectp->name, &names->str_dwo))
13015     {
13016       dwp_file->sections.str.s.section = sectp;
13017       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13018     }
13019   else if (section_is_p (sectp->name, &names->cu_index))
13020     {
13021       dwp_file->sections.cu_index.s.section = sectp;
13022       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13023     }
13024   else if (section_is_p (sectp->name, &names->tu_index))
13025     {
13026       dwp_file->sections.tu_index.s.section = sectp;
13027       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13028     }
13029 }
13030
13031 /* This function is mapped across the sections and remembers the offset and
13032    size of each of the DWP version 2 debugging sections that we are interested
13033    in.  This is split into a separate function because we don't know if we
13034    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13035
13036 static void
13037 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13038 {
13039   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13040   const struct dwop_section_names *names = &dwop_section_names;
13041   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13042
13043   /* Record the ELF section number for later lookup: this is what the
13044      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13045   gdb_assert (elf_section_nr < dwp_file->num_sections);
13046   dwp_file->elf_sections[elf_section_nr] = sectp;
13047
13048   /* Look for specific sections that we need.  */
13049   if (section_is_p (sectp->name, &names->abbrev_dwo))
13050     {
13051       dwp_file->sections.abbrev.s.section = sectp;
13052       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13053     }
13054   else if (section_is_p (sectp->name, &names->info_dwo))
13055     {
13056       dwp_file->sections.info.s.section = sectp;
13057       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13058     }
13059   else if (section_is_p (sectp->name, &names->line_dwo))
13060     {
13061       dwp_file->sections.line.s.section = sectp;
13062       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13063     }
13064   else if (section_is_p (sectp->name, &names->loc_dwo))
13065     {
13066       dwp_file->sections.loc.s.section = sectp;
13067       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13068     }
13069   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13070     {
13071       dwp_file->sections.macinfo.s.section = sectp;
13072       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13073     }
13074   else if (section_is_p (sectp->name, &names->macro_dwo))
13075     {
13076       dwp_file->sections.macro.s.section = sectp;
13077       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13078     }
13079   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13080     {
13081       dwp_file->sections.str_offsets.s.section = sectp;
13082       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13083     }
13084   else if (section_is_p (sectp->name, &names->types_dwo))
13085     {
13086       dwp_file->sections.types.s.section = sectp;
13087       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13088     }
13089 }
13090
13091 /* Hash function for dwp_file loaded CUs/TUs.  */
13092
13093 static hashval_t
13094 hash_dwp_loaded_cutus (const void *item)
13095 {
13096   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13097
13098   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13099   return dwo_unit->signature;
13100 }
13101
13102 /* Equality function for dwp_file loaded CUs/TUs.  */
13103
13104 static int
13105 eq_dwp_loaded_cutus (const void *a, const void *b)
13106 {
13107   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13108   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13109
13110   return dua->signature == dub->signature;
13111 }
13112
13113 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13114
13115 static htab_t
13116 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13117 {
13118   return htab_create_alloc_ex (3,
13119                                hash_dwp_loaded_cutus,
13120                                eq_dwp_loaded_cutus,
13121                                NULL,
13122                                &objfile->objfile_obstack,
13123                                hashtab_obstack_allocate,
13124                                dummy_obstack_deallocate);
13125 }
13126
13127 /* Try to open DWP file FILE_NAME.
13128    The result is the bfd handle of the file.
13129    If there is a problem finding or opening the file, return NULL.
13130    Upon success, the canonicalized path of the file is stored in the bfd,
13131    same as symfile_bfd_open.  */
13132
13133 static gdb_bfd_ref_ptr
13134 open_dwp_file (const char *file_name)
13135 {
13136   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
13137                                             1 /*search_cwd*/));
13138   if (abfd != NULL)
13139     return abfd;
13140
13141   /* Work around upstream bug 15652.
13142      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13143      [Whether that's a "bug" is debatable, but it is getting in our way.]
13144      We have no real idea where the dwp file is, because gdb's realpath-ing
13145      of the executable's path may have discarded the needed info.
13146      [IWBN if the dwp file name was recorded in the executable, akin to
13147      .gnu_debuglink, but that doesn't exist yet.]
13148      Strip the directory from FILE_NAME and search again.  */
13149   if (*debug_file_directory != '\0')
13150     {
13151       /* Don't implicitly search the current directory here.
13152          If the user wants to search "." to handle this case,
13153          it must be added to debug-file-directory.  */
13154       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
13155                                  0 /*search_cwd*/);
13156     }
13157
13158   return NULL;
13159 }
13160
13161 /* Initialize the use of the DWP file for the current objfile.
13162    By convention the name of the DWP file is ${objfile}.dwp.
13163    The result is NULL if it can't be found.  */
13164
13165 static struct dwp_file *
13166 open_and_init_dwp_file (void)
13167 {
13168   struct objfile *objfile = dwarf2_per_objfile->objfile;
13169   struct dwp_file *dwp_file;
13170
13171   /* Try to find first .dwp for the binary file before any symbolic links
13172      resolving.  */
13173
13174   /* If the objfile is a debug file, find the name of the real binary
13175      file and get the name of dwp file from there.  */
13176   std::string dwp_name;
13177   if (objfile->separate_debug_objfile_backlink != NULL)
13178     {
13179       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13180       const char *backlink_basename = lbasename (backlink->original_name);
13181
13182       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13183     }
13184   else
13185     dwp_name = objfile->original_name;
13186
13187   dwp_name += ".dwp";
13188
13189   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
13190   if (dbfd == NULL
13191       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13192     {
13193       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13194       dwp_name = objfile_name (objfile);
13195       dwp_name += ".dwp";
13196       dbfd = open_dwp_file (dwp_name.c_str ());
13197     }
13198
13199   if (dbfd == NULL)
13200     {
13201       if (dwarf_read_debug)
13202         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13203       return NULL;
13204     }
13205   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13206   dwp_file->name = bfd_get_filename (dbfd.get ());
13207   dwp_file->dbfd = dbfd.release ();
13208
13209   /* +1: section 0 is unused */
13210   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13211   dwp_file->elf_sections =
13212     OBSTACK_CALLOC (&objfile->objfile_obstack,
13213                     dwp_file->num_sections, asection *);
13214
13215   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13216                          dwp_file);
13217
13218   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
13219
13220   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
13221
13222   /* The DWP file version is stored in the hash table.  Oh well.  */
13223   if (dwp_file->cus && dwp_file->tus
13224       && dwp_file->cus->version != dwp_file->tus->version)
13225     {
13226       /* Technically speaking, we should try to limp along, but this is
13227          pretty bizarre.  We use pulongest here because that's the established
13228          portability solution (e.g, we cannot use %u for uint32_t).  */
13229       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13230                " TU version %s [in DWP file %s]"),
13231              pulongest (dwp_file->cus->version),
13232              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13233     }
13234
13235   if (dwp_file->cus)
13236     dwp_file->version = dwp_file->cus->version;
13237   else if (dwp_file->tus)
13238     dwp_file->version = dwp_file->tus->version;
13239   else
13240     dwp_file->version = 2;
13241
13242   if (dwp_file->version == 2)
13243     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13244                            dwp_file);
13245
13246   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13247   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13248
13249   if (dwarf_read_debug)
13250     {
13251       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13252       fprintf_unfiltered (gdb_stdlog,
13253                           "    %s CUs, %s TUs\n",
13254                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13255                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13256     }
13257
13258   return dwp_file;
13259 }
13260
13261 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13262
13263 static struct dwp_file *
13264 get_dwp_file (void)
13265 {
13266   if (! dwarf2_per_objfile->dwp_checked)
13267     {
13268       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
13269       dwarf2_per_objfile->dwp_checked = 1;
13270     }
13271   return dwarf2_per_objfile->dwp_file;
13272 }
13273
13274 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13275    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13276    or in the DWP file for the objfile, referenced by THIS_UNIT.
13277    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13278    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13279
13280    This is called, for example, when wanting to read a variable with a
13281    complex location.  Therefore we don't want to do file i/o for every call.
13282    Therefore we don't want to look for a DWO file on every call.
13283    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13284    then we check if we've already seen DWO_NAME, and only THEN do we check
13285    for a DWO file.
13286
13287    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13288    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13289
13290 static struct dwo_unit *
13291 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13292                  const char *dwo_name, const char *comp_dir,
13293                  ULONGEST signature, int is_debug_types)
13294 {
13295   struct objfile *objfile = dwarf2_per_objfile->objfile;
13296   const char *kind = is_debug_types ? "TU" : "CU";
13297   void **dwo_file_slot;
13298   struct dwo_file *dwo_file;
13299   struct dwp_file *dwp_file;
13300
13301   /* First see if there's a DWP file.
13302      If we have a DWP file but didn't find the DWO inside it, don't
13303      look for the original DWO file.  It makes gdb behave differently
13304      depending on whether one is debugging in the build tree.  */
13305
13306   dwp_file = get_dwp_file ();
13307   if (dwp_file != NULL)
13308     {
13309       const struct dwp_hash_table *dwp_htab =
13310         is_debug_types ? dwp_file->tus : dwp_file->cus;
13311
13312       if (dwp_htab != NULL)
13313         {
13314           struct dwo_unit *dwo_cutu =
13315             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
13316                                     signature, is_debug_types);
13317
13318           if (dwo_cutu != NULL)
13319             {
13320               if (dwarf_read_debug)
13321                 {
13322                   fprintf_unfiltered (gdb_stdlog,
13323                                       "Virtual DWO %s %s found: @%s\n",
13324                                       kind, hex_string (signature),
13325                                       host_address_to_string (dwo_cutu));
13326                 }
13327               return dwo_cutu;
13328             }
13329         }
13330     }
13331   else
13332     {
13333       /* No DWP file, look for the DWO file.  */
13334
13335       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
13336       if (*dwo_file_slot == NULL)
13337         {
13338           /* Read in the file and build a table of the CUs/TUs it contains.  */
13339           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13340         }
13341       /* NOTE: This will be NULL if unable to open the file.  */
13342       dwo_file = (struct dwo_file *) *dwo_file_slot;
13343
13344       if (dwo_file != NULL)
13345         {
13346           struct dwo_unit *dwo_cutu = NULL;
13347
13348           if (is_debug_types && dwo_file->tus)
13349             {
13350               struct dwo_unit find_dwo_cutu;
13351
13352               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13353               find_dwo_cutu.signature = signature;
13354               dwo_cutu
13355                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13356             }
13357           else if (!is_debug_types && dwo_file->cus)
13358             {
13359               struct dwo_unit find_dwo_cutu;
13360
13361               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13362               find_dwo_cutu.signature = signature;
13363               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13364                                                        &find_dwo_cutu);
13365             }
13366
13367           if (dwo_cutu != NULL)
13368             {
13369               if (dwarf_read_debug)
13370                 {
13371                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13372                                       kind, dwo_name, hex_string (signature),
13373                                       host_address_to_string (dwo_cutu));
13374                 }
13375               return dwo_cutu;
13376             }
13377         }
13378     }
13379
13380   /* We didn't find it.  This could mean a dwo_id mismatch, or
13381      someone deleted the DWO/DWP file, or the search path isn't set up
13382      correctly to find the file.  */
13383
13384   if (dwarf_read_debug)
13385     {
13386       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13387                           kind, dwo_name, hex_string (signature));
13388     }
13389
13390   /* This is a warning and not a complaint because it can be caused by
13391      pilot error (e.g., user accidentally deleting the DWO).  */
13392   {
13393     /* Print the name of the DWP file if we looked there, helps the user
13394        better diagnose the problem.  */
13395     std::string dwp_text;
13396
13397     if (dwp_file != NULL)
13398       dwp_text = string_printf (" [in DWP file %s]",
13399                                 lbasename (dwp_file->name));
13400
13401     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13402                " [in module %s]"),
13403              kind, dwo_name, hex_string (signature),
13404              dwp_text.c_str (),
13405              this_unit->is_debug_types ? "TU" : "CU",
13406              to_underlying (this_unit->sect_off), objfile_name (objfile));
13407   }
13408   return NULL;
13409 }
13410
13411 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13412    See lookup_dwo_cutu_unit for details.  */
13413
13414 static struct dwo_unit *
13415 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13416                       const char *dwo_name, const char *comp_dir,
13417                       ULONGEST signature)
13418 {
13419   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13420 }
13421
13422 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13423    See lookup_dwo_cutu_unit for details.  */
13424
13425 static struct dwo_unit *
13426 lookup_dwo_type_unit (struct signatured_type *this_tu,
13427                       const char *dwo_name, const char *comp_dir)
13428 {
13429   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13430 }
13431
13432 /* Traversal function for queue_and_load_all_dwo_tus.  */
13433
13434 static int
13435 queue_and_load_dwo_tu (void **slot, void *info)
13436 {
13437   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13438   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13439   ULONGEST signature = dwo_unit->signature;
13440   struct signatured_type *sig_type =
13441     lookup_dwo_signatured_type (per_cu->cu, signature);
13442
13443   if (sig_type != NULL)
13444     {
13445       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13446
13447       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13448          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13449          while processing PER_CU.  */
13450       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13451         load_full_type_unit (sig_cu);
13452       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13453     }
13454
13455   return 1;
13456 }
13457
13458 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13459    The DWO may have the only definition of the type, though it may not be
13460    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13461    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13462
13463 static void
13464 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13465 {
13466   struct dwo_unit *dwo_unit;
13467   struct dwo_file *dwo_file;
13468
13469   gdb_assert (!per_cu->is_debug_types);
13470   gdb_assert (get_dwp_file () == NULL);
13471   gdb_assert (per_cu->cu != NULL);
13472
13473   dwo_unit = per_cu->cu->dwo_unit;
13474   gdb_assert (dwo_unit != NULL);
13475
13476   dwo_file = dwo_unit->dwo_file;
13477   if (dwo_file->tus != NULL)
13478     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13479 }
13480
13481 /* Free all resources associated with DWO_FILE.
13482    Close the DWO file and munmap the sections.
13483    All memory should be on the objfile obstack.  */
13484
13485 static void
13486 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13487 {
13488
13489   /* Note: dbfd is NULL for virtual DWO files.  */
13490   gdb_bfd_unref (dwo_file->dbfd);
13491
13492   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13493 }
13494
13495 /* Wrapper for free_dwo_file for use in cleanups.  */
13496
13497 static void
13498 free_dwo_file_cleanup (void *arg)
13499 {
13500   struct dwo_file *dwo_file = (struct dwo_file *) arg;
13501   struct objfile *objfile = dwarf2_per_objfile->objfile;
13502
13503   free_dwo_file (dwo_file, objfile);
13504 }
13505
13506 /* Traversal function for free_dwo_files.  */
13507
13508 static int
13509 free_dwo_file_from_slot (void **slot, void *info)
13510 {
13511   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13512   struct objfile *objfile = (struct objfile *) info;
13513
13514   free_dwo_file (dwo_file, objfile);
13515
13516   return 1;
13517 }
13518
13519 /* Free all resources associated with DWO_FILES.  */
13520
13521 static void
13522 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13523 {
13524   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13525 }
13526 \f
13527 /* Read in various DIEs.  */
13528
13529 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13530    Inherit only the children of the DW_AT_abstract_origin DIE not being
13531    already referenced by DW_AT_abstract_origin from the children of the
13532    current DIE.  */
13533
13534 static void
13535 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13536 {
13537   struct die_info *child_die;
13538   sect_offset *offsetp;
13539   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13540   struct die_info *origin_die;
13541   /* Iterator of the ORIGIN_DIE children.  */
13542   struct die_info *origin_child_die;
13543   struct attribute *attr;
13544   struct dwarf2_cu *origin_cu;
13545   struct pending **origin_previous_list_in_scope;
13546
13547   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13548   if (!attr)
13549     return;
13550
13551   /* Note that following die references may follow to a die in a
13552      different cu.  */
13553
13554   origin_cu = cu;
13555   origin_die = follow_die_ref (die, attr, &origin_cu);
13556
13557   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13558      symbols in.  */
13559   origin_previous_list_in_scope = origin_cu->list_in_scope;
13560   origin_cu->list_in_scope = cu->list_in_scope;
13561
13562   if (die->tag != origin_die->tag
13563       && !(die->tag == DW_TAG_inlined_subroutine
13564            && origin_die->tag == DW_TAG_subprogram))
13565     complaint (&symfile_complaints,
13566                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13567                to_underlying (die->sect_off),
13568                to_underlying (origin_die->sect_off));
13569
13570   std::vector<sect_offset> offsets;
13571
13572   for (child_die = die->child;
13573        child_die && child_die->tag;
13574        child_die = sibling_die (child_die))
13575     {
13576       struct die_info *child_origin_die;
13577       struct dwarf2_cu *child_origin_cu;
13578
13579       /* We are trying to process concrete instance entries:
13580          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13581          it's not relevant to our analysis here. i.e. detecting DIEs that are
13582          present in the abstract instance but not referenced in the concrete
13583          one.  */
13584       if (child_die->tag == DW_TAG_call_site
13585           || child_die->tag == DW_TAG_GNU_call_site)
13586         continue;
13587
13588       /* For each CHILD_DIE, find the corresponding child of
13589          ORIGIN_DIE.  If there is more than one layer of
13590          DW_AT_abstract_origin, follow them all; there shouldn't be,
13591          but GCC versions at least through 4.4 generate this (GCC PR
13592          40573).  */
13593       child_origin_die = child_die;
13594       child_origin_cu = cu;
13595       while (1)
13596         {
13597           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13598                               child_origin_cu);
13599           if (attr == NULL)
13600             break;
13601           child_origin_die = follow_die_ref (child_origin_die, attr,
13602                                              &child_origin_cu);
13603         }
13604
13605       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13606          counterpart may exist.  */
13607       if (child_origin_die != child_die)
13608         {
13609           if (child_die->tag != child_origin_die->tag
13610               && !(child_die->tag == DW_TAG_inlined_subroutine
13611                    && child_origin_die->tag == DW_TAG_subprogram))
13612             complaint (&symfile_complaints,
13613                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13614                          "different tags"),
13615                        to_underlying (child_die->sect_off),
13616                        to_underlying (child_origin_die->sect_off));
13617           if (child_origin_die->parent != origin_die)
13618             complaint (&symfile_complaints,
13619                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13620                          "different parents"),
13621                        to_underlying (child_die->sect_off),
13622                        to_underlying (child_origin_die->sect_off));
13623           else
13624             offsets.push_back (child_origin_die->sect_off);
13625         }
13626     }
13627   std::sort (offsets.begin (), offsets.end ());
13628   sect_offset *offsets_end = offsets.data () + offsets.size ();
13629   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13630     if (offsetp[-1] == *offsetp)
13631       complaint (&symfile_complaints,
13632                  _("Multiple children of DIE 0x%x refer "
13633                    "to DIE 0x%x as their abstract origin"),
13634                  to_underlying (die->sect_off), to_underlying (*offsetp));
13635
13636   offsetp = offsets.data ();
13637   origin_child_die = origin_die->child;
13638   while (origin_child_die && origin_child_die->tag)
13639     {
13640       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13641       while (offsetp < offsets_end
13642              && *offsetp < origin_child_die->sect_off)
13643         offsetp++;
13644       if (offsetp >= offsets_end
13645           || *offsetp > origin_child_die->sect_off)
13646         {
13647           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13648              Check whether we're already processing ORIGIN_CHILD_DIE.
13649              This can happen with mutually referenced abstract_origins.
13650              PR 16581.  */
13651           if (!origin_child_die->in_process)
13652             process_die (origin_child_die, origin_cu);
13653         }
13654       origin_child_die = sibling_die (origin_child_die);
13655     }
13656   origin_cu->list_in_scope = origin_previous_list_in_scope;
13657 }
13658
13659 static void
13660 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13661 {
13662   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
13663   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13664   struct context_stack *newobj;
13665   CORE_ADDR lowpc;
13666   CORE_ADDR highpc;
13667   struct die_info *child_die;
13668   struct attribute *attr, *call_line, *call_file;
13669   const char *name;
13670   CORE_ADDR baseaddr;
13671   struct block *block;
13672   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13673   std::vector<struct symbol *> template_args;
13674   struct template_symbol *templ_func = NULL;
13675
13676   if (inlined_func)
13677     {
13678       /* If we do not have call site information, we can't show the
13679          caller of this inlined function.  That's too confusing, so
13680          only use the scope for local variables.  */
13681       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13682       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13683       if (call_line == NULL || call_file == NULL)
13684         {
13685           read_lexical_block_scope (die, cu);
13686           return;
13687         }
13688     }
13689
13690   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13691
13692   name = dwarf2_name (die, cu);
13693
13694   /* Ignore functions with missing or empty names.  These are actually
13695      illegal according to the DWARF standard.  */
13696   if (name == NULL)
13697     {
13698       complaint (&symfile_complaints,
13699                  _("missing name for subprogram DIE at %d"),
13700                  to_underlying (die->sect_off));
13701       return;
13702     }
13703
13704   /* Ignore functions with missing or invalid low and high pc attributes.  */
13705   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13706       <= PC_BOUNDS_INVALID)
13707     {
13708       attr = dwarf2_attr (die, DW_AT_external, cu);
13709       if (!attr || !DW_UNSND (attr))
13710         complaint (&symfile_complaints,
13711                    _("cannot get low and high bounds "
13712                      "for subprogram DIE at %d"),
13713                    to_underlying (die->sect_off));
13714       return;
13715     }
13716
13717   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13718   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13719
13720   /* If we have any template arguments, then we must allocate a
13721      different sort of symbol.  */
13722   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13723     {
13724       if (child_die->tag == DW_TAG_template_type_param
13725           || child_die->tag == DW_TAG_template_value_param)
13726         {
13727           templ_func = allocate_template_symbol (objfile);
13728           templ_func->subclass = SYMBOL_TEMPLATE;
13729           break;
13730         }
13731     }
13732
13733   newobj = push_context (0, lowpc);
13734   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
13735                                (struct symbol *) templ_func);
13736
13737   /* If there is a location expression for DW_AT_frame_base, record
13738      it.  */
13739   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13740   if (attr)
13741     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13742
13743   /* If there is a location for the static link, record it.  */
13744   newobj->static_link = NULL;
13745   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13746   if (attr)
13747     {
13748       newobj->static_link
13749         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13750       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13751     }
13752
13753   cu->list_in_scope = &local_symbols;
13754
13755   if (die->child != NULL)
13756     {
13757       child_die = die->child;
13758       while (child_die && child_die->tag)
13759         {
13760           if (child_die->tag == DW_TAG_template_type_param
13761               || child_die->tag == DW_TAG_template_value_param)
13762             {
13763               struct symbol *arg = new_symbol (child_die, NULL, cu);
13764
13765               if (arg != NULL)
13766                 template_args.push_back (arg);
13767             }
13768           else
13769             process_die (child_die, cu);
13770           child_die = sibling_die (child_die);
13771         }
13772     }
13773
13774   inherit_abstract_dies (die, cu);
13775
13776   /* If we have a DW_AT_specification, we might need to import using
13777      directives from the context of the specification DIE.  See the
13778      comment in determine_prefix.  */
13779   if (cu->language == language_cplus
13780       && dwarf2_attr (die, DW_AT_specification, cu))
13781     {
13782       struct dwarf2_cu *spec_cu = cu;
13783       struct die_info *spec_die = die_specification (die, &spec_cu);
13784
13785       while (spec_die)
13786         {
13787           child_die = spec_die->child;
13788           while (child_die && child_die->tag)
13789             {
13790               if (child_die->tag == DW_TAG_imported_module)
13791                 process_die (child_die, spec_cu);
13792               child_die = sibling_die (child_die);
13793             }
13794
13795           /* In some cases, GCC generates specification DIEs that
13796              themselves contain DW_AT_specification attributes.  */
13797           spec_die = die_specification (spec_die, &spec_cu);
13798         }
13799     }
13800
13801   newobj = pop_context ();
13802   /* Make a block for the local symbols within.  */
13803   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13804                         newobj->static_link, lowpc, highpc);
13805
13806   /* For C++, set the block's scope.  */
13807   if ((cu->language == language_cplus
13808        || cu->language == language_fortran
13809        || cu->language == language_d
13810        || cu->language == language_rust)
13811       && cu->processing_has_namespace_info)
13812     block_set_scope (block, determine_prefix (die, cu),
13813                      &objfile->objfile_obstack);
13814
13815   /* If we have address ranges, record them.  */
13816   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13817
13818   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13819
13820   /* Attach template arguments to function.  */
13821   if (!template_args.empty ())
13822     {
13823       gdb_assert (templ_func != NULL);
13824
13825       templ_func->n_template_arguments = template_args.size ();
13826       templ_func->template_arguments
13827         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13828                      templ_func->n_template_arguments);
13829       memcpy (templ_func->template_arguments,
13830               template_args.data (),
13831               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13832     }
13833
13834   /* In C++, we can have functions nested inside functions (e.g., when
13835      a function declares a class that has methods).  This means that
13836      when we finish processing a function scope, we may need to go
13837      back to building a containing block's symbol lists.  */
13838   local_symbols = newobj->locals;
13839   local_using_directives = newobj->local_using_directives;
13840
13841   /* If we've finished processing a top-level function, subsequent
13842      symbols go in the file symbol list.  */
13843   if (outermost_context_p ())
13844     cu->list_in_scope = &file_symbols;
13845 }
13846
13847 /* Process all the DIES contained within a lexical block scope.  Start
13848    a new scope, process the dies, and then close the scope.  */
13849
13850 static void
13851 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13852 {
13853   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
13854   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13855   struct context_stack *newobj;
13856   CORE_ADDR lowpc, highpc;
13857   struct die_info *child_die;
13858   CORE_ADDR baseaddr;
13859
13860   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13861
13862   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13863   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13864      as multiple lexical blocks?  Handling children in a sane way would
13865      be nasty.  Might be easier to properly extend generic blocks to
13866      describe ranges.  */
13867   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13868     {
13869     case PC_BOUNDS_NOT_PRESENT:
13870       /* DW_TAG_lexical_block has no attributes, process its children as if
13871          there was no wrapping by that DW_TAG_lexical_block.
13872          GCC does no longer produces such DWARF since GCC r224161.  */
13873       for (child_die = die->child;
13874            child_die != NULL && child_die->tag;
13875            child_die = sibling_die (child_die))
13876         process_die (child_die, cu);
13877       return;
13878     case PC_BOUNDS_INVALID:
13879       return;
13880     }
13881   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13882   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13883
13884   push_context (0, lowpc);
13885   if (die->child != NULL)
13886     {
13887       child_die = die->child;
13888       while (child_die && child_die->tag)
13889         {
13890           process_die (child_die, cu);
13891           child_die = sibling_die (child_die);
13892         }
13893     }
13894   inherit_abstract_dies (die, cu);
13895   newobj = pop_context ();
13896
13897   if (local_symbols != NULL || local_using_directives != NULL)
13898     {
13899       struct block *block
13900         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13901                         newobj->start_addr, highpc);
13902
13903       /* Note that recording ranges after traversing children, as we
13904          do here, means that recording a parent's ranges entails
13905          walking across all its children's ranges as they appear in
13906          the address map, which is quadratic behavior.
13907
13908          It would be nicer to record the parent's ranges before
13909          traversing its children, simply overriding whatever you find
13910          there.  But since we don't even decide whether to create a
13911          block until after we've traversed its children, that's hard
13912          to do.  */
13913       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13914     }
13915   local_symbols = newobj->locals;
13916   local_using_directives = newobj->local_using_directives;
13917 }
13918
13919 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13920
13921 static void
13922 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13923 {
13924   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
13925   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13926   CORE_ADDR pc, baseaddr;
13927   struct attribute *attr;
13928   struct call_site *call_site, call_site_local;
13929   void **slot;
13930   int nparams;
13931   struct die_info *child_die;
13932
13933   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13934
13935   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13936   if (attr == NULL)
13937     {
13938       /* This was a pre-DWARF-5 GNU extension alias
13939          for DW_AT_call_return_pc.  */
13940       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13941     }
13942   if (!attr)
13943     {
13944       complaint (&symfile_complaints,
13945                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13946                    "DIE 0x%x [in module %s]"),
13947                  to_underlying (die->sect_off), objfile_name (objfile));
13948       return;
13949     }
13950   pc = attr_value_as_address (attr) + baseaddr;
13951   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13952
13953   if (cu->call_site_htab == NULL)
13954     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13955                                                NULL, &objfile->objfile_obstack,
13956                                                hashtab_obstack_allocate, NULL);
13957   call_site_local.pc = pc;
13958   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13959   if (*slot != NULL)
13960     {
13961       complaint (&symfile_complaints,
13962                  _("Duplicate PC %s for DW_TAG_call_site "
13963                    "DIE 0x%x [in module %s]"),
13964                  paddress (gdbarch, pc), to_underlying (die->sect_off),
13965                  objfile_name (objfile));
13966       return;
13967     }
13968
13969   /* Count parameters at the caller.  */
13970
13971   nparams = 0;
13972   for (child_die = die->child; child_die && child_die->tag;
13973        child_die = sibling_die (child_die))
13974     {
13975       if (child_die->tag != DW_TAG_call_site_parameter
13976           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13977         {
13978           complaint (&symfile_complaints,
13979                      _("Tag %d is not DW_TAG_call_site_parameter in "
13980                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13981                      child_die->tag, to_underlying (child_die->sect_off),
13982                      objfile_name (objfile));
13983           continue;
13984         }
13985
13986       nparams++;
13987     }
13988
13989   call_site
13990     = ((struct call_site *)
13991        obstack_alloc (&objfile->objfile_obstack,
13992                       sizeof (*call_site)
13993                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13994   *slot = call_site;
13995   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13996   call_site->pc = pc;
13997
13998   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13999       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14000     {
14001       struct die_info *func_die;
14002
14003       /* Skip also over DW_TAG_inlined_subroutine.  */
14004       for (func_die = die->parent;
14005            func_die && func_die->tag != DW_TAG_subprogram
14006            && func_die->tag != DW_TAG_subroutine_type;
14007            func_die = func_die->parent);
14008
14009       /* DW_AT_call_all_calls is a superset
14010          of DW_AT_call_all_tail_calls.  */
14011       if (func_die
14012           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14013           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14014           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14015           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14016         {
14017           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14018              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14019              both the initial caller containing the real return address PC and
14020              the final callee containing the current PC of a chain of tail
14021              calls do not need to have the tail call list complete.  But any
14022              function candidate for a virtual tail call frame searched via
14023              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14024              determined unambiguously.  */
14025         }
14026       else
14027         {
14028           struct type *func_type = NULL;
14029
14030           if (func_die)
14031             func_type = get_die_type (func_die, cu);
14032           if (func_type != NULL)
14033             {
14034               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14035
14036               /* Enlist this call site to the function.  */
14037               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14038               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14039             }
14040           else
14041             complaint (&symfile_complaints,
14042                        _("Cannot find function owning DW_TAG_call_site "
14043                          "DIE 0x%x [in module %s]"),
14044                        to_underlying (die->sect_off), objfile_name (objfile));
14045         }
14046     }
14047
14048   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14049   if (attr == NULL)
14050     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14051   if (attr == NULL)
14052     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14053   if (attr == NULL)
14054     {
14055       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14056       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14057     }
14058   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14059   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14060     /* Keep NULL DWARF_BLOCK.  */;
14061   else if (attr_form_is_block (attr))
14062     {
14063       struct dwarf2_locexpr_baton *dlbaton;
14064
14065       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14066       dlbaton->data = DW_BLOCK (attr)->data;
14067       dlbaton->size = DW_BLOCK (attr)->size;
14068       dlbaton->per_cu = cu->per_cu;
14069
14070       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14071     }
14072   else if (attr_form_is_ref (attr))
14073     {
14074       struct dwarf2_cu *target_cu = cu;
14075       struct die_info *target_die;
14076
14077       target_die = follow_die_ref (die, attr, &target_cu);
14078       gdb_assert (target_cu->dwarf2_per_objfile->objfile == objfile);
14079       if (die_is_declaration (target_die, target_cu))
14080         {
14081           const char *target_physname;
14082
14083           /* Prefer the mangled name; otherwise compute the demangled one.  */
14084           target_physname = dw2_linkage_name (target_die, target_cu);
14085           if (target_physname == NULL)
14086             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14087           if (target_physname == NULL)
14088             complaint (&symfile_complaints,
14089                        _("DW_AT_call_target target DIE has invalid "
14090                          "physname, for referencing DIE 0x%x [in module %s]"),
14091                        to_underlying (die->sect_off), objfile_name (objfile));
14092           else
14093             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14094         }
14095       else
14096         {
14097           CORE_ADDR lowpc;
14098
14099           /* DW_AT_entry_pc should be preferred.  */
14100           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14101               <= PC_BOUNDS_INVALID)
14102             complaint (&symfile_complaints,
14103                        _("DW_AT_call_target target DIE has invalid "
14104                          "low pc, for referencing DIE 0x%x [in module %s]"),
14105                        to_underlying (die->sect_off), objfile_name (objfile));
14106           else
14107             {
14108               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14109               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14110             }
14111         }
14112     }
14113   else
14114     complaint (&symfile_complaints,
14115                _("DW_TAG_call_site DW_AT_call_target is neither "
14116                  "block nor reference, for DIE 0x%x [in module %s]"),
14117                to_underlying (die->sect_off), objfile_name (objfile));
14118
14119   call_site->per_cu = cu->per_cu;
14120
14121   for (child_die = die->child;
14122        child_die && child_die->tag;
14123        child_die = sibling_die (child_die))
14124     {
14125       struct call_site_parameter *parameter;
14126       struct attribute *loc, *origin;
14127
14128       if (child_die->tag != DW_TAG_call_site_parameter
14129           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14130         {
14131           /* Already printed the complaint above.  */
14132           continue;
14133         }
14134
14135       gdb_assert (call_site->parameter_count < nparams);
14136       parameter = &call_site->parameter[call_site->parameter_count];
14137
14138       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14139          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14140          register is contained in DW_AT_call_value.  */
14141
14142       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14143       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14144       if (origin == NULL)
14145         {
14146           /* This was a pre-DWARF-5 GNU extension alias
14147              for DW_AT_call_parameter.  */
14148           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14149         }
14150       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14151         {
14152           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14153
14154           sect_offset sect_off
14155             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14156           if (!offset_in_cu_p (&cu->header, sect_off))
14157             {
14158               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14159                  binding can be done only inside one CU.  Such referenced DIE
14160                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14161               complaint (&symfile_complaints,
14162                          _("DW_AT_call_parameter offset is not in CU for "
14163                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14164                          to_underlying (child_die->sect_off),
14165                          objfile_name (objfile));
14166               continue;
14167             }
14168           parameter->u.param_cu_off
14169             = (cu_offset) (sect_off - cu->header.sect_off);
14170         }
14171       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14172         {
14173           complaint (&symfile_complaints,
14174                      _("No DW_FORM_block* DW_AT_location for "
14175                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14176                      to_underlying (child_die->sect_off), objfile_name (objfile));
14177           continue;
14178         }
14179       else
14180         {
14181           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14182             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14183           if (parameter->u.dwarf_reg != -1)
14184             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14185           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14186                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14187                                              &parameter->u.fb_offset))
14188             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14189           else
14190             {
14191               complaint (&symfile_complaints,
14192                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14193                            "for DW_FORM_block* DW_AT_location is supported for "
14194                            "DW_TAG_call_site child DIE 0x%x "
14195                            "[in module %s]"),
14196                          to_underlying (child_die->sect_off),
14197                          objfile_name (objfile));
14198               continue;
14199             }
14200         }
14201
14202       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14203       if (attr == NULL)
14204         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14205       if (!attr_form_is_block (attr))
14206         {
14207           complaint (&symfile_complaints,
14208                      _("No DW_FORM_block* DW_AT_call_value for "
14209                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14210                      to_underlying (child_die->sect_off),
14211                      objfile_name (objfile));
14212           continue;
14213         }
14214       parameter->value = DW_BLOCK (attr)->data;
14215       parameter->value_size = DW_BLOCK (attr)->size;
14216
14217       /* Parameters are not pre-cleared by memset above.  */
14218       parameter->data_value = NULL;
14219       parameter->data_value_size = 0;
14220       call_site->parameter_count++;
14221
14222       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14223       if (attr == NULL)
14224         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14225       if (attr)
14226         {
14227           if (!attr_form_is_block (attr))
14228             complaint (&symfile_complaints,
14229                        _("No DW_FORM_block* DW_AT_call_data_value for "
14230                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14231                        to_underlying (child_die->sect_off),
14232                        objfile_name (objfile));
14233           else
14234             {
14235               parameter->data_value = DW_BLOCK (attr)->data;
14236               parameter->data_value_size = DW_BLOCK (attr)->size;
14237             }
14238         }
14239     }
14240 }
14241
14242 /* Helper function for read_variable.  If DIE represents a virtual
14243    table, then return the type of the concrete object that is
14244    associated with the virtual table.  Otherwise, return NULL.  */
14245
14246 static struct type *
14247 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14248 {
14249   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14250   if (attr == NULL)
14251     return NULL;
14252
14253   /* Find the type DIE.  */
14254   struct die_info *type_die = NULL;
14255   struct dwarf2_cu *type_cu = cu;
14256
14257   if (attr_form_is_ref (attr))
14258     type_die = follow_die_ref (die, attr, &type_cu);
14259   if (type_die == NULL)
14260     return NULL;
14261
14262   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14263     return NULL;
14264   return die_containing_type (type_die, type_cu);
14265 }
14266
14267 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14268
14269 static void
14270 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14271 {
14272   struct rust_vtable_symbol *storage = NULL;
14273
14274   if (cu->language == language_rust)
14275     {
14276       struct type *containing_type = rust_containing_type (die, cu);
14277
14278       if (containing_type != NULL)
14279         {
14280           struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14281
14282           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14283                                     struct rust_vtable_symbol);
14284           initialize_objfile_symbol (storage);
14285           storage->concrete_type = containing_type;
14286           storage->subclass = SYMBOL_RUST_VTABLE;
14287         }
14288     }
14289
14290   new_symbol_full (die, NULL, cu, storage);
14291 }
14292
14293 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14294    reading .debug_rnglists.
14295    Callback's type should be:
14296     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14297    Return true if the attributes are present and valid, otherwise,
14298    return false.  */
14299
14300 template <typename Callback>
14301 static bool
14302 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14303                          Callback &&callback)
14304 {
14305   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14306   bfd *obfd = objfile->obfd;
14307   /* Base address selection entry.  */
14308   CORE_ADDR base;
14309   int found_base;
14310   const gdb_byte *buffer;
14311   CORE_ADDR baseaddr;
14312   bool overflow = false;
14313
14314   found_base = cu->base_known;
14315   base = cu->base_address;
14316
14317   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14318   if (offset >= dwarf2_per_objfile->rnglists.size)
14319     {
14320       complaint (&symfile_complaints,
14321                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14322                  offset);
14323       return false;
14324     }
14325   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14326
14327   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14328
14329   while (1)
14330     {
14331       /* Initialize it due to a false compiler warning.  */
14332       CORE_ADDR range_beginning = 0, range_end = 0;
14333       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14334                                  + dwarf2_per_objfile->rnglists.size);
14335       unsigned int bytes_read;
14336
14337       if (buffer == buf_end)
14338         {
14339           overflow = true;
14340           break;
14341         }
14342       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14343       switch (rlet)
14344         {
14345         case DW_RLE_end_of_list:
14346           break;
14347         case DW_RLE_base_address:
14348           if (buffer + cu->header.addr_size > buf_end)
14349             {
14350               overflow = true;
14351               break;
14352             }
14353           base = read_address (obfd, buffer, cu, &bytes_read);
14354           found_base = 1;
14355           buffer += bytes_read;
14356           break;
14357         case DW_RLE_start_length:
14358           if (buffer + cu->header.addr_size > buf_end)
14359             {
14360               overflow = true;
14361               break;
14362             }
14363           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14364           buffer += bytes_read;
14365           range_end = (range_beginning
14366                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14367           buffer += bytes_read;
14368           if (buffer > buf_end)
14369             {
14370               overflow = true;
14371               break;
14372             }
14373           break;
14374         case DW_RLE_offset_pair:
14375           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14376           buffer += bytes_read;
14377           if (buffer > buf_end)
14378             {
14379               overflow = true;
14380               break;
14381             }
14382           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14383           buffer += bytes_read;
14384           if (buffer > buf_end)
14385             {
14386               overflow = true;
14387               break;
14388             }
14389           break;
14390         case DW_RLE_start_end:
14391           if (buffer + 2 * cu->header.addr_size > buf_end)
14392             {
14393               overflow = true;
14394               break;
14395             }
14396           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14397           buffer += bytes_read;
14398           range_end = read_address (obfd, buffer, cu, &bytes_read);
14399           buffer += bytes_read;
14400           break;
14401         default:
14402           complaint (&symfile_complaints,
14403                      _("Invalid .debug_rnglists data (no base address)"));
14404           return false;
14405         }
14406       if (rlet == DW_RLE_end_of_list || overflow)
14407         break;
14408       if (rlet == DW_RLE_base_address)
14409         continue;
14410
14411       if (!found_base)
14412         {
14413           /* We have no valid base address for the ranges
14414              data.  */
14415           complaint (&symfile_complaints,
14416                      _("Invalid .debug_rnglists data (no base address)"));
14417           return false;
14418         }
14419
14420       if (range_beginning > range_end)
14421         {
14422           /* Inverted range entries are invalid.  */
14423           complaint (&symfile_complaints,
14424                      _("Invalid .debug_rnglists data (inverted range)"));
14425           return false;
14426         }
14427
14428       /* Empty range entries have no effect.  */
14429       if (range_beginning == range_end)
14430         continue;
14431
14432       range_beginning += base;
14433       range_end += base;
14434
14435       /* A not-uncommon case of bad debug info.
14436          Don't pollute the addrmap with bad data.  */
14437       if (range_beginning + baseaddr == 0
14438           && !dwarf2_per_objfile->has_section_at_zero)
14439         {
14440           complaint (&symfile_complaints,
14441                      _(".debug_rnglists entry has start address of zero"
14442                        " [in module %s]"), objfile_name (objfile));
14443           continue;
14444         }
14445
14446       callback (range_beginning, range_end);
14447     }
14448
14449   if (overflow)
14450     {
14451       complaint (&symfile_complaints,
14452                  _("Offset %d is not terminated "
14453                    "for DW_AT_ranges attribute"),
14454                  offset);
14455       return false;
14456     }
14457
14458   return true;
14459 }
14460
14461 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14462    Callback's type should be:
14463     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14464    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14465
14466 template <typename Callback>
14467 static int
14468 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14469                        Callback &&callback)
14470 {
14471   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14472   struct comp_unit_head *cu_header = &cu->header;
14473   bfd *obfd = objfile->obfd;
14474   unsigned int addr_size = cu_header->addr_size;
14475   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14476   /* Base address selection entry.  */
14477   CORE_ADDR base;
14478   int found_base;
14479   unsigned int dummy;
14480   const gdb_byte *buffer;
14481   CORE_ADDR baseaddr;
14482
14483   if (cu_header->version >= 5)
14484     return dwarf2_rnglists_process (offset, cu, callback);
14485
14486   found_base = cu->base_known;
14487   base = cu->base_address;
14488
14489   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14490   if (offset >= dwarf2_per_objfile->ranges.size)
14491     {
14492       complaint (&symfile_complaints,
14493                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14494                  offset);
14495       return 0;
14496     }
14497   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14498
14499   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14500
14501   while (1)
14502     {
14503       CORE_ADDR range_beginning, range_end;
14504
14505       range_beginning = read_address (obfd, buffer, cu, &dummy);
14506       buffer += addr_size;
14507       range_end = read_address (obfd, buffer, cu, &dummy);
14508       buffer += addr_size;
14509       offset += 2 * addr_size;
14510
14511       /* An end of list marker is a pair of zero addresses.  */
14512       if (range_beginning == 0 && range_end == 0)
14513         /* Found the end of list entry.  */
14514         break;
14515
14516       /* Each base address selection entry is a pair of 2 values.
14517          The first is the largest possible address, the second is
14518          the base address.  Check for a base address here.  */
14519       if ((range_beginning & mask) == mask)
14520         {
14521           /* If we found the largest possible address, then we already
14522              have the base address in range_end.  */
14523           base = range_end;
14524           found_base = 1;
14525           continue;
14526         }
14527
14528       if (!found_base)
14529         {
14530           /* We have no valid base address for the ranges
14531              data.  */
14532           complaint (&symfile_complaints,
14533                      _("Invalid .debug_ranges data (no base address)"));
14534           return 0;
14535         }
14536
14537       if (range_beginning > range_end)
14538         {
14539           /* Inverted range entries are invalid.  */
14540           complaint (&symfile_complaints,
14541                      _("Invalid .debug_ranges data (inverted range)"));
14542           return 0;
14543         }
14544
14545       /* Empty range entries have no effect.  */
14546       if (range_beginning == range_end)
14547         continue;
14548
14549       range_beginning += base;
14550       range_end += base;
14551
14552       /* A not-uncommon case of bad debug info.
14553          Don't pollute the addrmap with bad data.  */
14554       if (range_beginning + baseaddr == 0
14555           && !dwarf2_per_objfile->has_section_at_zero)
14556         {
14557           complaint (&symfile_complaints,
14558                      _(".debug_ranges entry has start address of zero"
14559                        " [in module %s]"), objfile_name (objfile));
14560           continue;
14561         }
14562
14563       callback (range_beginning, range_end);
14564     }
14565
14566   return 1;
14567 }
14568
14569 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14570    Return 1 if the attributes are present and valid, otherwise, return 0.
14571    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14572
14573 static int
14574 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14575                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14576                     struct partial_symtab *ranges_pst)
14577 {
14578   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14579   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14580   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14581                                        SECT_OFF_TEXT (objfile));
14582   int low_set = 0;
14583   CORE_ADDR low = 0;
14584   CORE_ADDR high = 0;
14585   int retval;
14586
14587   retval = dwarf2_ranges_process (offset, cu,
14588     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14589     {
14590       if (ranges_pst != NULL)
14591         {
14592           CORE_ADDR lowpc;
14593           CORE_ADDR highpc;
14594
14595           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14596                                               range_beginning + baseaddr);
14597           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14598                                                range_end + baseaddr);
14599           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14600                              ranges_pst);
14601         }
14602
14603       /* FIXME: This is recording everything as a low-high
14604          segment of consecutive addresses.  We should have a
14605          data structure for discontiguous block ranges
14606          instead.  */
14607       if (! low_set)
14608         {
14609           low = range_beginning;
14610           high = range_end;
14611           low_set = 1;
14612         }
14613       else
14614         {
14615           if (range_beginning < low)
14616             low = range_beginning;
14617           if (range_end > high)
14618             high = range_end;
14619         }
14620     });
14621   if (!retval)
14622     return 0;
14623
14624   if (! low_set)
14625     /* If the first entry is an end-of-list marker, the range
14626        describes an empty scope, i.e. no instructions.  */
14627     return 0;
14628
14629   if (low_return)
14630     *low_return = low;
14631   if (high_return)
14632     *high_return = high;
14633   return 1;
14634 }
14635
14636 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14637    definition for the return value.  *LOWPC and *HIGHPC are set iff
14638    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14639
14640 static enum pc_bounds_kind
14641 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14642                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14643                       struct partial_symtab *pst)
14644 {
14645   struct attribute *attr;
14646   struct attribute *attr_high;
14647   CORE_ADDR low = 0;
14648   CORE_ADDR high = 0;
14649   enum pc_bounds_kind ret;
14650
14651   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14652   if (attr_high)
14653     {
14654       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14655       if (attr)
14656         {
14657           low = attr_value_as_address (attr);
14658           high = attr_value_as_address (attr_high);
14659           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14660             high += low;
14661         }
14662       else
14663         /* Found high w/o low attribute.  */
14664         return PC_BOUNDS_INVALID;
14665
14666       /* Found consecutive range of addresses.  */
14667       ret = PC_BOUNDS_HIGH_LOW;
14668     }
14669   else
14670     {
14671       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14672       if (attr != NULL)
14673         {
14674           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14675              We take advantage of the fact that DW_AT_ranges does not appear
14676              in DW_TAG_compile_unit of DWO files.  */
14677           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14678           unsigned int ranges_offset = (DW_UNSND (attr)
14679                                         + (need_ranges_base
14680                                            ? cu->ranges_base
14681                                            : 0));
14682
14683           /* Value of the DW_AT_ranges attribute is the offset in the
14684              .debug_ranges section.  */
14685           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14686             return PC_BOUNDS_INVALID;
14687           /* Found discontinuous range of addresses.  */
14688           ret = PC_BOUNDS_RANGES;
14689         }
14690       else
14691         return PC_BOUNDS_NOT_PRESENT;
14692     }
14693
14694   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14695   if (high <= low)
14696     return PC_BOUNDS_INVALID;
14697
14698   /* When using the GNU linker, .gnu.linkonce. sections are used to
14699      eliminate duplicate copies of functions and vtables and such.
14700      The linker will arbitrarily choose one and discard the others.
14701      The AT_*_pc values for such functions refer to local labels in
14702      these sections.  If the section from that file was discarded, the
14703      labels are not in the output, so the relocs get a value of 0.
14704      If this is a discarded function, mark the pc bounds as invalid,
14705      so that GDB will ignore it.  */
14706   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14707     return PC_BOUNDS_INVALID;
14708
14709   *lowpc = low;
14710   if (highpc)
14711     *highpc = high;
14712   return ret;
14713 }
14714
14715 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14716    its low and high PC addresses.  Do nothing if these addresses could not
14717    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14718    and HIGHPC to the high address if greater than HIGHPC.  */
14719
14720 static void
14721 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14722                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14723                                  struct dwarf2_cu *cu)
14724 {
14725   CORE_ADDR low, high;
14726   struct die_info *child = die->child;
14727
14728   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14729     {
14730       *lowpc = std::min (*lowpc, low);
14731       *highpc = std::max (*highpc, high);
14732     }
14733
14734   /* If the language does not allow nested subprograms (either inside
14735      subprograms or lexical blocks), we're done.  */
14736   if (cu->language != language_ada)
14737     return;
14738
14739   /* Check all the children of the given DIE.  If it contains nested
14740      subprograms, then check their pc bounds.  Likewise, we need to
14741      check lexical blocks as well, as they may also contain subprogram
14742      definitions.  */
14743   while (child && child->tag)
14744     {
14745       if (child->tag == DW_TAG_subprogram
14746           || child->tag == DW_TAG_lexical_block)
14747         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14748       child = sibling_die (child);
14749     }
14750 }
14751
14752 /* Get the low and high pc's represented by the scope DIE, and store
14753    them in *LOWPC and *HIGHPC.  If the correct values can't be
14754    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14755
14756 static void
14757 get_scope_pc_bounds (struct die_info *die,
14758                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14759                      struct dwarf2_cu *cu)
14760 {
14761   CORE_ADDR best_low = (CORE_ADDR) -1;
14762   CORE_ADDR best_high = (CORE_ADDR) 0;
14763   CORE_ADDR current_low, current_high;
14764
14765   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14766       >= PC_BOUNDS_RANGES)
14767     {
14768       best_low = current_low;
14769       best_high = current_high;
14770     }
14771   else
14772     {
14773       struct die_info *child = die->child;
14774
14775       while (child && child->tag)
14776         {
14777           switch (child->tag) {
14778           case DW_TAG_subprogram:
14779             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14780             break;
14781           case DW_TAG_namespace:
14782           case DW_TAG_module:
14783             /* FIXME: carlton/2004-01-16: Should we do this for
14784                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14785                that current GCC's always emit the DIEs corresponding
14786                to definitions of methods of classes as children of a
14787                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14788                the DIEs giving the declarations, which could be
14789                anywhere).  But I don't see any reason why the
14790                standards says that they have to be there.  */
14791             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14792
14793             if (current_low != ((CORE_ADDR) -1))
14794               {
14795                 best_low = std::min (best_low, current_low);
14796                 best_high = std::max (best_high, current_high);
14797               }
14798             break;
14799           default:
14800             /* Ignore.  */
14801             break;
14802           }
14803
14804           child = sibling_die (child);
14805         }
14806     }
14807
14808   *lowpc = best_low;
14809   *highpc = best_high;
14810 }
14811
14812 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14813    in DIE.  */
14814
14815 static void
14816 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14817                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14818 {
14819   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14820   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14821   struct attribute *attr;
14822   struct attribute *attr_high;
14823
14824   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14825   if (attr_high)
14826     {
14827       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14828       if (attr)
14829         {
14830           CORE_ADDR low = attr_value_as_address (attr);
14831           CORE_ADDR high = attr_value_as_address (attr_high);
14832
14833           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14834             high += low;
14835
14836           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14837           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14838           record_block_range (block, low, high - 1);
14839         }
14840     }
14841
14842   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14843   if (attr)
14844     {
14845       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14846          We take advantage of the fact that DW_AT_ranges does not appear
14847          in DW_TAG_compile_unit of DWO files.  */
14848       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14849
14850       /* The value of the DW_AT_ranges attribute is the offset of the
14851          address range list in the .debug_ranges section.  */
14852       unsigned long offset = (DW_UNSND (attr)
14853                               + (need_ranges_base ? cu->ranges_base : 0));
14854       const gdb_byte *buffer;
14855
14856       /* For some target architectures, but not others, the
14857          read_address function sign-extends the addresses it returns.
14858          To recognize base address selection entries, we need a
14859          mask.  */
14860       unsigned int addr_size = cu->header.addr_size;
14861       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14862
14863       /* The base address, to which the next pair is relative.  Note
14864          that this 'base' is a DWARF concept: most entries in a range
14865          list are relative, to reduce the number of relocs against the
14866          debugging information.  This is separate from this function's
14867          'baseaddr' argument, which GDB uses to relocate debugging
14868          information from a shared library based on the address at
14869          which the library was loaded.  */
14870       CORE_ADDR base = cu->base_address;
14871       int base_known = cu->base_known;
14872
14873       dwarf2_ranges_process (offset, cu,
14874         [&] (CORE_ADDR start, CORE_ADDR end)
14875         {
14876           start += baseaddr;
14877           end += baseaddr;
14878           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14879           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14880           record_block_range (block, start, end - 1);
14881         });
14882     }
14883 }
14884
14885 /* Check whether the producer field indicates either of GCC < 4.6, or the
14886    Intel C/C++ compiler, and cache the result in CU.  */
14887
14888 static void
14889 check_producer (struct dwarf2_cu *cu)
14890 {
14891   int major, minor;
14892
14893   if (cu->producer == NULL)
14894     {
14895       /* For unknown compilers expect their behavior is DWARF version
14896          compliant.
14897
14898          GCC started to support .debug_types sections by -gdwarf-4 since
14899          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14900          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14901          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14902          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14903     }
14904   else if (producer_is_gcc (cu->producer, &major, &minor))
14905     {
14906       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14907       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14908     }
14909   else if (producer_is_icc (cu->producer, &major, &minor))
14910     cu->producer_is_icc_lt_14 = major < 14;
14911   else
14912     {
14913       /* For other non-GCC compilers, expect their behavior is DWARF version
14914          compliant.  */
14915     }
14916
14917   cu->checked_producer = 1;
14918 }
14919
14920 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14921    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14922    during 4.6.0 experimental.  */
14923
14924 static int
14925 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14926 {
14927   if (!cu->checked_producer)
14928     check_producer (cu);
14929
14930   return cu->producer_is_gxx_lt_4_6;
14931 }
14932
14933 /* Return the default accessibility type if it is not overriden by
14934    DW_AT_accessibility.  */
14935
14936 static enum dwarf_access_attribute
14937 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14938 {
14939   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14940     {
14941       /* The default DWARF 2 accessibility for members is public, the default
14942          accessibility for inheritance is private.  */
14943
14944       if (die->tag != DW_TAG_inheritance)
14945         return DW_ACCESS_public;
14946       else
14947         return DW_ACCESS_private;
14948     }
14949   else
14950     {
14951       /* DWARF 3+ defines the default accessibility a different way.  The same
14952          rules apply now for DW_TAG_inheritance as for the members and it only
14953          depends on the container kind.  */
14954
14955       if (die->parent->tag == DW_TAG_class_type)
14956         return DW_ACCESS_private;
14957       else
14958         return DW_ACCESS_public;
14959     }
14960 }
14961
14962 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14963    offset.  If the attribute was not found return 0, otherwise return
14964    1.  If it was found but could not properly be handled, set *OFFSET
14965    to 0.  */
14966
14967 static int
14968 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14969                              LONGEST *offset)
14970 {
14971   struct attribute *attr;
14972
14973   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14974   if (attr != NULL)
14975     {
14976       *offset = 0;
14977
14978       /* Note that we do not check for a section offset first here.
14979          This is because DW_AT_data_member_location is new in DWARF 4,
14980          so if we see it, we can assume that a constant form is really
14981          a constant and not a section offset.  */
14982       if (attr_form_is_constant (attr))
14983         *offset = dwarf2_get_attr_constant_value (attr, 0);
14984       else if (attr_form_is_section_offset (attr))
14985         dwarf2_complex_location_expr_complaint ();
14986       else if (attr_form_is_block (attr))
14987         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14988       else
14989         dwarf2_complex_location_expr_complaint ();
14990
14991       return 1;
14992     }
14993
14994   return 0;
14995 }
14996
14997 /* Add an aggregate field to the field list.  */
14998
14999 static void
15000 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15001                   struct dwarf2_cu *cu)
15002 {
15003   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15004   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15005   struct nextfield *new_field;
15006   struct attribute *attr;
15007   struct field *fp;
15008   const char *fieldname = "";
15009
15010   /* Allocate a new field list entry and link it in.  */
15011   new_field = XNEW (struct nextfield);
15012   make_cleanup (xfree, new_field);
15013   memset (new_field, 0, sizeof (struct nextfield));
15014
15015   if (die->tag == DW_TAG_inheritance)
15016     {
15017       new_field->next = fip->baseclasses;
15018       fip->baseclasses = new_field;
15019     }
15020   else
15021     {
15022       new_field->next = fip->fields;
15023       fip->fields = new_field;
15024     }
15025   fip->nfields++;
15026
15027   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15028   if (attr)
15029     new_field->accessibility = DW_UNSND (attr);
15030   else
15031     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15032   if (new_field->accessibility != DW_ACCESS_public)
15033     fip->non_public_fields = 1;
15034
15035   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15036   if (attr)
15037     new_field->virtuality = DW_UNSND (attr);
15038   else
15039     new_field->virtuality = DW_VIRTUALITY_none;
15040
15041   fp = &new_field->field;
15042
15043   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15044     {
15045       LONGEST offset;
15046
15047       /* Data member other than a C++ static data member.  */
15048
15049       /* Get type of field.  */
15050       fp->type = die_type (die, cu);
15051
15052       SET_FIELD_BITPOS (*fp, 0);
15053
15054       /* Get bit size of field (zero if none).  */
15055       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15056       if (attr)
15057         {
15058           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15059         }
15060       else
15061         {
15062           FIELD_BITSIZE (*fp) = 0;
15063         }
15064
15065       /* Get bit offset of field.  */
15066       if (handle_data_member_location (die, cu, &offset))
15067         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15068       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15069       if (attr)
15070         {
15071           if (gdbarch_bits_big_endian (gdbarch))
15072             {
15073               /* For big endian bits, the DW_AT_bit_offset gives the
15074                  additional bit offset from the MSB of the containing
15075                  anonymous object to the MSB of the field.  We don't
15076                  have to do anything special since we don't need to
15077                  know the size of the anonymous object.  */
15078               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15079             }
15080           else
15081             {
15082               /* For little endian bits, compute the bit offset to the
15083                  MSB of the anonymous object, subtract off the number of
15084                  bits from the MSB of the field to the MSB of the
15085                  object, and then subtract off the number of bits of
15086                  the field itself.  The result is the bit offset of
15087                  the LSB of the field.  */
15088               int anonymous_size;
15089               int bit_offset = DW_UNSND (attr);
15090
15091               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15092               if (attr)
15093                 {
15094                   /* The size of the anonymous object containing
15095                      the bit field is explicit, so use the
15096                      indicated size (in bytes).  */
15097                   anonymous_size = DW_UNSND (attr);
15098                 }
15099               else
15100                 {
15101                   /* The size of the anonymous object containing
15102                      the bit field must be inferred from the type
15103                      attribute of the data member containing the
15104                      bit field.  */
15105                   anonymous_size = TYPE_LENGTH (fp->type);
15106                 }
15107               SET_FIELD_BITPOS (*fp,
15108                                 (FIELD_BITPOS (*fp)
15109                                  + anonymous_size * bits_per_byte
15110                                  - bit_offset - FIELD_BITSIZE (*fp)));
15111             }
15112         }
15113       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15114       if (attr != NULL)
15115         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15116                                 + dwarf2_get_attr_constant_value (attr, 0)));
15117
15118       /* Get name of field.  */
15119       fieldname = dwarf2_name (die, cu);
15120       if (fieldname == NULL)
15121         fieldname = "";
15122
15123       /* The name is already allocated along with this objfile, so we don't
15124          need to duplicate it for the type.  */
15125       fp->name = fieldname;
15126
15127       /* Change accessibility for artificial fields (e.g. virtual table
15128          pointer or virtual base class pointer) to private.  */
15129       if (dwarf2_attr (die, DW_AT_artificial, cu))
15130         {
15131           FIELD_ARTIFICIAL (*fp) = 1;
15132           new_field->accessibility = DW_ACCESS_private;
15133           fip->non_public_fields = 1;
15134         }
15135     }
15136   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15137     {
15138       /* C++ static member.  */
15139
15140       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15141          is a declaration, but all versions of G++ as of this writing
15142          (so through at least 3.2.1) incorrectly generate
15143          DW_TAG_variable tags.  */
15144
15145       const char *physname;
15146
15147       /* Get name of field.  */
15148       fieldname = dwarf2_name (die, cu);
15149       if (fieldname == NULL)
15150         return;
15151
15152       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15153       if (attr
15154           /* Only create a symbol if this is an external value.
15155              new_symbol checks this and puts the value in the global symbol
15156              table, which we want.  If it is not external, new_symbol
15157              will try to put the value in cu->list_in_scope which is wrong.  */
15158           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15159         {
15160           /* A static const member, not much different than an enum as far as
15161              we're concerned, except that we can support more types.  */
15162           new_symbol (die, NULL, cu);
15163         }
15164
15165       /* Get physical name.  */
15166       physname = dwarf2_physname (fieldname, die, cu);
15167
15168       /* The name is already allocated along with this objfile, so we don't
15169          need to duplicate it for the type.  */
15170       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15171       FIELD_TYPE (*fp) = die_type (die, cu);
15172       FIELD_NAME (*fp) = fieldname;
15173     }
15174   else if (die->tag == DW_TAG_inheritance)
15175     {
15176       LONGEST offset;
15177
15178       /* C++ base class field.  */
15179       if (handle_data_member_location (die, cu, &offset))
15180         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15181       FIELD_BITSIZE (*fp) = 0;
15182       FIELD_TYPE (*fp) = die_type (die, cu);
15183       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15184       fip->nbaseclasses++;
15185     }
15186 }
15187
15188 /* Can the type given by DIE define another type?  */
15189
15190 static bool
15191 type_can_define_types (const struct die_info *die)
15192 {
15193   switch (die->tag)
15194     {
15195     case DW_TAG_typedef:
15196     case DW_TAG_class_type:
15197     case DW_TAG_structure_type:
15198     case DW_TAG_union_type:
15199     case DW_TAG_enumeration_type:
15200       return true;
15201
15202     default:
15203       return false;
15204     }
15205 }
15206
15207 /* Add a type definition defined in the scope of the FIP's class.  */
15208
15209 static void
15210 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15211                       struct dwarf2_cu *cu)
15212 {
15213   struct decl_field_list *new_field;
15214   struct decl_field *fp;
15215
15216   /* Allocate a new field list entry and link it in.  */
15217   new_field = XCNEW (struct decl_field_list);
15218   make_cleanup (xfree, new_field);
15219
15220   gdb_assert (type_can_define_types (die));
15221
15222   fp = &new_field->field;
15223
15224   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15225   fp->name = dwarf2_name (die, cu);
15226   fp->type = read_type_die (die, cu);
15227
15228   /* Save accessibility.  */
15229   enum dwarf_access_attribute accessibility;
15230   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15231   if (attr != NULL)
15232     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15233   else
15234     accessibility = dwarf2_default_access_attribute (die, cu);
15235   switch (accessibility)
15236     {
15237     case DW_ACCESS_public:
15238       /* The assumed value if neither private nor protected.  */
15239       break;
15240     case DW_ACCESS_private:
15241       fp->is_private = 1;
15242       break;
15243     case DW_ACCESS_protected:
15244       fp->is_protected = 1;
15245       break;
15246     default:
15247       complaint (&symfile_complaints,
15248                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15249     }
15250
15251   if (die->tag == DW_TAG_typedef)
15252     {
15253       new_field->next = fip->typedef_field_list;
15254       fip->typedef_field_list = new_field;
15255       fip->typedef_field_list_count++;
15256     }
15257   else
15258     {
15259       new_field->next = fip->nested_types_list;
15260       fip->nested_types_list = new_field;
15261       fip->nested_types_list_count++;
15262     }
15263 }
15264
15265 /* Create the vector of fields, and attach it to the type.  */
15266
15267 static void
15268 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15269                               struct dwarf2_cu *cu)
15270 {
15271   int nfields = fip->nfields;
15272
15273   /* Record the field count, allocate space for the array of fields,
15274      and create blank accessibility bitfields if necessary.  */
15275   TYPE_NFIELDS (type) = nfields;
15276   TYPE_FIELDS (type) = (struct field *)
15277     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15278   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15279
15280   if (fip->non_public_fields && cu->language != language_ada)
15281     {
15282       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15283
15284       TYPE_FIELD_PRIVATE_BITS (type) =
15285         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15286       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15287
15288       TYPE_FIELD_PROTECTED_BITS (type) =
15289         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15290       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15291
15292       TYPE_FIELD_IGNORE_BITS (type) =
15293         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15294       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15295     }
15296
15297   /* If the type has baseclasses, allocate and clear a bit vector for
15298      TYPE_FIELD_VIRTUAL_BITS.  */
15299   if (fip->nbaseclasses && cu->language != language_ada)
15300     {
15301       int num_bytes = B_BYTES (fip->nbaseclasses);
15302       unsigned char *pointer;
15303
15304       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15305       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15306       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15307       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15308       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15309     }
15310
15311   /* Copy the saved-up fields into the field vector.  Start from the head of
15312      the list, adding to the tail of the field array, so that they end up in
15313      the same order in the array in which they were added to the list.  */
15314   while (nfields-- > 0)
15315     {
15316       struct nextfield *fieldp;
15317
15318       if (fip->fields)
15319         {
15320           fieldp = fip->fields;
15321           fip->fields = fieldp->next;
15322         }
15323       else
15324         {
15325           fieldp = fip->baseclasses;
15326           fip->baseclasses = fieldp->next;
15327         }
15328
15329       TYPE_FIELD (type, nfields) = fieldp->field;
15330       switch (fieldp->accessibility)
15331         {
15332         case DW_ACCESS_private:
15333           if (cu->language != language_ada)
15334             SET_TYPE_FIELD_PRIVATE (type, nfields);
15335           break;
15336
15337         case DW_ACCESS_protected:
15338           if (cu->language != language_ada)
15339             SET_TYPE_FIELD_PROTECTED (type, nfields);
15340           break;
15341
15342         case DW_ACCESS_public:
15343           break;
15344
15345         default:
15346           /* Unknown accessibility.  Complain and treat it as public.  */
15347           {
15348             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15349                        fieldp->accessibility);
15350           }
15351           break;
15352         }
15353       if (nfields < fip->nbaseclasses)
15354         {
15355           switch (fieldp->virtuality)
15356             {
15357             case DW_VIRTUALITY_virtual:
15358             case DW_VIRTUALITY_pure_virtual:
15359               if (cu->language == language_ada)
15360                 error (_("unexpected virtuality in component of Ada type"));
15361               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15362               break;
15363             }
15364         }
15365     }
15366 }
15367
15368 /* Return true if this member function is a constructor, false
15369    otherwise.  */
15370
15371 static int
15372 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15373 {
15374   const char *fieldname;
15375   const char *type_name;
15376   int len;
15377
15378   if (die->parent == NULL)
15379     return 0;
15380
15381   if (die->parent->tag != DW_TAG_structure_type
15382       && die->parent->tag != DW_TAG_union_type
15383       && die->parent->tag != DW_TAG_class_type)
15384     return 0;
15385
15386   fieldname = dwarf2_name (die, cu);
15387   type_name = dwarf2_name (die->parent, cu);
15388   if (fieldname == NULL || type_name == NULL)
15389     return 0;
15390
15391   len = strlen (fieldname);
15392   return (strncmp (fieldname, type_name, len) == 0
15393           && (type_name[len] == '\0' || type_name[len] == '<'));
15394 }
15395
15396 /* Add a member function to the proper fieldlist.  */
15397
15398 static void
15399 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15400                       struct type *type, struct dwarf2_cu *cu)
15401 {
15402   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15403   struct attribute *attr;
15404   struct fnfieldlist *flp;
15405   int i;
15406   struct fn_field *fnp;
15407   const char *fieldname;
15408   struct nextfnfield *new_fnfield;
15409   struct type *this_type;
15410   enum dwarf_access_attribute accessibility;
15411
15412   if (cu->language == language_ada)
15413     error (_("unexpected member function in Ada type"));
15414
15415   /* Get name of member function.  */
15416   fieldname = dwarf2_name (die, cu);
15417   if (fieldname == NULL)
15418     return;
15419
15420   /* Look up member function name in fieldlist.  */
15421   for (i = 0; i < fip->nfnfields; i++)
15422     {
15423       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15424         break;
15425     }
15426
15427   /* Create new list element if necessary.  */
15428   if (i < fip->nfnfields)
15429     flp = &fip->fnfieldlists[i];
15430   else
15431     {
15432       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15433         {
15434           fip->fnfieldlists = (struct fnfieldlist *)
15435             xrealloc (fip->fnfieldlists,
15436                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15437                       * sizeof (struct fnfieldlist));
15438           if (fip->nfnfields == 0)
15439             make_cleanup (free_current_contents, &fip->fnfieldlists);
15440         }
15441       flp = &fip->fnfieldlists[fip->nfnfields];
15442       flp->name = fieldname;
15443       flp->length = 0;
15444       flp->head = NULL;
15445       i = fip->nfnfields++;
15446     }
15447
15448   /* Create a new member function field and chain it to the field list
15449      entry.  */
15450   new_fnfield = XNEW (struct nextfnfield);
15451   make_cleanup (xfree, new_fnfield);
15452   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15453   new_fnfield->next = flp->head;
15454   flp->head = new_fnfield;
15455   flp->length++;
15456
15457   /* Fill in the member function field info.  */
15458   fnp = &new_fnfield->fnfield;
15459
15460   /* Delay processing of the physname until later.  */
15461   if (cu->language == language_cplus)
15462     {
15463       add_to_method_list (type, i, flp->length - 1, fieldname,
15464                           die, cu);
15465     }
15466   else
15467     {
15468       const char *physname = dwarf2_physname (fieldname, die, cu);
15469       fnp->physname = physname ? physname : "";
15470     }
15471
15472   fnp->type = alloc_type (objfile);
15473   this_type = read_type_die (die, cu);
15474   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15475     {
15476       int nparams = TYPE_NFIELDS (this_type);
15477
15478       /* TYPE is the domain of this method, and THIS_TYPE is the type
15479            of the method itself (TYPE_CODE_METHOD).  */
15480       smash_to_method_type (fnp->type, type,
15481                             TYPE_TARGET_TYPE (this_type),
15482                             TYPE_FIELDS (this_type),
15483                             TYPE_NFIELDS (this_type),
15484                             TYPE_VARARGS (this_type));
15485
15486       /* Handle static member functions.
15487          Dwarf2 has no clean way to discern C++ static and non-static
15488          member functions.  G++ helps GDB by marking the first
15489          parameter for non-static member functions (which is the this
15490          pointer) as artificial.  We obtain this information from
15491          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15492       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15493         fnp->voffset = VOFFSET_STATIC;
15494     }
15495   else
15496     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15497                dwarf2_full_name (fieldname, die, cu));
15498
15499   /* Get fcontext from DW_AT_containing_type if present.  */
15500   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15501     fnp->fcontext = die_containing_type (die, cu);
15502
15503   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15504      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15505
15506   /* Get accessibility.  */
15507   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15508   if (attr)
15509     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15510   else
15511     accessibility = dwarf2_default_access_attribute (die, cu);
15512   switch (accessibility)
15513     {
15514     case DW_ACCESS_private:
15515       fnp->is_private = 1;
15516       break;
15517     case DW_ACCESS_protected:
15518       fnp->is_protected = 1;
15519       break;
15520     }
15521
15522   /* Check for artificial methods.  */
15523   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15524   if (attr && DW_UNSND (attr) != 0)
15525     fnp->is_artificial = 1;
15526
15527   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15528
15529   /* Get index in virtual function table if it is a virtual member
15530      function.  For older versions of GCC, this is an offset in the
15531      appropriate virtual table, as specified by DW_AT_containing_type.
15532      For everyone else, it is an expression to be evaluated relative
15533      to the object address.  */
15534
15535   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15536   if (attr)
15537     {
15538       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15539         {
15540           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15541             {
15542               /* Old-style GCC.  */
15543               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15544             }
15545           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15546                    || (DW_BLOCK (attr)->size > 1
15547                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15548                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15549             {
15550               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15551               if ((fnp->voffset % cu->header.addr_size) != 0)
15552                 dwarf2_complex_location_expr_complaint ();
15553               else
15554                 fnp->voffset /= cu->header.addr_size;
15555               fnp->voffset += 2;
15556             }
15557           else
15558             dwarf2_complex_location_expr_complaint ();
15559
15560           if (!fnp->fcontext)
15561             {
15562               /* If there is no `this' field and no DW_AT_containing_type,
15563                  we cannot actually find a base class context for the
15564                  vtable!  */
15565               if (TYPE_NFIELDS (this_type) == 0
15566                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15567                 {
15568                   complaint (&symfile_complaints,
15569                              _("cannot determine context for virtual member "
15570                                "function \"%s\" (offset %d)"),
15571                              fieldname, to_underlying (die->sect_off));
15572                 }
15573               else
15574                 {
15575                   fnp->fcontext
15576                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15577                 }
15578             }
15579         }
15580       else if (attr_form_is_section_offset (attr))
15581         {
15582           dwarf2_complex_location_expr_complaint ();
15583         }
15584       else
15585         {
15586           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15587                                                  fieldname);
15588         }
15589     }
15590   else
15591     {
15592       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15593       if (attr && DW_UNSND (attr))
15594         {
15595           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15596           complaint (&symfile_complaints,
15597                      _("Member function \"%s\" (offset %d) is virtual "
15598                        "but the vtable offset is not specified"),
15599                      fieldname, to_underlying (die->sect_off));
15600           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15601           TYPE_CPLUS_DYNAMIC (type) = 1;
15602         }
15603     }
15604 }
15605
15606 /* Create the vector of member function fields, and attach it to the type.  */
15607
15608 static void
15609 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15610                                  struct dwarf2_cu *cu)
15611 {
15612   struct fnfieldlist *flp;
15613   int i;
15614
15615   if (cu->language == language_ada)
15616     error (_("unexpected member functions in Ada type"));
15617
15618   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15619   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15620     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15621
15622   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15623     {
15624       struct nextfnfield *nfp = flp->head;
15625       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15626       int k;
15627
15628       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15629       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15630       fn_flp->fn_fields = (struct fn_field *)
15631         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15632       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15633         fn_flp->fn_fields[k] = nfp->fnfield;
15634     }
15635
15636   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15637 }
15638
15639 /* Returns non-zero if NAME is the name of a vtable member in CU's
15640    language, zero otherwise.  */
15641 static int
15642 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15643 {
15644   static const char vptr[] = "_vptr";
15645
15646   /* Look for the C++ form of the vtable.  */
15647   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15648     return 1;
15649
15650   return 0;
15651 }
15652
15653 /* GCC outputs unnamed structures that are really pointers to member
15654    functions, with the ABI-specified layout.  If TYPE describes
15655    such a structure, smash it into a member function type.
15656
15657    GCC shouldn't do this; it should just output pointer to member DIEs.
15658    This is GCC PR debug/28767.  */
15659
15660 static void
15661 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15662 {
15663   struct type *pfn_type, *self_type, *new_type;
15664
15665   /* Check for a structure with no name and two children.  */
15666   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15667     return;
15668
15669   /* Check for __pfn and __delta members.  */
15670   if (TYPE_FIELD_NAME (type, 0) == NULL
15671       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15672       || TYPE_FIELD_NAME (type, 1) == NULL
15673       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15674     return;
15675
15676   /* Find the type of the method.  */
15677   pfn_type = TYPE_FIELD_TYPE (type, 0);
15678   if (pfn_type == NULL
15679       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15680       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15681     return;
15682
15683   /* Look for the "this" argument.  */
15684   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15685   if (TYPE_NFIELDS (pfn_type) == 0
15686       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15687       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15688     return;
15689
15690   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15691   new_type = alloc_type (objfile);
15692   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15693                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15694                         TYPE_VARARGS (pfn_type));
15695   smash_to_methodptr_type (type, new_type);
15696 }
15697
15698
15699 /* Called when we find the DIE that starts a structure or union scope
15700    (definition) to create a type for the structure or union.  Fill in
15701    the type's name and general properties; the members will not be
15702    processed until process_structure_scope.  A symbol table entry for
15703    the type will also not be done until process_structure_scope (assuming
15704    the type has a name).
15705
15706    NOTE: we need to call these functions regardless of whether or not the
15707    DIE has a DW_AT_name attribute, since it might be an anonymous
15708    structure or union.  This gets the type entered into our set of
15709    user defined types.  */
15710
15711 static struct type *
15712 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15713 {
15714   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15715   struct type *type;
15716   struct attribute *attr;
15717   const char *name;
15718
15719   /* If the definition of this type lives in .debug_types, read that type.
15720      Don't follow DW_AT_specification though, that will take us back up
15721      the chain and we want to go down.  */
15722   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15723   if (attr)
15724     {
15725       type = get_DW_AT_signature_type (die, attr, cu);
15726
15727       /* The type's CU may not be the same as CU.
15728          Ensure TYPE is recorded with CU in die_type_hash.  */
15729       return set_die_type (die, type, cu);
15730     }
15731
15732   type = alloc_type (objfile);
15733   INIT_CPLUS_SPECIFIC (type);
15734
15735   name = dwarf2_name (die, cu);
15736   if (name != NULL)
15737     {
15738       if (cu->language == language_cplus
15739           || cu->language == language_d
15740           || cu->language == language_rust)
15741         {
15742           const char *full_name = dwarf2_full_name (name, die, cu);
15743
15744           /* dwarf2_full_name might have already finished building the DIE's
15745              type.  If so, there is no need to continue.  */
15746           if (get_die_type (die, cu) != NULL)
15747             return get_die_type (die, cu);
15748
15749           TYPE_TAG_NAME (type) = full_name;
15750           if (die->tag == DW_TAG_structure_type
15751               || die->tag == DW_TAG_class_type)
15752             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15753         }
15754       else
15755         {
15756           /* The name is already allocated along with this objfile, so
15757              we don't need to duplicate it for the type.  */
15758           TYPE_TAG_NAME (type) = name;
15759           if (die->tag == DW_TAG_class_type)
15760             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15761         }
15762     }
15763
15764   if (die->tag == DW_TAG_structure_type)
15765     {
15766       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15767     }
15768   else if (die->tag == DW_TAG_union_type)
15769     {
15770       TYPE_CODE (type) = TYPE_CODE_UNION;
15771     }
15772   else
15773     {
15774       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15775     }
15776
15777   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15778     TYPE_DECLARED_CLASS (type) = 1;
15779
15780   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15781   if (attr)
15782     {
15783       if (attr_form_is_constant (attr))
15784         TYPE_LENGTH (type) = DW_UNSND (attr);
15785       else
15786         {
15787           /* For the moment, dynamic type sizes are not supported
15788              by GDB's struct type.  The actual size is determined
15789              on-demand when resolving the type of a given object,
15790              so set the type's length to zero for now.  Otherwise,
15791              we record an expression as the length, and that expression
15792              could lead to a very large value, which could eventually
15793              lead to us trying to allocate that much memory when creating
15794              a value of that type.  */
15795           TYPE_LENGTH (type) = 0;
15796         }
15797     }
15798   else
15799     {
15800       TYPE_LENGTH (type) = 0;
15801     }
15802
15803   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15804     {
15805       /* ICC<14 does not output the required DW_AT_declaration on
15806          incomplete types, but gives them a size of zero.  */
15807       TYPE_STUB (type) = 1;
15808     }
15809   else
15810     TYPE_STUB_SUPPORTED (type) = 1;
15811
15812   if (die_is_declaration (die, cu))
15813     TYPE_STUB (type) = 1;
15814   else if (attr == NULL && die->child == NULL
15815            && producer_is_realview (cu->producer))
15816     /* RealView does not output the required DW_AT_declaration
15817        on incomplete types.  */
15818     TYPE_STUB (type) = 1;
15819
15820   /* We need to add the type field to the die immediately so we don't
15821      infinitely recurse when dealing with pointers to the structure
15822      type within the structure itself.  */
15823   set_die_type (die, type, cu);
15824
15825   /* set_die_type should be already done.  */
15826   set_descriptive_type (type, die, cu);
15827
15828   return type;
15829 }
15830
15831 /* Finish creating a structure or union type, including filling in
15832    its members and creating a symbol for it.  */
15833
15834 static void
15835 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15836 {
15837   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15838   struct die_info *child_die;
15839   struct type *type;
15840
15841   type = get_die_type (die, cu);
15842   if (type == NULL)
15843     type = read_structure_type (die, cu);
15844
15845   if (die->child != NULL && ! die_is_declaration (die, cu))
15846     {
15847       struct field_info fi;
15848       std::vector<struct symbol *> template_args;
15849       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15850
15851       memset (&fi, 0, sizeof (struct field_info));
15852
15853       child_die = die->child;
15854
15855       while (child_die && child_die->tag)
15856         {
15857           if (child_die->tag == DW_TAG_member
15858               || child_die->tag == DW_TAG_variable)
15859             {
15860               /* NOTE: carlton/2002-11-05: A C++ static data member
15861                  should be a DW_TAG_member that is a declaration, but
15862                  all versions of G++ as of this writing (so through at
15863                  least 3.2.1) incorrectly generate DW_TAG_variable
15864                  tags for them instead.  */
15865               dwarf2_add_field (&fi, child_die, cu);
15866             }
15867           else if (child_die->tag == DW_TAG_subprogram)
15868             {
15869               /* Rust doesn't have member functions in the C++ sense.
15870                  However, it does emit ordinary functions as children
15871                  of a struct DIE.  */
15872               if (cu->language == language_rust)
15873                 read_func_scope (child_die, cu);
15874               else
15875                 {
15876                   /* C++ member function.  */
15877                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15878                 }
15879             }
15880           else if (child_die->tag == DW_TAG_inheritance)
15881             {
15882               /* C++ base class field.  */
15883               dwarf2_add_field (&fi, child_die, cu);
15884             }
15885           else if (type_can_define_types (child_die))
15886             dwarf2_add_type_defn (&fi, child_die, cu);
15887           else if (child_die->tag == DW_TAG_template_type_param
15888                    || child_die->tag == DW_TAG_template_value_param)
15889             {
15890               struct symbol *arg = new_symbol (child_die, NULL, cu);
15891
15892               if (arg != NULL)
15893                 template_args.push_back (arg);
15894             }
15895
15896           child_die = sibling_die (child_die);
15897         }
15898
15899       /* Attach template arguments to type.  */
15900       if (!template_args.empty ())
15901         {
15902           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15903           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15904           TYPE_TEMPLATE_ARGUMENTS (type)
15905             = XOBNEWVEC (&objfile->objfile_obstack,
15906                          struct symbol *,
15907                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15908           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15909                   template_args.data (),
15910                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15911                    * sizeof (struct symbol *)));
15912         }
15913
15914       /* Attach fields and member functions to the type.  */
15915       if (fi.nfields)
15916         dwarf2_attach_fields_to_type (&fi, type, cu);
15917       if (fi.nfnfields)
15918         {
15919           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15920
15921           /* Get the type which refers to the base class (possibly this
15922              class itself) which contains the vtable pointer for the current
15923              class from the DW_AT_containing_type attribute.  This use of
15924              DW_AT_containing_type is a GNU extension.  */
15925
15926           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15927             {
15928               struct type *t = die_containing_type (die, cu);
15929
15930               set_type_vptr_basetype (type, t);
15931               if (type == t)
15932                 {
15933                   int i;
15934
15935                   /* Our own class provides vtbl ptr.  */
15936                   for (i = TYPE_NFIELDS (t) - 1;
15937                        i >= TYPE_N_BASECLASSES (t);
15938                        --i)
15939                     {
15940                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15941
15942                       if (is_vtable_name (fieldname, cu))
15943                         {
15944                           set_type_vptr_fieldno (type, i);
15945                           break;
15946                         }
15947                     }
15948
15949                   /* Complain if virtual function table field not found.  */
15950                   if (i < TYPE_N_BASECLASSES (t))
15951                     complaint (&symfile_complaints,
15952                                _("virtual function table pointer "
15953                                  "not found when defining class '%s'"),
15954                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
15955                                "");
15956                 }
15957               else
15958                 {
15959                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15960                 }
15961             }
15962           else if (cu->producer
15963                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15964             {
15965               /* The IBM XLC compiler does not provide direct indication
15966                  of the containing type, but the vtable pointer is
15967                  always named __vfp.  */
15968
15969               int i;
15970
15971               for (i = TYPE_NFIELDS (type) - 1;
15972                    i >= TYPE_N_BASECLASSES (type);
15973                    --i)
15974                 {
15975                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15976                     {
15977                       set_type_vptr_fieldno (type, i);
15978                       set_type_vptr_basetype (type, type);
15979                       break;
15980                     }
15981                 }
15982             }
15983         }
15984
15985       /* Copy fi.typedef_field_list linked list elements content into the
15986          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15987       if (fi.typedef_field_list)
15988         {
15989           int i = fi.typedef_field_list_count;
15990
15991           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15992           TYPE_TYPEDEF_FIELD_ARRAY (type)
15993             = ((struct decl_field *)
15994                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
15995           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
15996
15997           /* Reverse the list order to keep the debug info elements order.  */
15998           while (--i >= 0)
15999             {
16000               struct decl_field *dest, *src;
16001
16002               dest = &TYPE_TYPEDEF_FIELD (type, i);
16003               src = &fi.typedef_field_list->field;
16004               fi.typedef_field_list = fi.typedef_field_list->next;
16005               *dest = *src;
16006             }
16007         }
16008
16009       /* Copy fi.nested_types_list linked list elements content into the
16010          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16011       if (fi.nested_types_list != NULL && cu->language != language_ada)
16012         {
16013           int i = fi.nested_types_list_count;
16014
16015           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16016           TYPE_NESTED_TYPES_ARRAY (type)
16017             = ((struct decl_field *)
16018                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16019           TYPE_NESTED_TYPES_COUNT (type) = i;
16020
16021           /* Reverse the list order to keep the debug info elements order.  */
16022           while (--i >= 0)
16023             {
16024               struct decl_field *dest, *src;
16025
16026               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16027               src = &fi.nested_types_list->field;
16028               fi.nested_types_list = fi.nested_types_list->next;
16029               *dest = *src;
16030             }
16031         }
16032
16033       do_cleanups (back_to);
16034     }
16035
16036   quirk_gcc_member_function_pointer (type, objfile);
16037
16038   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16039      snapshots) has been known to create a die giving a declaration
16040      for a class that has, as a child, a die giving a definition for a
16041      nested class.  So we have to process our children even if the
16042      current die is a declaration.  Normally, of course, a declaration
16043      won't have any children at all.  */
16044
16045   child_die = die->child;
16046
16047   while (child_die != NULL && child_die->tag)
16048     {
16049       if (child_die->tag == DW_TAG_member
16050           || child_die->tag == DW_TAG_variable
16051           || child_die->tag == DW_TAG_inheritance
16052           || child_die->tag == DW_TAG_template_value_param
16053           || child_die->tag == DW_TAG_template_type_param)
16054         {
16055           /* Do nothing.  */
16056         }
16057       else
16058         process_die (child_die, cu);
16059
16060       child_die = sibling_die (child_die);
16061     }
16062
16063   /* Do not consider external references.  According to the DWARF standard,
16064      these DIEs are identified by the fact that they have no byte_size
16065      attribute, and a declaration attribute.  */
16066   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16067       || !die_is_declaration (die, cu))
16068     new_symbol (die, type, cu);
16069 }
16070
16071 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16072    update TYPE using some information only available in DIE's children.  */
16073
16074 static void
16075 update_enumeration_type_from_children (struct die_info *die,
16076                                        struct type *type,
16077                                        struct dwarf2_cu *cu)
16078 {
16079   struct die_info *child_die;
16080   int unsigned_enum = 1;
16081   int flag_enum = 1;
16082   ULONGEST mask = 0;
16083
16084   auto_obstack obstack;
16085
16086   for (child_die = die->child;
16087        child_die != NULL && child_die->tag;
16088        child_die = sibling_die (child_die))
16089     {
16090       struct attribute *attr;
16091       LONGEST value;
16092       const gdb_byte *bytes;
16093       struct dwarf2_locexpr_baton *baton;
16094       const char *name;
16095
16096       if (child_die->tag != DW_TAG_enumerator)
16097         continue;
16098
16099       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16100       if (attr == NULL)
16101         continue;
16102
16103       name = dwarf2_name (child_die, cu);
16104       if (name == NULL)
16105         name = "<anonymous enumerator>";
16106
16107       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16108                                &value, &bytes, &baton);
16109       if (value < 0)
16110         {
16111           unsigned_enum = 0;
16112           flag_enum = 0;
16113         }
16114       else if ((mask & value) != 0)
16115         flag_enum = 0;
16116       else
16117         mask |= value;
16118
16119       /* If we already know that the enum type is neither unsigned, nor
16120          a flag type, no need to look at the rest of the enumerates.  */
16121       if (!unsigned_enum && !flag_enum)
16122         break;
16123     }
16124
16125   if (unsigned_enum)
16126     TYPE_UNSIGNED (type) = 1;
16127   if (flag_enum)
16128     TYPE_FLAG_ENUM (type) = 1;
16129 }
16130
16131 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16132    complete the type's fields yet, or create any symbols.  */
16133
16134 static struct type *
16135 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16136 {
16137   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16138   struct type *type;
16139   struct attribute *attr;
16140   const char *name;
16141
16142   /* If the definition of this type lives in .debug_types, read that type.
16143      Don't follow DW_AT_specification though, that will take us back up
16144      the chain and we want to go down.  */
16145   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16146   if (attr)
16147     {
16148       type = get_DW_AT_signature_type (die, attr, cu);
16149
16150       /* The type's CU may not be the same as CU.
16151          Ensure TYPE is recorded with CU in die_type_hash.  */
16152       return set_die_type (die, type, cu);
16153     }
16154
16155   type = alloc_type (objfile);
16156
16157   TYPE_CODE (type) = TYPE_CODE_ENUM;
16158   name = dwarf2_full_name (NULL, die, cu);
16159   if (name != NULL)
16160     TYPE_TAG_NAME (type) = name;
16161
16162   attr = dwarf2_attr (die, DW_AT_type, cu);
16163   if (attr != NULL)
16164     {
16165       struct type *underlying_type = die_type (die, cu);
16166
16167       TYPE_TARGET_TYPE (type) = underlying_type;
16168     }
16169
16170   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16171   if (attr)
16172     {
16173       TYPE_LENGTH (type) = DW_UNSND (attr);
16174     }
16175   else
16176     {
16177       TYPE_LENGTH (type) = 0;
16178     }
16179
16180   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16181      declared as private in the package spec, and then defined only
16182      inside the package body.  Such types are known as Taft Amendment
16183      Types.  When another package uses such a type, an incomplete DIE
16184      may be generated by the compiler.  */
16185   if (die_is_declaration (die, cu))
16186     TYPE_STUB (type) = 1;
16187
16188   /* Finish the creation of this type by using the enum's children.
16189      We must call this even when the underlying type has been provided
16190      so that we can determine if we're looking at a "flag" enum.  */
16191   update_enumeration_type_from_children (die, type, cu);
16192
16193   /* If this type has an underlying type that is not a stub, then we
16194      may use its attributes.  We always use the "unsigned" attribute
16195      in this situation, because ordinarily we guess whether the type
16196      is unsigned -- but the guess can be wrong and the underlying type
16197      can tell us the reality.  However, we defer to a local size
16198      attribute if one exists, because this lets the compiler override
16199      the underlying type if needed.  */
16200   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16201     {
16202       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16203       if (TYPE_LENGTH (type) == 0)
16204         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16205     }
16206
16207   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16208
16209   return set_die_type (die, type, cu);
16210 }
16211
16212 /* Given a pointer to a die which begins an enumeration, process all
16213    the dies that define the members of the enumeration, and create the
16214    symbol for the enumeration type.
16215
16216    NOTE: We reverse the order of the element list.  */
16217
16218 static void
16219 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16220 {
16221   struct type *this_type;
16222
16223   this_type = get_die_type (die, cu);
16224   if (this_type == NULL)
16225     this_type = read_enumeration_type (die, cu);
16226
16227   if (die->child != NULL)
16228     {
16229       struct die_info *child_die;
16230       struct symbol *sym;
16231       struct field *fields = NULL;
16232       int num_fields = 0;
16233       const char *name;
16234
16235       child_die = die->child;
16236       while (child_die && child_die->tag)
16237         {
16238           if (child_die->tag != DW_TAG_enumerator)
16239             {
16240               process_die (child_die, cu);
16241             }
16242           else
16243             {
16244               name = dwarf2_name (child_die, cu);
16245               if (name)
16246                 {
16247                   sym = new_symbol (child_die, this_type, cu);
16248
16249                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16250                     {
16251                       fields = (struct field *)
16252                         xrealloc (fields,
16253                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16254                                   * sizeof (struct field));
16255                     }
16256
16257                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16258                   FIELD_TYPE (fields[num_fields]) = NULL;
16259                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16260                   FIELD_BITSIZE (fields[num_fields]) = 0;
16261
16262                   num_fields++;
16263                 }
16264             }
16265
16266           child_die = sibling_die (child_die);
16267         }
16268
16269       if (num_fields)
16270         {
16271           TYPE_NFIELDS (this_type) = num_fields;
16272           TYPE_FIELDS (this_type) = (struct field *)
16273             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16274           memcpy (TYPE_FIELDS (this_type), fields,
16275                   sizeof (struct field) * num_fields);
16276           xfree (fields);
16277         }
16278     }
16279
16280   /* If we are reading an enum from a .debug_types unit, and the enum
16281      is a declaration, and the enum is not the signatured type in the
16282      unit, then we do not want to add a symbol for it.  Adding a
16283      symbol would in some cases obscure the true definition of the
16284      enum, giving users an incomplete type when the definition is
16285      actually available.  Note that we do not want to do this for all
16286      enums which are just declarations, because C++0x allows forward
16287      enum declarations.  */
16288   if (cu->per_cu->is_debug_types
16289       && die_is_declaration (die, cu))
16290     {
16291       struct signatured_type *sig_type;
16292
16293       sig_type = (struct signatured_type *) cu->per_cu;
16294       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16295       if (sig_type->type_offset_in_section != die->sect_off)
16296         return;
16297     }
16298
16299   new_symbol (die, this_type, cu);
16300 }
16301
16302 /* Extract all information from a DW_TAG_array_type DIE and put it in
16303    the DIE's type field.  For now, this only handles one dimensional
16304    arrays.  */
16305
16306 static struct type *
16307 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16308 {
16309   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16310   struct die_info *child_die;
16311   struct type *type;
16312   struct type *element_type, *range_type, *index_type;
16313   struct attribute *attr;
16314   const char *name;
16315   struct dynamic_prop *byte_stride_prop = NULL;
16316   unsigned int bit_stride = 0;
16317
16318   element_type = die_type (die, cu);
16319
16320   /* The die_type call above may have already set the type for this DIE.  */
16321   type = get_die_type (die, cu);
16322   if (type)
16323     return type;
16324
16325   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16326   if (attr != NULL)
16327     {
16328       int stride_ok;
16329
16330       byte_stride_prop
16331         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16332       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16333       if (!stride_ok)
16334         {
16335           complaint (&symfile_complaints,
16336                      _("unable to read array DW_AT_byte_stride "
16337                        " - DIE at 0x%x [in module %s]"),
16338                      to_underlying (die->sect_off),
16339                      objfile_name (cu->dwarf2_per_objfile->objfile));
16340           /* Ignore this attribute.  We will likely not be able to print
16341              arrays of this type correctly, but there is little we can do
16342              to help if we cannot read the attribute's value.  */
16343           byte_stride_prop = NULL;
16344         }
16345     }
16346
16347   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16348   if (attr != NULL)
16349     bit_stride = DW_UNSND (attr);
16350
16351   /* Irix 6.2 native cc creates array types without children for
16352      arrays with unspecified length.  */
16353   if (die->child == NULL)
16354     {
16355       index_type = objfile_type (objfile)->builtin_int;
16356       range_type = create_static_range_type (NULL, index_type, 0, -1);
16357       type = create_array_type_with_stride (NULL, element_type, range_type,
16358                                             byte_stride_prop, bit_stride);
16359       return set_die_type (die, type, cu);
16360     }
16361
16362   std::vector<struct type *> range_types;
16363   child_die = die->child;
16364   while (child_die && child_die->tag)
16365     {
16366       if (child_die->tag == DW_TAG_subrange_type)
16367         {
16368           struct type *child_type = read_type_die (child_die, cu);
16369
16370           if (child_type != NULL)
16371             {
16372               /* The range type was succesfully read.  Save it for the
16373                  array type creation.  */
16374               range_types.push_back (child_type);
16375             }
16376         }
16377       child_die = sibling_die (child_die);
16378     }
16379
16380   /* Dwarf2 dimensions are output from left to right, create the
16381      necessary array types in backwards order.  */
16382
16383   type = element_type;
16384
16385   if (read_array_order (die, cu) == DW_ORD_col_major)
16386     {
16387       int i = 0;
16388
16389       while (i < range_types.size ())
16390         type = create_array_type_with_stride (NULL, type, range_types[i++],
16391                                               byte_stride_prop, bit_stride);
16392     }
16393   else
16394     {
16395       size_t ndim = range_types.size ();
16396       while (ndim-- > 0)
16397         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16398                                               byte_stride_prop, bit_stride);
16399     }
16400
16401   /* Understand Dwarf2 support for vector types (like they occur on
16402      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16403      array type.  This is not part of the Dwarf2/3 standard yet, but a
16404      custom vendor extension.  The main difference between a regular
16405      array and the vector variant is that vectors are passed by value
16406      to functions.  */
16407   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16408   if (attr)
16409     make_vector_type (type);
16410
16411   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16412      implementation may choose to implement triple vectors using this
16413      attribute.  */
16414   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16415   if (attr)
16416     {
16417       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16418         TYPE_LENGTH (type) = DW_UNSND (attr);
16419       else
16420         complaint (&symfile_complaints,
16421                    _("DW_AT_byte_size for array type smaller "
16422                      "than the total size of elements"));
16423     }
16424
16425   name = dwarf2_name (die, cu);
16426   if (name)
16427     TYPE_NAME (type) = name;
16428
16429   /* Install the type in the die.  */
16430   set_die_type (die, type, cu);
16431
16432   /* set_die_type should be already done.  */
16433   set_descriptive_type (type, die, cu);
16434
16435   return type;
16436 }
16437
16438 static enum dwarf_array_dim_ordering
16439 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16440 {
16441   struct attribute *attr;
16442
16443   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16444
16445   if (attr)
16446     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16447
16448   /* GNU F77 is a special case, as at 08/2004 array type info is the
16449      opposite order to the dwarf2 specification, but data is still
16450      laid out as per normal fortran.
16451
16452      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16453      version checking.  */
16454
16455   if (cu->language == language_fortran
16456       && cu->producer && strstr (cu->producer, "GNU F77"))
16457     {
16458       return DW_ORD_row_major;
16459     }
16460
16461   switch (cu->language_defn->la_array_ordering)
16462     {
16463     case array_column_major:
16464       return DW_ORD_col_major;
16465     case array_row_major:
16466     default:
16467       return DW_ORD_row_major;
16468     };
16469 }
16470
16471 /* Extract all information from a DW_TAG_set_type DIE and put it in
16472    the DIE's type field.  */
16473
16474 static struct type *
16475 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16476 {
16477   struct type *domain_type, *set_type;
16478   struct attribute *attr;
16479
16480   domain_type = die_type (die, cu);
16481
16482   /* The die_type call above may have already set the type for this DIE.  */
16483   set_type = get_die_type (die, cu);
16484   if (set_type)
16485     return set_type;
16486
16487   set_type = create_set_type (NULL, domain_type);
16488
16489   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16490   if (attr)
16491     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16492
16493   return set_die_type (die, set_type, cu);
16494 }
16495
16496 /* A helper for read_common_block that creates a locexpr baton.
16497    SYM is the symbol which we are marking as computed.
16498    COMMON_DIE is the DIE for the common block.
16499    COMMON_LOC is the location expression attribute for the common
16500    block itself.
16501    MEMBER_LOC is the location expression attribute for the particular
16502    member of the common block that we are processing.
16503    CU is the CU from which the above come.  */
16504
16505 static void
16506 mark_common_block_symbol_computed (struct symbol *sym,
16507                                    struct die_info *common_die,
16508                                    struct attribute *common_loc,
16509                                    struct attribute *member_loc,
16510                                    struct dwarf2_cu *cu)
16511 {
16512   struct objfile *objfile = dwarf2_per_objfile->objfile;
16513   struct dwarf2_locexpr_baton *baton;
16514   gdb_byte *ptr;
16515   unsigned int cu_off;
16516   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16517   LONGEST offset = 0;
16518
16519   gdb_assert (common_loc && member_loc);
16520   gdb_assert (attr_form_is_block (common_loc));
16521   gdb_assert (attr_form_is_block (member_loc)
16522               || attr_form_is_constant (member_loc));
16523
16524   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16525   baton->per_cu = cu->per_cu;
16526   gdb_assert (baton->per_cu);
16527
16528   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16529
16530   if (attr_form_is_constant (member_loc))
16531     {
16532       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16533       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16534     }
16535   else
16536     baton->size += DW_BLOCK (member_loc)->size;
16537
16538   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16539   baton->data = ptr;
16540
16541   *ptr++ = DW_OP_call4;
16542   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16543   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16544   ptr += 4;
16545
16546   if (attr_form_is_constant (member_loc))
16547     {
16548       *ptr++ = DW_OP_addr;
16549       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16550       ptr += cu->header.addr_size;
16551     }
16552   else
16553     {
16554       /* We have to copy the data here, because DW_OP_call4 will only
16555          use a DW_AT_location attribute.  */
16556       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16557       ptr += DW_BLOCK (member_loc)->size;
16558     }
16559
16560   *ptr++ = DW_OP_plus;
16561   gdb_assert (ptr - baton->data == baton->size);
16562
16563   SYMBOL_LOCATION_BATON (sym) = baton;
16564   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16565 }
16566
16567 /* Create appropriate locally-scoped variables for all the
16568    DW_TAG_common_block entries.  Also create a struct common_block
16569    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16570    is used to sepate the common blocks name namespace from regular
16571    variable names.  */
16572
16573 static void
16574 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16575 {
16576   struct attribute *attr;
16577
16578   attr = dwarf2_attr (die, DW_AT_location, cu);
16579   if (attr)
16580     {
16581       /* Support the .debug_loc offsets.  */
16582       if (attr_form_is_block (attr))
16583         {
16584           /* Ok.  */
16585         }
16586       else if (attr_form_is_section_offset (attr))
16587         {
16588           dwarf2_complex_location_expr_complaint ();
16589           attr = NULL;
16590         }
16591       else
16592         {
16593           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16594                                                  "common block member");
16595           attr = NULL;
16596         }
16597     }
16598
16599   if (die->child != NULL)
16600     {
16601       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16602       struct die_info *child_die;
16603       size_t n_entries = 0, size;
16604       struct common_block *common_block;
16605       struct symbol *sym;
16606
16607       for (child_die = die->child;
16608            child_die && child_die->tag;
16609            child_die = sibling_die (child_die))
16610         ++n_entries;
16611
16612       size = (sizeof (struct common_block)
16613               + (n_entries - 1) * sizeof (struct symbol *));
16614       common_block
16615         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16616                                                  size);
16617       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16618       common_block->n_entries = 0;
16619
16620       for (child_die = die->child;
16621            child_die && child_die->tag;
16622            child_die = sibling_die (child_die))
16623         {
16624           /* Create the symbol in the DW_TAG_common_block block in the current
16625              symbol scope.  */
16626           sym = new_symbol (child_die, NULL, cu);
16627           if (sym != NULL)
16628             {
16629               struct attribute *member_loc;
16630
16631               common_block->contents[common_block->n_entries++] = sym;
16632
16633               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16634                                         cu);
16635               if (member_loc)
16636                 {
16637                   /* GDB has handled this for a long time, but it is
16638                      not specified by DWARF.  It seems to have been
16639                      emitted by gfortran at least as recently as:
16640                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16641                   complaint (&symfile_complaints,
16642                              _("Variable in common block has "
16643                                "DW_AT_data_member_location "
16644                                "- DIE at 0x%x [in module %s]"),
16645                              to_underlying (child_die->sect_off),
16646                              objfile_name (cu->dwarf2_per_objfile->objfile));
16647
16648                   if (attr_form_is_section_offset (member_loc))
16649                     dwarf2_complex_location_expr_complaint ();
16650                   else if (attr_form_is_constant (member_loc)
16651                            || attr_form_is_block (member_loc))
16652                     {
16653                       if (attr)
16654                         mark_common_block_symbol_computed (sym, die, attr,
16655                                                            member_loc, cu);
16656                     }
16657                   else
16658                     dwarf2_complex_location_expr_complaint ();
16659                 }
16660             }
16661         }
16662
16663       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16664       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16665     }
16666 }
16667
16668 /* Create a type for a C++ namespace.  */
16669
16670 static struct type *
16671 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16672 {
16673   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16674   const char *previous_prefix, *name;
16675   int is_anonymous;
16676   struct type *type;
16677
16678   /* For extensions, reuse the type of the original namespace.  */
16679   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16680     {
16681       struct die_info *ext_die;
16682       struct dwarf2_cu *ext_cu = cu;
16683
16684       ext_die = dwarf2_extension (die, &ext_cu);
16685       type = read_type_die (ext_die, ext_cu);
16686
16687       /* EXT_CU may not be the same as CU.
16688          Ensure TYPE is recorded with CU in die_type_hash.  */
16689       return set_die_type (die, type, cu);
16690     }
16691
16692   name = namespace_name (die, &is_anonymous, cu);
16693
16694   /* Now build the name of the current namespace.  */
16695
16696   previous_prefix = determine_prefix (die, cu);
16697   if (previous_prefix[0] != '\0')
16698     name = typename_concat (&objfile->objfile_obstack,
16699                             previous_prefix, name, 0, cu);
16700
16701   /* Create the type.  */
16702   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16703   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16704
16705   return set_die_type (die, type, cu);
16706 }
16707
16708 /* Read a namespace scope.  */
16709
16710 static void
16711 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16712 {
16713   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16714   int is_anonymous;
16715
16716   /* Add a symbol associated to this if we haven't seen the namespace
16717      before.  Also, add a using directive if it's an anonymous
16718      namespace.  */
16719
16720   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16721     {
16722       struct type *type;
16723
16724       type = read_type_die (die, cu);
16725       new_symbol (die, type, cu);
16726
16727       namespace_name (die, &is_anonymous, cu);
16728       if (is_anonymous)
16729         {
16730           const char *previous_prefix = determine_prefix (die, cu);
16731
16732           std::vector<const char *> excludes;
16733           add_using_directive (using_directives (cu->language),
16734                                previous_prefix, TYPE_NAME (type), NULL,
16735                                NULL, excludes, 0, &objfile->objfile_obstack);
16736         }
16737     }
16738
16739   if (die->child != NULL)
16740     {
16741       struct die_info *child_die = die->child;
16742
16743       while (child_die && child_die->tag)
16744         {
16745           process_die (child_die, cu);
16746           child_die = sibling_die (child_die);
16747         }
16748     }
16749 }
16750
16751 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16752    imported module.  Still we need that type as local Fortran "use ... only"
16753    declaration imports depend on the created type in determine_prefix.  */
16754
16755 static struct type *
16756 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16757 {
16758   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16759   const char *module_name;
16760   struct type *type;
16761
16762   module_name = dwarf2_name (die, cu);
16763   if (!module_name)
16764     complaint (&symfile_complaints,
16765                _("DW_TAG_module has no name, offset 0x%x"),
16766                to_underlying (die->sect_off));
16767   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16768
16769   /* determine_prefix uses TYPE_TAG_NAME.  */
16770   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16771
16772   return set_die_type (die, type, cu);
16773 }
16774
16775 /* Read a Fortran module.  */
16776
16777 static void
16778 read_module (struct die_info *die, struct dwarf2_cu *cu)
16779 {
16780   struct die_info *child_die = die->child;
16781   struct type *type;
16782
16783   type = read_type_die (die, cu);
16784   new_symbol (die, type, cu);
16785
16786   while (child_die && child_die->tag)
16787     {
16788       process_die (child_die, cu);
16789       child_die = sibling_die (child_die);
16790     }
16791 }
16792
16793 /* Return the name of the namespace represented by DIE.  Set
16794    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16795    namespace.  */
16796
16797 static const char *
16798 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16799 {
16800   struct die_info *current_die;
16801   const char *name = NULL;
16802
16803   /* Loop through the extensions until we find a name.  */
16804
16805   for (current_die = die;
16806        current_die != NULL;
16807        current_die = dwarf2_extension (die, &cu))
16808     {
16809       /* We don't use dwarf2_name here so that we can detect the absence
16810          of a name -> anonymous namespace.  */
16811       name = dwarf2_string_attr (die, DW_AT_name, cu);
16812
16813       if (name != NULL)
16814         break;
16815     }
16816
16817   /* Is it an anonymous namespace?  */
16818
16819   *is_anonymous = (name == NULL);
16820   if (*is_anonymous)
16821     name = CP_ANONYMOUS_NAMESPACE_STR;
16822
16823   return name;
16824 }
16825
16826 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16827    the user defined type vector.  */
16828
16829 static struct type *
16830 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16831 {
16832   struct gdbarch *gdbarch = get_objfile_arch (cu->dwarf2_per_objfile->objfile);
16833   struct comp_unit_head *cu_header = &cu->header;
16834   struct type *type;
16835   struct attribute *attr_byte_size;
16836   struct attribute *attr_address_class;
16837   int byte_size, addr_class;
16838   struct type *target_type;
16839
16840   target_type = die_type (die, cu);
16841
16842   /* The die_type call above may have already set the type for this DIE.  */
16843   type = get_die_type (die, cu);
16844   if (type)
16845     return type;
16846
16847   type = lookup_pointer_type (target_type);
16848
16849   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16850   if (attr_byte_size)
16851     byte_size = DW_UNSND (attr_byte_size);
16852   else
16853     byte_size = cu_header->addr_size;
16854
16855   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16856   if (attr_address_class)
16857     addr_class = DW_UNSND (attr_address_class);
16858   else
16859     addr_class = DW_ADDR_none;
16860
16861   /* If the pointer size or address class is different than the
16862      default, create a type variant marked as such and set the
16863      length accordingly.  */
16864   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16865     {
16866       if (gdbarch_address_class_type_flags_p (gdbarch))
16867         {
16868           int type_flags;
16869
16870           type_flags = gdbarch_address_class_type_flags
16871                          (gdbarch, byte_size, addr_class);
16872           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16873                       == 0);
16874           type = make_type_with_address_space (type, type_flags);
16875         }
16876       else if (TYPE_LENGTH (type) != byte_size)
16877         {
16878           complaint (&symfile_complaints,
16879                      _("invalid pointer size %d"), byte_size);
16880         }
16881       else
16882         {
16883           /* Should we also complain about unhandled address classes?  */
16884         }
16885     }
16886
16887   TYPE_LENGTH (type) = byte_size;
16888   return set_die_type (die, type, cu);
16889 }
16890
16891 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16892    the user defined type vector.  */
16893
16894 static struct type *
16895 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16896 {
16897   struct type *type;
16898   struct type *to_type;
16899   struct type *domain;
16900
16901   to_type = die_type (die, cu);
16902   domain = die_containing_type (die, cu);
16903
16904   /* The calls above may have already set the type for this DIE.  */
16905   type = get_die_type (die, cu);
16906   if (type)
16907     return type;
16908
16909   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16910     type = lookup_methodptr_type (to_type);
16911   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16912     {
16913       struct type *new_type = alloc_type (cu->dwarf2_per_objfile->objfile);
16914
16915       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16916                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16917                             TYPE_VARARGS (to_type));
16918       type = lookup_methodptr_type (new_type);
16919     }
16920   else
16921     type = lookup_memberptr_type (to_type, domain);
16922
16923   return set_die_type (die, type, cu);
16924 }
16925
16926 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16927    the user defined type vector.  */
16928
16929 static struct type *
16930 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16931                           enum type_code refcode)
16932 {
16933   struct comp_unit_head *cu_header = &cu->header;
16934   struct type *type, *target_type;
16935   struct attribute *attr;
16936
16937   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16938
16939   target_type = die_type (die, cu);
16940
16941   /* The die_type call above may have already set the type for this DIE.  */
16942   type = get_die_type (die, cu);
16943   if (type)
16944     return type;
16945
16946   type = lookup_reference_type (target_type, refcode);
16947   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16948   if (attr)
16949     {
16950       TYPE_LENGTH (type) = DW_UNSND (attr);
16951     }
16952   else
16953     {
16954       TYPE_LENGTH (type) = cu_header->addr_size;
16955     }
16956   return set_die_type (die, type, cu);
16957 }
16958
16959 /* Add the given cv-qualifiers to the element type of the array.  GCC
16960    outputs DWARF type qualifiers that apply to an array, not the
16961    element type.  But GDB relies on the array element type to carry
16962    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16963    specification.  */
16964
16965 static struct type *
16966 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16967                    struct type *base_type, int cnst, int voltl)
16968 {
16969   struct type *el_type, *inner_array;
16970
16971   base_type = copy_type (base_type);
16972   inner_array = base_type;
16973
16974   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16975     {
16976       TYPE_TARGET_TYPE (inner_array) =
16977         copy_type (TYPE_TARGET_TYPE (inner_array));
16978       inner_array = TYPE_TARGET_TYPE (inner_array);
16979     }
16980
16981   el_type = TYPE_TARGET_TYPE (inner_array);
16982   cnst |= TYPE_CONST (el_type);
16983   voltl |= TYPE_VOLATILE (el_type);
16984   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16985
16986   return set_die_type (die, base_type, cu);
16987 }
16988
16989 static struct type *
16990 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16991 {
16992   struct type *base_type, *cv_type;
16993
16994   base_type = die_type (die, cu);
16995
16996   /* The die_type call above may have already set the type for this DIE.  */
16997   cv_type = get_die_type (die, cu);
16998   if (cv_type)
16999     return cv_type;
17000
17001   /* In case the const qualifier is applied to an array type, the element type
17002      is so qualified, not the array type (section 6.7.3 of C99).  */
17003   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17004     return add_array_cv_type (die, cu, base_type, 1, 0);
17005
17006   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17007   return set_die_type (die, cv_type, cu);
17008 }
17009
17010 static struct type *
17011 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17012 {
17013   struct type *base_type, *cv_type;
17014
17015   base_type = die_type (die, cu);
17016
17017   /* The die_type call above may have already set the type for this DIE.  */
17018   cv_type = get_die_type (die, cu);
17019   if (cv_type)
17020     return cv_type;
17021
17022   /* In case the volatile qualifier is applied to an array type, the
17023      element type is so qualified, not the array type (section 6.7.3
17024      of C99).  */
17025   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17026     return add_array_cv_type (die, cu, base_type, 0, 1);
17027
17028   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17029   return set_die_type (die, cv_type, cu);
17030 }
17031
17032 /* Handle DW_TAG_restrict_type.  */
17033
17034 static struct type *
17035 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17036 {
17037   struct type *base_type, *cv_type;
17038
17039   base_type = die_type (die, cu);
17040
17041   /* The die_type call above may have already set the type for this DIE.  */
17042   cv_type = get_die_type (die, cu);
17043   if (cv_type)
17044     return cv_type;
17045
17046   cv_type = make_restrict_type (base_type);
17047   return set_die_type (die, cv_type, cu);
17048 }
17049
17050 /* Handle DW_TAG_atomic_type.  */
17051
17052 static struct type *
17053 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17054 {
17055   struct type *base_type, *cv_type;
17056
17057   base_type = die_type (die, cu);
17058
17059   /* The die_type call above may have already set the type for this DIE.  */
17060   cv_type = get_die_type (die, cu);
17061   if (cv_type)
17062     return cv_type;
17063
17064   cv_type = make_atomic_type (base_type);
17065   return set_die_type (die, cv_type, cu);
17066 }
17067
17068 /* Extract all information from a DW_TAG_string_type DIE and add to
17069    the user defined type vector.  It isn't really a user defined type,
17070    but it behaves like one, with other DIE's using an AT_user_def_type
17071    attribute to reference it.  */
17072
17073 static struct type *
17074 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17075 {
17076   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17077   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17078   struct type *type, *range_type, *index_type, *char_type;
17079   struct attribute *attr;
17080   unsigned int length;
17081
17082   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17083   if (attr)
17084     {
17085       length = DW_UNSND (attr);
17086     }
17087   else
17088     {
17089       /* Check for the DW_AT_byte_size attribute.  */
17090       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17091       if (attr)
17092         {
17093           length = DW_UNSND (attr);
17094         }
17095       else
17096         {
17097           length = 1;
17098         }
17099     }
17100
17101   index_type = objfile_type (objfile)->builtin_int;
17102   range_type = create_static_range_type (NULL, index_type, 1, length);
17103   char_type = language_string_char_type (cu->language_defn, gdbarch);
17104   type = create_string_type (NULL, char_type, range_type);
17105
17106   return set_die_type (die, type, cu);
17107 }
17108
17109 /* Assuming that DIE corresponds to a function, returns nonzero
17110    if the function is prototyped.  */
17111
17112 static int
17113 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17114 {
17115   struct attribute *attr;
17116
17117   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17118   if (attr && (DW_UNSND (attr) != 0))
17119     return 1;
17120
17121   /* The DWARF standard implies that the DW_AT_prototyped attribute
17122      is only meaninful for C, but the concept also extends to other
17123      languages that allow unprototyped functions (Eg: Objective C).
17124      For all other languages, assume that functions are always
17125      prototyped.  */
17126   if (cu->language != language_c
17127       && cu->language != language_objc
17128       && cu->language != language_opencl)
17129     return 1;
17130
17131   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17132      prototyped and unprototyped functions; default to prototyped,
17133      since that is more common in modern code (and RealView warns
17134      about unprototyped functions).  */
17135   if (producer_is_realview (cu->producer))
17136     return 1;
17137
17138   return 0;
17139 }
17140
17141 /* Handle DIES due to C code like:
17142
17143    struct foo
17144    {
17145    int (*funcp)(int a, long l);
17146    int b;
17147    };
17148
17149    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17150
17151 static struct type *
17152 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17153 {
17154   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17155   struct type *type;            /* Type that this function returns.  */
17156   struct type *ftype;           /* Function that returns above type.  */
17157   struct attribute *attr;
17158
17159   type = die_type (die, cu);
17160
17161   /* The die_type call above may have already set the type for this DIE.  */
17162   ftype = get_die_type (die, cu);
17163   if (ftype)
17164     return ftype;
17165
17166   ftype = lookup_function_type (type);
17167
17168   if (prototyped_function_p (die, cu))
17169     TYPE_PROTOTYPED (ftype) = 1;
17170
17171   /* Store the calling convention in the type if it's available in
17172      the subroutine die.  Otherwise set the calling convention to
17173      the default value DW_CC_normal.  */
17174   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17175   if (attr)
17176     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17177   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17178     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17179   else
17180     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17181
17182   /* Record whether the function returns normally to its caller or not
17183      if the DWARF producer set that information.  */
17184   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17185   if (attr && (DW_UNSND (attr) != 0))
17186     TYPE_NO_RETURN (ftype) = 1;
17187
17188   /* We need to add the subroutine type to the die immediately so
17189      we don't infinitely recurse when dealing with parameters
17190      declared as the same subroutine type.  */
17191   set_die_type (die, ftype, cu);
17192
17193   if (die->child != NULL)
17194     {
17195       struct type *void_type = objfile_type (objfile)->builtin_void;
17196       struct die_info *child_die;
17197       int nparams, iparams;
17198
17199       /* Count the number of parameters.
17200          FIXME: GDB currently ignores vararg functions, but knows about
17201          vararg member functions.  */
17202       nparams = 0;
17203       child_die = die->child;
17204       while (child_die && child_die->tag)
17205         {
17206           if (child_die->tag == DW_TAG_formal_parameter)
17207             nparams++;
17208           else if (child_die->tag == DW_TAG_unspecified_parameters)
17209             TYPE_VARARGS (ftype) = 1;
17210           child_die = sibling_die (child_die);
17211         }
17212
17213       /* Allocate storage for parameters and fill them in.  */
17214       TYPE_NFIELDS (ftype) = nparams;
17215       TYPE_FIELDS (ftype) = (struct field *)
17216         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17217
17218       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17219          even if we error out during the parameters reading below.  */
17220       for (iparams = 0; iparams < nparams; iparams++)
17221         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17222
17223       iparams = 0;
17224       child_die = die->child;
17225       while (child_die && child_die->tag)
17226         {
17227           if (child_die->tag == DW_TAG_formal_parameter)
17228             {
17229               struct type *arg_type;
17230
17231               /* DWARF version 2 has no clean way to discern C++
17232                  static and non-static member functions.  G++ helps
17233                  GDB by marking the first parameter for non-static
17234                  member functions (which is the this pointer) as
17235                  artificial.  We pass this information to
17236                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17237
17238                  DWARF version 3 added DW_AT_object_pointer, which GCC
17239                  4.5 does not yet generate.  */
17240               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17241               if (attr)
17242                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17243               else
17244                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17245               arg_type = die_type (child_die, cu);
17246
17247               /* RealView does not mark THIS as const, which the testsuite
17248                  expects.  GCC marks THIS as const in method definitions,
17249                  but not in the class specifications (GCC PR 43053).  */
17250               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17251                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17252                 {
17253                   int is_this = 0;
17254                   struct dwarf2_cu *arg_cu = cu;
17255                   const char *name = dwarf2_name (child_die, cu);
17256
17257                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17258                   if (attr)
17259                     {
17260                       /* If the compiler emits this, use it.  */
17261                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17262                         is_this = 1;
17263                     }
17264                   else if (name && strcmp (name, "this") == 0)
17265                     /* Function definitions will have the argument names.  */
17266                     is_this = 1;
17267                   else if (name == NULL && iparams == 0)
17268                     /* Declarations may not have the names, so like
17269                        elsewhere in GDB, assume an artificial first
17270                        argument is "this".  */
17271                     is_this = 1;
17272
17273                   if (is_this)
17274                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17275                                              arg_type, 0);
17276                 }
17277
17278               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17279               iparams++;
17280             }
17281           child_die = sibling_die (child_die);
17282         }
17283     }
17284
17285   return ftype;
17286 }
17287
17288 static struct type *
17289 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17290 {
17291   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17292   const char *name = NULL;
17293   struct type *this_type, *target_type;
17294
17295   name = dwarf2_full_name (NULL, die, cu);
17296   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17297   TYPE_TARGET_STUB (this_type) = 1;
17298   set_die_type (die, this_type, cu);
17299   target_type = die_type (die, cu);
17300   if (target_type != this_type)
17301     TYPE_TARGET_TYPE (this_type) = target_type;
17302   else
17303     {
17304       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17305          spec and cause infinite loops in GDB.  */
17306       complaint (&symfile_complaints,
17307                  _("Self-referential DW_TAG_typedef "
17308                    "- DIE at 0x%x [in module %s]"),
17309                  to_underlying (die->sect_off), objfile_name (objfile));
17310       TYPE_TARGET_TYPE (this_type) = NULL;
17311     }
17312   return this_type;
17313 }
17314
17315 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17316    (which may be different from NAME) to the architecture back-end to allow
17317    it to guess the correct format if necessary.  */
17318
17319 static struct type *
17320 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17321                         const char *name_hint)
17322 {
17323   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17324   const struct floatformat **format;
17325   struct type *type;
17326
17327   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17328   if (format)
17329     type = init_float_type (objfile, bits, name, format);
17330   else
17331     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17332
17333   return type;
17334 }
17335
17336 /* Find a representation of a given base type and install
17337    it in the TYPE field of the die.  */
17338
17339 static struct type *
17340 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17341 {
17342   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17343   struct type *type;
17344   struct attribute *attr;
17345   int encoding = 0, bits = 0;
17346   const char *name;
17347
17348   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17349   if (attr)
17350     {
17351       encoding = DW_UNSND (attr);
17352     }
17353   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17354   if (attr)
17355     {
17356       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17357     }
17358   name = dwarf2_name (die, cu);
17359   if (!name)
17360     {
17361       complaint (&symfile_complaints,
17362                  _("DW_AT_name missing from DW_TAG_base_type"));
17363     }
17364
17365   switch (encoding)
17366     {
17367       case DW_ATE_address:
17368         /* Turn DW_ATE_address into a void * pointer.  */
17369         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17370         type = init_pointer_type (objfile, bits, name, type);
17371         break;
17372       case DW_ATE_boolean:
17373         type = init_boolean_type (objfile, bits, 1, name);
17374         break;
17375       case DW_ATE_complex_float:
17376         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17377         type = init_complex_type (objfile, name, type);
17378         break;
17379       case DW_ATE_decimal_float:
17380         type = init_decfloat_type (objfile, bits, name);
17381         break;
17382       case DW_ATE_float:
17383         type = dwarf2_init_float_type (objfile, bits, name, name);
17384         break;
17385       case DW_ATE_signed:
17386         type = init_integer_type (objfile, bits, 0, name);
17387         break;
17388       case DW_ATE_unsigned:
17389         if (cu->language == language_fortran
17390             && name
17391             && startswith (name, "character("))
17392           type = init_character_type (objfile, bits, 1, name);
17393         else
17394           type = init_integer_type (objfile, bits, 1, name);
17395         break;
17396       case DW_ATE_signed_char:
17397         if (cu->language == language_ada || cu->language == language_m2
17398             || cu->language == language_pascal
17399             || cu->language == language_fortran)
17400           type = init_character_type (objfile, bits, 0, name);
17401         else
17402           type = init_integer_type (objfile, bits, 0, name);
17403         break;
17404       case DW_ATE_unsigned_char:
17405         if (cu->language == language_ada || cu->language == language_m2
17406             || cu->language == language_pascal
17407             || cu->language == language_fortran
17408             || cu->language == language_rust)
17409           type = init_character_type (objfile, bits, 1, name);
17410         else
17411           type = init_integer_type (objfile, bits, 1, name);
17412         break;
17413       case DW_ATE_UTF:
17414         {
17415           gdbarch *arch = get_objfile_arch (objfile);
17416
17417           if (bits == 16)
17418             type = builtin_type (arch)->builtin_char16;
17419           else if (bits == 32)
17420             type = builtin_type (arch)->builtin_char32;
17421           else
17422             {
17423               complaint (&symfile_complaints,
17424                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17425                          bits);
17426               type = init_integer_type (objfile, bits, 1, name);
17427             }
17428           return set_die_type (die, type, cu);
17429         }
17430         break;
17431
17432       default:
17433         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17434                    dwarf_type_encoding_name (encoding));
17435         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17436         break;
17437     }
17438
17439   if (name && strcmp (name, "char") == 0)
17440     TYPE_NOSIGN (type) = 1;
17441
17442   return set_die_type (die, type, cu);
17443 }
17444
17445 /* Parse dwarf attribute if it's a block, reference or constant and put the
17446    resulting value of the attribute into struct bound_prop.
17447    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17448
17449 static int
17450 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17451                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17452 {
17453   struct dwarf2_property_baton *baton;
17454   struct obstack *obstack = &cu->dwarf2_per_objfile->objfile->objfile_obstack;
17455
17456   if (attr == NULL || prop == NULL)
17457     return 0;
17458
17459   if (attr_form_is_block (attr))
17460     {
17461       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17462       baton->referenced_type = NULL;
17463       baton->locexpr.per_cu = cu->per_cu;
17464       baton->locexpr.size = DW_BLOCK (attr)->size;
17465       baton->locexpr.data = DW_BLOCK (attr)->data;
17466       prop->data.baton = baton;
17467       prop->kind = PROP_LOCEXPR;
17468       gdb_assert (prop->data.baton != NULL);
17469     }
17470   else if (attr_form_is_ref (attr))
17471     {
17472       struct dwarf2_cu *target_cu = cu;
17473       struct die_info *target_die;
17474       struct attribute *target_attr;
17475
17476       target_die = follow_die_ref (die, attr, &target_cu);
17477       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17478       if (target_attr == NULL)
17479         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17480                                    target_cu);
17481       if (target_attr == NULL)
17482         return 0;
17483
17484       switch (target_attr->name)
17485         {
17486           case DW_AT_location:
17487             if (attr_form_is_section_offset (target_attr))
17488               {
17489                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17490                 baton->referenced_type = die_type (target_die, target_cu);
17491                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17492                 prop->data.baton = baton;
17493                 prop->kind = PROP_LOCLIST;
17494                 gdb_assert (prop->data.baton != NULL);
17495               }
17496             else if (attr_form_is_block (target_attr))
17497               {
17498                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17499                 baton->referenced_type = die_type (target_die, target_cu);
17500                 baton->locexpr.per_cu = cu->per_cu;
17501                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17502                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17503                 prop->data.baton = baton;
17504                 prop->kind = PROP_LOCEXPR;
17505                 gdb_assert (prop->data.baton != NULL);
17506               }
17507             else
17508               {
17509                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17510                                                        "dynamic property");
17511                 return 0;
17512               }
17513             break;
17514           case DW_AT_data_member_location:
17515             {
17516               LONGEST offset;
17517
17518               if (!handle_data_member_location (target_die, target_cu,
17519                                                 &offset))
17520                 return 0;
17521
17522               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17523               baton->referenced_type = read_type_die (target_die->parent,
17524                                                       target_cu);
17525               baton->offset_info.offset = offset;
17526               baton->offset_info.type = die_type (target_die, target_cu);
17527               prop->data.baton = baton;
17528               prop->kind = PROP_ADDR_OFFSET;
17529               break;
17530             }
17531         }
17532     }
17533   else if (attr_form_is_constant (attr))
17534     {
17535       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17536       prop->kind = PROP_CONST;
17537     }
17538   else
17539     {
17540       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17541                                              dwarf2_name (die, cu));
17542       return 0;
17543     }
17544
17545   return 1;
17546 }
17547
17548 /* Read the given DW_AT_subrange DIE.  */
17549
17550 static struct type *
17551 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17552 {
17553   struct type *base_type, *orig_base_type;
17554   struct type *range_type;
17555   struct attribute *attr;
17556   struct dynamic_prop low, high;
17557   int low_default_is_valid;
17558   int high_bound_is_count = 0;
17559   const char *name;
17560   LONGEST negative_mask;
17561
17562   orig_base_type = die_type (die, cu);
17563   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17564      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17565      creating the range type, but we use the result of check_typedef
17566      when examining properties of the type.  */
17567   base_type = check_typedef (orig_base_type);
17568
17569   /* The die_type call above may have already set the type for this DIE.  */
17570   range_type = get_die_type (die, cu);
17571   if (range_type)
17572     return range_type;
17573
17574   low.kind = PROP_CONST;
17575   high.kind = PROP_CONST;
17576   high.data.const_val = 0;
17577
17578   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17579      omitting DW_AT_lower_bound.  */
17580   switch (cu->language)
17581     {
17582     case language_c:
17583     case language_cplus:
17584       low.data.const_val = 0;
17585       low_default_is_valid = 1;
17586       break;
17587     case language_fortran:
17588       low.data.const_val = 1;
17589       low_default_is_valid = 1;
17590       break;
17591     case language_d:
17592     case language_objc:
17593     case language_rust:
17594       low.data.const_val = 0;
17595       low_default_is_valid = (cu->header.version >= 4);
17596       break;
17597     case language_ada:
17598     case language_m2:
17599     case language_pascal:
17600       low.data.const_val = 1;
17601       low_default_is_valid = (cu->header.version >= 4);
17602       break;
17603     default:
17604       low.data.const_val = 0;
17605       low_default_is_valid = 0;
17606       break;
17607     }
17608
17609   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17610   if (attr)
17611     attr_to_dynamic_prop (attr, die, cu, &low);
17612   else if (!low_default_is_valid)
17613     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17614                                       "- DIE at 0x%x [in module %s]"),
17615                to_underlying (die->sect_off),
17616                objfile_name (cu->dwarf2_per_objfile->objfile));
17617
17618   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17619   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17620     {
17621       attr = dwarf2_attr (die, DW_AT_count, cu);
17622       if (attr_to_dynamic_prop (attr, die, cu, &high))
17623         {
17624           /* If bounds are constant do the final calculation here.  */
17625           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17626             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17627           else
17628             high_bound_is_count = 1;
17629         }
17630     }
17631
17632   /* Dwarf-2 specifications explicitly allows to create subrange types
17633      without specifying a base type.
17634      In that case, the base type must be set to the type of
17635      the lower bound, upper bound or count, in that order, if any of these
17636      three attributes references an object that has a type.
17637      If no base type is found, the Dwarf-2 specifications say that
17638      a signed integer type of size equal to the size of an address should
17639      be used.
17640      For the following C code: `extern char gdb_int [];'
17641      GCC produces an empty range DIE.
17642      FIXME: muller/2010-05-28: Possible references to object for low bound,
17643      high bound or count are not yet handled by this code.  */
17644   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17645     {
17646       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17647       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17648       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17649       struct type *int_type = objfile_type (objfile)->builtin_int;
17650
17651       /* Test "int", "long int", and "long long int" objfile types,
17652          and select the first one having a size above or equal to the
17653          architecture address size.  */
17654       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17655         base_type = int_type;
17656       else
17657         {
17658           int_type = objfile_type (objfile)->builtin_long;
17659           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17660             base_type = int_type;
17661           else
17662             {
17663               int_type = objfile_type (objfile)->builtin_long_long;
17664               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17665                 base_type = int_type;
17666             }
17667         }
17668     }
17669
17670   /* Normally, the DWARF producers are expected to use a signed
17671      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17672      But this is unfortunately not always the case, as witnessed
17673      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17674      is used instead.  To work around that ambiguity, we treat
17675      the bounds as signed, and thus sign-extend their values, when
17676      the base type is signed.  */
17677   negative_mask =
17678     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17679   if (low.kind == PROP_CONST
17680       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17681     low.data.const_val |= negative_mask;
17682   if (high.kind == PROP_CONST
17683       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17684     high.data.const_val |= negative_mask;
17685
17686   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17687
17688   if (high_bound_is_count)
17689     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17690
17691   /* Ada expects an empty array on no boundary attributes.  */
17692   if (attr == NULL && cu->language != language_ada)
17693     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17694
17695   name = dwarf2_name (die, cu);
17696   if (name)
17697     TYPE_NAME (range_type) = name;
17698
17699   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17700   if (attr)
17701     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17702
17703   set_die_type (die, range_type, cu);
17704
17705   /* set_die_type should be already done.  */
17706   set_descriptive_type (range_type, die, cu);
17707
17708   return range_type;
17709 }
17710
17711 static struct type *
17712 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17713 {
17714   struct type *type;
17715
17716   type = init_type (cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID, 0, NULL);
17717   TYPE_NAME (type) = dwarf2_name (die, cu);
17718
17719   /* In Ada, an unspecified type is typically used when the description
17720      of the type is defered to a different unit.  When encountering
17721      such a type, we treat it as a stub, and try to resolve it later on,
17722      when needed.  */
17723   if (cu->language == language_ada)
17724     TYPE_STUB (type) = 1;
17725
17726   return set_die_type (die, type, cu);
17727 }
17728
17729 /* Read a single die and all its descendents.  Set the die's sibling
17730    field to NULL; set other fields in the die correctly, and set all
17731    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17732    location of the info_ptr after reading all of those dies.  PARENT
17733    is the parent of the die in question.  */
17734
17735 static struct die_info *
17736 read_die_and_children (const struct die_reader_specs *reader,
17737                        const gdb_byte *info_ptr,
17738                        const gdb_byte **new_info_ptr,
17739                        struct die_info *parent)
17740 {
17741   struct die_info *die;
17742   const gdb_byte *cur_ptr;
17743   int has_children;
17744
17745   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17746   if (die == NULL)
17747     {
17748       *new_info_ptr = cur_ptr;
17749       return NULL;
17750     }
17751   store_in_ref_table (die, reader->cu);
17752
17753   if (has_children)
17754     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17755   else
17756     {
17757       die->child = NULL;
17758       *new_info_ptr = cur_ptr;
17759     }
17760
17761   die->sibling = NULL;
17762   die->parent = parent;
17763   return die;
17764 }
17765
17766 /* Read a die, all of its descendents, and all of its siblings; set
17767    all of the fields of all of the dies correctly.  Arguments are as
17768    in read_die_and_children.  */
17769
17770 static struct die_info *
17771 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17772                          const gdb_byte *info_ptr,
17773                          const gdb_byte **new_info_ptr,
17774                          struct die_info *parent)
17775 {
17776   struct die_info *first_die, *last_sibling;
17777   const gdb_byte *cur_ptr;
17778
17779   cur_ptr = info_ptr;
17780   first_die = last_sibling = NULL;
17781
17782   while (1)
17783     {
17784       struct die_info *die
17785         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17786
17787       if (die == NULL)
17788         {
17789           *new_info_ptr = cur_ptr;
17790           return first_die;
17791         }
17792
17793       if (!first_die)
17794         first_die = die;
17795       else
17796         last_sibling->sibling = die;
17797
17798       last_sibling = die;
17799     }
17800 }
17801
17802 /* Read a die, all of its descendents, and all of its siblings; set
17803    all of the fields of all of the dies correctly.  Arguments are as
17804    in read_die_and_children.
17805    This the main entry point for reading a DIE and all its children.  */
17806
17807 static struct die_info *
17808 read_die_and_siblings (const struct die_reader_specs *reader,
17809                        const gdb_byte *info_ptr,
17810                        const gdb_byte **new_info_ptr,
17811                        struct die_info *parent)
17812 {
17813   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17814                                                   new_info_ptr, parent);
17815
17816   if (dwarf_die_debug)
17817     {
17818       fprintf_unfiltered (gdb_stdlog,
17819                           "Read die from %s@0x%x of %s:\n",
17820                           get_section_name (reader->die_section),
17821                           (unsigned) (info_ptr - reader->die_section->buffer),
17822                           bfd_get_filename (reader->abfd));
17823       dump_die (die, dwarf_die_debug);
17824     }
17825
17826   return die;
17827 }
17828
17829 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17830    attributes.
17831    The caller is responsible for filling in the extra attributes
17832    and updating (*DIEP)->num_attrs.
17833    Set DIEP to point to a newly allocated die with its information,
17834    except for its child, sibling, and parent fields.
17835    Set HAS_CHILDREN to tell whether the die has children or not.  */
17836
17837 static const gdb_byte *
17838 read_full_die_1 (const struct die_reader_specs *reader,
17839                  struct die_info **diep, const gdb_byte *info_ptr,
17840                  int *has_children, int num_extra_attrs)
17841 {
17842   unsigned int abbrev_number, bytes_read, i;
17843   struct abbrev_info *abbrev;
17844   struct die_info *die;
17845   struct dwarf2_cu *cu = reader->cu;
17846   bfd *abfd = reader->abfd;
17847
17848   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17849   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17850   info_ptr += bytes_read;
17851   if (!abbrev_number)
17852     {
17853       *diep = NULL;
17854       *has_children = 0;
17855       return info_ptr;
17856     }
17857
17858   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
17859   if (!abbrev)
17860     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17861            abbrev_number,
17862            bfd_get_filename (abfd));
17863
17864   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17865   die->sect_off = sect_off;
17866   die->tag = abbrev->tag;
17867   die->abbrev = abbrev_number;
17868
17869   /* Make the result usable.
17870      The caller needs to update num_attrs after adding the extra
17871      attributes.  */
17872   die->num_attrs = abbrev->num_attrs;
17873
17874   for (i = 0; i < abbrev->num_attrs; ++i)
17875     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17876                                info_ptr);
17877
17878   *diep = die;
17879   *has_children = abbrev->has_children;
17880   return info_ptr;
17881 }
17882
17883 /* Read a die and all its attributes.
17884    Set DIEP to point to a newly allocated die with its information,
17885    except for its child, sibling, and parent fields.
17886    Set HAS_CHILDREN to tell whether the die has children or not.  */
17887
17888 static const gdb_byte *
17889 read_full_die (const struct die_reader_specs *reader,
17890                struct die_info **diep, const gdb_byte *info_ptr,
17891                int *has_children)
17892 {
17893   const gdb_byte *result;
17894
17895   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17896
17897   if (dwarf_die_debug)
17898     {
17899       fprintf_unfiltered (gdb_stdlog,
17900                           "Read die from %s@0x%x of %s:\n",
17901                           get_section_name (reader->die_section),
17902                           (unsigned) (info_ptr - reader->die_section->buffer),
17903                           bfd_get_filename (reader->abfd));
17904       dump_die (*diep, dwarf_die_debug);
17905     }
17906
17907   return result;
17908 }
17909 \f
17910 /* Abbreviation tables.
17911
17912    In DWARF version 2, the description of the debugging information is
17913    stored in a separate .debug_abbrev section.  Before we read any
17914    dies from a section we read in all abbreviations and install them
17915    in a hash table.  */
17916
17917 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17918
17919 static struct abbrev_info *
17920 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
17921 {
17922   struct abbrev_info *abbrev;
17923
17924   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
17925   memset (abbrev, 0, sizeof (struct abbrev_info));
17926
17927   return abbrev;
17928 }
17929
17930 /* Add an abbreviation to the table.  */
17931
17932 static void
17933 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
17934                          unsigned int abbrev_number,
17935                          struct abbrev_info *abbrev)
17936 {
17937   unsigned int hash_number;
17938
17939   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17940   abbrev->next = abbrev_table->abbrevs[hash_number];
17941   abbrev_table->abbrevs[hash_number] = abbrev;
17942 }
17943
17944 /* Look up an abbrev in the table.
17945    Returns NULL if the abbrev is not found.  */
17946
17947 static struct abbrev_info *
17948 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
17949                             unsigned int abbrev_number)
17950 {
17951   unsigned int hash_number;
17952   struct abbrev_info *abbrev;
17953
17954   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17955   abbrev = abbrev_table->abbrevs[hash_number];
17956
17957   while (abbrev)
17958     {
17959       if (abbrev->number == abbrev_number)
17960         return abbrev;
17961       abbrev = abbrev->next;
17962     }
17963   return NULL;
17964 }
17965
17966 /* Read in an abbrev table.  */
17967
17968 static struct abbrev_table *
17969 abbrev_table_read_table (struct dwarf2_section_info *section,
17970                          sect_offset sect_off)
17971 {
17972   struct objfile *objfile = dwarf2_per_objfile->objfile;
17973   bfd *abfd = get_section_bfd_owner (section);
17974   struct abbrev_table *abbrev_table;
17975   const gdb_byte *abbrev_ptr;
17976   struct abbrev_info *cur_abbrev;
17977   unsigned int abbrev_number, bytes_read, abbrev_name;
17978   unsigned int abbrev_form;
17979   struct attr_abbrev *cur_attrs;
17980   unsigned int allocated_attrs;
17981
17982   abbrev_table = XNEW (struct abbrev_table);
17983   abbrev_table->sect_off = sect_off;
17984   obstack_init (&abbrev_table->abbrev_obstack);
17985   abbrev_table->abbrevs =
17986     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
17987                ABBREV_HASH_SIZE);
17988   memset (abbrev_table->abbrevs, 0,
17989           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
17990
17991   dwarf2_read_section (objfile, section);
17992   abbrev_ptr = section->buffer + to_underlying (sect_off);
17993   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17994   abbrev_ptr += bytes_read;
17995
17996   allocated_attrs = ATTR_ALLOC_CHUNK;
17997   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17998
17999   /* Loop until we reach an abbrev number of 0.  */
18000   while (abbrev_number)
18001     {
18002       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
18003
18004       /* read in abbrev header */
18005       cur_abbrev->number = abbrev_number;
18006       cur_abbrev->tag
18007         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18008       abbrev_ptr += bytes_read;
18009       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18010       abbrev_ptr += 1;
18011
18012       /* now read in declarations */
18013       for (;;)
18014         {
18015           LONGEST implicit_const;
18016
18017           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18018           abbrev_ptr += bytes_read;
18019           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18020           abbrev_ptr += bytes_read;
18021           if (abbrev_form == DW_FORM_implicit_const)
18022             {
18023               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18024                                                    &bytes_read);
18025               abbrev_ptr += bytes_read;
18026             }
18027           else
18028             {
18029               /* Initialize it due to a false compiler warning.  */
18030               implicit_const = -1;
18031             }
18032
18033           if (abbrev_name == 0)
18034             break;
18035
18036           if (cur_abbrev->num_attrs == allocated_attrs)
18037             {
18038               allocated_attrs += ATTR_ALLOC_CHUNK;
18039               cur_attrs
18040                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18041             }
18042
18043           cur_attrs[cur_abbrev->num_attrs].name
18044             = (enum dwarf_attribute) abbrev_name;
18045           cur_attrs[cur_abbrev->num_attrs].form
18046             = (enum dwarf_form) abbrev_form;
18047           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18048           ++cur_abbrev->num_attrs;
18049         }
18050
18051       cur_abbrev->attrs =
18052         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18053                    cur_abbrev->num_attrs);
18054       memcpy (cur_abbrev->attrs, cur_attrs,
18055               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18056
18057       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
18058
18059       /* Get next abbreviation.
18060          Under Irix6 the abbreviations for a compilation unit are not
18061          always properly terminated with an abbrev number of 0.
18062          Exit loop if we encounter an abbreviation which we have
18063          already read (which means we are about to read the abbreviations
18064          for the next compile unit) or if the end of the abbreviation
18065          table is reached.  */
18066       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18067         break;
18068       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18069       abbrev_ptr += bytes_read;
18070       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
18071         break;
18072     }
18073
18074   xfree (cur_attrs);
18075   return abbrev_table;
18076 }
18077
18078 /* Free the resources held by ABBREV_TABLE.  */
18079
18080 static void
18081 abbrev_table_free (struct abbrev_table *abbrev_table)
18082 {
18083   obstack_free (&abbrev_table->abbrev_obstack, NULL);
18084   xfree (abbrev_table);
18085 }
18086
18087 /* Same as abbrev_table_free but as a cleanup.
18088    We pass in a pointer to the pointer to the table so that we can
18089    set the pointer to NULL when we're done.  It also simplifies
18090    build_type_psymtabs_1.  */
18091
18092 static void
18093 abbrev_table_free_cleanup (void *table_ptr)
18094 {
18095   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
18096
18097   if (*abbrev_table_ptr != NULL)
18098     abbrev_table_free (*abbrev_table_ptr);
18099   *abbrev_table_ptr = NULL;
18100 }
18101
18102 /* Read the abbrev table for CU from ABBREV_SECTION.  */
18103
18104 static void
18105 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
18106                      struct dwarf2_section_info *abbrev_section)
18107 {
18108   cu->abbrev_table =
18109     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
18110 }
18111
18112 /* Release the memory used by the abbrev table for a compilation unit.  */
18113
18114 static void
18115 dwarf2_free_abbrev_table (void *ptr_to_cu)
18116 {
18117   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
18118
18119   if (cu->abbrev_table != NULL)
18120     abbrev_table_free (cu->abbrev_table);
18121   /* Set this to NULL so that we SEGV if we try to read it later,
18122      and also because free_comp_unit verifies this is NULL.  */
18123   cu->abbrev_table = NULL;
18124 }
18125 \f
18126 /* Returns nonzero if TAG represents a type that we might generate a partial
18127    symbol for.  */
18128
18129 static int
18130 is_type_tag_for_partial (int tag)
18131 {
18132   switch (tag)
18133     {
18134 #if 0
18135     /* Some types that would be reasonable to generate partial symbols for,
18136        that we don't at present.  */
18137     case DW_TAG_array_type:
18138     case DW_TAG_file_type:
18139     case DW_TAG_ptr_to_member_type:
18140     case DW_TAG_set_type:
18141     case DW_TAG_string_type:
18142     case DW_TAG_subroutine_type:
18143 #endif
18144     case DW_TAG_base_type:
18145     case DW_TAG_class_type:
18146     case DW_TAG_interface_type:
18147     case DW_TAG_enumeration_type:
18148     case DW_TAG_structure_type:
18149     case DW_TAG_subrange_type:
18150     case DW_TAG_typedef:
18151     case DW_TAG_union_type:
18152       return 1;
18153     default:
18154       return 0;
18155     }
18156 }
18157
18158 /* Load all DIEs that are interesting for partial symbols into memory.  */
18159
18160 static struct partial_die_info *
18161 load_partial_dies (const struct die_reader_specs *reader,
18162                    const gdb_byte *info_ptr, int building_psymtab)
18163 {
18164   struct dwarf2_cu *cu = reader->cu;
18165   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18166   struct partial_die_info *part_die;
18167   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18168   struct abbrev_info *abbrev;
18169   unsigned int bytes_read;
18170   unsigned int load_all = 0;
18171   int nesting_level = 1;
18172
18173   parent_die = NULL;
18174   last_die = NULL;
18175
18176   gdb_assert (cu->per_cu != NULL);
18177   if (cu->per_cu->load_all_dies)
18178     load_all = 1;
18179
18180   cu->partial_dies
18181     = htab_create_alloc_ex (cu->header.length / 12,
18182                             partial_die_hash,
18183                             partial_die_eq,
18184                             NULL,
18185                             &cu->comp_unit_obstack,
18186                             hashtab_obstack_allocate,
18187                             dummy_obstack_deallocate);
18188
18189   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18190
18191   while (1)
18192     {
18193       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
18194
18195       /* A NULL abbrev means the end of a series of children.  */
18196       if (abbrev == NULL)
18197         {
18198           if (--nesting_level == 0)
18199             {
18200               /* PART_DIE was probably the last thing allocated on the
18201                  comp_unit_obstack, so we could call obstack_free
18202                  here.  We don't do that because the waste is small,
18203                  and will be cleaned up when we're done with this
18204                  compilation unit.  This way, we're also more robust
18205                  against other users of the comp_unit_obstack.  */
18206               return first_die;
18207             }
18208           info_ptr += bytes_read;
18209           last_die = parent_die;
18210           parent_die = parent_die->die_parent;
18211           continue;
18212         }
18213
18214       /* Check for template arguments.  We never save these; if
18215          they're seen, we just mark the parent, and go on our way.  */
18216       if (parent_die != NULL
18217           && cu->language == language_cplus
18218           && (abbrev->tag == DW_TAG_template_type_param
18219               || abbrev->tag == DW_TAG_template_value_param))
18220         {
18221           parent_die->has_template_arguments = 1;
18222
18223           if (!load_all)
18224             {
18225               /* We don't need a partial DIE for the template argument.  */
18226               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18227               continue;
18228             }
18229         }
18230
18231       /* We only recurse into c++ subprograms looking for template arguments.
18232          Skip their other children.  */
18233       if (!load_all
18234           && cu->language == language_cplus
18235           && parent_die != NULL
18236           && parent_die->tag == DW_TAG_subprogram)
18237         {
18238           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18239           continue;
18240         }
18241
18242       /* Check whether this DIE is interesting enough to save.  Normally
18243          we would not be interested in members here, but there may be
18244          later variables referencing them via DW_AT_specification (for
18245          static members).  */
18246       if (!load_all
18247           && !is_type_tag_for_partial (abbrev->tag)
18248           && abbrev->tag != DW_TAG_constant
18249           && abbrev->tag != DW_TAG_enumerator
18250           && abbrev->tag != DW_TAG_subprogram
18251           && abbrev->tag != DW_TAG_lexical_block
18252           && abbrev->tag != DW_TAG_variable
18253           && abbrev->tag != DW_TAG_namespace
18254           && abbrev->tag != DW_TAG_module
18255           && abbrev->tag != DW_TAG_member
18256           && abbrev->tag != DW_TAG_imported_unit
18257           && abbrev->tag != DW_TAG_imported_declaration)
18258         {
18259           /* Otherwise we skip to the next sibling, if any.  */
18260           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18261           continue;
18262         }
18263
18264       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18265                                    info_ptr);
18266
18267       /* This two-pass algorithm for processing partial symbols has a
18268          high cost in cache pressure.  Thus, handle some simple cases
18269          here which cover the majority of C partial symbols.  DIEs
18270          which neither have specification tags in them, nor could have
18271          specification tags elsewhere pointing at them, can simply be
18272          processed and discarded.
18273
18274          This segment is also optional; scan_partial_symbols and
18275          add_partial_symbol will handle these DIEs if we chain
18276          them in normally.  When compilers which do not emit large
18277          quantities of duplicate debug information are more common,
18278          this code can probably be removed.  */
18279
18280       /* Any complete simple types at the top level (pretty much all
18281          of them, for a language without namespaces), can be processed
18282          directly.  */
18283       if (parent_die == NULL
18284           && part_die->has_specification == 0
18285           && part_die->is_declaration == 0
18286           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18287               || part_die->tag == DW_TAG_base_type
18288               || part_die->tag == DW_TAG_subrange_type))
18289         {
18290           if (building_psymtab && part_die->name != NULL)
18291             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18292                                  VAR_DOMAIN, LOC_TYPEDEF,
18293                                  &objfile->static_psymbols,
18294                                  0, cu->language, objfile);
18295           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18296           continue;
18297         }
18298
18299       /* The exception for DW_TAG_typedef with has_children above is
18300          a workaround of GCC PR debug/47510.  In the case of this complaint
18301          type_name_no_tag_or_error will error on such types later.
18302
18303          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18304          it could not find the child DIEs referenced later, this is checked
18305          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18306
18307       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18308         complaint (&symfile_complaints,
18309                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18310                      "- DIE at 0x%x [in module %s]"),
18311                    to_underlying (part_die->sect_off), objfile_name (objfile));
18312
18313       /* If we're at the second level, and we're an enumerator, and
18314          our parent has no specification (meaning possibly lives in a
18315          namespace elsewhere), then we can add the partial symbol now
18316          instead of queueing it.  */
18317       if (part_die->tag == DW_TAG_enumerator
18318           && parent_die != NULL
18319           && parent_die->die_parent == NULL
18320           && parent_die->tag == DW_TAG_enumeration_type
18321           && parent_die->has_specification == 0)
18322         {
18323           if (part_die->name == NULL)
18324             complaint (&symfile_complaints,
18325                        _("malformed enumerator DIE ignored"));
18326           else if (building_psymtab)
18327             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18328                                  VAR_DOMAIN, LOC_CONST,
18329                                  cu->language == language_cplus
18330                                  ? &objfile->global_psymbols
18331                                  : &objfile->static_psymbols,
18332                                  0, cu->language, objfile);
18333
18334           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18335           continue;
18336         }
18337
18338       /* We'll save this DIE so link it in.  */
18339       part_die->die_parent = parent_die;
18340       part_die->die_sibling = NULL;
18341       part_die->die_child = NULL;
18342
18343       if (last_die && last_die == parent_die)
18344         last_die->die_child = part_die;
18345       else if (last_die)
18346         last_die->die_sibling = part_die;
18347
18348       last_die = part_die;
18349
18350       if (first_die == NULL)
18351         first_die = part_die;
18352
18353       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18354          find interesting need to be in the hash table, because we
18355          also have the parent/sibling/child chains; only those that we
18356          might refer to by offset later during partial symbol reading.
18357
18358          For now this means things that might have be the target of a
18359          DW_AT_specification, DW_AT_abstract_origin, or
18360          DW_AT_extension.  DW_AT_extension will refer only to
18361          namespaces; DW_AT_abstract_origin refers to functions (and
18362          many things under the function DIE, but we do not recurse
18363          into function DIEs during partial symbol reading) and
18364          possibly variables as well; DW_AT_specification refers to
18365          declarations.  Declarations ought to have the DW_AT_declaration
18366          flag.  It happens that GCC forgets to put it in sometimes, but
18367          only for functions, not for types.
18368
18369          Adding more things than necessary to the hash table is harmless
18370          except for the performance cost.  Adding too few will result in
18371          wasted time in find_partial_die, when we reread the compilation
18372          unit with load_all_dies set.  */
18373
18374       if (load_all
18375           || abbrev->tag == DW_TAG_constant
18376           || abbrev->tag == DW_TAG_subprogram
18377           || abbrev->tag == DW_TAG_variable
18378           || abbrev->tag == DW_TAG_namespace
18379           || part_die->is_declaration)
18380         {
18381           void **slot;
18382
18383           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18384                                            to_underlying (part_die->sect_off),
18385                                            INSERT);
18386           *slot = part_die;
18387         }
18388
18389       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18390
18391       /* For some DIEs we want to follow their children (if any).  For C
18392          we have no reason to follow the children of structures; for other
18393          languages we have to, so that we can get at method physnames
18394          to infer fully qualified class names, for DW_AT_specification,
18395          and for C++ template arguments.  For C++, we also look one level
18396          inside functions to find template arguments (if the name of the
18397          function does not already contain the template arguments).
18398
18399          For Ada, we need to scan the children of subprograms and lexical
18400          blocks as well because Ada allows the definition of nested
18401          entities that could be interesting for the debugger, such as
18402          nested subprograms for instance.  */
18403       if (last_die->has_children
18404           && (load_all
18405               || last_die->tag == DW_TAG_namespace
18406               || last_die->tag == DW_TAG_module
18407               || last_die->tag == DW_TAG_enumeration_type
18408               || (cu->language == language_cplus
18409                   && last_die->tag == DW_TAG_subprogram
18410                   && (last_die->name == NULL
18411                       || strchr (last_die->name, '<') == NULL))
18412               || (cu->language != language_c
18413                   && (last_die->tag == DW_TAG_class_type
18414                       || last_die->tag == DW_TAG_interface_type
18415                       || last_die->tag == DW_TAG_structure_type
18416                       || last_die->tag == DW_TAG_union_type))
18417               || (cu->language == language_ada
18418                   && (last_die->tag == DW_TAG_subprogram
18419                       || last_die->tag == DW_TAG_lexical_block))))
18420         {
18421           nesting_level++;
18422           parent_die = last_die;
18423           continue;
18424         }
18425
18426       /* Otherwise we skip to the next sibling, if any.  */
18427       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18428
18429       /* Back to the top, do it again.  */
18430     }
18431 }
18432
18433 /* Read a minimal amount of information into the minimal die structure.  */
18434
18435 static const gdb_byte *
18436 read_partial_die (const struct die_reader_specs *reader,
18437                   struct partial_die_info *part_die,
18438                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18439                   const gdb_byte *info_ptr)
18440 {
18441   struct dwarf2_cu *cu = reader->cu;
18442   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18443   const gdb_byte *buffer = reader->buffer;
18444   unsigned int i;
18445   struct attribute attr;
18446   int has_low_pc_attr = 0;
18447   int has_high_pc_attr = 0;
18448   int high_pc_relative = 0;
18449
18450   memset (part_die, 0, sizeof (struct partial_die_info));
18451
18452   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18453
18454   info_ptr += abbrev_len;
18455
18456   if (abbrev == NULL)
18457     return info_ptr;
18458
18459   part_die->tag = abbrev->tag;
18460   part_die->has_children = abbrev->has_children;
18461
18462   for (i = 0; i < abbrev->num_attrs; ++i)
18463     {
18464       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18465
18466       /* Store the data if it is of an attribute we want to keep in a
18467          partial symbol table.  */
18468       switch (attr.name)
18469         {
18470         case DW_AT_name:
18471           switch (part_die->tag)
18472             {
18473             case DW_TAG_compile_unit:
18474             case DW_TAG_partial_unit:
18475             case DW_TAG_type_unit:
18476               /* Compilation units have a DW_AT_name that is a filename, not
18477                  a source language identifier.  */
18478             case DW_TAG_enumeration_type:
18479             case DW_TAG_enumerator:
18480               /* These tags always have simple identifiers already; no need
18481                  to canonicalize them.  */
18482               part_die->name = DW_STRING (&attr);
18483               break;
18484             default:
18485               part_die->name
18486                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18487                                             &objfile->per_bfd->storage_obstack);
18488               break;
18489             }
18490           break;
18491         case DW_AT_linkage_name:
18492         case DW_AT_MIPS_linkage_name:
18493           /* Note that both forms of linkage name might appear.  We
18494              assume they will be the same, and we only store the last
18495              one we see.  */
18496           if (cu->language == language_ada)
18497             part_die->name = DW_STRING (&attr);
18498           part_die->linkage_name = DW_STRING (&attr);
18499           break;
18500         case DW_AT_low_pc:
18501           has_low_pc_attr = 1;
18502           part_die->lowpc = attr_value_as_address (&attr);
18503           break;
18504         case DW_AT_high_pc:
18505           has_high_pc_attr = 1;
18506           part_die->highpc = attr_value_as_address (&attr);
18507           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18508                 high_pc_relative = 1;
18509           break;
18510         case DW_AT_location:
18511           /* Support the .debug_loc offsets.  */
18512           if (attr_form_is_block (&attr))
18513             {
18514                part_die->d.locdesc = DW_BLOCK (&attr);
18515             }
18516           else if (attr_form_is_section_offset (&attr))
18517             {
18518               dwarf2_complex_location_expr_complaint ();
18519             }
18520           else
18521             {
18522               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18523                                                      "partial symbol information");
18524             }
18525           break;
18526         case DW_AT_external:
18527           part_die->is_external = DW_UNSND (&attr);
18528           break;
18529         case DW_AT_declaration:
18530           part_die->is_declaration = DW_UNSND (&attr);
18531           break;
18532         case DW_AT_type:
18533           part_die->has_type = 1;
18534           break;
18535         case DW_AT_abstract_origin:
18536         case DW_AT_specification:
18537         case DW_AT_extension:
18538           part_die->has_specification = 1;
18539           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18540           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18541                                    || cu->per_cu->is_dwz);
18542           break;
18543         case DW_AT_sibling:
18544           /* Ignore absolute siblings, they might point outside of
18545              the current compile unit.  */
18546           if (attr.form == DW_FORM_ref_addr)
18547             complaint (&symfile_complaints,
18548                        _("ignoring absolute DW_AT_sibling"));
18549           else
18550             {
18551               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18552               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18553
18554               if (sibling_ptr < info_ptr)
18555                 complaint (&symfile_complaints,
18556                            _("DW_AT_sibling points backwards"));
18557               else if (sibling_ptr > reader->buffer_end)
18558                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18559               else
18560                 part_die->sibling = sibling_ptr;
18561             }
18562           break;
18563         case DW_AT_byte_size:
18564           part_die->has_byte_size = 1;
18565           break;
18566         case DW_AT_const_value:
18567           part_die->has_const_value = 1;
18568           break;
18569         case DW_AT_calling_convention:
18570           /* DWARF doesn't provide a way to identify a program's source-level
18571              entry point.  DW_AT_calling_convention attributes are only meant
18572              to describe functions' calling conventions.
18573
18574              However, because it's a necessary piece of information in
18575              Fortran, and before DWARF 4 DW_CC_program was the only
18576              piece of debugging information whose definition refers to
18577              a 'main program' at all, several compilers marked Fortran
18578              main programs with DW_CC_program --- even when those
18579              functions use the standard calling conventions.
18580
18581              Although DWARF now specifies a way to provide this
18582              information, we support this practice for backward
18583              compatibility.  */
18584           if (DW_UNSND (&attr) == DW_CC_program
18585               && cu->language == language_fortran)
18586             part_die->main_subprogram = 1;
18587           break;
18588         case DW_AT_inline:
18589           if (DW_UNSND (&attr) == DW_INL_inlined
18590               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18591             part_die->may_be_inlined = 1;
18592           break;
18593
18594         case DW_AT_import:
18595           if (part_die->tag == DW_TAG_imported_unit)
18596             {
18597               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18598               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18599                                   || cu->per_cu->is_dwz);
18600             }
18601           break;
18602
18603         case DW_AT_main_subprogram:
18604           part_die->main_subprogram = DW_UNSND (&attr);
18605           break;
18606
18607         default:
18608           break;
18609         }
18610     }
18611
18612   if (high_pc_relative)
18613     part_die->highpc += part_die->lowpc;
18614
18615   if (has_low_pc_attr && has_high_pc_attr)
18616     {
18617       /* When using the GNU linker, .gnu.linkonce. sections are used to
18618          eliminate duplicate copies of functions and vtables and such.
18619          The linker will arbitrarily choose one and discard the others.
18620          The AT_*_pc values for such functions refer to local labels in
18621          these sections.  If the section from that file was discarded, the
18622          labels are not in the output, so the relocs get a value of 0.
18623          If this is a discarded function, mark the pc bounds as invalid,
18624          so that GDB will ignore it.  */
18625       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18626         {
18627           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18628
18629           complaint (&symfile_complaints,
18630                      _("DW_AT_low_pc %s is zero "
18631                        "for DIE at 0x%x [in module %s]"),
18632                      paddress (gdbarch, part_die->lowpc),
18633                      to_underlying (part_die->sect_off), objfile_name (objfile));
18634         }
18635       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18636       else if (part_die->lowpc >= part_die->highpc)
18637         {
18638           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18639
18640           complaint (&symfile_complaints,
18641                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18642                        "for DIE at 0x%x [in module %s]"),
18643                      paddress (gdbarch, part_die->lowpc),
18644                      paddress (gdbarch, part_die->highpc),
18645                      to_underlying (part_die->sect_off),
18646                      objfile_name (objfile));
18647         }
18648       else
18649         part_die->has_pc_info = 1;
18650     }
18651
18652   return info_ptr;
18653 }
18654
18655 /* Find a cached partial DIE at OFFSET in CU.  */
18656
18657 static struct partial_die_info *
18658 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18659 {
18660   struct partial_die_info *lookup_die = NULL;
18661   struct partial_die_info part_die;
18662
18663   part_die.sect_off = sect_off;
18664   lookup_die = ((struct partial_die_info *)
18665                 htab_find_with_hash (cu->partial_dies, &part_die,
18666                                      to_underlying (sect_off)));
18667
18668   return lookup_die;
18669 }
18670
18671 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18672    except in the case of .debug_types DIEs which do not reference
18673    outside their CU (they do however referencing other types via
18674    DW_FORM_ref_sig8).  */
18675
18676 static struct partial_die_info *
18677 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18678 {
18679   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18680   struct dwarf2_per_cu_data *per_cu = NULL;
18681   struct partial_die_info *pd = NULL;
18682
18683   if (offset_in_dwz == cu->per_cu->is_dwz
18684       && offset_in_cu_p (&cu->header, sect_off))
18685     {
18686       pd = find_partial_die_in_comp_unit (sect_off, cu);
18687       if (pd != NULL)
18688         return pd;
18689       /* We missed recording what we needed.
18690          Load all dies and try again.  */
18691       per_cu = cu->per_cu;
18692     }
18693   else
18694     {
18695       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18696       if (cu->per_cu->is_debug_types)
18697         {
18698           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18699                    " external reference to offset 0x%x [in module %s].\n"),
18700                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18701                  bfd_get_filename (objfile->obfd));
18702         }
18703       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18704                                                  objfile);
18705
18706       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18707         load_partial_comp_unit (per_cu);
18708
18709       per_cu->cu->last_used = 0;
18710       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18711     }
18712
18713   /* If we didn't find it, and not all dies have been loaded,
18714      load them all and try again.  */
18715
18716   if (pd == NULL && per_cu->load_all_dies == 0)
18717     {
18718       per_cu->load_all_dies = 1;
18719
18720       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18721          THIS_CU->cu may already be in use.  So we can't just free it and
18722          replace its DIEs with the ones we read in.  Instead, we leave those
18723          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18724          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18725          set.  */
18726       load_partial_comp_unit (per_cu);
18727
18728       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18729     }
18730
18731   if (pd == NULL)
18732     internal_error (__FILE__, __LINE__,
18733                     _("could not find partial DIE 0x%x "
18734                       "in cache [from module %s]\n"),
18735                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18736   return pd;
18737 }
18738
18739 /* See if we can figure out if the class lives in a namespace.  We do
18740    this by looking for a member function; its demangled name will
18741    contain namespace info, if there is any.  */
18742
18743 static void
18744 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18745                                   struct dwarf2_cu *cu)
18746 {
18747   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18748      what template types look like, because the demangler
18749      frequently doesn't give the same name as the debug info.  We
18750      could fix this by only using the demangled name to get the
18751      prefix (but see comment in read_structure_type).  */
18752
18753   struct partial_die_info *real_pdi;
18754   struct partial_die_info *child_pdi;
18755
18756   /* If this DIE (this DIE's specification, if any) has a parent, then
18757      we should not do this.  We'll prepend the parent's fully qualified
18758      name when we create the partial symbol.  */
18759
18760   real_pdi = struct_pdi;
18761   while (real_pdi->has_specification)
18762     real_pdi = find_partial_die (real_pdi->spec_offset,
18763                                  real_pdi->spec_is_dwz, cu);
18764
18765   if (real_pdi->die_parent != NULL)
18766     return;
18767
18768   for (child_pdi = struct_pdi->die_child;
18769        child_pdi != NULL;
18770        child_pdi = child_pdi->die_sibling)
18771     {
18772       if (child_pdi->tag == DW_TAG_subprogram
18773           && child_pdi->linkage_name != NULL)
18774         {
18775           char *actual_class_name
18776             = language_class_name_from_physname (cu->language_defn,
18777                                                  child_pdi->linkage_name);
18778           if (actual_class_name != NULL)
18779             {
18780               struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18781               struct_pdi->name
18782                 = ((const char *)
18783                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18784                                   actual_class_name,
18785                                   strlen (actual_class_name)));
18786               xfree (actual_class_name);
18787             }
18788           break;
18789         }
18790     }
18791 }
18792
18793 /* Adjust PART_DIE before generating a symbol for it.  This function
18794    may set the is_external flag or change the DIE's name.  */
18795
18796 static void
18797 fixup_partial_die (struct partial_die_info *part_die,
18798                    struct dwarf2_cu *cu)
18799 {
18800   /* Once we've fixed up a die, there's no point in doing so again.
18801      This also avoids a memory leak if we were to call
18802      guess_partial_die_structure_name multiple times.  */
18803   if (part_die->fixup_called)
18804     return;
18805
18806   /* If we found a reference attribute and the DIE has no name, try
18807      to find a name in the referred to DIE.  */
18808
18809   if (part_die->name == NULL && part_die->has_specification)
18810     {
18811       struct partial_die_info *spec_die;
18812
18813       spec_die = find_partial_die (part_die->spec_offset,
18814                                    part_die->spec_is_dwz, cu);
18815
18816       fixup_partial_die (spec_die, cu);
18817
18818       if (spec_die->name)
18819         {
18820           part_die->name = spec_die->name;
18821
18822           /* Copy DW_AT_external attribute if it is set.  */
18823           if (spec_die->is_external)
18824             part_die->is_external = spec_die->is_external;
18825         }
18826     }
18827
18828   /* Set default names for some unnamed DIEs.  */
18829
18830   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18831     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18832
18833   /* If there is no parent die to provide a namespace, and there are
18834      children, see if we can determine the namespace from their linkage
18835      name.  */
18836   if (cu->language == language_cplus
18837       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18838       && part_die->die_parent == NULL
18839       && part_die->has_children
18840       && (part_die->tag == DW_TAG_class_type
18841           || part_die->tag == DW_TAG_structure_type
18842           || part_die->tag == DW_TAG_union_type))
18843     guess_partial_die_structure_name (part_die, cu);
18844
18845   /* GCC might emit a nameless struct or union that has a linkage
18846      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18847   if (part_die->name == NULL
18848       && (part_die->tag == DW_TAG_class_type
18849           || part_die->tag == DW_TAG_interface_type
18850           || part_die->tag == DW_TAG_structure_type
18851           || part_die->tag == DW_TAG_union_type)
18852       && part_die->linkage_name != NULL)
18853     {
18854       char *demangled;
18855
18856       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18857       if (demangled)
18858         {
18859           const char *base;
18860
18861           /* Strip any leading namespaces/classes, keep only the base name.
18862              DW_AT_name for named DIEs does not contain the prefixes.  */
18863           base = strrchr (demangled, ':');
18864           if (base && base > demangled && base[-1] == ':')
18865             base++;
18866           else
18867             base = demangled;
18868
18869           struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18870           part_die->name
18871             = ((const char *)
18872                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18873                               base, strlen (base)));
18874           xfree (demangled);
18875         }
18876     }
18877
18878   part_die->fixup_called = 1;
18879 }
18880
18881 /* Read an attribute value described by an attribute form.  */
18882
18883 static const gdb_byte *
18884 read_attribute_value (const struct die_reader_specs *reader,
18885                       struct attribute *attr, unsigned form,
18886                       LONGEST implicit_const, const gdb_byte *info_ptr)
18887 {
18888   struct dwarf2_cu *cu = reader->cu;
18889   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18890   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18891   bfd *abfd = reader->abfd;
18892   struct comp_unit_head *cu_header = &cu->header;
18893   unsigned int bytes_read;
18894   struct dwarf_block *blk;
18895
18896   attr->form = (enum dwarf_form) form;
18897   switch (form)
18898     {
18899     case DW_FORM_ref_addr:
18900       if (cu->header.version == 2)
18901         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18902       else
18903         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18904                                        &cu->header, &bytes_read);
18905       info_ptr += bytes_read;
18906       break;
18907     case DW_FORM_GNU_ref_alt:
18908       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18909       info_ptr += bytes_read;
18910       break;
18911     case DW_FORM_addr:
18912       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18913       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18914       info_ptr += bytes_read;
18915       break;
18916     case DW_FORM_block2:
18917       blk = dwarf_alloc_block (cu);
18918       blk->size = read_2_bytes (abfd, info_ptr);
18919       info_ptr += 2;
18920       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18921       info_ptr += blk->size;
18922       DW_BLOCK (attr) = blk;
18923       break;
18924     case DW_FORM_block4:
18925       blk = dwarf_alloc_block (cu);
18926       blk->size = read_4_bytes (abfd, info_ptr);
18927       info_ptr += 4;
18928       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18929       info_ptr += blk->size;
18930       DW_BLOCK (attr) = blk;
18931       break;
18932     case DW_FORM_data2:
18933       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18934       info_ptr += 2;
18935       break;
18936     case DW_FORM_data4:
18937       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18938       info_ptr += 4;
18939       break;
18940     case DW_FORM_data8:
18941       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18942       info_ptr += 8;
18943       break;
18944     case DW_FORM_data16:
18945       blk = dwarf_alloc_block (cu);
18946       blk->size = 16;
18947       blk->data = read_n_bytes (abfd, info_ptr, 16);
18948       info_ptr += 16;
18949       DW_BLOCK (attr) = blk;
18950       break;
18951     case DW_FORM_sec_offset:
18952       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18953       info_ptr += bytes_read;
18954       break;
18955     case DW_FORM_string:
18956       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18957       DW_STRING_IS_CANONICAL (attr) = 0;
18958       info_ptr += bytes_read;
18959       break;
18960     case DW_FORM_strp:
18961       if (!cu->per_cu->is_dwz)
18962         {
18963           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
18964                                                    &bytes_read);
18965           DW_STRING_IS_CANONICAL (attr) = 0;
18966           info_ptr += bytes_read;
18967           break;
18968         }
18969       /* FALLTHROUGH */
18970     case DW_FORM_line_strp:
18971       if (!cu->per_cu->is_dwz)
18972         {
18973           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
18974                                                         cu_header, &bytes_read);
18975           DW_STRING_IS_CANONICAL (attr) = 0;
18976           info_ptr += bytes_read;
18977           break;
18978         }
18979       /* FALLTHROUGH */
18980     case DW_FORM_GNU_strp_alt:
18981       {
18982         struct dwz_file *dwz = dwarf2_get_dwz_file ();
18983         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18984                                           &bytes_read);
18985
18986         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
18987         DW_STRING_IS_CANONICAL (attr) = 0;
18988         info_ptr += bytes_read;
18989       }
18990       break;
18991     case DW_FORM_exprloc:
18992     case DW_FORM_block:
18993       blk = dwarf_alloc_block (cu);
18994       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18995       info_ptr += bytes_read;
18996       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18997       info_ptr += blk->size;
18998       DW_BLOCK (attr) = blk;
18999       break;
19000     case DW_FORM_block1:
19001       blk = dwarf_alloc_block (cu);
19002       blk->size = read_1_byte (abfd, info_ptr);
19003       info_ptr += 1;
19004       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19005       info_ptr += blk->size;
19006       DW_BLOCK (attr) = blk;
19007       break;
19008     case DW_FORM_data1:
19009       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19010       info_ptr += 1;
19011       break;
19012     case DW_FORM_flag:
19013       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19014       info_ptr += 1;
19015       break;
19016     case DW_FORM_flag_present:
19017       DW_UNSND (attr) = 1;
19018       break;
19019     case DW_FORM_sdata:
19020       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19021       info_ptr += bytes_read;
19022       break;
19023     case DW_FORM_udata:
19024       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19025       info_ptr += bytes_read;
19026       break;
19027     case DW_FORM_ref1:
19028       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19029                          + read_1_byte (abfd, info_ptr));
19030       info_ptr += 1;
19031       break;
19032     case DW_FORM_ref2:
19033       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19034                          + read_2_bytes (abfd, info_ptr));
19035       info_ptr += 2;
19036       break;
19037     case DW_FORM_ref4:
19038       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19039                          + read_4_bytes (abfd, info_ptr));
19040       info_ptr += 4;
19041       break;
19042     case DW_FORM_ref8:
19043       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19044                          + read_8_bytes (abfd, info_ptr));
19045       info_ptr += 8;
19046       break;
19047     case DW_FORM_ref_sig8:
19048       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19049       info_ptr += 8;
19050       break;
19051     case DW_FORM_ref_udata:
19052       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19053                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19054       info_ptr += bytes_read;
19055       break;
19056     case DW_FORM_indirect:
19057       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19058       info_ptr += bytes_read;
19059       if (form == DW_FORM_implicit_const)
19060         {
19061           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19062           info_ptr += bytes_read;
19063         }
19064       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19065                                        info_ptr);
19066       break;
19067     case DW_FORM_implicit_const:
19068       DW_SND (attr) = implicit_const;
19069       break;
19070     case DW_FORM_GNU_addr_index:
19071       if (reader->dwo_file == NULL)
19072         {
19073           /* For now flag a hard error.
19074              Later we can turn this into a complaint.  */
19075           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19076                  dwarf_form_name (form),
19077                  bfd_get_filename (abfd));
19078         }
19079       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19080       info_ptr += bytes_read;
19081       break;
19082     case DW_FORM_GNU_str_index:
19083       if (reader->dwo_file == NULL)
19084         {
19085           /* For now flag a hard error.
19086              Later we can turn this into a complaint if warranted.  */
19087           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19088                  dwarf_form_name (form),
19089                  bfd_get_filename (abfd));
19090         }
19091       {
19092         ULONGEST str_index =
19093           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19094
19095         DW_STRING (attr) = read_str_index (reader, str_index);
19096         DW_STRING_IS_CANONICAL (attr) = 0;
19097         info_ptr += bytes_read;
19098       }
19099       break;
19100     default:
19101       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19102              dwarf_form_name (form),
19103              bfd_get_filename (abfd));
19104     }
19105
19106   /* Super hack.  */
19107   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19108     attr->form = DW_FORM_GNU_ref_alt;
19109
19110   /* We have seen instances where the compiler tried to emit a byte
19111      size attribute of -1 which ended up being encoded as an unsigned
19112      0xffffffff.  Although 0xffffffff is technically a valid size value,
19113      an object of this size seems pretty unlikely so we can relatively
19114      safely treat these cases as if the size attribute was invalid and
19115      treat them as zero by default.  */
19116   if (attr->name == DW_AT_byte_size
19117       && form == DW_FORM_data4
19118       && DW_UNSND (attr) >= 0xffffffff)
19119     {
19120       complaint
19121         (&symfile_complaints,
19122          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19123          hex_string (DW_UNSND (attr)));
19124       DW_UNSND (attr) = 0;
19125     }
19126
19127   return info_ptr;
19128 }
19129
19130 /* Read an attribute described by an abbreviated attribute.  */
19131
19132 static const gdb_byte *
19133 read_attribute (const struct die_reader_specs *reader,
19134                 struct attribute *attr, struct attr_abbrev *abbrev,
19135                 const gdb_byte *info_ptr)
19136 {
19137   attr->name = abbrev->name;
19138   return read_attribute_value (reader, attr, abbrev->form,
19139                                abbrev->implicit_const, info_ptr);
19140 }
19141
19142 /* Read dwarf information from a buffer.  */
19143
19144 static unsigned int
19145 read_1_byte (bfd *abfd, const gdb_byte *buf)
19146 {
19147   return bfd_get_8 (abfd, buf);
19148 }
19149
19150 static int
19151 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19152 {
19153   return bfd_get_signed_8 (abfd, buf);
19154 }
19155
19156 static unsigned int
19157 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19158 {
19159   return bfd_get_16 (abfd, buf);
19160 }
19161
19162 static int
19163 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19164 {
19165   return bfd_get_signed_16 (abfd, buf);
19166 }
19167
19168 static unsigned int
19169 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19170 {
19171   return bfd_get_32 (abfd, buf);
19172 }
19173
19174 static int
19175 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19176 {
19177   return bfd_get_signed_32 (abfd, buf);
19178 }
19179
19180 static ULONGEST
19181 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19182 {
19183   return bfd_get_64 (abfd, buf);
19184 }
19185
19186 static CORE_ADDR
19187 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19188               unsigned int *bytes_read)
19189 {
19190   struct comp_unit_head *cu_header = &cu->header;
19191   CORE_ADDR retval = 0;
19192
19193   if (cu_header->signed_addr_p)
19194     {
19195       switch (cu_header->addr_size)
19196         {
19197         case 2:
19198           retval = bfd_get_signed_16 (abfd, buf);
19199           break;
19200         case 4:
19201           retval = bfd_get_signed_32 (abfd, buf);
19202           break;
19203         case 8:
19204           retval = bfd_get_signed_64 (abfd, buf);
19205           break;
19206         default:
19207           internal_error (__FILE__, __LINE__,
19208                           _("read_address: bad switch, signed [in module %s]"),
19209                           bfd_get_filename (abfd));
19210         }
19211     }
19212   else
19213     {
19214       switch (cu_header->addr_size)
19215         {
19216         case 2:
19217           retval = bfd_get_16 (abfd, buf);
19218           break;
19219         case 4:
19220           retval = bfd_get_32 (abfd, buf);
19221           break;
19222         case 8:
19223           retval = bfd_get_64 (abfd, buf);
19224           break;
19225         default:
19226           internal_error (__FILE__, __LINE__,
19227                           _("read_address: bad switch, "
19228                             "unsigned [in module %s]"),
19229                           bfd_get_filename (abfd));
19230         }
19231     }
19232
19233   *bytes_read = cu_header->addr_size;
19234   return retval;
19235 }
19236
19237 /* Read the initial length from a section.  The (draft) DWARF 3
19238    specification allows the initial length to take up either 4 bytes
19239    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19240    bytes describe the length and all offsets will be 8 bytes in length
19241    instead of 4.
19242
19243    An older, non-standard 64-bit format is also handled by this
19244    function.  The older format in question stores the initial length
19245    as an 8-byte quantity without an escape value.  Lengths greater
19246    than 2^32 aren't very common which means that the initial 4 bytes
19247    is almost always zero.  Since a length value of zero doesn't make
19248    sense for the 32-bit format, this initial zero can be considered to
19249    be an escape value which indicates the presence of the older 64-bit
19250    format.  As written, the code can't detect (old format) lengths
19251    greater than 4GB.  If it becomes necessary to handle lengths
19252    somewhat larger than 4GB, we could allow other small values (such
19253    as the non-sensical values of 1, 2, and 3) to also be used as
19254    escape values indicating the presence of the old format.
19255
19256    The value returned via bytes_read should be used to increment the
19257    relevant pointer after calling read_initial_length().
19258
19259    [ Note:  read_initial_length() and read_offset() are based on the
19260      document entitled "DWARF Debugging Information Format", revision
19261      3, draft 8, dated November 19, 2001.  This document was obtained
19262      from:
19263
19264         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19265
19266      This document is only a draft and is subject to change.  (So beware.)
19267
19268      Details regarding the older, non-standard 64-bit format were
19269      determined empirically by examining 64-bit ELF files produced by
19270      the SGI toolchain on an IRIX 6.5 machine.
19271
19272      - Kevin, July 16, 2002
19273    ] */
19274
19275 static LONGEST
19276 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19277 {
19278   LONGEST length = bfd_get_32 (abfd, buf);
19279
19280   if (length == 0xffffffff)
19281     {
19282       length = bfd_get_64 (abfd, buf + 4);
19283       *bytes_read = 12;
19284     }
19285   else if (length == 0)
19286     {
19287       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19288       length = bfd_get_64 (abfd, buf);
19289       *bytes_read = 8;
19290     }
19291   else
19292     {
19293       *bytes_read = 4;
19294     }
19295
19296   return length;
19297 }
19298
19299 /* Cover function for read_initial_length.
19300    Returns the length of the object at BUF, and stores the size of the
19301    initial length in *BYTES_READ and stores the size that offsets will be in
19302    *OFFSET_SIZE.
19303    If the initial length size is not equivalent to that specified in
19304    CU_HEADER then issue a complaint.
19305    This is useful when reading non-comp-unit headers.  */
19306
19307 static LONGEST
19308 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19309                                         const struct comp_unit_head *cu_header,
19310                                         unsigned int *bytes_read,
19311                                         unsigned int *offset_size)
19312 {
19313   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19314
19315   gdb_assert (cu_header->initial_length_size == 4
19316               || cu_header->initial_length_size == 8
19317               || cu_header->initial_length_size == 12);
19318
19319   if (cu_header->initial_length_size != *bytes_read)
19320     complaint (&symfile_complaints,
19321                _("intermixed 32-bit and 64-bit DWARF sections"));
19322
19323   *offset_size = (*bytes_read == 4) ? 4 : 8;
19324   return length;
19325 }
19326
19327 /* Read an offset from the data stream.  The size of the offset is
19328    given by cu_header->offset_size.  */
19329
19330 static LONGEST
19331 read_offset (bfd *abfd, const gdb_byte *buf,
19332              const struct comp_unit_head *cu_header,
19333              unsigned int *bytes_read)
19334 {
19335   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19336
19337   *bytes_read = cu_header->offset_size;
19338   return offset;
19339 }
19340
19341 /* Read an offset from the data stream.  */
19342
19343 static LONGEST
19344 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19345 {
19346   LONGEST retval = 0;
19347
19348   switch (offset_size)
19349     {
19350     case 4:
19351       retval = bfd_get_32 (abfd, buf);
19352       break;
19353     case 8:
19354       retval = bfd_get_64 (abfd, buf);
19355       break;
19356     default:
19357       internal_error (__FILE__, __LINE__,
19358                       _("read_offset_1: bad switch [in module %s]"),
19359                       bfd_get_filename (abfd));
19360     }
19361
19362   return retval;
19363 }
19364
19365 static const gdb_byte *
19366 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19367 {
19368   /* If the size of a host char is 8 bits, we can return a pointer
19369      to the buffer, otherwise we have to copy the data to a buffer
19370      allocated on the temporary obstack.  */
19371   gdb_assert (HOST_CHAR_BIT == 8);
19372   return buf;
19373 }
19374
19375 static const char *
19376 read_direct_string (bfd *abfd, const gdb_byte *buf,
19377                     unsigned int *bytes_read_ptr)
19378 {
19379   /* If the size of a host char is 8 bits, we can return a pointer
19380      to the string, otherwise we have to copy the string to a buffer
19381      allocated on the temporary obstack.  */
19382   gdb_assert (HOST_CHAR_BIT == 8);
19383   if (*buf == '\0')
19384     {
19385       *bytes_read_ptr = 1;
19386       return NULL;
19387     }
19388   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19389   return (const char *) buf;
19390 }
19391
19392 /* Return pointer to string at section SECT offset STR_OFFSET with error
19393    reporting strings FORM_NAME and SECT_NAME.  */
19394
19395 static const char *
19396 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
19397                                      struct dwarf2_section_info *sect,
19398                                      const char *form_name,
19399                                      const char *sect_name)
19400 {
19401   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
19402   if (sect->buffer == NULL)
19403     error (_("%s used without %s section [in module %s]"),
19404            form_name, sect_name, bfd_get_filename (abfd));
19405   if (str_offset >= sect->size)
19406     error (_("%s pointing outside of %s section [in module %s]"),
19407            form_name, sect_name, bfd_get_filename (abfd));
19408   gdb_assert (HOST_CHAR_BIT == 8);
19409   if (sect->buffer[str_offset] == '\0')
19410     return NULL;
19411   return (const char *) (sect->buffer + str_offset);
19412 }
19413
19414 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19415
19416 static const char *
19417 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
19418 {
19419   return read_indirect_string_at_offset_from (abfd, str_offset,
19420                                               &dwarf2_per_objfile->str,
19421                                               "DW_FORM_strp", ".debug_str");
19422 }
19423
19424 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19425
19426 static const char *
19427 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
19428 {
19429   return read_indirect_string_at_offset_from (abfd, str_offset,
19430                                               &dwarf2_per_objfile->line_str,
19431                                               "DW_FORM_line_strp",
19432                                               ".debug_line_str");
19433 }
19434
19435 /* Read a string at offset STR_OFFSET in the .debug_str section from
19436    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19437    the string consists of a single NUL byte, return NULL; otherwise
19438    return a pointer to the string.  */
19439
19440 static const char *
19441 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
19442 {
19443   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
19444
19445   if (dwz->str.buffer == NULL)
19446     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19447              "section [in module %s]"),
19448            bfd_get_filename (dwz->dwz_bfd));
19449   if (str_offset >= dwz->str.size)
19450     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19451              ".debug_str section [in module %s]"),
19452            bfd_get_filename (dwz->dwz_bfd));
19453   gdb_assert (HOST_CHAR_BIT == 8);
19454   if (dwz->str.buffer[str_offset] == '\0')
19455     return NULL;
19456   return (const char *) (dwz->str.buffer + str_offset);
19457 }
19458
19459 /* Return pointer to string at .debug_str offset as read from BUF.
19460    BUF is assumed to be in a compilation unit described by CU_HEADER.
19461    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19462
19463 static const char *
19464 read_indirect_string (bfd *abfd, const gdb_byte *buf,
19465                       const struct comp_unit_head *cu_header,
19466                       unsigned int *bytes_read_ptr)
19467 {
19468   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19469
19470   return read_indirect_string_at_offset (abfd, str_offset);
19471 }
19472
19473 /* Return pointer to string at .debug_line_str offset as read from BUF.
19474    BUF is assumed to be in a compilation unit described by CU_HEADER.
19475    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19476
19477 static const char *
19478 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
19479                            const struct comp_unit_head *cu_header,
19480                            unsigned int *bytes_read_ptr)
19481 {
19482   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19483
19484   return read_indirect_line_string_at_offset (abfd, str_offset);
19485 }
19486
19487 ULONGEST
19488 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19489                           unsigned int *bytes_read_ptr)
19490 {
19491   ULONGEST result;
19492   unsigned int num_read;
19493   int shift;
19494   unsigned char byte;
19495
19496   result = 0;
19497   shift = 0;
19498   num_read = 0;
19499   while (1)
19500     {
19501       byte = bfd_get_8 (abfd, buf);
19502       buf++;
19503       num_read++;
19504       result |= ((ULONGEST) (byte & 127) << shift);
19505       if ((byte & 128) == 0)
19506         {
19507           break;
19508         }
19509       shift += 7;
19510     }
19511   *bytes_read_ptr = num_read;
19512   return result;
19513 }
19514
19515 static LONGEST
19516 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19517                     unsigned int *bytes_read_ptr)
19518 {
19519   LONGEST result;
19520   int shift, num_read;
19521   unsigned char byte;
19522
19523   result = 0;
19524   shift = 0;
19525   num_read = 0;
19526   while (1)
19527     {
19528       byte = bfd_get_8 (abfd, buf);
19529       buf++;
19530       num_read++;
19531       result |= ((LONGEST) (byte & 127) << shift);
19532       shift += 7;
19533       if ((byte & 128) == 0)
19534         {
19535           break;
19536         }
19537     }
19538   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19539     result |= -(((LONGEST) 1) << shift);
19540   *bytes_read_ptr = num_read;
19541   return result;
19542 }
19543
19544 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19545    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19546    ADDR_SIZE is the size of addresses from the CU header.  */
19547
19548 static CORE_ADDR
19549 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
19550 {
19551   struct objfile *objfile = dwarf2_per_objfile->objfile;
19552   bfd *abfd = objfile->obfd;
19553   const gdb_byte *info_ptr;
19554
19555   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19556   if (dwarf2_per_objfile->addr.buffer == NULL)
19557     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19558            objfile_name (objfile));
19559   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19560     error (_("DW_FORM_addr_index pointing outside of "
19561              ".debug_addr section [in module %s]"),
19562            objfile_name (objfile));
19563   info_ptr = (dwarf2_per_objfile->addr.buffer
19564               + addr_base + addr_index * addr_size);
19565   if (addr_size == 4)
19566     return bfd_get_32 (abfd, info_ptr);
19567   else
19568     return bfd_get_64 (abfd, info_ptr);
19569 }
19570
19571 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19572
19573 static CORE_ADDR
19574 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19575 {
19576   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
19577 }
19578
19579 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19580
19581 static CORE_ADDR
19582 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19583                              unsigned int *bytes_read)
19584 {
19585   bfd *abfd = cu->dwarf2_per_objfile->objfile->obfd;
19586   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19587
19588   return read_addr_index (cu, addr_index);
19589 }
19590
19591 /* Data structure to pass results from dwarf2_read_addr_index_reader
19592    back to dwarf2_read_addr_index.  */
19593
19594 struct dwarf2_read_addr_index_data
19595 {
19596   ULONGEST addr_base;
19597   int addr_size;
19598 };
19599
19600 /* die_reader_func for dwarf2_read_addr_index.  */
19601
19602 static void
19603 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19604                                const gdb_byte *info_ptr,
19605                                struct die_info *comp_unit_die,
19606                                int has_children,
19607                                void *data)
19608 {
19609   struct dwarf2_cu *cu = reader->cu;
19610   struct dwarf2_read_addr_index_data *aidata =
19611     (struct dwarf2_read_addr_index_data *) data;
19612
19613   aidata->addr_base = cu->addr_base;
19614   aidata->addr_size = cu->header.addr_size;
19615 }
19616
19617 /* Given an index in .debug_addr, fetch the value.
19618    NOTE: This can be called during dwarf expression evaluation,
19619    long after the debug information has been read, and thus per_cu->cu
19620    may no longer exist.  */
19621
19622 CORE_ADDR
19623 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19624                         unsigned int addr_index)
19625 {
19626   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
19627   struct dwarf2_cu *cu = per_cu->cu;
19628   ULONGEST addr_base;
19629   int addr_size;
19630
19631   /* This is intended to be called from outside this file.  */
19632   dw2_setup (objfile);
19633
19634   /* We need addr_base and addr_size.
19635      If we don't have PER_CU->cu, we have to get it.
19636      Nasty, but the alternative is storing the needed info in PER_CU,
19637      which at this point doesn't seem justified: it's not clear how frequently
19638      it would get used and it would increase the size of every PER_CU.
19639      Entry points like dwarf2_per_cu_addr_size do a similar thing
19640      so we're not in uncharted territory here.
19641      Alas we need to be a bit more complicated as addr_base is contained
19642      in the DIE.
19643
19644      We don't need to read the entire CU(/TU).
19645      We just need the header and top level die.
19646
19647      IWBN to use the aging mechanism to let us lazily later discard the CU.
19648      For now we skip this optimization.  */
19649
19650   if (cu != NULL)
19651     {
19652       addr_base = cu->addr_base;
19653       addr_size = cu->header.addr_size;
19654     }
19655   else
19656     {
19657       struct dwarf2_read_addr_index_data aidata;
19658
19659       /* Note: We can't use init_cutu_and_read_dies_simple here,
19660          we need addr_base.  */
19661       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19662                                dwarf2_read_addr_index_reader, &aidata);
19663       addr_base = aidata.addr_base;
19664       addr_size = aidata.addr_size;
19665     }
19666
19667   return read_addr_index_1 (addr_index, addr_base, addr_size);
19668 }
19669
19670 /* Given a DW_FORM_GNU_str_index, fetch the string.
19671    This is only used by the Fission support.  */
19672
19673 static const char *
19674 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19675 {
19676   struct objfile *objfile = dwarf2_per_objfile->objfile;
19677   const char *objf_name = objfile_name (objfile);
19678   bfd *abfd = objfile->obfd;
19679   struct dwarf2_cu *cu = reader->cu;
19680   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19681   struct dwarf2_section_info *str_offsets_section =
19682     &reader->dwo_file->sections.str_offsets;
19683   const gdb_byte *info_ptr;
19684   ULONGEST str_offset;
19685   static const char form_name[] = "DW_FORM_GNU_str_index";
19686
19687   dwarf2_read_section (objfile, str_section);
19688   dwarf2_read_section (objfile, str_offsets_section);
19689   if (str_section->buffer == NULL)
19690     error (_("%s used without .debug_str.dwo section"
19691              " in CU at offset 0x%x [in module %s]"),
19692            form_name, to_underlying (cu->header.sect_off), objf_name);
19693   if (str_offsets_section->buffer == NULL)
19694     error (_("%s used without .debug_str_offsets.dwo section"
19695              " in CU at offset 0x%x [in module %s]"),
19696            form_name, to_underlying (cu->header.sect_off), objf_name);
19697   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19698     error (_("%s pointing outside of .debug_str_offsets.dwo"
19699              " section in CU at offset 0x%x [in module %s]"),
19700            form_name, to_underlying (cu->header.sect_off), objf_name);
19701   info_ptr = (str_offsets_section->buffer
19702               + str_index * cu->header.offset_size);
19703   if (cu->header.offset_size == 4)
19704     str_offset = bfd_get_32 (abfd, info_ptr);
19705   else
19706     str_offset = bfd_get_64 (abfd, info_ptr);
19707   if (str_offset >= str_section->size)
19708     error (_("Offset from %s pointing outside of"
19709              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19710            form_name, to_underlying (cu->header.sect_off), objf_name);
19711   return (const char *) (str_section->buffer + str_offset);
19712 }
19713
19714 /* Return the length of an LEB128 number in BUF.  */
19715
19716 static int
19717 leb128_size (const gdb_byte *buf)
19718 {
19719   const gdb_byte *begin = buf;
19720   gdb_byte byte;
19721
19722   while (1)
19723     {
19724       byte = *buf++;
19725       if ((byte & 128) == 0)
19726         return buf - begin;
19727     }
19728 }
19729
19730 static void
19731 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19732 {
19733   switch (lang)
19734     {
19735     case DW_LANG_C89:
19736     case DW_LANG_C99:
19737     case DW_LANG_C11:
19738     case DW_LANG_C:
19739     case DW_LANG_UPC:
19740       cu->language = language_c;
19741       break;
19742     case DW_LANG_Java:
19743     case DW_LANG_C_plus_plus:
19744     case DW_LANG_C_plus_plus_11:
19745     case DW_LANG_C_plus_plus_14:
19746       cu->language = language_cplus;
19747       break;
19748     case DW_LANG_D:
19749       cu->language = language_d;
19750       break;
19751     case DW_LANG_Fortran77:
19752     case DW_LANG_Fortran90:
19753     case DW_LANG_Fortran95:
19754     case DW_LANG_Fortran03:
19755     case DW_LANG_Fortran08:
19756       cu->language = language_fortran;
19757       break;
19758     case DW_LANG_Go:
19759       cu->language = language_go;
19760       break;
19761     case DW_LANG_Mips_Assembler:
19762       cu->language = language_asm;
19763       break;
19764     case DW_LANG_Ada83:
19765     case DW_LANG_Ada95:
19766       cu->language = language_ada;
19767       break;
19768     case DW_LANG_Modula2:
19769       cu->language = language_m2;
19770       break;
19771     case DW_LANG_Pascal83:
19772       cu->language = language_pascal;
19773       break;
19774     case DW_LANG_ObjC:
19775       cu->language = language_objc;
19776       break;
19777     case DW_LANG_Rust:
19778     case DW_LANG_Rust_old:
19779       cu->language = language_rust;
19780       break;
19781     case DW_LANG_Cobol74:
19782     case DW_LANG_Cobol85:
19783     default:
19784       cu->language = language_minimal;
19785       break;
19786     }
19787   cu->language_defn = language_def (cu->language);
19788 }
19789
19790 /* Return the named attribute or NULL if not there.  */
19791
19792 static struct attribute *
19793 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19794 {
19795   for (;;)
19796     {
19797       unsigned int i;
19798       struct attribute *spec = NULL;
19799
19800       for (i = 0; i < die->num_attrs; ++i)
19801         {
19802           if (die->attrs[i].name == name)
19803             return &die->attrs[i];
19804           if (die->attrs[i].name == DW_AT_specification
19805               || die->attrs[i].name == DW_AT_abstract_origin)
19806             spec = &die->attrs[i];
19807         }
19808
19809       if (!spec)
19810         break;
19811
19812       die = follow_die_ref (die, spec, &cu);
19813     }
19814
19815   return NULL;
19816 }
19817
19818 /* Return the named attribute or NULL if not there,
19819    but do not follow DW_AT_specification, etc.
19820    This is for use in contexts where we're reading .debug_types dies.
19821    Following DW_AT_specification, DW_AT_abstract_origin will take us
19822    back up the chain, and we want to go down.  */
19823
19824 static struct attribute *
19825 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19826 {
19827   unsigned int i;
19828
19829   for (i = 0; i < die->num_attrs; ++i)
19830     if (die->attrs[i].name == name)
19831       return &die->attrs[i];
19832
19833   return NULL;
19834 }
19835
19836 /* Return the string associated with a string-typed attribute, or NULL if it
19837    is either not found or is of an incorrect type.  */
19838
19839 static const char *
19840 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19841 {
19842   struct attribute *attr;
19843   const char *str = NULL;
19844
19845   attr = dwarf2_attr (die, name, cu);
19846
19847   if (attr != NULL)
19848     {
19849       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19850           || attr->form == DW_FORM_string
19851           || attr->form == DW_FORM_GNU_str_index
19852           || attr->form == DW_FORM_GNU_strp_alt)
19853         str = DW_STRING (attr);
19854       else
19855         complaint (&symfile_complaints,
19856                    _("string type expected for attribute %s for "
19857                      "DIE at 0x%x in module %s"),
19858                    dwarf_attr_name (name), to_underlying (die->sect_off),
19859                    objfile_name (cu->dwarf2_per_objfile->objfile));
19860     }
19861
19862   return str;
19863 }
19864
19865 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19866    and holds a non-zero value.  This function should only be used for
19867    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19868
19869 static int
19870 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19871 {
19872   struct attribute *attr = dwarf2_attr (die, name, cu);
19873
19874   return (attr && DW_UNSND (attr));
19875 }
19876
19877 static int
19878 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19879 {
19880   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19881      which value is non-zero.  However, we have to be careful with
19882      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19883      (via dwarf2_flag_true_p) follows this attribute.  So we may
19884      end up accidently finding a declaration attribute that belongs
19885      to a different DIE referenced by the specification attribute,
19886      even though the given DIE does not have a declaration attribute.  */
19887   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19888           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19889 }
19890
19891 /* Return the die giving the specification for DIE, if there is
19892    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19893    containing the return value on output.  If there is no
19894    specification, but there is an abstract origin, that is
19895    returned.  */
19896
19897 static struct die_info *
19898 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19899 {
19900   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19901                                              *spec_cu);
19902
19903   if (spec_attr == NULL)
19904     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19905
19906   if (spec_attr == NULL)
19907     return NULL;
19908   else
19909     return follow_die_ref (die, spec_attr, spec_cu);
19910 }
19911
19912 /* Stub for free_line_header to match void * callback types.  */
19913
19914 static void
19915 free_line_header_voidp (void *arg)
19916 {
19917   struct line_header *lh = (struct line_header *) arg;
19918
19919   delete lh;
19920 }
19921
19922 void
19923 line_header::add_include_dir (const char *include_dir)
19924 {
19925   if (dwarf_line_debug >= 2)
19926     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19927                         include_dirs.size () + 1, include_dir);
19928
19929   include_dirs.push_back (include_dir);
19930 }
19931
19932 void
19933 line_header::add_file_name (const char *name,
19934                             dir_index d_index,
19935                             unsigned int mod_time,
19936                             unsigned int length)
19937 {
19938   if (dwarf_line_debug >= 2)
19939     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19940                         (unsigned) file_names.size () + 1, name);
19941
19942   file_names.emplace_back (name, d_index, mod_time, length);
19943 }
19944
19945 /* A convenience function to find the proper .debug_line section for a CU.  */
19946
19947 static struct dwarf2_section_info *
19948 get_debug_line_section (struct dwarf2_cu *cu)
19949 {
19950   struct dwarf2_section_info *section;
19951
19952   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19953      DWO file.  */
19954   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19955     section = &cu->dwo_unit->dwo_file->sections.line;
19956   else if (cu->per_cu->is_dwz)
19957     {
19958       struct dwz_file *dwz = dwarf2_get_dwz_file ();
19959
19960       section = &dwz->line;
19961     }
19962   else
19963     section = &dwarf2_per_objfile->line;
19964
19965   return section;
19966 }
19967
19968 /* Read directory or file name entry format, starting with byte of
19969    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19970    entries count and the entries themselves in the described entry
19971    format.  */
19972
19973 static void
19974 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
19975                         struct line_header *lh,
19976                         const struct comp_unit_head *cu_header,
19977                         void (*callback) (struct line_header *lh,
19978                                           const char *name,
19979                                           dir_index d_index,
19980                                           unsigned int mod_time,
19981                                           unsigned int length))
19982 {
19983   gdb_byte format_count, formati;
19984   ULONGEST data_count, datai;
19985   const gdb_byte *buf = *bufp;
19986   const gdb_byte *format_header_data;
19987   unsigned int bytes_read;
19988
19989   format_count = read_1_byte (abfd, buf);
19990   buf += 1;
19991   format_header_data = buf;
19992   for (formati = 0; formati < format_count; formati++)
19993     {
19994       read_unsigned_leb128 (abfd, buf, &bytes_read);
19995       buf += bytes_read;
19996       read_unsigned_leb128 (abfd, buf, &bytes_read);
19997       buf += bytes_read;
19998     }
19999
20000   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20001   buf += bytes_read;
20002   for (datai = 0; datai < data_count; datai++)
20003     {
20004       const gdb_byte *format = format_header_data;
20005       struct file_entry fe;
20006
20007       for (formati = 0; formati < format_count; formati++)
20008         {
20009           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20010           format += bytes_read;
20011
20012           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20013           format += bytes_read;
20014
20015           gdb::optional<const char *> string;
20016           gdb::optional<unsigned int> uint;
20017
20018           switch (form)
20019             {
20020             case DW_FORM_string:
20021               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20022               buf += bytes_read;
20023               break;
20024
20025             case DW_FORM_line_strp:
20026               string.emplace (read_indirect_line_string (abfd, buf,
20027                                                          cu_header,
20028                                                          &bytes_read));
20029               buf += bytes_read;
20030               break;
20031
20032             case DW_FORM_data1:
20033               uint.emplace (read_1_byte (abfd, buf));
20034               buf += 1;
20035               break;
20036
20037             case DW_FORM_data2:
20038               uint.emplace (read_2_bytes (abfd, buf));
20039               buf += 2;
20040               break;
20041
20042             case DW_FORM_data4:
20043               uint.emplace (read_4_bytes (abfd, buf));
20044               buf += 4;
20045               break;
20046
20047             case DW_FORM_data8:
20048               uint.emplace (read_8_bytes (abfd, buf));
20049               buf += 8;
20050               break;
20051
20052             case DW_FORM_udata:
20053               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20054               buf += bytes_read;
20055               break;
20056
20057             case DW_FORM_block:
20058               /* It is valid only for DW_LNCT_timestamp which is ignored by
20059                  current GDB.  */
20060               break;
20061             }
20062
20063           switch (content_type)
20064             {
20065             case DW_LNCT_path:
20066               if (string.has_value ())
20067                 fe.name = *string;
20068               break;
20069             case DW_LNCT_directory_index:
20070               if (uint.has_value ())
20071                 fe.d_index = (dir_index) *uint;
20072               break;
20073             case DW_LNCT_timestamp:
20074               if (uint.has_value ())
20075                 fe.mod_time = *uint;
20076               break;
20077             case DW_LNCT_size:
20078               if (uint.has_value ())
20079                 fe.length = *uint;
20080               break;
20081             case DW_LNCT_MD5:
20082               break;
20083             default:
20084               complaint (&symfile_complaints,
20085                          _("Unknown format content type %s"),
20086                          pulongest (content_type));
20087             }
20088         }
20089
20090       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20091     }
20092
20093   *bufp = buf;
20094 }
20095
20096 /* Read the statement program header starting at OFFSET in
20097    .debug_line, or .debug_line.dwo.  Return a pointer
20098    to a struct line_header, allocated using xmalloc.
20099    Returns NULL if there is a problem reading the header, e.g., if it
20100    has a version we don't understand.
20101
20102    NOTE: the strings in the include directory and file name tables of
20103    the returned object point into the dwarf line section buffer,
20104    and must not be freed.  */
20105
20106 static line_header_up
20107 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20108 {
20109   const gdb_byte *line_ptr;
20110   unsigned int bytes_read, offset_size;
20111   int i;
20112   const char *cur_dir, *cur_file;
20113   struct dwarf2_section_info *section;
20114   bfd *abfd;
20115
20116   section = get_debug_line_section (cu);
20117   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20118   if (section->buffer == NULL)
20119     {
20120       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20121         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20122       else
20123         complaint (&symfile_complaints, _("missing .debug_line section"));
20124       return 0;
20125     }
20126
20127   /* We can't do this until we know the section is non-empty.
20128      Only then do we know we have such a section.  */
20129   abfd = get_section_bfd_owner (section);
20130
20131   /* Make sure that at least there's room for the total_length field.
20132      That could be 12 bytes long, but we're just going to fudge that.  */
20133   if (to_underlying (sect_off) + 4 >= section->size)
20134     {
20135       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20136       return 0;
20137     }
20138
20139   line_header_up lh (new line_header ());
20140
20141   lh->sect_off = sect_off;
20142   lh->offset_in_dwz = cu->per_cu->is_dwz;
20143
20144   line_ptr = section->buffer + to_underlying (sect_off);
20145
20146   /* Read in the header.  */
20147   lh->total_length =
20148     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20149                                             &bytes_read, &offset_size);
20150   line_ptr += bytes_read;
20151   if (line_ptr + lh->total_length > (section->buffer + section->size))
20152     {
20153       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20154       return 0;
20155     }
20156   lh->statement_program_end = line_ptr + lh->total_length;
20157   lh->version = read_2_bytes (abfd, line_ptr);
20158   line_ptr += 2;
20159   if (lh->version > 5)
20160     {
20161       /* This is a version we don't understand.  The format could have
20162          changed in ways we don't handle properly so just punt.  */
20163       complaint (&symfile_complaints,
20164                  _("unsupported version in .debug_line section"));
20165       return NULL;
20166     }
20167   if (lh->version >= 5)
20168     {
20169       gdb_byte segment_selector_size;
20170
20171       /* Skip address size.  */
20172       read_1_byte (abfd, line_ptr);
20173       line_ptr += 1;
20174
20175       segment_selector_size = read_1_byte (abfd, line_ptr);
20176       line_ptr += 1;
20177       if (segment_selector_size != 0)
20178         {
20179           complaint (&symfile_complaints,
20180                      _("unsupported segment selector size %u "
20181                        "in .debug_line section"),
20182                      segment_selector_size);
20183           return NULL;
20184         }
20185     }
20186   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20187   line_ptr += offset_size;
20188   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20189   line_ptr += 1;
20190   if (lh->version >= 4)
20191     {
20192       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20193       line_ptr += 1;
20194     }
20195   else
20196     lh->maximum_ops_per_instruction = 1;
20197
20198   if (lh->maximum_ops_per_instruction == 0)
20199     {
20200       lh->maximum_ops_per_instruction = 1;
20201       complaint (&symfile_complaints,
20202                  _("invalid maximum_ops_per_instruction "
20203                    "in `.debug_line' section"));
20204     }
20205
20206   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20207   line_ptr += 1;
20208   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20209   line_ptr += 1;
20210   lh->line_range = read_1_byte (abfd, line_ptr);
20211   line_ptr += 1;
20212   lh->opcode_base = read_1_byte (abfd, line_ptr);
20213   line_ptr += 1;
20214   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20215
20216   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20217   for (i = 1; i < lh->opcode_base; ++i)
20218     {
20219       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20220       line_ptr += 1;
20221     }
20222
20223   if (lh->version >= 5)
20224     {
20225       /* Read directory table.  */
20226       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20227                               [] (struct line_header *lh, const char *name,
20228                                   dir_index d_index, unsigned int mod_time,
20229                                   unsigned int length)
20230         {
20231           lh->add_include_dir (name);
20232         });
20233
20234       /* Read file name table.  */
20235       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20236                               [] (struct line_header *lh, const char *name,
20237                                   dir_index d_index, unsigned int mod_time,
20238                                   unsigned int length)
20239         {
20240           lh->add_file_name (name, d_index, mod_time, length);
20241         });
20242     }
20243   else
20244     {
20245       /* Read directory table.  */
20246       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20247         {
20248           line_ptr += bytes_read;
20249           lh->add_include_dir (cur_dir);
20250         }
20251       line_ptr += bytes_read;
20252
20253       /* Read file name table.  */
20254       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20255         {
20256           unsigned int mod_time, length;
20257           dir_index d_index;
20258
20259           line_ptr += bytes_read;
20260           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20261           line_ptr += bytes_read;
20262           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20263           line_ptr += bytes_read;
20264           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20265           line_ptr += bytes_read;
20266
20267           lh->add_file_name (cur_file, d_index, mod_time, length);
20268         }
20269       line_ptr += bytes_read;
20270     }
20271   lh->statement_program_start = line_ptr;
20272
20273   if (line_ptr > (section->buffer + section->size))
20274     complaint (&symfile_complaints,
20275                _("line number info header doesn't "
20276                  "fit in `.debug_line' section"));
20277
20278   return lh;
20279 }
20280
20281 /* Subroutine of dwarf_decode_lines to simplify it.
20282    Return the file name of the psymtab for included file FILE_INDEX
20283    in line header LH of PST.
20284    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20285    If space for the result is malloc'd, it will be freed by a cleanup.
20286    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20287
20288    The function creates dangling cleanup registration.  */
20289
20290 static const char *
20291 psymtab_include_file_name (const struct line_header *lh, int file_index,
20292                            const struct partial_symtab *pst,
20293                            const char *comp_dir)
20294 {
20295   const file_entry &fe = lh->file_names[file_index];
20296   const char *include_name = fe.name;
20297   const char *include_name_to_compare = include_name;
20298   const char *pst_filename;
20299   char *copied_name = NULL;
20300   int file_is_pst;
20301
20302   const char *dir_name = fe.include_dir (lh);
20303
20304   if (!IS_ABSOLUTE_PATH (include_name)
20305       && (dir_name != NULL || comp_dir != NULL))
20306     {
20307       /* Avoid creating a duplicate psymtab for PST.
20308          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20309          Before we do the comparison, however, we need to account
20310          for DIR_NAME and COMP_DIR.
20311          First prepend dir_name (if non-NULL).  If we still don't
20312          have an absolute path prepend comp_dir (if non-NULL).
20313          However, the directory we record in the include-file's
20314          psymtab does not contain COMP_DIR (to match the
20315          corresponding symtab(s)).
20316
20317          Example:
20318
20319          bash$ cd /tmp
20320          bash$ gcc -g ./hello.c
20321          include_name = "hello.c"
20322          dir_name = "."
20323          DW_AT_comp_dir = comp_dir = "/tmp"
20324          DW_AT_name = "./hello.c"
20325
20326       */
20327
20328       if (dir_name != NULL)
20329         {
20330           char *tem = concat (dir_name, SLASH_STRING,
20331                               include_name, (char *)NULL);
20332
20333           make_cleanup (xfree, tem);
20334           include_name = tem;
20335           include_name_to_compare = include_name;
20336         }
20337       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20338         {
20339           char *tem = concat (comp_dir, SLASH_STRING,
20340                               include_name, (char *)NULL);
20341
20342           make_cleanup (xfree, tem);
20343           include_name_to_compare = tem;
20344         }
20345     }
20346
20347   pst_filename = pst->filename;
20348   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20349     {
20350       copied_name = concat (pst->dirname, SLASH_STRING,
20351                             pst_filename, (char *)NULL);
20352       pst_filename = copied_name;
20353     }
20354
20355   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20356
20357   if (copied_name != NULL)
20358     xfree (copied_name);
20359
20360   if (file_is_pst)
20361     return NULL;
20362   return include_name;
20363 }
20364
20365 /* State machine to track the state of the line number program.  */
20366
20367 class lnp_state_machine
20368 {
20369 public:
20370   /* Initialize a machine state for the start of a line number
20371      program.  */
20372   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20373
20374   file_entry *current_file ()
20375   {
20376     /* lh->file_names is 0-based, but the file name numbers in the
20377        statement program are 1-based.  */
20378     return m_line_header->file_name_at (m_file);
20379   }
20380
20381   /* Record the line in the state machine.  END_SEQUENCE is true if
20382      we're processing the end of a sequence.  */
20383   void record_line (bool end_sequence);
20384
20385   /* Check address and if invalid nop-out the rest of the lines in this
20386      sequence.  */
20387   void check_line_address (struct dwarf2_cu *cu,
20388                            const gdb_byte *line_ptr,
20389                            CORE_ADDR lowpc, CORE_ADDR address);
20390
20391   void handle_set_discriminator (unsigned int discriminator)
20392   {
20393     m_discriminator = discriminator;
20394     m_line_has_non_zero_discriminator |= discriminator != 0;
20395   }
20396
20397   /* Handle DW_LNE_set_address.  */
20398   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20399   {
20400     m_op_index = 0;
20401     address += baseaddr;
20402     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20403   }
20404
20405   /* Handle DW_LNS_advance_pc.  */
20406   void handle_advance_pc (CORE_ADDR adjust);
20407
20408   /* Handle a special opcode.  */
20409   void handle_special_opcode (unsigned char op_code);
20410
20411   /* Handle DW_LNS_advance_line.  */
20412   void handle_advance_line (int line_delta)
20413   {
20414     advance_line (line_delta);
20415   }
20416
20417   /* Handle DW_LNS_set_file.  */
20418   void handle_set_file (file_name_index file);
20419
20420   /* Handle DW_LNS_negate_stmt.  */
20421   void handle_negate_stmt ()
20422   {
20423     m_is_stmt = !m_is_stmt;
20424   }
20425
20426   /* Handle DW_LNS_const_add_pc.  */
20427   void handle_const_add_pc ();
20428
20429   /* Handle DW_LNS_fixed_advance_pc.  */
20430   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20431   {
20432     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20433     m_op_index = 0;
20434   }
20435
20436   /* Handle DW_LNS_copy.  */
20437   void handle_copy ()
20438   {
20439     record_line (false);
20440     m_discriminator = 0;
20441   }
20442
20443   /* Handle DW_LNE_end_sequence.  */
20444   void handle_end_sequence ()
20445   {
20446     m_record_line_callback = ::record_line;
20447   }
20448
20449 private:
20450   /* Advance the line by LINE_DELTA.  */
20451   void advance_line (int line_delta)
20452   {
20453     m_line += line_delta;
20454
20455     if (line_delta != 0)
20456       m_line_has_non_zero_discriminator = m_discriminator != 0;
20457   }
20458
20459   gdbarch *m_gdbarch;
20460
20461   /* True if we're recording lines.
20462      Otherwise we're building partial symtabs and are just interested in
20463      finding include files mentioned by the line number program.  */
20464   bool m_record_lines_p;
20465
20466   /* The line number header.  */
20467   line_header *m_line_header;
20468
20469   /* These are part of the standard DWARF line number state machine,
20470      and initialized according to the DWARF spec.  */
20471
20472   unsigned char m_op_index = 0;
20473   /* The line table index (1-based) of the current file.  */
20474   file_name_index m_file = (file_name_index) 1;
20475   unsigned int m_line = 1;
20476
20477   /* These are initialized in the constructor.  */
20478
20479   CORE_ADDR m_address;
20480   bool m_is_stmt;
20481   unsigned int m_discriminator;
20482
20483   /* Additional bits of state we need to track.  */
20484
20485   /* The last file that we called dwarf2_start_subfile for.
20486      This is only used for TLLs.  */
20487   unsigned int m_last_file = 0;
20488   /* The last file a line number was recorded for.  */
20489   struct subfile *m_last_subfile = NULL;
20490
20491   /* The function to call to record a line.  */
20492   record_line_ftype *m_record_line_callback = NULL;
20493
20494   /* The last line number that was recorded, used to coalesce
20495      consecutive entries for the same line.  This can happen, for
20496      example, when discriminators are present.  PR 17276.  */
20497   unsigned int m_last_line = 0;
20498   bool m_line_has_non_zero_discriminator = false;
20499 };
20500
20501 void
20502 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20503 {
20504   CORE_ADDR addr_adj = (((m_op_index + adjust)
20505                          / m_line_header->maximum_ops_per_instruction)
20506                         * m_line_header->minimum_instruction_length);
20507   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20508   m_op_index = ((m_op_index + adjust)
20509                 % m_line_header->maximum_ops_per_instruction);
20510 }
20511
20512 void
20513 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20514 {
20515   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20516   CORE_ADDR addr_adj = (((m_op_index
20517                           + (adj_opcode / m_line_header->line_range))
20518                          / m_line_header->maximum_ops_per_instruction)
20519                         * m_line_header->minimum_instruction_length);
20520   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20521   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20522                 % m_line_header->maximum_ops_per_instruction);
20523
20524   int line_delta = (m_line_header->line_base
20525                     + (adj_opcode % m_line_header->line_range));
20526   advance_line (line_delta);
20527   record_line (false);
20528   m_discriminator = 0;
20529 }
20530
20531 void
20532 lnp_state_machine::handle_set_file (file_name_index file)
20533 {
20534   m_file = file;
20535
20536   const file_entry *fe = current_file ();
20537   if (fe == NULL)
20538     dwarf2_debug_line_missing_file_complaint ();
20539   else if (m_record_lines_p)
20540     {
20541       const char *dir = fe->include_dir (m_line_header);
20542
20543       m_last_subfile = current_subfile;
20544       m_line_has_non_zero_discriminator = m_discriminator != 0;
20545       dwarf2_start_subfile (fe->name, dir);
20546     }
20547 }
20548
20549 void
20550 lnp_state_machine::handle_const_add_pc ()
20551 {
20552   CORE_ADDR adjust
20553     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20554
20555   CORE_ADDR addr_adj
20556     = (((m_op_index + adjust)
20557         / m_line_header->maximum_ops_per_instruction)
20558        * m_line_header->minimum_instruction_length);
20559
20560   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20561   m_op_index = ((m_op_index + adjust)
20562                 % m_line_header->maximum_ops_per_instruction);
20563 }
20564
20565 /* Ignore this record_line request.  */
20566
20567 static void
20568 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20569 {
20570   return;
20571 }
20572
20573 /* Return non-zero if we should add LINE to the line number table.
20574    LINE is the line to add, LAST_LINE is the last line that was added,
20575    LAST_SUBFILE is the subfile for LAST_LINE.
20576    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20577    had a non-zero discriminator.
20578
20579    We have to be careful in the presence of discriminators.
20580    E.g., for this line:
20581
20582      for (i = 0; i < 100000; i++);
20583
20584    clang can emit four line number entries for that one line,
20585    each with a different discriminator.
20586    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20587
20588    However, we want gdb to coalesce all four entries into one.
20589    Otherwise the user could stepi into the middle of the line and
20590    gdb would get confused about whether the pc really was in the
20591    middle of the line.
20592
20593    Things are further complicated by the fact that two consecutive
20594    line number entries for the same line is a heuristic used by gcc
20595    to denote the end of the prologue.  So we can't just discard duplicate
20596    entries, we have to be selective about it.  The heuristic we use is
20597    that we only collapse consecutive entries for the same line if at least
20598    one of those entries has a non-zero discriminator.  PR 17276.
20599
20600    Note: Addresses in the line number state machine can never go backwards
20601    within one sequence, thus this coalescing is ok.  */
20602
20603 static int
20604 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20605                      int line_has_non_zero_discriminator,
20606                      struct subfile *last_subfile)
20607 {
20608   if (current_subfile != last_subfile)
20609     return 1;
20610   if (line != last_line)
20611     return 1;
20612   /* Same line for the same file that we've seen already.
20613      As a last check, for pr 17276, only record the line if the line
20614      has never had a non-zero discriminator.  */
20615   if (!line_has_non_zero_discriminator)
20616     return 1;
20617   return 0;
20618 }
20619
20620 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20621    in the line table of subfile SUBFILE.  */
20622
20623 static void
20624 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20625                      unsigned int line, CORE_ADDR address,
20626                      record_line_ftype p_record_line)
20627 {
20628   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20629
20630   if (dwarf_line_debug)
20631     {
20632       fprintf_unfiltered (gdb_stdlog,
20633                           "Recording line %u, file %s, address %s\n",
20634                           line, lbasename (subfile->name),
20635                           paddress (gdbarch, address));
20636     }
20637
20638   (*p_record_line) (subfile, line, addr);
20639 }
20640
20641 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20642    Mark the end of a set of line number records.
20643    The arguments are the same as for dwarf_record_line_1.
20644    If SUBFILE is NULL the request is ignored.  */
20645
20646 static void
20647 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20648                    CORE_ADDR address, record_line_ftype p_record_line)
20649 {
20650   if (subfile == NULL)
20651     return;
20652
20653   if (dwarf_line_debug)
20654     {
20655       fprintf_unfiltered (gdb_stdlog,
20656                           "Finishing current line, file %s, address %s\n",
20657                           lbasename (subfile->name),
20658                           paddress (gdbarch, address));
20659     }
20660
20661   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20662 }
20663
20664 void
20665 lnp_state_machine::record_line (bool end_sequence)
20666 {
20667   if (dwarf_line_debug)
20668     {
20669       fprintf_unfiltered (gdb_stdlog,
20670                           "Processing actual line %u: file %u,"
20671                           " address %s, is_stmt %u, discrim %u\n",
20672                           m_line, to_underlying (m_file),
20673                           paddress (m_gdbarch, m_address),
20674                           m_is_stmt, m_discriminator);
20675     }
20676
20677   file_entry *fe = current_file ();
20678
20679   if (fe == NULL)
20680     dwarf2_debug_line_missing_file_complaint ();
20681   /* For now we ignore lines not starting on an instruction boundary.
20682      But not when processing end_sequence for compatibility with the
20683      previous version of the code.  */
20684   else if (m_op_index == 0 || end_sequence)
20685     {
20686       fe->included_p = 1;
20687       if (m_record_lines_p && m_is_stmt)
20688         {
20689           if (m_last_subfile != current_subfile || end_sequence)
20690             {
20691               dwarf_finish_line (m_gdbarch, m_last_subfile,
20692                                  m_address, m_record_line_callback);
20693             }
20694
20695           if (!end_sequence)
20696             {
20697               if (dwarf_record_line_p (m_line, m_last_line,
20698                                        m_line_has_non_zero_discriminator,
20699                                        m_last_subfile))
20700                 {
20701                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20702                                        m_line, m_address,
20703                                        m_record_line_callback);
20704                 }
20705               m_last_subfile = current_subfile;
20706               m_last_line = m_line;
20707             }
20708         }
20709     }
20710 }
20711
20712 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20713                                       bool record_lines_p)
20714 {
20715   m_gdbarch = arch;
20716   m_record_lines_p = record_lines_p;
20717   m_line_header = lh;
20718
20719   m_record_line_callback = ::record_line;
20720
20721   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20722      was a line entry for it so that the backend has a chance to adjust it
20723      and also record it in case it needs it.  This is currently used by MIPS
20724      code, cf. `mips_adjust_dwarf2_line'.  */
20725   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20726   m_is_stmt = lh->default_is_stmt;
20727   m_discriminator = 0;
20728 }
20729
20730 void
20731 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20732                                        const gdb_byte *line_ptr,
20733                                        CORE_ADDR lowpc, CORE_ADDR address)
20734 {
20735   /* If address < lowpc then it's not a usable value, it's outside the
20736      pc range of the CU.  However, we restrict the test to only address
20737      values of zero to preserve GDB's previous behaviour which is to
20738      handle the specific case of a function being GC'd by the linker.  */
20739
20740   if (address == 0 && address < lowpc)
20741     {
20742       /* This line table is for a function which has been
20743          GCd by the linker.  Ignore it.  PR gdb/12528 */
20744
20745       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
20746       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20747
20748       complaint (&symfile_complaints,
20749                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20750                  line_offset, objfile_name (objfile));
20751       m_record_line_callback = noop_record_line;
20752       /* Note: record_line_callback is left as noop_record_line until
20753          we see DW_LNE_end_sequence.  */
20754     }
20755 }
20756
20757 /* Subroutine of dwarf_decode_lines to simplify it.
20758    Process the line number information in LH.
20759    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20760    program in order to set included_p for every referenced header.  */
20761
20762 static void
20763 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20764                       const int decode_for_pst_p, CORE_ADDR lowpc)
20765 {
20766   const gdb_byte *line_ptr, *extended_end;
20767   const gdb_byte *line_end;
20768   unsigned int bytes_read, extended_len;
20769   unsigned char op_code, extended_op;
20770   CORE_ADDR baseaddr;
20771   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
20772   bfd *abfd = objfile->obfd;
20773   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20774   /* True if we're recording line info (as opposed to building partial
20775      symtabs and just interested in finding include files mentioned by
20776      the line number program).  */
20777   bool record_lines_p = !decode_for_pst_p;
20778
20779   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20780
20781   line_ptr = lh->statement_program_start;
20782   line_end = lh->statement_program_end;
20783
20784   /* Read the statement sequences until there's nothing left.  */
20785   while (line_ptr < line_end)
20786     {
20787       /* The DWARF line number program state machine.  Reset the state
20788          machine at the start of each sequence.  */
20789       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20790       bool end_sequence = false;
20791
20792       if (record_lines_p)
20793         {
20794           /* Start a subfile for the current file of the state
20795              machine.  */
20796           const file_entry *fe = state_machine.current_file ();
20797
20798           if (fe != NULL)
20799             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20800         }
20801
20802       /* Decode the table.  */
20803       while (line_ptr < line_end && !end_sequence)
20804         {
20805           op_code = read_1_byte (abfd, line_ptr);
20806           line_ptr += 1;
20807
20808           if (op_code >= lh->opcode_base)
20809             {
20810               /* Special opcode.  */
20811               state_machine.handle_special_opcode (op_code);
20812             }
20813           else switch (op_code)
20814             {
20815             case DW_LNS_extended_op:
20816               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20817                                                    &bytes_read);
20818               line_ptr += bytes_read;
20819               extended_end = line_ptr + extended_len;
20820               extended_op = read_1_byte (abfd, line_ptr);
20821               line_ptr += 1;
20822               switch (extended_op)
20823                 {
20824                 case DW_LNE_end_sequence:
20825                   state_machine.handle_end_sequence ();
20826                   end_sequence = true;
20827                   break;
20828                 case DW_LNE_set_address:
20829                   {
20830                     CORE_ADDR address
20831                       = read_address (abfd, line_ptr, cu, &bytes_read);
20832                     line_ptr += bytes_read;
20833
20834                     state_machine.check_line_address (cu, line_ptr,
20835                                                       lowpc, address);
20836                     state_machine.handle_set_address (baseaddr, address);
20837                   }
20838                   break;
20839                 case DW_LNE_define_file:
20840                   {
20841                     const char *cur_file;
20842                     unsigned int mod_time, length;
20843                     dir_index dindex;
20844
20845                     cur_file = read_direct_string (abfd, line_ptr,
20846                                                    &bytes_read);
20847                     line_ptr += bytes_read;
20848                     dindex = (dir_index)
20849                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20850                     line_ptr += bytes_read;
20851                     mod_time =
20852                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20853                     line_ptr += bytes_read;
20854                     length =
20855                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20856                     line_ptr += bytes_read;
20857                     lh->add_file_name (cur_file, dindex, mod_time, length);
20858                   }
20859                   break;
20860                 case DW_LNE_set_discriminator:
20861                   {
20862                     /* The discriminator is not interesting to the
20863                        debugger; just ignore it.  We still need to
20864                        check its value though:
20865                        if there are consecutive entries for the same
20866                        (non-prologue) line we want to coalesce them.
20867                        PR 17276.  */
20868                     unsigned int discr
20869                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20870                     line_ptr += bytes_read;
20871
20872                     state_machine.handle_set_discriminator (discr);
20873                   }
20874                   break;
20875                 default:
20876                   complaint (&symfile_complaints,
20877                              _("mangled .debug_line section"));
20878                   return;
20879                 }
20880               /* Make sure that we parsed the extended op correctly.  If e.g.
20881                  we expected a different address size than the producer used,
20882                  we may have read the wrong number of bytes.  */
20883               if (line_ptr != extended_end)
20884                 {
20885                   complaint (&symfile_complaints,
20886                              _("mangled .debug_line section"));
20887                   return;
20888                 }
20889               break;
20890             case DW_LNS_copy:
20891               state_machine.handle_copy ();
20892               break;
20893             case DW_LNS_advance_pc:
20894               {
20895                 CORE_ADDR adjust
20896                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20897                 line_ptr += bytes_read;
20898
20899                 state_machine.handle_advance_pc (adjust);
20900               }
20901               break;
20902             case DW_LNS_advance_line:
20903               {
20904                 int line_delta
20905                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20906                 line_ptr += bytes_read;
20907
20908                 state_machine.handle_advance_line (line_delta);
20909               }
20910               break;
20911             case DW_LNS_set_file:
20912               {
20913                 file_name_index file
20914                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20915                                                             &bytes_read);
20916                 line_ptr += bytes_read;
20917
20918                 state_machine.handle_set_file (file);
20919               }
20920               break;
20921             case DW_LNS_set_column:
20922               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20923               line_ptr += bytes_read;
20924               break;
20925             case DW_LNS_negate_stmt:
20926               state_machine.handle_negate_stmt ();
20927               break;
20928             case DW_LNS_set_basic_block:
20929               break;
20930             /* Add to the address register of the state machine the
20931                address increment value corresponding to special opcode
20932                255.  I.e., this value is scaled by the minimum
20933                instruction length since special opcode 255 would have
20934                scaled the increment.  */
20935             case DW_LNS_const_add_pc:
20936               state_machine.handle_const_add_pc ();
20937               break;
20938             case DW_LNS_fixed_advance_pc:
20939               {
20940                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20941                 line_ptr += 2;
20942
20943                 state_machine.handle_fixed_advance_pc (addr_adj);
20944               }
20945               break;
20946             default:
20947               {
20948                 /* Unknown standard opcode, ignore it.  */
20949                 int i;
20950
20951                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20952                   {
20953                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20954                     line_ptr += bytes_read;
20955                   }
20956               }
20957             }
20958         }
20959
20960       if (!end_sequence)
20961         dwarf2_debug_line_missing_end_sequence_complaint ();
20962
20963       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20964          in which case we still finish recording the last line).  */
20965       state_machine.record_line (true);
20966     }
20967 }
20968
20969 /* Decode the Line Number Program (LNP) for the given line_header
20970    structure and CU.  The actual information extracted and the type
20971    of structures created from the LNP depends on the value of PST.
20972
20973    1. If PST is NULL, then this procedure uses the data from the program
20974       to create all necessary symbol tables, and their linetables.
20975
20976    2. If PST is not NULL, this procedure reads the program to determine
20977       the list of files included by the unit represented by PST, and
20978       builds all the associated partial symbol tables.
20979
20980    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20981    It is used for relative paths in the line table.
20982    NOTE: When processing partial symtabs (pst != NULL),
20983    comp_dir == pst->dirname.
20984
20985    NOTE: It is important that psymtabs have the same file name (via strcmp)
20986    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20987    symtab we don't use it in the name of the psymtabs we create.
20988    E.g. expand_line_sal requires this when finding psymtabs to expand.
20989    A good testcase for this is mb-inline.exp.
20990
20991    LOWPC is the lowest address in CU (or 0 if not known).
20992
20993    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20994    for its PC<->lines mapping information.  Otherwise only the filename
20995    table is read in.  */
20996
20997 static void
20998 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20999                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21000                     CORE_ADDR lowpc, int decode_mapping)
21001 {
21002   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21003   const int decode_for_pst_p = (pst != NULL);
21004
21005   if (decode_mapping)
21006     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21007
21008   if (decode_for_pst_p)
21009     {
21010       int file_index;
21011
21012       /* Now that we're done scanning the Line Header Program, we can
21013          create the psymtab of each included file.  */
21014       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21015         if (lh->file_names[file_index].included_p == 1)
21016           {
21017             const char *include_name =
21018               psymtab_include_file_name (lh, file_index, pst, comp_dir);
21019             if (include_name != NULL)
21020               dwarf2_create_include_psymtab (include_name, pst, objfile);
21021           }
21022     }
21023   else
21024     {
21025       /* Make sure a symtab is created for every file, even files
21026          which contain only variables (i.e. no code with associated
21027          line numbers).  */
21028       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21029       int i;
21030
21031       for (i = 0; i < lh->file_names.size (); i++)
21032         {
21033           file_entry &fe = lh->file_names[i];
21034
21035           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21036
21037           if (current_subfile->symtab == NULL)
21038             {
21039               current_subfile->symtab
21040                 = allocate_symtab (cust, current_subfile->name);
21041             }
21042           fe.symtab = current_subfile->symtab;
21043         }
21044     }
21045 }
21046
21047 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21048    DIRNAME the name of the source directory which contains FILENAME
21049    or NULL if not known.
21050    This routine tries to keep line numbers from identical absolute and
21051    relative file names in a common subfile.
21052
21053    Using the `list' example from the GDB testsuite, which resides in
21054    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21055    of /srcdir/list0.c yields the following debugging information for list0.c:
21056
21057    DW_AT_name:          /srcdir/list0.c
21058    DW_AT_comp_dir:      /compdir
21059    files.files[0].name: list0.h
21060    files.files[0].dir:  /srcdir
21061    files.files[1].name: list0.c
21062    files.files[1].dir:  /srcdir
21063
21064    The line number information for list0.c has to end up in a single
21065    subfile, so that `break /srcdir/list0.c:1' works as expected.
21066    start_subfile will ensure that this happens provided that we pass the
21067    concatenation of files.files[1].dir and files.files[1].name as the
21068    subfile's name.  */
21069
21070 static void
21071 dwarf2_start_subfile (const char *filename, const char *dirname)
21072 {
21073   char *copy = NULL;
21074
21075   /* In order not to lose the line information directory,
21076      we concatenate it to the filename when it makes sense.
21077      Note that the Dwarf3 standard says (speaking of filenames in line
21078      information): ``The directory index is ignored for file names
21079      that represent full path names''.  Thus ignoring dirname in the
21080      `else' branch below isn't an issue.  */
21081
21082   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21083     {
21084       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21085       filename = copy;
21086     }
21087
21088   start_subfile (filename);
21089
21090   if (copy != NULL)
21091     xfree (copy);
21092 }
21093
21094 /* Start a symtab for DWARF.
21095    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21096
21097 static struct compunit_symtab *
21098 dwarf2_start_symtab (struct dwarf2_cu *cu,
21099                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21100 {
21101   struct compunit_symtab *cust
21102     = start_symtab (cu->dwarf2_per_objfile->objfile, name, comp_dir, low_pc,
21103                     cu->language);
21104
21105   record_debugformat ("DWARF 2");
21106   record_producer (cu->producer);
21107
21108   /* We assume that we're processing GCC output.  */
21109   processing_gcc_compilation = 2;
21110
21111   cu->processing_has_namespace_info = 0;
21112
21113   return cust;
21114 }
21115
21116 static void
21117 var_decode_location (struct attribute *attr, struct symbol *sym,
21118                      struct dwarf2_cu *cu)
21119 {
21120   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21121   struct comp_unit_head *cu_header = &cu->header;
21122
21123   /* NOTE drow/2003-01-30: There used to be a comment and some special
21124      code here to turn a symbol with DW_AT_external and a
21125      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21126      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21127      with some versions of binutils) where shared libraries could have
21128      relocations against symbols in their debug information - the
21129      minimal symbol would have the right address, but the debug info
21130      would not.  It's no longer necessary, because we will explicitly
21131      apply relocations when we read in the debug information now.  */
21132
21133   /* A DW_AT_location attribute with no contents indicates that a
21134      variable has been optimized away.  */
21135   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21136     {
21137       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21138       return;
21139     }
21140
21141   /* Handle one degenerate form of location expression specially, to
21142      preserve GDB's previous behavior when section offsets are
21143      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21144      then mark this symbol as LOC_STATIC.  */
21145
21146   if (attr_form_is_block (attr)
21147       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21148            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21149           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21150               && (DW_BLOCK (attr)->size
21151                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21152     {
21153       unsigned int dummy;
21154
21155       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21156         SYMBOL_VALUE_ADDRESS (sym) =
21157           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21158       else
21159         SYMBOL_VALUE_ADDRESS (sym) =
21160           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21161       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21162       fixup_symbol_section (sym, objfile);
21163       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21164                                               SYMBOL_SECTION (sym));
21165       return;
21166     }
21167
21168   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21169      expression evaluator, and use LOC_COMPUTED only when necessary
21170      (i.e. when the value of a register or memory location is
21171      referenced, or a thread-local block, etc.).  Then again, it might
21172      not be worthwhile.  I'm assuming that it isn't unless performance
21173      or memory numbers show me otherwise.  */
21174
21175   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21176
21177   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21178     cu->has_loclist = 1;
21179 }
21180
21181 /* Given a pointer to a DWARF information entry, figure out if we need
21182    to make a symbol table entry for it, and if so, create a new entry
21183    and return a pointer to it.
21184    If TYPE is NULL, determine symbol type from the die, otherwise
21185    used the passed type.
21186    If SPACE is not NULL, use it to hold the new symbol.  If it is
21187    NULL, allocate a new symbol on the objfile's obstack.  */
21188
21189 static struct symbol *
21190 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21191                  struct symbol *space)
21192 {
21193   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21195   struct symbol *sym = NULL;
21196   const char *name;
21197   struct attribute *attr = NULL;
21198   struct attribute *attr2 = NULL;
21199   CORE_ADDR baseaddr;
21200   struct pending **list_to_add = NULL;
21201
21202   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21203
21204   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21205
21206   name = dwarf2_name (die, cu);
21207   if (name)
21208     {
21209       const char *linkagename;
21210       int suppress_add = 0;
21211
21212       if (space)
21213         sym = space;
21214       else
21215         sym = allocate_symbol (objfile);
21216       OBJSTAT (objfile, n_syms++);
21217
21218       /* Cache this symbol's name and the name's demangled form (if any).  */
21219       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21220       linkagename = dwarf2_physname (name, die, cu);
21221       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21222
21223       /* Fortran does not have mangling standard and the mangling does differ
21224          between gfortran, iFort etc.  */
21225       if (cu->language == language_fortran
21226           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21227         symbol_set_demangled_name (&(sym->ginfo),
21228                                    dwarf2_full_name (name, die, cu),
21229                                    NULL);
21230
21231       /* Default assumptions.
21232          Use the passed type or decode it from the die.  */
21233       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21234       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21235       if (type != NULL)
21236         SYMBOL_TYPE (sym) = type;
21237       else
21238         SYMBOL_TYPE (sym) = die_type (die, cu);
21239       attr = dwarf2_attr (die,
21240                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21241                           cu);
21242       if (attr)
21243         {
21244           SYMBOL_LINE (sym) = DW_UNSND (attr);
21245         }
21246
21247       attr = dwarf2_attr (die,
21248                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21249                           cu);
21250       if (attr)
21251         {
21252           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21253           struct file_entry *fe;
21254
21255           if (cu->line_header != NULL)
21256             fe = cu->line_header->file_name_at (file_index);
21257           else
21258             fe = NULL;
21259
21260           if (fe == NULL)
21261             complaint (&symfile_complaints,
21262                        _("file index out of range"));
21263           else
21264             symbol_set_symtab (sym, fe->symtab);
21265         }
21266
21267       switch (die->tag)
21268         {
21269         case DW_TAG_label:
21270           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21271           if (attr)
21272             {
21273               CORE_ADDR addr;
21274
21275               addr = attr_value_as_address (attr);
21276               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21277               SYMBOL_VALUE_ADDRESS (sym) = addr;
21278             }
21279           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21280           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21281           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21282           add_symbol_to_list (sym, cu->list_in_scope);
21283           break;
21284         case DW_TAG_subprogram:
21285           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21286              finish_block.  */
21287           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21288           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21289           if ((attr2 && (DW_UNSND (attr2) != 0))
21290               || cu->language == language_ada)
21291             {
21292               /* Subprograms marked external are stored as a global symbol.
21293                  Ada subprograms, whether marked external or not, are always
21294                  stored as a global symbol, because we want to be able to
21295                  access them globally.  For instance, we want to be able
21296                  to break on a nested subprogram without having to
21297                  specify the context.  */
21298               list_to_add = &global_symbols;
21299             }
21300           else
21301             {
21302               list_to_add = cu->list_in_scope;
21303             }
21304           break;
21305         case DW_TAG_inlined_subroutine:
21306           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21307              finish_block.  */
21308           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21309           SYMBOL_INLINED (sym) = 1;
21310           list_to_add = cu->list_in_scope;
21311           break;
21312         case DW_TAG_template_value_param:
21313           suppress_add = 1;
21314           /* Fall through.  */
21315         case DW_TAG_constant:
21316         case DW_TAG_variable:
21317         case DW_TAG_member:
21318           /* Compilation with minimal debug info may result in
21319              variables with missing type entries.  Change the
21320              misleading `void' type to something sensible.  */
21321           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21322             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21323
21324           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21325           /* In the case of DW_TAG_member, we should only be called for
21326              static const members.  */
21327           if (die->tag == DW_TAG_member)
21328             {
21329               /* dwarf2_add_field uses die_is_declaration,
21330                  so we do the same.  */
21331               gdb_assert (die_is_declaration (die, cu));
21332               gdb_assert (attr);
21333             }
21334           if (attr)
21335             {
21336               dwarf2_const_value (attr, sym, cu);
21337               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21338               if (!suppress_add)
21339                 {
21340                   if (attr2 && (DW_UNSND (attr2) != 0))
21341                     list_to_add = &global_symbols;
21342                   else
21343                     list_to_add = cu->list_in_scope;
21344                 }
21345               break;
21346             }
21347           attr = dwarf2_attr (die, DW_AT_location, cu);
21348           if (attr)
21349             {
21350               var_decode_location (attr, sym, cu);
21351               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21352
21353               /* Fortran explicitly imports any global symbols to the local
21354                  scope by DW_TAG_common_block.  */
21355               if (cu->language == language_fortran && die->parent
21356                   && die->parent->tag == DW_TAG_common_block)
21357                 attr2 = NULL;
21358
21359               if (SYMBOL_CLASS (sym) == LOC_STATIC
21360                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21361                   && !dwarf2_per_objfile->has_section_at_zero)
21362                 {
21363                   /* When a static variable is eliminated by the linker,
21364                      the corresponding debug information is not stripped
21365                      out, but the variable address is set to null;
21366                      do not add such variables into symbol table.  */
21367                 }
21368               else if (attr2 && (DW_UNSND (attr2) != 0))
21369                 {
21370                   /* Workaround gfortran PR debug/40040 - it uses
21371                      DW_AT_location for variables in -fPIC libraries which may
21372                      get overriden by other libraries/executable and get
21373                      a different address.  Resolve it by the minimal symbol
21374                      which may come from inferior's executable using copy
21375                      relocation.  Make this workaround only for gfortran as for
21376                      other compilers GDB cannot guess the minimal symbol
21377                      Fortran mangling kind.  */
21378                   if (cu->language == language_fortran && die->parent
21379                       && die->parent->tag == DW_TAG_module
21380                       && cu->producer
21381                       && startswith (cu->producer, "GNU Fortran"))
21382                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21383
21384                   /* A variable with DW_AT_external is never static,
21385                      but it may be block-scoped.  */
21386                   list_to_add = (cu->list_in_scope == &file_symbols
21387                                  ? &global_symbols : cu->list_in_scope);
21388                 }
21389               else
21390                 list_to_add = cu->list_in_scope;
21391             }
21392           else
21393             {
21394               /* We do not know the address of this symbol.
21395                  If it is an external symbol and we have type information
21396                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21397                  The address of the variable will then be determined from
21398                  the minimal symbol table whenever the variable is
21399                  referenced.  */
21400               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21401
21402               /* Fortran explicitly imports any global symbols to the local
21403                  scope by DW_TAG_common_block.  */
21404               if (cu->language == language_fortran && die->parent
21405                   && die->parent->tag == DW_TAG_common_block)
21406                 {
21407                   /* SYMBOL_CLASS doesn't matter here because
21408                      read_common_block is going to reset it.  */
21409                   if (!suppress_add)
21410                     list_to_add = cu->list_in_scope;
21411                 }
21412               else if (attr2 && (DW_UNSND (attr2) != 0)
21413                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21414                 {
21415                   /* A variable with DW_AT_external is never static, but it
21416                      may be block-scoped.  */
21417                   list_to_add = (cu->list_in_scope == &file_symbols
21418                                  ? &global_symbols : cu->list_in_scope);
21419
21420                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21421                 }
21422               else if (!die_is_declaration (die, cu))
21423                 {
21424                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21425                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21426                   if (!suppress_add)
21427                     list_to_add = cu->list_in_scope;
21428                 }
21429             }
21430           break;
21431         case DW_TAG_formal_parameter:
21432           /* If we are inside a function, mark this as an argument.  If
21433              not, we might be looking at an argument to an inlined function
21434              when we do not have enough information to show inlined frames;
21435              pretend it's a local variable in that case so that the user can
21436              still see it.  */
21437           if (context_stack_depth > 0
21438               && context_stack[context_stack_depth - 1].name != NULL)
21439             SYMBOL_IS_ARGUMENT (sym) = 1;
21440           attr = dwarf2_attr (die, DW_AT_location, cu);
21441           if (attr)
21442             {
21443               var_decode_location (attr, sym, cu);
21444             }
21445           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21446           if (attr)
21447             {
21448               dwarf2_const_value (attr, sym, cu);
21449             }
21450
21451           list_to_add = cu->list_in_scope;
21452           break;
21453         case DW_TAG_unspecified_parameters:
21454           /* From varargs functions; gdb doesn't seem to have any
21455              interest in this information, so just ignore it for now.
21456              (FIXME?) */
21457           break;
21458         case DW_TAG_template_type_param:
21459           suppress_add = 1;
21460           /* Fall through.  */
21461         case DW_TAG_class_type:
21462         case DW_TAG_interface_type:
21463         case DW_TAG_structure_type:
21464         case DW_TAG_union_type:
21465         case DW_TAG_set_type:
21466         case DW_TAG_enumeration_type:
21467           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21468           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21469
21470           {
21471             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21472                really ever be static objects: otherwise, if you try
21473                to, say, break of a class's method and you're in a file
21474                which doesn't mention that class, it won't work unless
21475                the check for all static symbols in lookup_symbol_aux
21476                saves you.  See the OtherFileClass tests in
21477                gdb.c++/namespace.exp.  */
21478
21479             if (!suppress_add)
21480               {
21481                 list_to_add = (cu->list_in_scope == &file_symbols
21482                                && cu->language == language_cplus
21483                                ? &global_symbols : cu->list_in_scope);
21484
21485                 /* The semantics of C++ state that "struct foo {
21486                    ... }" also defines a typedef for "foo".  */
21487                 if (cu->language == language_cplus
21488                     || cu->language == language_ada
21489                     || cu->language == language_d
21490                     || cu->language == language_rust)
21491                   {
21492                     /* The symbol's name is already allocated along
21493                        with this objfile, so we don't need to
21494                        duplicate it for the type.  */
21495                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21496                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21497                   }
21498               }
21499           }
21500           break;
21501         case DW_TAG_typedef:
21502           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21503           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21504           list_to_add = cu->list_in_scope;
21505           break;
21506         case DW_TAG_base_type:
21507         case DW_TAG_subrange_type:
21508           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21509           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21510           list_to_add = cu->list_in_scope;
21511           break;
21512         case DW_TAG_enumerator:
21513           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21514           if (attr)
21515             {
21516               dwarf2_const_value (attr, sym, cu);
21517             }
21518           {
21519             /* NOTE: carlton/2003-11-10: See comment above in the
21520                DW_TAG_class_type, etc. block.  */
21521
21522             list_to_add = (cu->list_in_scope == &file_symbols
21523                            && cu->language == language_cplus
21524                            ? &global_symbols : cu->list_in_scope);
21525           }
21526           break;
21527         case DW_TAG_imported_declaration:
21528         case DW_TAG_namespace:
21529           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21530           list_to_add = &global_symbols;
21531           break;
21532         case DW_TAG_module:
21533           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21534           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21535           list_to_add = &global_symbols;
21536           break;
21537         case DW_TAG_common_block:
21538           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21539           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21540           add_symbol_to_list (sym, cu->list_in_scope);
21541           break;
21542         default:
21543           /* Not a tag we recognize.  Hopefully we aren't processing
21544              trash data, but since we must specifically ignore things
21545              we don't recognize, there is nothing else we should do at
21546              this point.  */
21547           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21548                      dwarf_tag_name (die->tag));
21549           break;
21550         }
21551
21552       if (suppress_add)
21553         {
21554           sym->hash_next = objfile->template_symbols;
21555           objfile->template_symbols = sym;
21556           list_to_add = NULL;
21557         }
21558
21559       if (list_to_add != NULL)
21560         add_symbol_to_list (sym, list_to_add);
21561
21562       /* For the benefit of old versions of GCC, check for anonymous
21563          namespaces based on the demangled name.  */
21564       if (!cu->processing_has_namespace_info
21565           && cu->language == language_cplus)
21566         cp_scan_for_anonymous_namespaces (sym, objfile);
21567     }
21568   return (sym);
21569 }
21570
21571 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
21572
21573 static struct symbol *
21574 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21575 {
21576   return new_symbol_full (die, type, cu, NULL);
21577 }
21578
21579 /* Given an attr with a DW_FORM_dataN value in host byte order,
21580    zero-extend it as appropriate for the symbol's type.  The DWARF
21581    standard (v4) is not entirely clear about the meaning of using
21582    DW_FORM_dataN for a constant with a signed type, where the type is
21583    wider than the data.  The conclusion of a discussion on the DWARF
21584    list was that this is unspecified.  We choose to always zero-extend
21585    because that is the interpretation long in use by GCC.  */
21586
21587 static gdb_byte *
21588 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21589                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21590 {
21591   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21592   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21593                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21594   LONGEST l = DW_UNSND (attr);
21595
21596   if (bits < sizeof (*value) * 8)
21597     {
21598       l &= ((LONGEST) 1 << bits) - 1;
21599       *value = l;
21600     }
21601   else if (bits == sizeof (*value) * 8)
21602     *value = l;
21603   else
21604     {
21605       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21606       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21607       return bytes;
21608     }
21609
21610   return NULL;
21611 }
21612
21613 /* Read a constant value from an attribute.  Either set *VALUE, or if
21614    the value does not fit in *VALUE, set *BYTES - either already
21615    allocated on the objfile obstack, or newly allocated on OBSTACK,
21616    or, set *BATON, if we translated the constant to a location
21617    expression.  */
21618
21619 static void
21620 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21621                          const char *name, struct obstack *obstack,
21622                          struct dwarf2_cu *cu,
21623                          LONGEST *value, const gdb_byte **bytes,
21624                          struct dwarf2_locexpr_baton **baton)
21625 {
21626   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21627   struct comp_unit_head *cu_header = &cu->header;
21628   struct dwarf_block *blk;
21629   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21630                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21631
21632   *value = 0;
21633   *bytes = NULL;
21634   *baton = NULL;
21635
21636   switch (attr->form)
21637     {
21638     case DW_FORM_addr:
21639     case DW_FORM_GNU_addr_index:
21640       {
21641         gdb_byte *data;
21642
21643         if (TYPE_LENGTH (type) != cu_header->addr_size)
21644           dwarf2_const_value_length_mismatch_complaint (name,
21645                                                         cu_header->addr_size,
21646                                                         TYPE_LENGTH (type));
21647         /* Symbols of this form are reasonably rare, so we just
21648            piggyback on the existing location code rather than writing
21649            a new implementation of symbol_computed_ops.  */
21650         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21651         (*baton)->per_cu = cu->per_cu;
21652         gdb_assert ((*baton)->per_cu);
21653
21654         (*baton)->size = 2 + cu_header->addr_size;
21655         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21656         (*baton)->data = data;
21657
21658         data[0] = DW_OP_addr;
21659         store_unsigned_integer (&data[1], cu_header->addr_size,
21660                                 byte_order, DW_ADDR (attr));
21661         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21662       }
21663       break;
21664     case DW_FORM_string:
21665     case DW_FORM_strp:
21666     case DW_FORM_GNU_str_index:
21667     case DW_FORM_GNU_strp_alt:
21668       /* DW_STRING is already allocated on the objfile obstack, point
21669          directly to it.  */
21670       *bytes = (const gdb_byte *) DW_STRING (attr);
21671       break;
21672     case DW_FORM_block1:
21673     case DW_FORM_block2:
21674     case DW_FORM_block4:
21675     case DW_FORM_block:
21676     case DW_FORM_exprloc:
21677     case DW_FORM_data16:
21678       blk = DW_BLOCK (attr);
21679       if (TYPE_LENGTH (type) != blk->size)
21680         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21681                                                       TYPE_LENGTH (type));
21682       *bytes = blk->data;
21683       break;
21684
21685       /* The DW_AT_const_value attributes are supposed to carry the
21686          symbol's value "represented as it would be on the target
21687          architecture."  By the time we get here, it's already been
21688          converted to host endianness, so we just need to sign- or
21689          zero-extend it as appropriate.  */
21690     case DW_FORM_data1:
21691       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21692       break;
21693     case DW_FORM_data2:
21694       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21695       break;
21696     case DW_FORM_data4:
21697       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21698       break;
21699     case DW_FORM_data8:
21700       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21701       break;
21702
21703     case DW_FORM_sdata:
21704     case DW_FORM_implicit_const:
21705       *value = DW_SND (attr);
21706       break;
21707
21708     case DW_FORM_udata:
21709       *value = DW_UNSND (attr);
21710       break;
21711
21712     default:
21713       complaint (&symfile_complaints,
21714                  _("unsupported const value attribute form: '%s'"),
21715                  dwarf_form_name (attr->form));
21716       *value = 0;
21717       break;
21718     }
21719 }
21720
21721
21722 /* Copy constant value from an attribute to a symbol.  */
21723
21724 static void
21725 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21726                     struct dwarf2_cu *cu)
21727 {
21728   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21729   LONGEST value;
21730   const gdb_byte *bytes;
21731   struct dwarf2_locexpr_baton *baton;
21732
21733   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21734                            SYMBOL_PRINT_NAME (sym),
21735                            &objfile->objfile_obstack, cu,
21736                            &value, &bytes, &baton);
21737
21738   if (baton != NULL)
21739     {
21740       SYMBOL_LOCATION_BATON (sym) = baton;
21741       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21742     }
21743   else if (bytes != NULL)
21744      {
21745       SYMBOL_VALUE_BYTES (sym) = bytes;
21746       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21747     }
21748   else
21749     {
21750       SYMBOL_VALUE (sym) = value;
21751       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21752     }
21753 }
21754
21755 /* Return the type of the die in question using its DW_AT_type attribute.  */
21756
21757 static struct type *
21758 die_type (struct die_info *die, struct dwarf2_cu *cu)
21759 {
21760   struct attribute *type_attr;
21761
21762   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21763   if (!type_attr)
21764     {
21765       /* A missing DW_AT_type represents a void type.  */
21766       return objfile_type (cu->dwarf2_per_objfile->objfile)->builtin_void;
21767     }
21768
21769   return lookup_die_type (die, type_attr, cu);
21770 }
21771
21772 /* True iff CU's producer generates GNAT Ada auxiliary information
21773    that allows to find parallel types through that information instead
21774    of having to do expensive parallel lookups by type name.  */
21775
21776 static int
21777 need_gnat_info (struct dwarf2_cu *cu)
21778 {
21779   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21780      of GNAT produces this auxiliary information, without any indication
21781      that it is produced.  Part of enhancing the FSF version of GNAT
21782      to produce that information will be to put in place an indicator
21783      that we can use in order to determine whether the descriptive type
21784      info is available or not.  One suggestion that has been made is
21785      to use a new attribute, attached to the CU die.  For now, assume
21786      that the descriptive type info is not available.  */
21787   return 0;
21788 }
21789
21790 /* Return the auxiliary type of the die in question using its
21791    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21792    attribute is not present.  */
21793
21794 static struct type *
21795 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21796 {
21797   struct attribute *type_attr;
21798
21799   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21800   if (!type_attr)
21801     return NULL;
21802
21803   return lookup_die_type (die, type_attr, cu);
21804 }
21805
21806 /* If DIE has a descriptive_type attribute, then set the TYPE's
21807    descriptive type accordingly.  */
21808
21809 static void
21810 set_descriptive_type (struct type *type, struct die_info *die,
21811                       struct dwarf2_cu *cu)
21812 {
21813   struct type *descriptive_type = die_descriptive_type (die, cu);
21814
21815   if (descriptive_type)
21816     {
21817       ALLOCATE_GNAT_AUX_TYPE (type);
21818       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21819     }
21820 }
21821
21822 /* Return the containing type of the die in question using its
21823    DW_AT_containing_type attribute.  */
21824
21825 static struct type *
21826 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21827 {
21828   struct attribute *type_attr;
21829
21830   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21831   if (!type_attr)
21832     error (_("Dwarf Error: Problem turning containing type into gdb type "
21833              "[in module %s]"), objfile_name (cu->dwarf2_per_objfile->objfile));
21834
21835   return lookup_die_type (die, type_attr, cu);
21836 }
21837
21838 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21839
21840 static struct type *
21841 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21842 {
21843   struct objfile *objfile = dwarf2_per_objfile->objfile;
21844   char *message, *saved;
21845
21846   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21847                         objfile_name (objfile),
21848                         to_underlying (cu->header.sect_off),
21849                         to_underlying (die->sect_off));
21850   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21851                                   message, strlen (message));
21852   xfree (message);
21853
21854   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21855 }
21856
21857 /* Look up the type of DIE in CU using its type attribute ATTR.
21858    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21859    DW_AT_containing_type.
21860    If there is no type substitute an error marker.  */
21861
21862 static struct type *
21863 lookup_die_type (struct die_info *die, const struct attribute *attr,
21864                  struct dwarf2_cu *cu)
21865 {
21866   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21867   struct type *this_type;
21868
21869   gdb_assert (attr->name == DW_AT_type
21870               || attr->name == DW_AT_GNAT_descriptive_type
21871               || attr->name == DW_AT_containing_type);
21872
21873   /* First see if we have it cached.  */
21874
21875   if (attr->form == DW_FORM_GNU_ref_alt)
21876     {
21877       struct dwarf2_per_cu_data *per_cu;
21878       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21879
21880       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, objfile);
21881       this_type = get_die_type_at_offset (sect_off, per_cu);
21882     }
21883   else if (attr_form_is_ref (attr))
21884     {
21885       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21886
21887       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21888     }
21889   else if (attr->form == DW_FORM_ref_sig8)
21890     {
21891       ULONGEST signature = DW_SIGNATURE (attr);
21892
21893       return get_signatured_type (die, signature, cu);
21894     }
21895   else
21896     {
21897       complaint (&symfile_complaints,
21898                  _("Dwarf Error: Bad type attribute %s in DIE"
21899                    " at 0x%x [in module %s]"),
21900                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21901                  objfile_name (objfile));
21902       return build_error_marker_type (cu, die);
21903     }
21904
21905   /* If not cached we need to read it in.  */
21906
21907   if (this_type == NULL)
21908     {
21909       struct die_info *type_die = NULL;
21910       struct dwarf2_cu *type_cu = cu;
21911
21912       if (attr_form_is_ref (attr))
21913         type_die = follow_die_ref (die, attr, &type_cu);
21914       if (type_die == NULL)
21915         return build_error_marker_type (cu, die);
21916       /* If we find the type now, it's probably because the type came
21917          from an inter-CU reference and the type's CU got expanded before
21918          ours.  */
21919       this_type = read_type_die (type_die, type_cu);
21920     }
21921
21922   /* If we still don't have a type use an error marker.  */
21923
21924   if (this_type == NULL)
21925     return build_error_marker_type (cu, die);
21926
21927   return this_type;
21928 }
21929
21930 /* Return the type in DIE, CU.
21931    Returns NULL for invalid types.
21932
21933    This first does a lookup in die_type_hash,
21934    and only reads the die in if necessary.
21935
21936    NOTE: This can be called when reading in partial or full symbols.  */
21937
21938 static struct type *
21939 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21940 {
21941   struct type *this_type;
21942
21943   this_type = get_die_type (die, cu);
21944   if (this_type)
21945     return this_type;
21946
21947   return read_type_die_1 (die, cu);
21948 }
21949
21950 /* Read the type in DIE, CU.
21951    Returns NULL for invalid types.  */
21952
21953 static struct type *
21954 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21955 {
21956   struct type *this_type = NULL;
21957
21958   switch (die->tag)
21959     {
21960     case DW_TAG_class_type:
21961     case DW_TAG_interface_type:
21962     case DW_TAG_structure_type:
21963     case DW_TAG_union_type:
21964       this_type = read_structure_type (die, cu);
21965       break;
21966     case DW_TAG_enumeration_type:
21967       this_type = read_enumeration_type (die, cu);
21968       break;
21969     case DW_TAG_subprogram:
21970     case DW_TAG_subroutine_type:
21971     case DW_TAG_inlined_subroutine:
21972       this_type = read_subroutine_type (die, cu);
21973       break;
21974     case DW_TAG_array_type:
21975       this_type = read_array_type (die, cu);
21976       break;
21977     case DW_TAG_set_type:
21978       this_type = read_set_type (die, cu);
21979       break;
21980     case DW_TAG_pointer_type:
21981       this_type = read_tag_pointer_type (die, cu);
21982       break;
21983     case DW_TAG_ptr_to_member_type:
21984       this_type = read_tag_ptr_to_member_type (die, cu);
21985       break;
21986     case DW_TAG_reference_type:
21987       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21988       break;
21989     case DW_TAG_rvalue_reference_type:
21990       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21991       break;
21992     case DW_TAG_const_type:
21993       this_type = read_tag_const_type (die, cu);
21994       break;
21995     case DW_TAG_volatile_type:
21996       this_type = read_tag_volatile_type (die, cu);
21997       break;
21998     case DW_TAG_restrict_type:
21999       this_type = read_tag_restrict_type (die, cu);
22000       break;
22001     case DW_TAG_string_type:
22002       this_type = read_tag_string_type (die, cu);
22003       break;
22004     case DW_TAG_typedef:
22005       this_type = read_typedef (die, cu);
22006       break;
22007     case DW_TAG_subrange_type:
22008       this_type = read_subrange_type (die, cu);
22009       break;
22010     case DW_TAG_base_type:
22011       this_type = read_base_type (die, cu);
22012       break;
22013     case DW_TAG_unspecified_type:
22014       this_type = read_unspecified_type (die, cu);
22015       break;
22016     case DW_TAG_namespace:
22017       this_type = read_namespace_type (die, cu);
22018       break;
22019     case DW_TAG_module:
22020       this_type = read_module_type (die, cu);
22021       break;
22022     case DW_TAG_atomic_type:
22023       this_type = read_tag_atomic_type (die, cu);
22024       break;
22025     default:
22026       complaint (&symfile_complaints,
22027                  _("unexpected tag in read_type_die: '%s'"),
22028                  dwarf_tag_name (die->tag));
22029       break;
22030     }
22031
22032   return this_type;
22033 }
22034
22035 /* See if we can figure out if the class lives in a namespace.  We do
22036    this by looking for a member function; its demangled name will
22037    contain namespace info, if there is any.
22038    Return the computed name or NULL.
22039    Space for the result is allocated on the objfile's obstack.
22040    This is the full-die version of guess_partial_die_structure_name.
22041    In this case we know DIE has no useful parent.  */
22042
22043 static char *
22044 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22045 {
22046   struct die_info *spec_die;
22047   struct dwarf2_cu *spec_cu;
22048   struct die_info *child;
22049   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22050
22051   spec_cu = cu;
22052   spec_die = die_specification (die, &spec_cu);
22053   if (spec_die != NULL)
22054     {
22055       die = spec_die;
22056       cu = spec_cu;
22057     }
22058
22059   for (child = die->child;
22060        child != NULL;
22061        child = child->sibling)
22062     {
22063       if (child->tag == DW_TAG_subprogram)
22064         {
22065           const char *linkage_name = dw2_linkage_name (child, cu);
22066
22067           if (linkage_name != NULL)
22068             {
22069               char *actual_name
22070                 = language_class_name_from_physname (cu->language_defn,
22071                                                      linkage_name);
22072               char *name = NULL;
22073
22074               if (actual_name != NULL)
22075                 {
22076                   const char *die_name = dwarf2_name (die, cu);
22077
22078                   if (die_name != NULL
22079                       && strcmp (die_name, actual_name) != 0)
22080                     {
22081                       /* Strip off the class name from the full name.
22082                          We want the prefix.  */
22083                       int die_name_len = strlen (die_name);
22084                       int actual_name_len = strlen (actual_name);
22085
22086                       /* Test for '::' as a sanity check.  */
22087                       if (actual_name_len > die_name_len + 2
22088                           && actual_name[actual_name_len
22089                                          - die_name_len - 1] == ':')
22090                         name = (char *) obstack_copy0 (
22091                           &objfile->per_bfd->storage_obstack,
22092                           actual_name, actual_name_len - die_name_len - 2);
22093                     }
22094                 }
22095               xfree (actual_name);
22096               return name;
22097             }
22098         }
22099     }
22100
22101   return NULL;
22102 }
22103
22104 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22105    prefix part in such case.  See
22106    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22107
22108 static const char *
22109 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22110 {
22111   struct attribute *attr;
22112   const char *base;
22113
22114   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22115       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22116     return NULL;
22117
22118   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22119     return NULL;
22120
22121   attr = dw2_linkage_name_attr (die, cu);
22122   if (attr == NULL || DW_STRING (attr) == NULL)
22123     return NULL;
22124
22125   /* dwarf2_name had to be already called.  */
22126   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22127
22128   /* Strip the base name, keep any leading namespaces/classes.  */
22129   base = strrchr (DW_STRING (attr), ':');
22130   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22131     return "";
22132
22133   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22134   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22135                                  DW_STRING (attr),
22136                                  &base[-1] - DW_STRING (attr));
22137 }
22138
22139 /* Return the name of the namespace/class that DIE is defined within,
22140    or "" if we can't tell.  The caller should not xfree the result.
22141
22142    For example, if we're within the method foo() in the following
22143    code:
22144
22145    namespace N {
22146      class C {
22147        void foo () {
22148        }
22149      };
22150    }
22151
22152    then determine_prefix on foo's die will return "N::C".  */
22153
22154 static const char *
22155 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22156 {
22157   struct die_info *parent, *spec_die;
22158   struct dwarf2_cu *spec_cu;
22159   struct type *parent_type;
22160   const char *retval;
22161
22162   if (cu->language != language_cplus
22163       && cu->language != language_fortran && cu->language != language_d
22164       && cu->language != language_rust)
22165     return "";
22166
22167   retval = anonymous_struct_prefix (die, cu);
22168   if (retval)
22169     return retval;
22170
22171   /* We have to be careful in the presence of DW_AT_specification.
22172      For example, with GCC 3.4, given the code
22173
22174      namespace N {
22175        void foo() {
22176          // Definition of N::foo.
22177        }
22178      }
22179
22180      then we'll have a tree of DIEs like this:
22181
22182      1: DW_TAG_compile_unit
22183        2: DW_TAG_namespace        // N
22184          3: DW_TAG_subprogram     // declaration of N::foo
22185        4: DW_TAG_subprogram       // definition of N::foo
22186             DW_AT_specification   // refers to die #3
22187
22188      Thus, when processing die #4, we have to pretend that we're in
22189      the context of its DW_AT_specification, namely the contex of die
22190      #3.  */
22191   spec_cu = cu;
22192   spec_die = die_specification (die, &spec_cu);
22193   if (spec_die == NULL)
22194     parent = die->parent;
22195   else
22196     {
22197       parent = spec_die->parent;
22198       cu = spec_cu;
22199     }
22200
22201   if (parent == NULL)
22202     return "";
22203   else if (parent->building_fullname)
22204     {
22205       const char *name;
22206       const char *parent_name;
22207
22208       /* It has been seen on RealView 2.2 built binaries,
22209          DW_TAG_template_type_param types actually _defined_ as
22210          children of the parent class:
22211
22212          enum E {};
22213          template class <class Enum> Class{};
22214          Class<enum E> class_e;
22215
22216          1: DW_TAG_class_type (Class)
22217            2: DW_TAG_enumeration_type (E)
22218              3: DW_TAG_enumerator (enum1:0)
22219              3: DW_TAG_enumerator (enum2:1)
22220              ...
22221            2: DW_TAG_template_type_param
22222               DW_AT_type  DW_FORM_ref_udata (E)
22223
22224          Besides being broken debug info, it can put GDB into an
22225          infinite loop.  Consider:
22226
22227          When we're building the full name for Class<E>, we'll start
22228          at Class, and go look over its template type parameters,
22229          finding E.  We'll then try to build the full name of E, and
22230          reach here.  We're now trying to build the full name of E,
22231          and look over the parent DIE for containing scope.  In the
22232          broken case, if we followed the parent DIE of E, we'd again
22233          find Class, and once again go look at its template type
22234          arguments, etc., etc.  Simply don't consider such parent die
22235          as source-level parent of this die (it can't be, the language
22236          doesn't allow it), and break the loop here.  */
22237       name = dwarf2_name (die, cu);
22238       parent_name = dwarf2_name (parent, cu);
22239       complaint (&symfile_complaints,
22240                  _("template param type '%s' defined within parent '%s'"),
22241                  name ? name : "<unknown>",
22242                  parent_name ? parent_name : "<unknown>");
22243       return "";
22244     }
22245   else
22246     switch (parent->tag)
22247       {
22248       case DW_TAG_namespace:
22249         parent_type = read_type_die (parent, cu);
22250         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22251            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22252            Work around this problem here.  */
22253         if (cu->language == language_cplus
22254             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22255           return "";
22256         /* We give a name to even anonymous namespaces.  */
22257         return TYPE_TAG_NAME (parent_type);
22258       case DW_TAG_class_type:
22259       case DW_TAG_interface_type:
22260       case DW_TAG_structure_type:
22261       case DW_TAG_union_type:
22262       case DW_TAG_module:
22263         parent_type = read_type_die (parent, cu);
22264         if (TYPE_TAG_NAME (parent_type) != NULL)
22265           return TYPE_TAG_NAME (parent_type);
22266         else
22267           /* An anonymous structure is only allowed non-static data
22268              members; no typedefs, no member functions, et cetera.
22269              So it does not need a prefix.  */
22270           return "";
22271       case DW_TAG_compile_unit:
22272       case DW_TAG_partial_unit:
22273         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22274         if (cu->language == language_cplus
22275             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22276             && die->child != NULL
22277             && (die->tag == DW_TAG_class_type
22278                 || die->tag == DW_TAG_structure_type
22279                 || die->tag == DW_TAG_union_type))
22280           {
22281             char *name = guess_full_die_structure_name (die, cu);
22282             if (name != NULL)
22283               return name;
22284           }
22285         return "";
22286       case DW_TAG_enumeration_type:
22287         parent_type = read_type_die (parent, cu);
22288         if (TYPE_DECLARED_CLASS (parent_type))
22289           {
22290             if (TYPE_TAG_NAME (parent_type) != NULL)
22291               return TYPE_TAG_NAME (parent_type);
22292             return "";
22293           }
22294         /* Fall through.  */
22295       default:
22296         return determine_prefix (parent, cu);
22297       }
22298 }
22299
22300 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22301    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22302    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22303    an obconcat, otherwise allocate storage for the result.  The CU argument is
22304    used to determine the language and hence, the appropriate separator.  */
22305
22306 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22307
22308 static char *
22309 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22310                  int physname, struct dwarf2_cu *cu)
22311 {
22312   const char *lead = "";
22313   const char *sep;
22314
22315   if (suffix == NULL || suffix[0] == '\0'
22316       || prefix == NULL || prefix[0] == '\0')
22317     sep = "";
22318   else if (cu->language == language_d)
22319     {
22320       /* For D, the 'main' function could be defined in any module, but it
22321          should never be prefixed.  */
22322       if (strcmp (suffix, "D main") == 0)
22323         {
22324           prefix = "";
22325           sep = "";
22326         }
22327       else
22328         sep = ".";
22329     }
22330   else if (cu->language == language_fortran && physname)
22331     {
22332       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22333          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22334
22335       lead = "__";
22336       sep = "_MOD_";
22337     }
22338   else
22339     sep = "::";
22340
22341   if (prefix == NULL)
22342     prefix = "";
22343   if (suffix == NULL)
22344     suffix = "";
22345
22346   if (obs == NULL)
22347     {
22348       char *retval
22349         = ((char *)
22350            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22351
22352       strcpy (retval, lead);
22353       strcat (retval, prefix);
22354       strcat (retval, sep);
22355       strcat (retval, suffix);
22356       return retval;
22357     }
22358   else
22359     {
22360       /* We have an obstack.  */
22361       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22362     }
22363 }
22364
22365 /* Return sibling of die, NULL if no sibling.  */
22366
22367 static struct die_info *
22368 sibling_die (struct die_info *die)
22369 {
22370   return die->sibling;
22371 }
22372
22373 /* Get name of a die, return NULL if not found.  */
22374
22375 static const char *
22376 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22377                           struct obstack *obstack)
22378 {
22379   if (name && cu->language == language_cplus)
22380     {
22381       std::string canon_name = cp_canonicalize_string (name);
22382
22383       if (!canon_name.empty ())
22384         {
22385           if (canon_name != name)
22386             name = (const char *) obstack_copy0 (obstack,
22387                                                  canon_name.c_str (),
22388                                                  canon_name.length ());
22389         }
22390     }
22391
22392   return name;
22393 }
22394
22395 /* Get name of a die, return NULL if not found.
22396    Anonymous namespaces are converted to their magic string.  */
22397
22398 static const char *
22399 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22400 {
22401   struct attribute *attr;
22402   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22403
22404   attr = dwarf2_attr (die, DW_AT_name, cu);
22405   if ((!attr || !DW_STRING (attr))
22406       && die->tag != DW_TAG_namespace
22407       && die->tag != DW_TAG_class_type
22408       && die->tag != DW_TAG_interface_type
22409       && die->tag != DW_TAG_structure_type
22410       && die->tag != DW_TAG_union_type)
22411     return NULL;
22412
22413   switch (die->tag)
22414     {
22415     case DW_TAG_compile_unit:
22416     case DW_TAG_partial_unit:
22417       /* Compilation units have a DW_AT_name that is a filename, not
22418          a source language identifier.  */
22419     case DW_TAG_enumeration_type:
22420     case DW_TAG_enumerator:
22421       /* These tags always have simple identifiers already; no need
22422          to canonicalize them.  */
22423       return DW_STRING (attr);
22424
22425     case DW_TAG_namespace:
22426       if (attr != NULL && DW_STRING (attr) != NULL)
22427         return DW_STRING (attr);
22428       return CP_ANONYMOUS_NAMESPACE_STR;
22429
22430     case DW_TAG_class_type:
22431     case DW_TAG_interface_type:
22432     case DW_TAG_structure_type:
22433     case DW_TAG_union_type:
22434       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22435          structures or unions.  These were of the form "._%d" in GCC 4.1,
22436          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22437          and GCC 4.4.  We work around this problem by ignoring these.  */
22438       if (attr && DW_STRING (attr)
22439           && (startswith (DW_STRING (attr), "._")
22440               || startswith (DW_STRING (attr), "<anonymous")))
22441         return NULL;
22442
22443       /* GCC might emit a nameless typedef that has a linkage name.  See
22444          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22445       if (!attr || DW_STRING (attr) == NULL)
22446         {
22447           char *demangled = NULL;
22448
22449           attr = dw2_linkage_name_attr (die, cu);
22450           if (attr == NULL || DW_STRING (attr) == NULL)
22451             return NULL;
22452
22453           /* Avoid demangling DW_STRING (attr) the second time on a second
22454              call for the same DIE.  */
22455           if (!DW_STRING_IS_CANONICAL (attr))
22456             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22457
22458           if (demangled)
22459             {
22460               const char *base;
22461
22462               /* FIXME: we already did this for the partial symbol... */
22463               DW_STRING (attr)
22464                 = ((const char *)
22465                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22466                                   demangled, strlen (demangled)));
22467               DW_STRING_IS_CANONICAL (attr) = 1;
22468               xfree (demangled);
22469
22470               /* Strip any leading namespaces/classes, keep only the base name.
22471                  DW_AT_name for named DIEs does not contain the prefixes.  */
22472               base = strrchr (DW_STRING (attr), ':');
22473               if (base && base > DW_STRING (attr) && base[-1] == ':')
22474                 return &base[1];
22475               else
22476                 return DW_STRING (attr);
22477             }
22478         }
22479       break;
22480
22481     default:
22482       break;
22483     }
22484
22485   if (!DW_STRING_IS_CANONICAL (attr))
22486     {
22487       DW_STRING (attr)
22488         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22489                                     &objfile->per_bfd->storage_obstack);
22490       DW_STRING_IS_CANONICAL (attr) = 1;
22491     }
22492   return DW_STRING (attr);
22493 }
22494
22495 /* Return the die that this die in an extension of, or NULL if there
22496    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22497    containing the return value on output.  */
22498
22499 static struct die_info *
22500 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22501 {
22502   struct attribute *attr;
22503
22504   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22505   if (attr == NULL)
22506     return NULL;
22507
22508   return follow_die_ref (die, attr, ext_cu);
22509 }
22510
22511 /* Convert a DIE tag into its string name.  */
22512
22513 static const char *
22514 dwarf_tag_name (unsigned tag)
22515 {
22516   const char *name = get_DW_TAG_name (tag);
22517
22518   if (name == NULL)
22519     return "DW_TAG_<unknown>";
22520
22521   return name;
22522 }
22523
22524 /* Convert a DWARF attribute code into its string name.  */
22525
22526 static const char *
22527 dwarf_attr_name (unsigned attr)
22528 {
22529   const char *name;
22530
22531 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22532   if (attr == DW_AT_MIPS_fde)
22533     return "DW_AT_MIPS_fde";
22534 #else
22535   if (attr == DW_AT_HP_block_index)
22536     return "DW_AT_HP_block_index";
22537 #endif
22538
22539   name = get_DW_AT_name (attr);
22540
22541   if (name == NULL)
22542     return "DW_AT_<unknown>";
22543
22544   return name;
22545 }
22546
22547 /* Convert a DWARF value form code into its string name.  */
22548
22549 static const char *
22550 dwarf_form_name (unsigned form)
22551 {
22552   const char *name = get_DW_FORM_name (form);
22553
22554   if (name == NULL)
22555     return "DW_FORM_<unknown>";
22556
22557   return name;
22558 }
22559
22560 static const char *
22561 dwarf_bool_name (unsigned mybool)
22562 {
22563   if (mybool)
22564     return "TRUE";
22565   else
22566     return "FALSE";
22567 }
22568
22569 /* Convert a DWARF type code into its string name.  */
22570
22571 static const char *
22572 dwarf_type_encoding_name (unsigned enc)
22573 {
22574   const char *name = get_DW_ATE_name (enc);
22575
22576   if (name == NULL)
22577     return "DW_ATE_<unknown>";
22578
22579   return name;
22580 }
22581
22582 static void
22583 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22584 {
22585   unsigned int i;
22586
22587   print_spaces (indent, f);
22588   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22589                       dwarf_tag_name (die->tag), die->abbrev,
22590                       to_underlying (die->sect_off));
22591
22592   if (die->parent != NULL)
22593     {
22594       print_spaces (indent, f);
22595       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22596                           to_underlying (die->parent->sect_off));
22597     }
22598
22599   print_spaces (indent, f);
22600   fprintf_unfiltered (f, "  has children: %s\n",
22601            dwarf_bool_name (die->child != NULL));
22602
22603   print_spaces (indent, f);
22604   fprintf_unfiltered (f, "  attributes:\n");
22605
22606   for (i = 0; i < die->num_attrs; ++i)
22607     {
22608       print_spaces (indent, f);
22609       fprintf_unfiltered (f, "    %s (%s) ",
22610                dwarf_attr_name (die->attrs[i].name),
22611                dwarf_form_name (die->attrs[i].form));
22612
22613       switch (die->attrs[i].form)
22614         {
22615         case DW_FORM_addr:
22616         case DW_FORM_GNU_addr_index:
22617           fprintf_unfiltered (f, "address: ");
22618           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22619           break;
22620         case DW_FORM_block2:
22621         case DW_FORM_block4:
22622         case DW_FORM_block:
22623         case DW_FORM_block1:
22624           fprintf_unfiltered (f, "block: size %s",
22625                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22626           break;
22627         case DW_FORM_exprloc:
22628           fprintf_unfiltered (f, "expression: size %s",
22629                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22630           break;
22631         case DW_FORM_data16:
22632           fprintf_unfiltered (f, "constant of 16 bytes");
22633           break;
22634         case DW_FORM_ref_addr:
22635           fprintf_unfiltered (f, "ref address: ");
22636           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22637           break;
22638         case DW_FORM_GNU_ref_alt:
22639           fprintf_unfiltered (f, "alt ref address: ");
22640           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22641           break;
22642         case DW_FORM_ref1:
22643         case DW_FORM_ref2:
22644         case DW_FORM_ref4:
22645         case DW_FORM_ref8:
22646         case DW_FORM_ref_udata:
22647           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22648                               (long) (DW_UNSND (&die->attrs[i])));
22649           break;
22650         case DW_FORM_data1:
22651         case DW_FORM_data2:
22652         case DW_FORM_data4:
22653         case DW_FORM_data8:
22654         case DW_FORM_udata:
22655         case DW_FORM_sdata:
22656           fprintf_unfiltered (f, "constant: %s",
22657                               pulongest (DW_UNSND (&die->attrs[i])));
22658           break;
22659         case DW_FORM_sec_offset:
22660           fprintf_unfiltered (f, "section offset: %s",
22661                               pulongest (DW_UNSND (&die->attrs[i])));
22662           break;
22663         case DW_FORM_ref_sig8:
22664           fprintf_unfiltered (f, "signature: %s",
22665                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22666           break;
22667         case DW_FORM_string:
22668         case DW_FORM_strp:
22669         case DW_FORM_line_strp:
22670         case DW_FORM_GNU_str_index:
22671         case DW_FORM_GNU_strp_alt:
22672           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22673                    DW_STRING (&die->attrs[i])
22674                    ? DW_STRING (&die->attrs[i]) : "",
22675                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22676           break;
22677         case DW_FORM_flag:
22678           if (DW_UNSND (&die->attrs[i]))
22679             fprintf_unfiltered (f, "flag: TRUE");
22680           else
22681             fprintf_unfiltered (f, "flag: FALSE");
22682           break;
22683         case DW_FORM_flag_present:
22684           fprintf_unfiltered (f, "flag: TRUE");
22685           break;
22686         case DW_FORM_indirect:
22687           /* The reader will have reduced the indirect form to
22688              the "base form" so this form should not occur.  */
22689           fprintf_unfiltered (f, 
22690                               "unexpected attribute form: DW_FORM_indirect");
22691           break;
22692         case DW_FORM_implicit_const:
22693           fprintf_unfiltered (f, "constant: %s",
22694                               plongest (DW_SND (&die->attrs[i])));
22695           break;
22696         default:
22697           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22698                    die->attrs[i].form);
22699           break;
22700         }
22701       fprintf_unfiltered (f, "\n");
22702     }
22703 }
22704
22705 static void
22706 dump_die_for_error (struct die_info *die)
22707 {
22708   dump_die_shallow (gdb_stderr, 0, die);
22709 }
22710
22711 static void
22712 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22713 {
22714   int indent = level * 4;
22715
22716   gdb_assert (die != NULL);
22717
22718   if (level >= max_level)
22719     return;
22720
22721   dump_die_shallow (f, indent, die);
22722
22723   if (die->child != NULL)
22724     {
22725       print_spaces (indent, f);
22726       fprintf_unfiltered (f, "  Children:");
22727       if (level + 1 < max_level)
22728         {
22729           fprintf_unfiltered (f, "\n");
22730           dump_die_1 (f, level + 1, max_level, die->child);
22731         }
22732       else
22733         {
22734           fprintf_unfiltered (f,
22735                               " [not printed, max nesting level reached]\n");
22736         }
22737     }
22738
22739   if (die->sibling != NULL && level > 0)
22740     {
22741       dump_die_1 (f, level, max_level, die->sibling);
22742     }
22743 }
22744
22745 /* This is called from the pdie macro in gdbinit.in.
22746    It's not static so gcc will keep a copy callable from gdb.  */
22747
22748 void
22749 dump_die (struct die_info *die, int max_level)
22750 {
22751   dump_die_1 (gdb_stdlog, 0, max_level, die);
22752 }
22753
22754 static void
22755 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22756 {
22757   void **slot;
22758
22759   slot = htab_find_slot_with_hash (cu->die_hash, die,
22760                                    to_underlying (die->sect_off),
22761                                    INSERT);
22762
22763   *slot = die;
22764 }
22765
22766 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22767    required kind.  */
22768
22769 static sect_offset
22770 dwarf2_get_ref_die_offset (const struct attribute *attr)
22771 {
22772   if (attr_form_is_ref (attr))
22773     return (sect_offset) DW_UNSND (attr);
22774
22775   complaint (&symfile_complaints,
22776              _("unsupported die ref attribute form: '%s'"),
22777              dwarf_form_name (attr->form));
22778   return {};
22779 }
22780
22781 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22782  * the value held by the attribute is not constant.  */
22783
22784 static LONGEST
22785 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22786 {
22787   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22788     return DW_SND (attr);
22789   else if (attr->form == DW_FORM_udata
22790            || attr->form == DW_FORM_data1
22791            || attr->form == DW_FORM_data2
22792            || attr->form == DW_FORM_data4
22793            || attr->form == DW_FORM_data8)
22794     return DW_UNSND (attr);
22795   else
22796     {
22797       /* For DW_FORM_data16 see attr_form_is_constant.  */
22798       complaint (&symfile_complaints,
22799                  _("Attribute value is not a constant (%s)"),
22800                  dwarf_form_name (attr->form));
22801       return default_value;
22802     }
22803 }
22804
22805 /* Follow reference or signature attribute ATTR of SRC_DIE.
22806    On entry *REF_CU is the CU of SRC_DIE.
22807    On exit *REF_CU is the CU of the result.  */
22808
22809 static struct die_info *
22810 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22811                        struct dwarf2_cu **ref_cu)
22812 {
22813   struct die_info *die;
22814
22815   if (attr_form_is_ref (attr))
22816     die = follow_die_ref (src_die, attr, ref_cu);
22817   else if (attr->form == DW_FORM_ref_sig8)
22818     die = follow_die_sig (src_die, attr, ref_cu);
22819   else
22820     {
22821       dump_die_for_error (src_die);
22822       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22823              objfile_name ((*ref_cu)->dwarf2_per_objfile->objfile));
22824     }
22825
22826   return die;
22827 }
22828
22829 /* Follow reference OFFSET.
22830    On entry *REF_CU is the CU of the source die referencing OFFSET.
22831    On exit *REF_CU is the CU of the result.
22832    Returns NULL if OFFSET is invalid.  */
22833
22834 static struct die_info *
22835 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22836                    struct dwarf2_cu **ref_cu)
22837 {
22838   struct die_info temp_die;
22839   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22840   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22841
22842   gdb_assert (cu->per_cu != NULL);
22843
22844   target_cu = cu;
22845
22846   if (cu->per_cu->is_debug_types)
22847     {
22848       /* .debug_types CUs cannot reference anything outside their CU.
22849          If they need to, they have to reference a signatured type via
22850          DW_FORM_ref_sig8.  */
22851       if (!offset_in_cu_p (&cu->header, sect_off))
22852         return NULL;
22853     }
22854   else if (offset_in_dwz != cu->per_cu->is_dwz
22855            || !offset_in_cu_p (&cu->header, sect_off))
22856     {
22857       struct dwarf2_per_cu_data *per_cu;
22858
22859       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22860                                                  objfile);
22861
22862       /* If necessary, add it to the queue and load its DIEs.  */
22863       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22864         load_full_comp_unit (per_cu, cu->language);
22865
22866       target_cu = per_cu->cu;
22867     }
22868   else if (cu->dies == NULL)
22869     {
22870       /* We're loading full DIEs during partial symbol reading.  */
22871       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22872       load_full_comp_unit (cu->per_cu, language_minimal);
22873     }
22874
22875   *ref_cu = target_cu;
22876   temp_die.sect_off = sect_off;
22877   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22878                                                   &temp_die,
22879                                                   to_underlying (sect_off));
22880 }
22881
22882 /* Follow reference attribute ATTR of SRC_DIE.
22883    On entry *REF_CU is the CU of SRC_DIE.
22884    On exit *REF_CU is the CU of the result.  */
22885
22886 static struct die_info *
22887 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22888                 struct dwarf2_cu **ref_cu)
22889 {
22890   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22891   struct dwarf2_cu *cu = *ref_cu;
22892   struct die_info *die;
22893
22894   die = follow_die_offset (sect_off,
22895                            (attr->form == DW_FORM_GNU_ref_alt
22896                             || cu->per_cu->is_dwz),
22897                            ref_cu);
22898   if (!die)
22899     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22900            "at 0x%x [in module %s]"),
22901            to_underlying (sect_off), to_underlying (src_die->sect_off),
22902            objfile_name (cu->dwarf2_per_objfile->objfile));
22903
22904   return die;
22905 }
22906
22907 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22908    Returned value is intended for DW_OP_call*.  Returned
22909    dwarf2_locexpr_baton->data has lifetime of
22910    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22911
22912 struct dwarf2_locexpr_baton
22913 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22914                                struct dwarf2_per_cu_data *per_cu,
22915                                CORE_ADDR (*get_frame_pc) (void *baton),
22916                                void *baton)
22917 {
22918   struct dwarf2_cu *cu;
22919   struct die_info *die;
22920   struct attribute *attr;
22921   struct dwarf2_locexpr_baton retval;
22922   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22923
22924   dw2_setup (objfile);
22925
22926   if (per_cu->cu == NULL)
22927     load_cu (per_cu);
22928   cu = per_cu->cu;
22929   if (cu == NULL)
22930     {
22931       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22932          Instead just throw an error, not much else we can do.  */
22933       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22934              to_underlying (sect_off), objfile_name (objfile));
22935     }
22936
22937   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22938   if (!die)
22939     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22940            to_underlying (sect_off), objfile_name (objfile));
22941
22942   attr = dwarf2_attr (die, DW_AT_location, cu);
22943   if (!attr)
22944     {
22945       /* DWARF: "If there is no such attribute, then there is no effect.".
22946          DATA is ignored if SIZE is 0.  */
22947
22948       retval.data = NULL;
22949       retval.size = 0;
22950     }
22951   else if (attr_form_is_section_offset (attr))
22952     {
22953       struct dwarf2_loclist_baton loclist_baton;
22954       CORE_ADDR pc = (*get_frame_pc) (baton);
22955       size_t size;
22956
22957       fill_in_loclist_baton (cu, &loclist_baton, attr);
22958
22959       retval.data = dwarf2_find_location_expression (&loclist_baton,
22960                                                      &size, pc);
22961       retval.size = size;
22962     }
22963   else
22964     {
22965       if (!attr_form_is_block (attr))
22966         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
22967                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22968                to_underlying (sect_off), objfile_name (objfile));
22969
22970       retval.data = DW_BLOCK (attr)->data;
22971       retval.size = DW_BLOCK (attr)->size;
22972     }
22973   retval.per_cu = cu->per_cu;
22974
22975   age_cached_comp_units ();
22976
22977   return retval;
22978 }
22979
22980 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22981    offset.  */
22982
22983 struct dwarf2_locexpr_baton
22984 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22985                              struct dwarf2_per_cu_data *per_cu,
22986                              CORE_ADDR (*get_frame_pc) (void *baton),
22987                              void *baton)
22988 {
22989   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22990
22991   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22992 }
22993
22994 /* Write a constant of a given type as target-ordered bytes into
22995    OBSTACK.  */
22996
22997 static const gdb_byte *
22998 write_constant_as_bytes (struct obstack *obstack,
22999                          enum bfd_endian byte_order,
23000                          struct type *type,
23001                          ULONGEST value,
23002                          LONGEST *len)
23003 {
23004   gdb_byte *result;
23005
23006   *len = TYPE_LENGTH (type);
23007   result = (gdb_byte *) obstack_alloc (obstack, *len);
23008   store_unsigned_integer (result, *len, byte_order, value);
23009
23010   return result;
23011 }
23012
23013 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23014    pointer to the constant bytes and set LEN to the length of the
23015    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23016    does not have a DW_AT_const_value, return NULL.  */
23017
23018 const gdb_byte *
23019 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23020                              struct dwarf2_per_cu_data *per_cu,
23021                              struct obstack *obstack,
23022                              LONGEST *len)
23023 {
23024   struct dwarf2_cu *cu;
23025   struct die_info *die;
23026   struct attribute *attr;
23027   const gdb_byte *result = NULL;
23028   struct type *type;
23029   LONGEST value;
23030   enum bfd_endian byte_order;
23031   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23032
23033   dw2_setup (objfile);
23034
23035   if (per_cu->cu == NULL)
23036     load_cu (per_cu);
23037   cu = per_cu->cu;
23038   if (cu == NULL)
23039     {
23040       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23041          Instead just throw an error, not much else we can do.  */
23042       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23043              to_underlying (sect_off), objfile_name (objfile));
23044     }
23045
23046   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23047   if (!die)
23048     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23049            to_underlying (sect_off), objfile_name (objfile));
23050
23051
23052   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23053   if (attr == NULL)
23054     return NULL;
23055
23056   byte_order = (bfd_big_endian (objfile->obfd)
23057                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23058
23059   switch (attr->form)
23060     {
23061     case DW_FORM_addr:
23062     case DW_FORM_GNU_addr_index:
23063       {
23064         gdb_byte *tem;
23065
23066         *len = cu->header.addr_size;
23067         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23068         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23069         result = tem;
23070       }
23071       break;
23072     case DW_FORM_string:
23073     case DW_FORM_strp:
23074     case DW_FORM_GNU_str_index:
23075     case DW_FORM_GNU_strp_alt:
23076       /* DW_STRING is already allocated on the objfile obstack, point
23077          directly to it.  */
23078       result = (const gdb_byte *) DW_STRING (attr);
23079       *len = strlen (DW_STRING (attr));
23080       break;
23081     case DW_FORM_block1:
23082     case DW_FORM_block2:
23083     case DW_FORM_block4:
23084     case DW_FORM_block:
23085     case DW_FORM_exprloc:
23086     case DW_FORM_data16:
23087       result = DW_BLOCK (attr)->data;
23088       *len = DW_BLOCK (attr)->size;
23089       break;
23090
23091       /* The DW_AT_const_value attributes are supposed to carry the
23092          symbol's value "represented as it would be on the target
23093          architecture."  By the time we get here, it's already been
23094          converted to host endianness, so we just need to sign- or
23095          zero-extend it as appropriate.  */
23096     case DW_FORM_data1:
23097       type = die_type (die, cu);
23098       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23099       if (result == NULL)
23100         result = write_constant_as_bytes (obstack, byte_order,
23101                                           type, value, len);
23102       break;
23103     case DW_FORM_data2:
23104       type = die_type (die, cu);
23105       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23106       if (result == NULL)
23107         result = write_constant_as_bytes (obstack, byte_order,
23108                                           type, value, len);
23109       break;
23110     case DW_FORM_data4:
23111       type = die_type (die, cu);
23112       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23113       if (result == NULL)
23114         result = write_constant_as_bytes (obstack, byte_order,
23115                                           type, value, len);
23116       break;
23117     case DW_FORM_data8:
23118       type = die_type (die, cu);
23119       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23120       if (result == NULL)
23121         result = write_constant_as_bytes (obstack, byte_order,
23122                                           type, value, len);
23123       break;
23124
23125     case DW_FORM_sdata:
23126     case DW_FORM_implicit_const:
23127       type = die_type (die, cu);
23128       result = write_constant_as_bytes (obstack, byte_order,
23129                                         type, DW_SND (attr), len);
23130       break;
23131
23132     case DW_FORM_udata:
23133       type = die_type (die, cu);
23134       result = write_constant_as_bytes (obstack, byte_order,
23135                                         type, DW_UNSND (attr), len);
23136       break;
23137
23138     default:
23139       complaint (&symfile_complaints,
23140                  _("unsupported const value attribute form: '%s'"),
23141                  dwarf_form_name (attr->form));
23142       break;
23143     }
23144
23145   return result;
23146 }
23147
23148 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23149    valid type for this die is found.  */
23150
23151 struct type *
23152 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23153                                 struct dwarf2_per_cu_data *per_cu)
23154 {
23155   struct dwarf2_cu *cu;
23156   struct die_info *die;
23157
23158   dw2_setup (per_cu->dwarf2_per_objfile->objfile);
23159
23160   if (per_cu->cu == NULL)
23161     load_cu (per_cu);
23162   cu = per_cu->cu;
23163   if (!cu)
23164     return NULL;
23165
23166   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23167   if (!die)
23168     return NULL;
23169
23170   return die_type (die, cu);
23171 }
23172
23173 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23174    PER_CU.  */
23175
23176 struct type *
23177 dwarf2_get_die_type (cu_offset die_offset,
23178                      struct dwarf2_per_cu_data *per_cu)
23179 {
23180   dw2_setup (per_cu->dwarf2_per_objfile->objfile);
23181
23182   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23183   return get_die_type_at_offset (die_offset_sect, per_cu);
23184 }
23185
23186 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23187    On entry *REF_CU is the CU of SRC_DIE.
23188    On exit *REF_CU is the CU of the result.
23189    Returns NULL if the referenced DIE isn't found.  */
23190
23191 static struct die_info *
23192 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23193                   struct dwarf2_cu **ref_cu)
23194 {
23195   struct die_info temp_die;
23196   struct dwarf2_cu *sig_cu;
23197   struct die_info *die;
23198
23199   /* While it might be nice to assert sig_type->type == NULL here,
23200      we can get here for DW_AT_imported_declaration where we need
23201      the DIE not the type.  */
23202
23203   /* If necessary, add it to the queue and load its DIEs.  */
23204
23205   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23206     read_signatured_type (sig_type);
23207
23208   sig_cu = sig_type->per_cu.cu;
23209   gdb_assert (sig_cu != NULL);
23210   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23211   temp_die.sect_off = sig_type->type_offset_in_section;
23212   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23213                                                  to_underlying (temp_die.sect_off));
23214   if (die)
23215     {
23216       /* For .gdb_index version 7 keep track of included TUs.
23217          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23218       if (dwarf2_per_objfile->index_table != NULL
23219           && dwarf2_per_objfile->index_table->version <= 7)
23220         {
23221           VEC_safe_push (dwarf2_per_cu_ptr,
23222                          (*ref_cu)->per_cu->imported_symtabs,
23223                          sig_cu->per_cu);
23224         }
23225
23226       *ref_cu = sig_cu;
23227       return die;
23228     }
23229
23230   return NULL;
23231 }
23232
23233 /* Follow signatured type referenced by ATTR in SRC_DIE.
23234    On entry *REF_CU is the CU of SRC_DIE.
23235    On exit *REF_CU is the CU of the result.
23236    The result is the DIE of the type.
23237    If the referenced type cannot be found an error is thrown.  */
23238
23239 static struct die_info *
23240 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23241                 struct dwarf2_cu **ref_cu)
23242 {
23243   ULONGEST signature = DW_SIGNATURE (attr);
23244   struct signatured_type *sig_type;
23245   struct die_info *die;
23246
23247   gdb_assert (attr->form == DW_FORM_ref_sig8);
23248
23249   sig_type = lookup_signatured_type (*ref_cu, signature);
23250   /* sig_type will be NULL if the signatured type is missing from
23251      the debug info.  */
23252   if (sig_type == NULL)
23253     {
23254       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23255                " from DIE at 0x%x [in module %s]"),
23256              hex_string (signature), to_underlying (src_die->sect_off),
23257              objfile_name ((*ref_cu)->dwarf2_per_objfile->objfile));
23258     }
23259
23260   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23261   if (die == NULL)
23262     {
23263       dump_die_for_error (src_die);
23264       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23265                " from DIE at 0x%x [in module %s]"),
23266              hex_string (signature), to_underlying (src_die->sect_off),
23267              objfile_name ((*ref_cu)->dwarf2_per_objfile->objfile));
23268     }
23269
23270   return die;
23271 }
23272
23273 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23274    reading in and processing the type unit if necessary.  */
23275
23276 static struct type *
23277 get_signatured_type (struct die_info *die, ULONGEST signature,
23278                      struct dwarf2_cu *cu)
23279 {
23280   struct signatured_type *sig_type;
23281   struct dwarf2_cu *type_cu;
23282   struct die_info *type_die;
23283   struct type *type;
23284
23285   sig_type = lookup_signatured_type (cu, signature);
23286   /* sig_type will be NULL if the signatured type is missing from
23287      the debug info.  */
23288   if (sig_type == NULL)
23289     {
23290       complaint (&symfile_complaints,
23291                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23292                    " from DIE at 0x%x [in module %s]"),
23293                  hex_string (signature), to_underlying (die->sect_off),
23294                  objfile_name (dwarf2_per_objfile->objfile));
23295       return build_error_marker_type (cu, die);
23296     }
23297
23298   /* If we already know the type we're done.  */
23299   if (sig_type->type != NULL)
23300     return sig_type->type;
23301
23302   type_cu = cu;
23303   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23304   if (type_die != NULL)
23305     {
23306       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23307          is created.  This is important, for example, because for c++ classes
23308          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23309       type = read_type_die (type_die, type_cu);
23310       if (type == NULL)
23311         {
23312           complaint (&symfile_complaints,
23313                      _("Dwarf Error: Cannot build signatured type %s"
23314                        " referenced from DIE at 0x%x [in module %s]"),
23315                      hex_string (signature), to_underlying (die->sect_off),
23316                      objfile_name (dwarf2_per_objfile->objfile));
23317           type = build_error_marker_type (cu, die);
23318         }
23319     }
23320   else
23321     {
23322       complaint (&symfile_complaints,
23323                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23324                    " from DIE at 0x%x [in module %s]"),
23325                  hex_string (signature), to_underlying (die->sect_off),
23326                  objfile_name (dwarf2_per_objfile->objfile));
23327       type = build_error_marker_type (cu, die);
23328     }
23329   sig_type->type = type;
23330
23331   return type;
23332 }
23333
23334 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23335    reading in and processing the type unit if necessary.  */
23336
23337 static struct type *
23338 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23339                           struct dwarf2_cu *cu) /* ARI: editCase function */
23340 {
23341   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23342   if (attr_form_is_ref (attr))
23343     {
23344       struct dwarf2_cu *type_cu = cu;
23345       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23346
23347       return read_type_die (type_die, type_cu);
23348     }
23349   else if (attr->form == DW_FORM_ref_sig8)
23350     {
23351       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23352     }
23353   else
23354     {
23355       complaint (&symfile_complaints,
23356                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23357                    " at 0x%x [in module %s]"),
23358                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23359                  objfile_name (dwarf2_per_objfile->objfile));
23360       return build_error_marker_type (cu, die);
23361     }
23362 }
23363
23364 /* Load the DIEs associated with type unit PER_CU into memory.  */
23365
23366 static void
23367 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23368 {
23369   struct signatured_type *sig_type;
23370
23371   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23372   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23373
23374   /* We have the per_cu, but we need the signatured_type.
23375      Fortunately this is an easy translation.  */
23376   gdb_assert (per_cu->is_debug_types);
23377   sig_type = (struct signatured_type *) per_cu;
23378
23379   gdb_assert (per_cu->cu == NULL);
23380
23381   read_signatured_type (sig_type);
23382
23383   gdb_assert (per_cu->cu != NULL);
23384 }
23385
23386 /* die_reader_func for read_signatured_type.
23387    This is identical to load_full_comp_unit_reader,
23388    but is kept separate for now.  */
23389
23390 static void
23391 read_signatured_type_reader (const struct die_reader_specs *reader,
23392                              const gdb_byte *info_ptr,
23393                              struct die_info *comp_unit_die,
23394                              int has_children,
23395                              void *data)
23396 {
23397   struct dwarf2_cu *cu = reader->cu;
23398
23399   gdb_assert (cu->die_hash == NULL);
23400   cu->die_hash =
23401     htab_create_alloc_ex (cu->header.length / 12,
23402                           die_hash,
23403                           die_eq,
23404                           NULL,
23405                           &cu->comp_unit_obstack,
23406                           hashtab_obstack_allocate,
23407                           dummy_obstack_deallocate);
23408
23409   if (has_children)
23410     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23411                                                   &info_ptr, comp_unit_die);
23412   cu->dies = comp_unit_die;
23413   /* comp_unit_die is not stored in die_hash, no need.  */
23414
23415   /* We try not to read any attributes in this function, because not
23416      all CUs needed for references have been loaded yet, and symbol
23417      table processing isn't initialized.  But we have to set the CU language,
23418      or we won't be able to build types correctly.
23419      Similarly, if we do not read the producer, we can not apply
23420      producer-specific interpretation.  */
23421   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23422 }
23423
23424 /* Read in a signatured type and build its CU and DIEs.
23425    If the type is a stub for the real type in a DWO file,
23426    read in the real type from the DWO file as well.  */
23427
23428 static void
23429 read_signatured_type (struct signatured_type *sig_type)
23430 {
23431   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23432
23433   gdb_assert (per_cu->is_debug_types);
23434   gdb_assert (per_cu->cu == NULL);
23435
23436   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23437                            read_signatured_type_reader, NULL);
23438   sig_type->per_cu.tu_read = 1;
23439 }
23440
23441 /* Decode simple location descriptions.
23442    Given a pointer to a dwarf block that defines a location, compute
23443    the location and return the value.
23444
23445    NOTE drow/2003-11-18: This function is called in two situations
23446    now: for the address of static or global variables (partial symbols
23447    only) and for offsets into structures which are expected to be
23448    (more or less) constant.  The partial symbol case should go away,
23449    and only the constant case should remain.  That will let this
23450    function complain more accurately.  A few special modes are allowed
23451    without complaint for global variables (for instance, global
23452    register values and thread-local values).
23453
23454    A location description containing no operations indicates that the
23455    object is optimized out.  The return value is 0 for that case.
23456    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23457    callers will only want a very basic result and this can become a
23458    complaint.
23459
23460    Note that stack[0] is unused except as a default error return.  */
23461
23462 static CORE_ADDR
23463 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23464 {
23465   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
23466   size_t i;
23467   size_t size = blk->size;
23468   const gdb_byte *data = blk->data;
23469   CORE_ADDR stack[64];
23470   int stacki;
23471   unsigned int bytes_read, unsnd;
23472   gdb_byte op;
23473
23474   i = 0;
23475   stacki = 0;
23476   stack[stacki] = 0;
23477   stack[++stacki] = 0;
23478
23479   while (i < size)
23480     {
23481       op = data[i++];
23482       switch (op)
23483         {
23484         case DW_OP_lit0:
23485         case DW_OP_lit1:
23486         case DW_OP_lit2:
23487         case DW_OP_lit3:
23488         case DW_OP_lit4:
23489         case DW_OP_lit5:
23490         case DW_OP_lit6:
23491         case DW_OP_lit7:
23492         case DW_OP_lit8:
23493         case DW_OP_lit9:
23494         case DW_OP_lit10:
23495         case DW_OP_lit11:
23496         case DW_OP_lit12:
23497         case DW_OP_lit13:
23498         case DW_OP_lit14:
23499         case DW_OP_lit15:
23500         case DW_OP_lit16:
23501         case DW_OP_lit17:
23502         case DW_OP_lit18:
23503         case DW_OP_lit19:
23504         case DW_OP_lit20:
23505         case DW_OP_lit21:
23506         case DW_OP_lit22:
23507         case DW_OP_lit23:
23508         case DW_OP_lit24:
23509         case DW_OP_lit25:
23510         case DW_OP_lit26:
23511         case DW_OP_lit27:
23512         case DW_OP_lit28:
23513         case DW_OP_lit29:
23514         case DW_OP_lit30:
23515         case DW_OP_lit31:
23516           stack[++stacki] = op - DW_OP_lit0;
23517           break;
23518
23519         case DW_OP_reg0:
23520         case DW_OP_reg1:
23521         case DW_OP_reg2:
23522         case DW_OP_reg3:
23523         case DW_OP_reg4:
23524         case DW_OP_reg5:
23525         case DW_OP_reg6:
23526         case DW_OP_reg7:
23527         case DW_OP_reg8:
23528         case DW_OP_reg9:
23529         case DW_OP_reg10:
23530         case DW_OP_reg11:
23531         case DW_OP_reg12:
23532         case DW_OP_reg13:
23533         case DW_OP_reg14:
23534         case DW_OP_reg15:
23535         case DW_OP_reg16:
23536         case DW_OP_reg17:
23537         case DW_OP_reg18:
23538         case DW_OP_reg19:
23539         case DW_OP_reg20:
23540         case DW_OP_reg21:
23541         case DW_OP_reg22:
23542         case DW_OP_reg23:
23543         case DW_OP_reg24:
23544         case DW_OP_reg25:
23545         case DW_OP_reg26:
23546         case DW_OP_reg27:
23547         case DW_OP_reg28:
23548         case DW_OP_reg29:
23549         case DW_OP_reg30:
23550         case DW_OP_reg31:
23551           stack[++stacki] = op - DW_OP_reg0;
23552           if (i < size)
23553             dwarf2_complex_location_expr_complaint ();
23554           break;
23555
23556         case DW_OP_regx:
23557           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23558           i += bytes_read;
23559           stack[++stacki] = unsnd;
23560           if (i < size)
23561             dwarf2_complex_location_expr_complaint ();
23562           break;
23563
23564         case DW_OP_addr:
23565           stack[++stacki] = read_address (objfile->obfd, &data[i],
23566                                           cu, &bytes_read);
23567           i += bytes_read;
23568           break;
23569
23570         case DW_OP_const1u:
23571           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23572           i += 1;
23573           break;
23574
23575         case DW_OP_const1s:
23576           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23577           i += 1;
23578           break;
23579
23580         case DW_OP_const2u:
23581           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23582           i += 2;
23583           break;
23584
23585         case DW_OP_const2s:
23586           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23587           i += 2;
23588           break;
23589
23590         case DW_OP_const4u:
23591           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23592           i += 4;
23593           break;
23594
23595         case DW_OP_const4s:
23596           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23597           i += 4;
23598           break;
23599
23600         case DW_OP_const8u:
23601           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23602           i += 8;
23603           break;
23604
23605         case DW_OP_constu:
23606           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23607                                                   &bytes_read);
23608           i += bytes_read;
23609           break;
23610
23611         case DW_OP_consts:
23612           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23613           i += bytes_read;
23614           break;
23615
23616         case DW_OP_dup:
23617           stack[stacki + 1] = stack[stacki];
23618           stacki++;
23619           break;
23620
23621         case DW_OP_plus:
23622           stack[stacki - 1] += stack[stacki];
23623           stacki--;
23624           break;
23625
23626         case DW_OP_plus_uconst:
23627           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23628                                                  &bytes_read);
23629           i += bytes_read;
23630           break;
23631
23632         case DW_OP_minus:
23633           stack[stacki - 1] -= stack[stacki];
23634           stacki--;
23635           break;
23636
23637         case DW_OP_deref:
23638           /* If we're not the last op, then we definitely can't encode
23639              this using GDB's address_class enum.  This is valid for partial
23640              global symbols, although the variable's address will be bogus
23641              in the psymtab.  */
23642           if (i < size)
23643             dwarf2_complex_location_expr_complaint ();
23644           break;
23645
23646         case DW_OP_GNU_push_tls_address:
23647         case DW_OP_form_tls_address:
23648           /* The top of the stack has the offset from the beginning
23649              of the thread control block at which the variable is located.  */
23650           /* Nothing should follow this operator, so the top of stack would
23651              be returned.  */
23652           /* This is valid for partial global symbols, but the variable's
23653              address will be bogus in the psymtab.  Make it always at least
23654              non-zero to not look as a variable garbage collected by linker
23655              which have DW_OP_addr 0.  */
23656           if (i < size)
23657             dwarf2_complex_location_expr_complaint ();
23658           stack[stacki]++;
23659           break;
23660
23661         case DW_OP_GNU_uninit:
23662           break;
23663
23664         case DW_OP_GNU_addr_index:
23665         case DW_OP_GNU_const_index:
23666           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23667                                                          &bytes_read);
23668           i += bytes_read;
23669           break;
23670
23671         default:
23672           {
23673             const char *name = get_DW_OP_name (op);
23674
23675             if (name)
23676               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23677                          name);
23678             else
23679               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23680                          op);
23681           }
23682
23683           return (stack[stacki]);
23684         }
23685
23686       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23687          outside of the allocated space.  Also enforce minimum>0.  */
23688       if (stacki >= ARRAY_SIZE (stack) - 1)
23689         {
23690           complaint (&symfile_complaints,
23691                      _("location description stack overflow"));
23692           return 0;
23693         }
23694
23695       if (stacki <= 0)
23696         {
23697           complaint (&symfile_complaints,
23698                      _("location description stack underflow"));
23699           return 0;
23700         }
23701     }
23702   return (stack[stacki]);
23703 }
23704
23705 /* memory allocation interface */
23706
23707 static struct dwarf_block *
23708 dwarf_alloc_block (struct dwarf2_cu *cu)
23709 {
23710   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23711 }
23712
23713 static struct die_info *
23714 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23715 {
23716   struct die_info *die;
23717   size_t size = sizeof (struct die_info);
23718
23719   if (num_attrs > 1)
23720     size += (num_attrs - 1) * sizeof (struct attribute);
23721
23722   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23723   memset (die, 0, sizeof (struct die_info));
23724   return (die);
23725 }
23726
23727 \f
23728 /* Macro support.  */
23729
23730 /* Return file name relative to the compilation directory of file number I in
23731    *LH's file name table.  The result is allocated using xmalloc; the caller is
23732    responsible for freeing it.  */
23733
23734 static char *
23735 file_file_name (int file, struct line_header *lh)
23736 {
23737   /* Is the file number a valid index into the line header's file name
23738      table?  Remember that file numbers start with one, not zero.  */
23739   if (1 <= file && file <= lh->file_names.size ())
23740     {
23741       const file_entry &fe = lh->file_names[file - 1];
23742
23743       if (!IS_ABSOLUTE_PATH (fe.name))
23744         {
23745           const char *dir = fe.include_dir (lh);
23746           if (dir != NULL)
23747             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23748         }
23749       return xstrdup (fe.name);
23750     }
23751   else
23752     {
23753       /* The compiler produced a bogus file number.  We can at least
23754          record the macro definitions made in the file, even if we
23755          won't be able to find the file by name.  */
23756       char fake_name[80];
23757
23758       xsnprintf (fake_name, sizeof (fake_name),
23759                  "<bad macro file number %d>", file);
23760
23761       complaint (&symfile_complaints,
23762                  _("bad file number in macro information (%d)"),
23763                  file);
23764
23765       return xstrdup (fake_name);
23766     }
23767 }
23768
23769 /* Return the full name of file number I in *LH's file name table.
23770    Use COMP_DIR as the name of the current directory of the
23771    compilation.  The result is allocated using xmalloc; the caller is
23772    responsible for freeing it.  */
23773 static char *
23774 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23775 {
23776   /* Is the file number a valid index into the line header's file name
23777      table?  Remember that file numbers start with one, not zero.  */
23778   if (1 <= file && file <= lh->file_names.size ())
23779     {
23780       char *relative = file_file_name (file, lh);
23781
23782       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23783         return relative;
23784       return reconcat (relative, comp_dir, SLASH_STRING,
23785                        relative, (char *) NULL);
23786     }
23787   else
23788     return file_file_name (file, lh);
23789 }
23790
23791
23792 static struct macro_source_file *
23793 macro_start_file (int file, int line,
23794                   struct macro_source_file *current_file,
23795                   struct line_header *lh)
23796 {
23797   /* File name relative to the compilation directory of this source file.  */
23798   char *file_name = file_file_name (file, lh);
23799
23800   if (! current_file)
23801     {
23802       /* Note: We don't create a macro table for this compilation unit
23803          at all until we actually get a filename.  */
23804       struct macro_table *macro_table = get_macro_table ();
23805
23806       /* If we have no current file, then this must be the start_file
23807          directive for the compilation unit's main source file.  */
23808       current_file = macro_set_main (macro_table, file_name);
23809       macro_define_special (macro_table);
23810     }
23811   else
23812     current_file = macro_include (current_file, line, file_name);
23813
23814   xfree (file_name);
23815
23816   return current_file;
23817 }
23818
23819 static const char *
23820 consume_improper_spaces (const char *p, const char *body)
23821 {
23822   if (*p == ' ')
23823     {
23824       complaint (&symfile_complaints,
23825                  _("macro definition contains spaces "
23826                    "in formal argument list:\n`%s'"),
23827                  body);
23828
23829       while (*p == ' ')
23830         p++;
23831     }
23832
23833   return p;
23834 }
23835
23836
23837 static void
23838 parse_macro_definition (struct macro_source_file *file, int line,
23839                         const char *body)
23840 {
23841   const char *p;
23842
23843   /* The body string takes one of two forms.  For object-like macro
23844      definitions, it should be:
23845
23846         <macro name> " " <definition>
23847
23848      For function-like macro definitions, it should be:
23849
23850         <macro name> "() " <definition>
23851      or
23852         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23853
23854      Spaces may appear only where explicitly indicated, and in the
23855      <definition>.
23856
23857      The Dwarf 2 spec says that an object-like macro's name is always
23858      followed by a space, but versions of GCC around March 2002 omit
23859      the space when the macro's definition is the empty string.
23860
23861      The Dwarf 2 spec says that there should be no spaces between the
23862      formal arguments in a function-like macro's formal argument list,
23863      but versions of GCC around March 2002 include spaces after the
23864      commas.  */
23865
23866
23867   /* Find the extent of the macro name.  The macro name is terminated
23868      by either a space or null character (for an object-like macro) or
23869      an opening paren (for a function-like macro).  */
23870   for (p = body; *p; p++)
23871     if (*p == ' ' || *p == '(')
23872       break;
23873
23874   if (*p == ' ' || *p == '\0')
23875     {
23876       /* It's an object-like macro.  */
23877       int name_len = p - body;
23878       char *name = savestring (body, name_len);
23879       const char *replacement;
23880
23881       if (*p == ' ')
23882         replacement = body + name_len + 1;
23883       else
23884         {
23885           dwarf2_macro_malformed_definition_complaint (body);
23886           replacement = body + name_len;
23887         }
23888
23889       macro_define_object (file, line, name, replacement);
23890
23891       xfree (name);
23892     }
23893   else if (*p == '(')
23894     {
23895       /* It's a function-like macro.  */
23896       char *name = savestring (body, p - body);
23897       int argc = 0;
23898       int argv_size = 1;
23899       char **argv = XNEWVEC (char *, argv_size);
23900
23901       p++;
23902
23903       p = consume_improper_spaces (p, body);
23904
23905       /* Parse the formal argument list.  */
23906       while (*p && *p != ')')
23907         {
23908           /* Find the extent of the current argument name.  */
23909           const char *arg_start = p;
23910
23911           while (*p && *p != ',' && *p != ')' && *p != ' ')
23912             p++;
23913
23914           if (! *p || p == arg_start)
23915             dwarf2_macro_malformed_definition_complaint (body);
23916           else
23917             {
23918               /* Make sure argv has room for the new argument.  */
23919               if (argc >= argv_size)
23920                 {
23921                   argv_size *= 2;
23922                   argv = XRESIZEVEC (char *, argv, argv_size);
23923                 }
23924
23925               argv[argc++] = savestring (arg_start, p - arg_start);
23926             }
23927
23928           p = consume_improper_spaces (p, body);
23929
23930           /* Consume the comma, if present.  */
23931           if (*p == ',')
23932             {
23933               p++;
23934
23935               p = consume_improper_spaces (p, body);
23936             }
23937         }
23938
23939       if (*p == ')')
23940         {
23941           p++;
23942
23943           if (*p == ' ')
23944             /* Perfectly formed definition, no complaints.  */
23945             macro_define_function (file, line, name,
23946                                    argc, (const char **) argv,
23947                                    p + 1);
23948           else if (*p == '\0')
23949             {
23950               /* Complain, but do define it.  */
23951               dwarf2_macro_malformed_definition_complaint (body);
23952               macro_define_function (file, line, name,
23953                                      argc, (const char **) argv,
23954                                      p);
23955             }
23956           else
23957             /* Just complain.  */
23958             dwarf2_macro_malformed_definition_complaint (body);
23959         }
23960       else
23961         /* Just complain.  */
23962         dwarf2_macro_malformed_definition_complaint (body);
23963
23964       xfree (name);
23965       {
23966         int i;
23967
23968         for (i = 0; i < argc; i++)
23969           xfree (argv[i]);
23970       }
23971       xfree (argv);
23972     }
23973   else
23974     dwarf2_macro_malformed_definition_complaint (body);
23975 }
23976
23977 /* Skip some bytes from BYTES according to the form given in FORM.
23978    Returns the new pointer.  */
23979
23980 static const gdb_byte *
23981 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23982                  enum dwarf_form form,
23983                  unsigned int offset_size,
23984                  struct dwarf2_section_info *section)
23985 {
23986   unsigned int bytes_read;
23987
23988   switch (form)
23989     {
23990     case DW_FORM_data1:
23991     case DW_FORM_flag:
23992       ++bytes;
23993       break;
23994
23995     case DW_FORM_data2:
23996       bytes += 2;
23997       break;
23998
23999     case DW_FORM_data4:
24000       bytes += 4;
24001       break;
24002
24003     case DW_FORM_data8:
24004       bytes += 8;
24005       break;
24006
24007     case DW_FORM_data16:
24008       bytes += 16;
24009       break;
24010
24011     case DW_FORM_string:
24012       read_direct_string (abfd, bytes, &bytes_read);
24013       bytes += bytes_read;
24014       break;
24015
24016     case DW_FORM_sec_offset:
24017     case DW_FORM_strp:
24018     case DW_FORM_GNU_strp_alt:
24019       bytes += offset_size;
24020       break;
24021
24022     case DW_FORM_block:
24023       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24024       bytes += bytes_read;
24025       break;
24026
24027     case DW_FORM_block1:
24028       bytes += 1 + read_1_byte (abfd, bytes);
24029       break;
24030     case DW_FORM_block2:
24031       bytes += 2 + read_2_bytes (abfd, bytes);
24032       break;
24033     case DW_FORM_block4:
24034       bytes += 4 + read_4_bytes (abfd, bytes);
24035       break;
24036
24037     case DW_FORM_sdata:
24038     case DW_FORM_udata:
24039     case DW_FORM_GNU_addr_index:
24040     case DW_FORM_GNU_str_index:
24041       bytes = gdb_skip_leb128 (bytes, buffer_end);
24042       if (bytes == NULL)
24043         {
24044           dwarf2_section_buffer_overflow_complaint (section);
24045           return NULL;
24046         }
24047       break;
24048
24049     case DW_FORM_implicit_const:
24050       break;
24051
24052     default:
24053       {
24054         complaint (&symfile_complaints,
24055                    _("invalid form 0x%x in `%s'"),
24056                    form, get_section_name (section));
24057         return NULL;
24058       }
24059     }
24060
24061   return bytes;
24062 }
24063
24064 /* A helper for dwarf_decode_macros that handles skipping an unknown
24065    opcode.  Returns an updated pointer to the macro data buffer; or,
24066    on error, issues a complaint and returns NULL.  */
24067
24068 static const gdb_byte *
24069 skip_unknown_opcode (unsigned int opcode,
24070                      const gdb_byte **opcode_definitions,
24071                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24072                      bfd *abfd,
24073                      unsigned int offset_size,
24074                      struct dwarf2_section_info *section)
24075 {
24076   unsigned int bytes_read, i;
24077   unsigned long arg;
24078   const gdb_byte *defn;
24079
24080   if (opcode_definitions[opcode] == NULL)
24081     {
24082       complaint (&symfile_complaints,
24083                  _("unrecognized DW_MACFINO opcode 0x%x"),
24084                  opcode);
24085       return NULL;
24086     }
24087
24088   defn = opcode_definitions[opcode];
24089   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24090   defn += bytes_read;
24091
24092   for (i = 0; i < arg; ++i)
24093     {
24094       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24095                                  (enum dwarf_form) defn[i], offset_size,
24096                                  section);
24097       if (mac_ptr == NULL)
24098         {
24099           /* skip_form_bytes already issued the complaint.  */
24100           return NULL;
24101         }
24102     }
24103
24104   return mac_ptr;
24105 }
24106
24107 /* A helper function which parses the header of a macro section.
24108    If the macro section is the extended (for now called "GNU") type,
24109    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24110    the header, or issues a complaint and returns NULL on error.  */
24111
24112 static const gdb_byte *
24113 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24114                           bfd *abfd,
24115                           const gdb_byte *mac_ptr,
24116                           unsigned int *offset_size,
24117                           int section_is_gnu)
24118 {
24119   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24120
24121   if (section_is_gnu)
24122     {
24123       unsigned int version, flags;
24124
24125       version = read_2_bytes (abfd, mac_ptr);
24126       if (version != 4 && version != 5)
24127         {
24128           complaint (&symfile_complaints,
24129                      _("unrecognized version `%d' in .debug_macro section"),
24130                      version);
24131           return NULL;
24132         }
24133       mac_ptr += 2;
24134
24135       flags = read_1_byte (abfd, mac_ptr);
24136       ++mac_ptr;
24137       *offset_size = (flags & 1) ? 8 : 4;
24138
24139       if ((flags & 2) != 0)
24140         /* We don't need the line table offset.  */
24141         mac_ptr += *offset_size;
24142
24143       /* Vendor opcode descriptions.  */
24144       if ((flags & 4) != 0)
24145         {
24146           unsigned int i, count;
24147
24148           count = read_1_byte (abfd, mac_ptr);
24149           ++mac_ptr;
24150           for (i = 0; i < count; ++i)
24151             {
24152               unsigned int opcode, bytes_read;
24153               unsigned long arg;
24154
24155               opcode = read_1_byte (abfd, mac_ptr);
24156               ++mac_ptr;
24157               opcode_definitions[opcode] = mac_ptr;
24158               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24159               mac_ptr += bytes_read;
24160               mac_ptr += arg;
24161             }
24162         }
24163     }
24164
24165   return mac_ptr;
24166 }
24167
24168 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24169    including DW_MACRO_import.  */
24170
24171 static void
24172 dwarf_decode_macro_bytes (bfd *abfd,
24173                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24174                           struct macro_source_file *current_file,
24175                           struct line_header *lh,
24176                           struct dwarf2_section_info *section,
24177                           int section_is_gnu, int section_is_dwz,
24178                           unsigned int offset_size,
24179                           htab_t include_hash)
24180 {
24181   struct objfile *objfile = dwarf2_per_objfile->objfile;
24182   enum dwarf_macro_record_type macinfo_type;
24183   int at_commandline;
24184   const gdb_byte *opcode_definitions[256];
24185
24186   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24187                                       &offset_size, section_is_gnu);
24188   if (mac_ptr == NULL)
24189     {
24190       /* We already issued a complaint.  */
24191       return;
24192     }
24193
24194   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24195      GDB is still reading the definitions from command line.  First
24196      DW_MACINFO_start_file will need to be ignored as it was already executed
24197      to create CURRENT_FILE for the main source holding also the command line
24198      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24199      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24200
24201   at_commandline = 1;
24202
24203   do
24204     {
24205       /* Do we at least have room for a macinfo type byte?  */
24206       if (mac_ptr >= mac_end)
24207         {
24208           dwarf2_section_buffer_overflow_complaint (section);
24209           break;
24210         }
24211
24212       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24213       mac_ptr++;
24214
24215       /* Note that we rely on the fact that the corresponding GNU and
24216          DWARF constants are the same.  */
24217       DIAGNOSTIC_PUSH
24218       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24219       switch (macinfo_type)
24220         {
24221           /* A zero macinfo type indicates the end of the macro
24222              information.  */
24223         case 0:
24224           break;
24225
24226         case DW_MACRO_define:
24227         case DW_MACRO_undef:
24228         case DW_MACRO_define_strp:
24229         case DW_MACRO_undef_strp:
24230         case DW_MACRO_define_sup:
24231         case DW_MACRO_undef_sup:
24232           {
24233             unsigned int bytes_read;
24234             int line;
24235             const char *body;
24236             int is_define;
24237
24238             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24239             mac_ptr += bytes_read;
24240
24241             if (macinfo_type == DW_MACRO_define
24242                 || macinfo_type == DW_MACRO_undef)
24243               {
24244                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24245                 mac_ptr += bytes_read;
24246               }
24247             else
24248               {
24249                 LONGEST str_offset;
24250
24251                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24252                 mac_ptr += offset_size;
24253
24254                 if (macinfo_type == DW_MACRO_define_sup
24255                     || macinfo_type == DW_MACRO_undef_sup
24256                     || section_is_dwz)
24257                   {
24258                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
24259
24260                     body = read_indirect_string_from_dwz (dwz, str_offset);
24261                   }
24262                 else
24263                   body = read_indirect_string_at_offset (abfd, str_offset);
24264               }
24265
24266             is_define = (macinfo_type == DW_MACRO_define
24267                          || macinfo_type == DW_MACRO_define_strp
24268                          || macinfo_type == DW_MACRO_define_sup);
24269             if (! current_file)
24270               {
24271                 /* DWARF violation as no main source is present.  */
24272                 complaint (&symfile_complaints,
24273                            _("debug info with no main source gives macro %s "
24274                              "on line %d: %s"),
24275                            is_define ? _("definition") : _("undefinition"),
24276                            line, body);
24277                 break;
24278               }
24279             if ((line == 0 && !at_commandline)
24280                 || (line != 0 && at_commandline))
24281               complaint (&symfile_complaints,
24282                          _("debug info gives %s macro %s with %s line %d: %s"),
24283                          at_commandline ? _("command-line") : _("in-file"),
24284                          is_define ? _("definition") : _("undefinition"),
24285                          line == 0 ? _("zero") : _("non-zero"), line, body);
24286
24287             if (is_define)
24288               parse_macro_definition (current_file, line, body);
24289             else
24290               {
24291                 gdb_assert (macinfo_type == DW_MACRO_undef
24292                             || macinfo_type == DW_MACRO_undef_strp
24293                             || macinfo_type == DW_MACRO_undef_sup);
24294                 macro_undef (current_file, line, body);
24295               }
24296           }
24297           break;
24298
24299         case DW_MACRO_start_file:
24300           {
24301             unsigned int bytes_read;
24302             int line, file;
24303
24304             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24305             mac_ptr += bytes_read;
24306             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24307             mac_ptr += bytes_read;
24308
24309             if ((line == 0 && !at_commandline)
24310                 || (line != 0 && at_commandline))
24311               complaint (&symfile_complaints,
24312                          _("debug info gives source %d included "
24313                            "from %s at %s line %d"),
24314                          file, at_commandline ? _("command-line") : _("file"),
24315                          line == 0 ? _("zero") : _("non-zero"), line);
24316
24317             if (at_commandline)
24318               {
24319                 /* This DW_MACRO_start_file was executed in the
24320                    pass one.  */
24321                 at_commandline = 0;
24322               }
24323             else
24324               current_file = macro_start_file (file, line, current_file, lh);
24325           }
24326           break;
24327
24328         case DW_MACRO_end_file:
24329           if (! current_file)
24330             complaint (&symfile_complaints,
24331                        _("macro debug info has an unmatched "
24332                          "`close_file' directive"));
24333           else
24334             {
24335               current_file = current_file->included_by;
24336               if (! current_file)
24337                 {
24338                   enum dwarf_macro_record_type next_type;
24339
24340                   /* GCC circa March 2002 doesn't produce the zero
24341                      type byte marking the end of the compilation
24342                      unit.  Complain if it's not there, but exit no
24343                      matter what.  */
24344
24345                   /* Do we at least have room for a macinfo type byte?  */
24346                   if (mac_ptr >= mac_end)
24347                     {
24348                       dwarf2_section_buffer_overflow_complaint (section);
24349                       return;
24350                     }
24351
24352                   /* We don't increment mac_ptr here, so this is just
24353                      a look-ahead.  */
24354                   next_type
24355                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24356                                                                   mac_ptr);
24357                   if (next_type != 0)
24358                     complaint (&symfile_complaints,
24359                                _("no terminating 0-type entry for "
24360                                  "macros in `.debug_macinfo' section"));
24361
24362                   return;
24363                 }
24364             }
24365           break;
24366
24367         case DW_MACRO_import:
24368         case DW_MACRO_import_sup:
24369           {
24370             LONGEST offset;
24371             void **slot;
24372             bfd *include_bfd = abfd;
24373             struct dwarf2_section_info *include_section = section;
24374             const gdb_byte *include_mac_end = mac_end;
24375             int is_dwz = section_is_dwz;
24376             const gdb_byte *new_mac_ptr;
24377
24378             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24379             mac_ptr += offset_size;
24380
24381             if (macinfo_type == DW_MACRO_import_sup)
24382               {
24383                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
24384
24385                 dwarf2_read_section (objfile, &dwz->macro);
24386
24387                 include_section = &dwz->macro;
24388                 include_bfd = get_section_bfd_owner (include_section);
24389                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24390                 is_dwz = 1;
24391               }
24392
24393             new_mac_ptr = include_section->buffer + offset;
24394             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24395
24396             if (*slot != NULL)
24397               {
24398                 /* This has actually happened; see
24399                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24400                 complaint (&symfile_complaints,
24401                            _("recursive DW_MACRO_import in "
24402                              ".debug_macro section"));
24403               }
24404             else
24405               {
24406                 *slot = (void *) new_mac_ptr;
24407
24408                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
24409                                           include_mac_end, current_file, lh,
24410                                           section, section_is_gnu, is_dwz,
24411                                           offset_size, include_hash);
24412
24413                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24414               }
24415           }
24416           break;
24417
24418         case DW_MACINFO_vendor_ext:
24419           if (!section_is_gnu)
24420             {
24421               unsigned int bytes_read;
24422
24423               /* This reads the constant, but since we don't recognize
24424                  any vendor extensions, we ignore it.  */
24425               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24426               mac_ptr += bytes_read;
24427               read_direct_string (abfd, mac_ptr, &bytes_read);
24428               mac_ptr += bytes_read;
24429
24430               /* We don't recognize any vendor extensions.  */
24431               break;
24432             }
24433           /* FALLTHROUGH */
24434
24435         default:
24436           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24437                                          mac_ptr, mac_end, abfd, offset_size,
24438                                          section);
24439           if (mac_ptr == NULL)
24440             return;
24441           break;
24442         }
24443       DIAGNOSTIC_POP
24444     } while (macinfo_type != 0);
24445 }
24446
24447 static void
24448 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24449                      int section_is_gnu)
24450 {
24451   struct objfile *objfile = dwarf2_per_objfile->objfile;
24452   struct line_header *lh = cu->line_header;
24453   bfd *abfd;
24454   const gdb_byte *mac_ptr, *mac_end;
24455   struct macro_source_file *current_file = 0;
24456   enum dwarf_macro_record_type macinfo_type;
24457   unsigned int offset_size = cu->header.offset_size;
24458   const gdb_byte *opcode_definitions[256];
24459   void **slot;
24460   struct dwarf2_section_info *section;
24461   const char *section_name;
24462
24463   if (cu->dwo_unit != NULL)
24464     {
24465       if (section_is_gnu)
24466         {
24467           section = &cu->dwo_unit->dwo_file->sections.macro;
24468           section_name = ".debug_macro.dwo";
24469         }
24470       else
24471         {
24472           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24473           section_name = ".debug_macinfo.dwo";
24474         }
24475     }
24476   else
24477     {
24478       if (section_is_gnu)
24479         {
24480           section = &dwarf2_per_objfile->macro;
24481           section_name = ".debug_macro";
24482         }
24483       else
24484         {
24485           section = &dwarf2_per_objfile->macinfo;
24486           section_name = ".debug_macinfo";
24487         }
24488     }
24489
24490   dwarf2_read_section (objfile, section);
24491   if (section->buffer == NULL)
24492     {
24493       complaint (&symfile_complaints, _("missing %s section"), section_name);
24494       return;
24495     }
24496   abfd = get_section_bfd_owner (section);
24497
24498   /* First pass: Find the name of the base filename.
24499      This filename is needed in order to process all macros whose definition
24500      (or undefinition) comes from the command line.  These macros are defined
24501      before the first DW_MACINFO_start_file entry, and yet still need to be
24502      associated to the base file.
24503
24504      To determine the base file name, we scan the macro definitions until we
24505      reach the first DW_MACINFO_start_file entry.  We then initialize
24506      CURRENT_FILE accordingly so that any macro definition found before the
24507      first DW_MACINFO_start_file can still be associated to the base file.  */
24508
24509   mac_ptr = section->buffer + offset;
24510   mac_end = section->buffer + section->size;
24511
24512   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24513                                       &offset_size, section_is_gnu);
24514   if (mac_ptr == NULL)
24515     {
24516       /* We already issued a complaint.  */
24517       return;
24518     }
24519
24520   do
24521     {
24522       /* Do we at least have room for a macinfo type byte?  */
24523       if (mac_ptr >= mac_end)
24524         {
24525           /* Complaint is printed during the second pass as GDB will probably
24526              stop the first pass earlier upon finding
24527              DW_MACINFO_start_file.  */
24528           break;
24529         }
24530
24531       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24532       mac_ptr++;
24533
24534       /* Note that we rely on the fact that the corresponding GNU and
24535          DWARF constants are the same.  */
24536       DIAGNOSTIC_PUSH
24537       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24538       switch (macinfo_type)
24539         {
24540           /* A zero macinfo type indicates the end of the macro
24541              information.  */
24542         case 0:
24543           break;
24544
24545         case DW_MACRO_define:
24546         case DW_MACRO_undef:
24547           /* Only skip the data by MAC_PTR.  */
24548           {
24549             unsigned int bytes_read;
24550
24551             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24552             mac_ptr += bytes_read;
24553             read_direct_string (abfd, mac_ptr, &bytes_read);
24554             mac_ptr += bytes_read;
24555           }
24556           break;
24557
24558         case DW_MACRO_start_file:
24559           {
24560             unsigned int bytes_read;
24561             int line, file;
24562
24563             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24564             mac_ptr += bytes_read;
24565             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24566             mac_ptr += bytes_read;
24567
24568             current_file = macro_start_file (file, line, current_file, lh);
24569           }
24570           break;
24571
24572         case DW_MACRO_end_file:
24573           /* No data to skip by MAC_PTR.  */
24574           break;
24575
24576         case DW_MACRO_define_strp:
24577         case DW_MACRO_undef_strp:
24578         case DW_MACRO_define_sup:
24579         case DW_MACRO_undef_sup:
24580           {
24581             unsigned int bytes_read;
24582
24583             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24584             mac_ptr += bytes_read;
24585             mac_ptr += offset_size;
24586           }
24587           break;
24588
24589         case DW_MACRO_import:
24590         case DW_MACRO_import_sup:
24591           /* Note that, according to the spec, a transparent include
24592              chain cannot call DW_MACRO_start_file.  So, we can just
24593              skip this opcode.  */
24594           mac_ptr += offset_size;
24595           break;
24596
24597         case DW_MACINFO_vendor_ext:
24598           /* Only skip the data by MAC_PTR.  */
24599           if (!section_is_gnu)
24600             {
24601               unsigned int bytes_read;
24602
24603               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24604               mac_ptr += bytes_read;
24605               read_direct_string (abfd, mac_ptr, &bytes_read);
24606               mac_ptr += bytes_read;
24607             }
24608           /* FALLTHROUGH */
24609
24610         default:
24611           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24612                                          mac_ptr, mac_end, abfd, offset_size,
24613                                          section);
24614           if (mac_ptr == NULL)
24615             return;
24616           break;
24617         }
24618       DIAGNOSTIC_POP
24619     } while (macinfo_type != 0 && current_file == NULL);
24620
24621   /* Second pass: Process all entries.
24622
24623      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24624      command-line macro definitions/undefinitions.  This flag is unset when we
24625      reach the first DW_MACINFO_start_file entry.  */
24626
24627   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24628                                            htab_eq_pointer,
24629                                            NULL, xcalloc, xfree));
24630   mac_ptr = section->buffer + offset;
24631   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24632   *slot = (void *) mac_ptr;
24633   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
24634                             current_file, lh, section,
24635                             section_is_gnu, 0, offset_size,
24636                             include_hash.get ());
24637 }
24638
24639 /* Check if the attribute's form is a DW_FORM_block*
24640    if so return true else false.  */
24641
24642 static int
24643 attr_form_is_block (const struct attribute *attr)
24644 {
24645   return (attr == NULL ? 0 :
24646       attr->form == DW_FORM_block1
24647       || attr->form == DW_FORM_block2
24648       || attr->form == DW_FORM_block4
24649       || attr->form == DW_FORM_block
24650       || attr->form == DW_FORM_exprloc);
24651 }
24652
24653 /* Return non-zero if ATTR's value is a section offset --- classes
24654    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24655    You may use DW_UNSND (attr) to retrieve such offsets.
24656
24657    Section 7.5.4, "Attribute Encodings", explains that no attribute
24658    may have a value that belongs to more than one of these classes; it
24659    would be ambiguous if we did, because we use the same forms for all
24660    of them.  */
24661
24662 static int
24663 attr_form_is_section_offset (const struct attribute *attr)
24664 {
24665   return (attr->form == DW_FORM_data4
24666           || attr->form == DW_FORM_data8
24667           || attr->form == DW_FORM_sec_offset);
24668 }
24669
24670 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24671    zero otherwise.  When this function returns true, you can apply
24672    dwarf2_get_attr_constant_value to it.
24673
24674    However, note that for some attributes you must check
24675    attr_form_is_section_offset before using this test.  DW_FORM_data4
24676    and DW_FORM_data8 are members of both the constant class, and of
24677    the classes that contain offsets into other debug sections
24678    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24679    that, if an attribute's can be either a constant or one of the
24680    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24681    taken as section offsets, not constants.
24682
24683    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24684    cannot handle that.  */
24685
24686 static int
24687 attr_form_is_constant (const struct attribute *attr)
24688 {
24689   switch (attr->form)
24690     {
24691     case DW_FORM_sdata:
24692     case DW_FORM_udata:
24693     case DW_FORM_data1:
24694     case DW_FORM_data2:
24695     case DW_FORM_data4:
24696     case DW_FORM_data8:
24697     case DW_FORM_implicit_const:
24698       return 1;
24699     default:
24700       return 0;
24701     }
24702 }
24703
24704
24705 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24706    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24707
24708 static int
24709 attr_form_is_ref (const struct attribute *attr)
24710 {
24711   switch (attr->form)
24712     {
24713     case DW_FORM_ref_addr:
24714     case DW_FORM_ref1:
24715     case DW_FORM_ref2:
24716     case DW_FORM_ref4:
24717     case DW_FORM_ref8:
24718     case DW_FORM_ref_udata:
24719     case DW_FORM_GNU_ref_alt:
24720       return 1;
24721     default:
24722       return 0;
24723     }
24724 }
24725
24726 /* Return the .debug_loc section to use for CU.
24727    For DWO files use .debug_loc.dwo.  */
24728
24729 static struct dwarf2_section_info *
24730 cu_debug_loc_section (struct dwarf2_cu *cu)
24731 {
24732   if (cu->dwo_unit)
24733     {
24734       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24735       
24736       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24737     }
24738   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24739                                   : &dwarf2_per_objfile->loc);
24740 }
24741
24742 /* A helper function that fills in a dwarf2_loclist_baton.  */
24743
24744 static void
24745 fill_in_loclist_baton (struct dwarf2_cu *cu,
24746                        struct dwarf2_loclist_baton *baton,
24747                        const struct attribute *attr)
24748 {
24749   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24750
24751   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24752
24753   baton->per_cu = cu->per_cu;
24754   gdb_assert (baton->per_cu);
24755   /* We don't know how long the location list is, but make sure we
24756      don't run off the edge of the section.  */
24757   baton->size = section->size - DW_UNSND (attr);
24758   baton->data = section->buffer + DW_UNSND (attr);
24759   baton->base_address = cu->base_address;
24760   baton->from_dwo = cu->dwo_unit != NULL;
24761 }
24762
24763 static void
24764 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24765                              struct dwarf2_cu *cu, int is_block)
24766 {
24767   struct objfile *objfile = dwarf2_per_objfile->objfile;
24768   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24769
24770   if (attr_form_is_section_offset (attr)
24771       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24772          the section.  If so, fall through to the complaint in the
24773          other branch.  */
24774       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24775     {
24776       struct dwarf2_loclist_baton *baton;
24777
24778       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24779
24780       fill_in_loclist_baton (cu, baton, attr);
24781
24782       if (cu->base_known == 0)
24783         complaint (&symfile_complaints,
24784                    _("Location list used without "
24785                      "specifying the CU base address."));
24786
24787       SYMBOL_ACLASS_INDEX (sym) = (is_block
24788                                    ? dwarf2_loclist_block_index
24789                                    : dwarf2_loclist_index);
24790       SYMBOL_LOCATION_BATON (sym) = baton;
24791     }
24792   else
24793     {
24794       struct dwarf2_locexpr_baton *baton;
24795
24796       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24797       baton->per_cu = cu->per_cu;
24798       gdb_assert (baton->per_cu);
24799
24800       if (attr_form_is_block (attr))
24801         {
24802           /* Note that we're just copying the block's data pointer
24803              here, not the actual data.  We're still pointing into the
24804              info_buffer for SYM's objfile; right now we never release
24805              that buffer, but when we do clean up properly this may
24806              need to change.  */
24807           baton->size = DW_BLOCK (attr)->size;
24808           baton->data = DW_BLOCK (attr)->data;
24809         }
24810       else
24811         {
24812           dwarf2_invalid_attrib_class_complaint ("location description",
24813                                                  SYMBOL_NATURAL_NAME (sym));
24814           baton->size = 0;
24815         }
24816
24817       SYMBOL_ACLASS_INDEX (sym) = (is_block
24818                                    ? dwarf2_locexpr_block_index
24819                                    : dwarf2_locexpr_index);
24820       SYMBOL_LOCATION_BATON (sym) = baton;
24821     }
24822 }
24823
24824 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24825    came from a separate debuginfo file, then the master objfile is
24826    returned.  */
24827
24828 struct objfile *
24829 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24830 {
24831   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24832
24833   /* Return the master objfile, so that we can report and look up the
24834      correct file containing this variable.  */
24835   if (objfile->separate_debug_objfile_backlink)
24836     objfile = objfile->separate_debug_objfile_backlink;
24837
24838   return objfile;
24839 }
24840
24841 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24842    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24843    CU_HEADERP first.  */
24844
24845 static const struct comp_unit_head *
24846 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24847                        struct dwarf2_per_cu_data *per_cu)
24848 {
24849   const gdb_byte *info_ptr;
24850
24851   if (per_cu->cu)
24852     return &per_cu->cu->header;
24853
24854   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24855
24856   memset (cu_headerp, 0, sizeof (*cu_headerp));
24857   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24858                        rcuh_kind::COMPILE);
24859
24860   return cu_headerp;
24861 }
24862
24863 /* Return the address size given in the compilation unit header for CU.  */
24864
24865 int
24866 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24867 {
24868   struct comp_unit_head cu_header_local;
24869   const struct comp_unit_head *cu_headerp;
24870
24871   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24872
24873   return cu_headerp->addr_size;
24874 }
24875
24876 /* Return the offset size given in the compilation unit header for CU.  */
24877
24878 int
24879 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24880 {
24881   struct comp_unit_head cu_header_local;
24882   const struct comp_unit_head *cu_headerp;
24883
24884   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24885
24886   return cu_headerp->offset_size;
24887 }
24888
24889 /* See its dwarf2loc.h declaration.  */
24890
24891 int
24892 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24893 {
24894   struct comp_unit_head cu_header_local;
24895   const struct comp_unit_head *cu_headerp;
24896
24897   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24898
24899   if (cu_headerp->version == 2)
24900     return cu_headerp->addr_size;
24901   else
24902     return cu_headerp->offset_size;
24903 }
24904
24905 /* Return the text offset of the CU.  The returned offset comes from
24906    this CU's objfile.  If this objfile came from a separate debuginfo
24907    file, then the offset may be different from the corresponding
24908    offset in the parent objfile.  */
24909
24910 CORE_ADDR
24911 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24912 {
24913   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24914
24915   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24916 }
24917
24918 /* Return DWARF version number of PER_CU.  */
24919
24920 short
24921 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24922 {
24923   return per_cu->dwarf_version;
24924 }
24925
24926 /* Locate the .debug_info compilation unit from CU's objfile which contains
24927    the DIE at OFFSET.  Raises an error on failure.  */
24928
24929 static struct dwarf2_per_cu_data *
24930 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24931                                   unsigned int offset_in_dwz,
24932                                   struct objfile *objfile)
24933 {
24934   struct dwarf2_per_cu_data *this_cu;
24935   int low, high;
24936   const sect_offset *cu_off;
24937
24938   low = 0;
24939   high = dwarf2_per_objfile->n_comp_units - 1;
24940   while (high > low)
24941     {
24942       struct dwarf2_per_cu_data *mid_cu;
24943       int mid = low + (high - low) / 2;
24944
24945       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24946       cu_off = &mid_cu->sect_off;
24947       if (mid_cu->is_dwz > offset_in_dwz
24948           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24949         high = mid;
24950       else
24951         low = mid + 1;
24952     }
24953   gdb_assert (low == high);
24954   this_cu = dwarf2_per_objfile->all_comp_units[low];
24955   cu_off = &this_cu->sect_off;
24956   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24957     {
24958       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24959         error (_("Dwarf Error: could not find partial DIE containing "
24960                "offset 0x%x [in module %s]"),
24961                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
24962
24963       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24964                   <= sect_off);
24965       return dwarf2_per_objfile->all_comp_units[low-1];
24966     }
24967   else
24968     {
24969       this_cu = dwarf2_per_objfile->all_comp_units[low];
24970       if (low == dwarf2_per_objfile->n_comp_units - 1
24971           && sect_off >= this_cu->sect_off + this_cu->length)
24972         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
24973       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24974       return this_cu;
24975     }
24976 }
24977
24978 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24979
24980 static void
24981 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
24982 {
24983   memset (cu, 0, sizeof (*cu));
24984   per_cu->cu = cu;
24985   cu->per_cu = per_cu;
24986   cu->dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
24987   obstack_init (&cu->comp_unit_obstack);
24988 }
24989
24990 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24991
24992 static void
24993 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24994                        enum language pretend_language)
24995 {
24996   struct attribute *attr;
24997
24998   /* Set the language we're debugging.  */
24999   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25000   if (attr)
25001     set_cu_language (DW_UNSND (attr), cu);
25002   else
25003     {
25004       cu->language = pretend_language;
25005       cu->language_defn = language_def (cu->language);
25006     }
25007
25008   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25009 }
25010
25011 /* Release one cached compilation unit, CU.  We unlink it from the tree
25012    of compilation units, but we don't remove it from the read_in_chain;
25013    the caller is responsible for that.
25014    NOTE: DATA is a void * because this function is also used as a
25015    cleanup routine.  */
25016
25017 static void
25018 free_heap_comp_unit (void *data)
25019 {
25020   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25021
25022   gdb_assert (cu->per_cu != NULL);
25023   cu->per_cu->cu = NULL;
25024   cu->per_cu = NULL;
25025
25026   obstack_free (&cu->comp_unit_obstack, NULL);
25027
25028   xfree (cu);
25029 }
25030
25031 /* This cleanup function is passed the address of a dwarf2_cu on the stack
25032    when we're finished with it.  We can't free the pointer itself, but be
25033    sure to unlink it from the cache.  Also release any associated storage.  */
25034
25035 static void
25036 free_stack_comp_unit (void *data)
25037 {
25038   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25039
25040   gdb_assert (cu->per_cu != NULL);
25041   cu->per_cu->cu = NULL;
25042   cu->per_cu = NULL;
25043
25044   obstack_free (&cu->comp_unit_obstack, NULL);
25045   cu->partial_dies = NULL;
25046 }
25047
25048 /* Free all cached compilation units.  */
25049
25050 static void
25051 free_cached_comp_units (void *data)
25052 {
25053   dwarf2_per_objfile->free_cached_comp_units ();
25054 }
25055
25056 /* Increase the age counter on each cached compilation unit, and free
25057    any that are too old.  */
25058
25059 static void
25060 age_cached_comp_units (void)
25061 {
25062   struct dwarf2_per_cu_data *per_cu, **last_chain;
25063
25064   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25065   per_cu = dwarf2_per_objfile->read_in_chain;
25066   while (per_cu != NULL)
25067     {
25068       per_cu->cu->last_used ++;
25069       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25070         dwarf2_mark (per_cu->cu);
25071       per_cu = per_cu->cu->read_in_chain;
25072     }
25073
25074   per_cu = dwarf2_per_objfile->read_in_chain;
25075   last_chain = &dwarf2_per_objfile->read_in_chain;
25076   while (per_cu != NULL)
25077     {
25078       struct dwarf2_per_cu_data *next_cu;
25079
25080       next_cu = per_cu->cu->read_in_chain;
25081
25082       if (!per_cu->cu->mark)
25083         {
25084           free_heap_comp_unit (per_cu->cu);
25085           *last_chain = next_cu;
25086         }
25087       else
25088         last_chain = &per_cu->cu->read_in_chain;
25089
25090       per_cu = next_cu;
25091     }
25092 }
25093
25094 /* Remove a single compilation unit from the cache.  */
25095
25096 static void
25097 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25098 {
25099   struct dwarf2_per_cu_data *per_cu, **last_chain;
25100
25101   per_cu = dwarf2_per_objfile->read_in_chain;
25102   last_chain = &dwarf2_per_objfile->read_in_chain;
25103   while (per_cu != NULL)
25104     {
25105       struct dwarf2_per_cu_data *next_cu;
25106
25107       next_cu = per_cu->cu->read_in_chain;
25108
25109       if (per_cu == target_per_cu)
25110         {
25111           free_heap_comp_unit (per_cu->cu);
25112           per_cu->cu = NULL;
25113           *last_chain = next_cu;
25114           break;
25115         }
25116       else
25117         last_chain = &per_cu->cu->read_in_chain;
25118
25119       per_cu = next_cu;
25120     }
25121 }
25122
25123 /* Release all extra memory associated with OBJFILE.  */
25124
25125 void
25126 dwarf2_free_objfile (struct objfile *objfile)
25127 {
25128   dwarf2_per_objfile
25129     = (struct dwarf2_per_objfile *) objfile_data (objfile,
25130                                                   dwarf2_objfile_data_key);
25131
25132   if (dwarf2_per_objfile == NULL)
25133     return;
25134
25135   dwarf2_per_objfile->~dwarf2_per_objfile ();
25136 }
25137
25138 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25139    We store these in a hash table separate from the DIEs, and preserve them
25140    when the DIEs are flushed out of cache.
25141
25142    The CU "per_cu" pointer is needed because offset alone is not enough to
25143    uniquely identify the type.  A file may have multiple .debug_types sections,
25144    or the type may come from a DWO file.  Furthermore, while it's more logical
25145    to use per_cu->section+offset, with Fission the section with the data is in
25146    the DWO file but we don't know that section at the point we need it.
25147    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25148    because we can enter the lookup routine, get_die_type_at_offset, from
25149    outside this file, and thus won't necessarily have PER_CU->cu.
25150    Fortunately, PER_CU is stable for the life of the objfile.  */
25151
25152 struct dwarf2_per_cu_offset_and_type
25153 {
25154   const struct dwarf2_per_cu_data *per_cu;
25155   sect_offset sect_off;
25156   struct type *type;
25157 };
25158
25159 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25160
25161 static hashval_t
25162 per_cu_offset_and_type_hash (const void *item)
25163 {
25164   const struct dwarf2_per_cu_offset_and_type *ofs
25165     = (const struct dwarf2_per_cu_offset_and_type *) item;
25166
25167   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25168 }
25169
25170 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25171
25172 static int
25173 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25174 {
25175   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25176     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25177   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25178     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25179
25180   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25181           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25182 }
25183
25184 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25185    table if necessary.  For convenience, return TYPE.
25186
25187    The DIEs reading must have careful ordering to:
25188     * Not cause infite loops trying to read in DIEs as a prerequisite for
25189       reading current DIE.
25190     * Not trying to dereference contents of still incompletely read in types
25191       while reading in other DIEs.
25192     * Enable referencing still incompletely read in types just by a pointer to
25193       the type without accessing its fields.
25194
25195    Therefore caller should follow these rules:
25196      * Try to fetch any prerequisite types we may need to build this DIE type
25197        before building the type and calling set_die_type.
25198      * After building type call set_die_type for current DIE as soon as
25199        possible before fetching more types to complete the current type.
25200      * Make the type as complete as possible before fetching more types.  */
25201
25202 static struct type *
25203 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25204 {
25205   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25206   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
25207   struct attribute *attr;
25208   struct dynamic_prop prop;
25209
25210   /* For Ada types, make sure that the gnat-specific data is always
25211      initialized (if not already set).  There are a few types where
25212      we should not be doing so, because the type-specific area is
25213      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25214      where the type-specific area is used to store the floatformat).
25215      But this is not a problem, because the gnat-specific information
25216      is actually not needed for these types.  */
25217   if (need_gnat_info (cu)
25218       && TYPE_CODE (type) != TYPE_CODE_FUNC
25219       && TYPE_CODE (type) != TYPE_CODE_FLT
25220       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25221       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25222       && TYPE_CODE (type) != TYPE_CODE_METHOD
25223       && !HAVE_GNAT_AUX_INFO (type))
25224     INIT_GNAT_SPECIFIC (type);
25225
25226   /* Read DW_AT_allocated and set in type.  */
25227   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25228   if (attr_form_is_block (attr))
25229     {
25230       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25231         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25232     }
25233   else if (attr != NULL)
25234     {
25235       complaint (&symfile_complaints,
25236                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25237                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25238                  to_underlying (die->sect_off));
25239     }
25240
25241   /* Read DW_AT_associated and set in type.  */
25242   attr = dwarf2_attr (die, DW_AT_associated, cu);
25243   if (attr_form_is_block (attr))
25244     {
25245       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25246         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25247     }
25248   else if (attr != NULL)
25249     {
25250       complaint (&symfile_complaints,
25251                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25252                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25253                  to_underlying (die->sect_off));
25254     }
25255
25256   /* Read DW_AT_data_location and set in type.  */
25257   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25258   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25259     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25260
25261   if (dwarf2_per_objfile->die_type_hash == NULL)
25262     {
25263       dwarf2_per_objfile->die_type_hash =
25264         htab_create_alloc_ex (127,
25265                               per_cu_offset_and_type_hash,
25266                               per_cu_offset_and_type_eq,
25267                               NULL,
25268                               &objfile->objfile_obstack,
25269                               hashtab_obstack_allocate,
25270                               dummy_obstack_deallocate);
25271     }
25272
25273   ofs.per_cu = cu->per_cu;
25274   ofs.sect_off = die->sect_off;
25275   ofs.type = type;
25276   slot = (struct dwarf2_per_cu_offset_and_type **)
25277     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25278   if (*slot)
25279     complaint (&symfile_complaints,
25280                _("A problem internal to GDB: DIE 0x%x has type already set"),
25281                to_underlying (die->sect_off));
25282   *slot = XOBNEW (&objfile->objfile_obstack,
25283                   struct dwarf2_per_cu_offset_and_type);
25284   **slot = ofs;
25285   return type;
25286 }
25287
25288 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25289    or return NULL if the die does not have a saved type.  */
25290
25291 static struct type *
25292 get_die_type_at_offset (sect_offset sect_off,
25293                         struct dwarf2_per_cu_data *per_cu)
25294 {
25295   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25296
25297   if (dwarf2_per_objfile->die_type_hash == NULL)
25298     return NULL;
25299
25300   ofs.per_cu = per_cu;
25301   ofs.sect_off = sect_off;
25302   slot = ((struct dwarf2_per_cu_offset_and_type *)
25303           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25304   if (slot)
25305     return slot->type;
25306   else
25307     return NULL;
25308 }
25309
25310 /* Look up the type for DIE in CU in die_type_hash,
25311    or return NULL if DIE does not have a saved type.  */
25312
25313 static struct type *
25314 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25315 {
25316   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25317 }
25318
25319 /* Add a dependence relationship from CU to REF_PER_CU.  */
25320
25321 static void
25322 dwarf2_add_dependence (struct dwarf2_cu *cu,
25323                        struct dwarf2_per_cu_data *ref_per_cu)
25324 {
25325   void **slot;
25326
25327   if (cu->dependencies == NULL)
25328     cu->dependencies
25329       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25330                               NULL, &cu->comp_unit_obstack,
25331                               hashtab_obstack_allocate,
25332                               dummy_obstack_deallocate);
25333
25334   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25335   if (*slot == NULL)
25336     *slot = ref_per_cu;
25337 }
25338
25339 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25340    Set the mark field in every compilation unit in the
25341    cache that we must keep because we are keeping CU.  */
25342
25343 static int
25344 dwarf2_mark_helper (void **slot, void *data)
25345 {
25346   struct dwarf2_per_cu_data *per_cu;
25347
25348   per_cu = (struct dwarf2_per_cu_data *) *slot;
25349
25350   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25351      reading of the chain.  As such dependencies remain valid it is not much
25352      useful to track and undo them during QUIT cleanups.  */
25353   if (per_cu->cu == NULL)
25354     return 1;
25355
25356   if (per_cu->cu->mark)
25357     return 1;
25358   per_cu->cu->mark = 1;
25359
25360   if (per_cu->cu->dependencies != NULL)
25361     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25362
25363   return 1;
25364 }
25365
25366 /* Set the mark field in CU and in every other compilation unit in the
25367    cache that we must keep because we are keeping CU.  */
25368
25369 static void
25370 dwarf2_mark (struct dwarf2_cu *cu)
25371 {
25372   if (cu->mark)
25373     return;
25374   cu->mark = 1;
25375   if (cu->dependencies != NULL)
25376     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25377 }
25378
25379 static void
25380 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25381 {
25382   while (per_cu)
25383     {
25384       per_cu->cu->mark = 0;
25385       per_cu = per_cu->cu->read_in_chain;
25386     }
25387 }
25388
25389 /* Trivial hash function for partial_die_info: the hash value of a DIE
25390    is its offset in .debug_info for this objfile.  */
25391
25392 static hashval_t
25393 partial_die_hash (const void *item)
25394 {
25395   const struct partial_die_info *part_die
25396     = (const struct partial_die_info *) item;
25397
25398   return to_underlying (part_die->sect_off);
25399 }
25400
25401 /* Trivial comparison function for partial_die_info structures: two DIEs
25402    are equal if they have the same offset.  */
25403
25404 static int
25405 partial_die_eq (const void *item_lhs, const void *item_rhs)
25406 {
25407   const struct partial_die_info *part_die_lhs
25408     = (const struct partial_die_info *) item_lhs;
25409   const struct partial_die_info *part_die_rhs
25410     = (const struct partial_die_info *) item_rhs;
25411
25412   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25413 }
25414
25415 static struct cmd_list_element *set_dwarf_cmdlist;
25416 static struct cmd_list_element *show_dwarf_cmdlist;
25417
25418 static void
25419 set_dwarf_cmd (const char *args, int from_tty)
25420 {
25421   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25422              gdb_stdout);
25423 }
25424
25425 static void
25426 show_dwarf_cmd (const char *args, int from_tty)
25427 {
25428   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25429 }
25430
25431 /* Free data associated with OBJFILE, if necessary.  */
25432
25433 static void
25434 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25435 {
25436   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25437   int ix;
25438
25439   /* Make sure we don't accidentally use dwarf2_per_objfile while
25440      cleaning up.  */
25441   dwarf2_per_objfile = NULL;
25442
25443   for (ix = 0; ix < data->n_comp_units; ++ix)
25444    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25445
25446   for (ix = 0; ix < data->n_type_units; ++ix)
25447     VEC_free (dwarf2_per_cu_ptr,
25448               data->all_type_units[ix]->per_cu.imported_symtabs);
25449   xfree (data->all_type_units);
25450
25451   VEC_free (dwarf2_section_info_def, data->types);
25452
25453   if (data->dwo_files)
25454     free_dwo_files (data->dwo_files, objfile);
25455   if (data->dwp_file)
25456     gdb_bfd_unref (data->dwp_file->dbfd);
25457
25458   if (data->dwz_file && data->dwz_file->dwz_bfd)
25459     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25460
25461   if (data->index_table != NULL)
25462     data->index_table->~mapped_index ();
25463 }
25464
25465 \f
25466 /* The "save gdb-index" command.  */
25467
25468 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25469    error checking.  */
25470
25471 static void
25472 file_write (FILE *file, const void *data, size_t size)
25473 {
25474   if (fwrite (data, 1, size, file) != size)
25475     error (_("couldn't data write to file"));
25476 }
25477
25478 /* Write the contents of VEC to FILE, with error checking.  */
25479
25480 template<typename Elem, typename Alloc>
25481 static void
25482 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25483 {
25484   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25485 }
25486
25487 /* In-memory buffer to prepare data to be written later to a file.  */
25488 class data_buf
25489 {
25490 public:
25491   /* Copy DATA to the end of the buffer.  */
25492   template<typename T>
25493   void append_data (const T &data)
25494   {
25495     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25496                reinterpret_cast<const gdb_byte *> (&data + 1),
25497                grow (sizeof (data)));
25498   }
25499
25500   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25501      terminating zero is appended too.  */
25502   void append_cstr0 (const char *cstr)
25503   {
25504     const size_t size = strlen (cstr) + 1;
25505     std::copy (cstr, cstr + size, grow (size));
25506   }
25507
25508   /* Store INPUT as ULEB128 to the end of buffer.  */
25509   void append_unsigned_leb128 (ULONGEST input)
25510   {
25511     for (;;)
25512       {
25513         gdb_byte output = input & 0x7f;
25514         input >>= 7;
25515         if (input)
25516           output |= 0x80;
25517         append_data (output);
25518         if (input == 0)
25519           break;
25520       }
25521   }
25522
25523   /* Accept a host-format integer in VAL and append it to the buffer
25524      as a target-format integer which is LEN bytes long.  */
25525   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25526   {
25527     ::store_unsigned_integer (grow (len), len, byte_order, val);
25528   }
25529
25530   /* Return the size of the buffer.  */
25531   size_t size () const
25532   {
25533     return m_vec.size ();
25534   }
25535
25536   /* Return true iff the buffer is empty.  */
25537   bool empty () const
25538   {
25539     return m_vec.empty ();
25540   }
25541
25542   /* Write the buffer to FILE.  */
25543   void file_write (FILE *file) const
25544   {
25545     ::file_write (file, m_vec);
25546   }
25547
25548 private:
25549   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25550      the start of the new block.  */
25551   gdb_byte *grow (size_t size)
25552   {
25553     m_vec.resize (m_vec.size () + size);
25554     return &*m_vec.end () - size;
25555   }
25556
25557   gdb::byte_vector m_vec;
25558 };
25559
25560 /* An entry in the symbol table.  */
25561 struct symtab_index_entry
25562 {
25563   /* The name of the symbol.  */
25564   const char *name;
25565   /* The offset of the name in the constant pool.  */
25566   offset_type index_offset;
25567   /* A sorted vector of the indices of all the CUs that hold an object
25568      of this name.  */
25569   std::vector<offset_type> cu_indices;
25570 };
25571
25572 /* The symbol table.  This is a power-of-2-sized hash table.  */
25573 struct mapped_symtab
25574 {
25575   mapped_symtab ()
25576   {
25577     data.resize (1024);
25578   }
25579
25580   offset_type n_elements = 0;
25581   std::vector<symtab_index_entry> data;
25582 };
25583
25584 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25585    the slot.
25586    
25587    Function is used only during write_hash_table so no index format backward
25588    compatibility is needed.  */
25589
25590 static symtab_index_entry &
25591 find_slot (struct mapped_symtab *symtab, const char *name)
25592 {
25593   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25594
25595   index = hash & (symtab->data.size () - 1);
25596   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25597
25598   for (;;)
25599     {
25600       if (symtab->data[index].name == NULL
25601           || strcmp (name, symtab->data[index].name) == 0)
25602         return symtab->data[index];
25603       index = (index + step) & (symtab->data.size () - 1);
25604     }
25605 }
25606
25607 /* Expand SYMTAB's hash table.  */
25608
25609 static void
25610 hash_expand (struct mapped_symtab *symtab)
25611 {
25612   auto old_entries = std::move (symtab->data);
25613
25614   symtab->data.clear ();
25615   symtab->data.resize (old_entries.size () * 2);
25616
25617   for (auto &it : old_entries)
25618     if (it.name != NULL)
25619       {
25620         auto &ref = find_slot (symtab, it.name);
25621         ref = std::move (it);
25622       }
25623 }
25624
25625 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25626    CU_INDEX is the index of the CU in which the symbol appears.
25627    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25628
25629 static void
25630 add_index_entry (struct mapped_symtab *symtab, const char *name,
25631                  int is_static, gdb_index_symbol_kind kind,
25632                  offset_type cu_index)
25633 {
25634   offset_type cu_index_and_attrs;
25635
25636   ++symtab->n_elements;
25637   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25638     hash_expand (symtab);
25639
25640   symtab_index_entry &slot = find_slot (symtab, name);
25641   if (slot.name == NULL)
25642     {
25643       slot.name = name;
25644       /* index_offset is set later.  */
25645     }
25646
25647   cu_index_and_attrs = 0;
25648   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25649   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25650   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25651
25652   /* We don't want to record an index value twice as we want to avoid the
25653      duplication.
25654      We process all global symbols and then all static symbols
25655      (which would allow us to avoid the duplication by only having to check
25656      the last entry pushed), but a symbol could have multiple kinds in one CU.
25657      To keep things simple we don't worry about the duplication here and
25658      sort and uniqufy the list after we've processed all symbols.  */
25659   slot.cu_indices.push_back (cu_index_and_attrs);
25660 }
25661
25662 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25663
25664 static void
25665 uniquify_cu_indices (struct mapped_symtab *symtab)
25666 {
25667   for (auto &entry : symtab->data)
25668     {
25669       if (entry.name != NULL && !entry.cu_indices.empty ())
25670         {
25671           auto &cu_indices = entry.cu_indices;
25672           std::sort (cu_indices.begin (), cu_indices.end ());
25673           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25674           cu_indices.erase (from, cu_indices.end ());
25675         }
25676     }
25677 }
25678
25679 /* A form of 'const char *' suitable for container keys.  Only the
25680    pointer is stored.  The strings themselves are compared, not the
25681    pointers.  */
25682 class c_str_view
25683 {
25684 public:
25685   c_str_view (const char *cstr)
25686     : m_cstr (cstr)
25687   {}
25688
25689   bool operator== (const c_str_view &other) const
25690   {
25691     return strcmp (m_cstr, other.m_cstr) == 0;
25692   }
25693
25694   /* Return the underlying C string.  Note, the returned string is
25695      only a reference with lifetime of this object.  */
25696   const char *c_str () const
25697   {
25698     return m_cstr;
25699   }
25700
25701 private:
25702   friend class c_str_view_hasher;
25703   const char *const m_cstr;
25704 };
25705
25706 /* A std::unordered_map::hasher for c_str_view that uses the right
25707    hash function for strings in a mapped index.  */
25708 class c_str_view_hasher
25709 {
25710 public:
25711   size_t operator () (const c_str_view &x) const
25712   {
25713     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25714   }
25715 };
25716
25717 /* A std::unordered_map::hasher for std::vector<>.  */
25718 template<typename T>
25719 class vector_hasher
25720 {
25721 public:
25722   size_t operator () (const std::vector<T> &key) const
25723   {
25724     return iterative_hash (key.data (),
25725                            sizeof (key.front ()) * key.size (), 0);
25726   }
25727 };
25728
25729 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25730    constant pool entries going into the data buffer CPOOL.  */
25731
25732 static void
25733 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25734 {
25735   {
25736     /* Elements are sorted vectors of the indices of all the CUs that
25737        hold an object of this name.  */
25738     std::unordered_map<std::vector<offset_type>, offset_type,
25739                        vector_hasher<offset_type>>
25740       symbol_hash_table;
25741
25742     /* We add all the index vectors to the constant pool first, to
25743        ensure alignment is ok.  */
25744     for (symtab_index_entry &entry : symtab->data)
25745       {
25746         if (entry.name == NULL)
25747           continue;
25748         gdb_assert (entry.index_offset == 0);
25749
25750         /* Finding before inserting is faster than always trying to
25751            insert, because inserting always allocates a node, does the
25752            lookup, and then destroys the new node if another node
25753            already had the same key.  C++17 try_emplace will avoid
25754            this.  */
25755         const auto found
25756           = symbol_hash_table.find (entry.cu_indices);
25757         if (found != symbol_hash_table.end ())
25758           {
25759             entry.index_offset = found->second;
25760             continue;
25761           }
25762
25763         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25764         entry.index_offset = cpool.size ();
25765         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25766         for (const auto index : entry.cu_indices)
25767           cpool.append_data (MAYBE_SWAP (index));
25768       }
25769   }
25770
25771   /* Now write out the hash table.  */
25772   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25773   for (const auto &entry : symtab->data)
25774     {
25775       offset_type str_off, vec_off;
25776
25777       if (entry.name != NULL)
25778         {
25779           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25780           if (insertpair.second)
25781             cpool.append_cstr0 (entry.name);
25782           str_off = insertpair.first->second;
25783           vec_off = entry.index_offset;
25784         }
25785       else
25786         {
25787           /* While 0 is a valid constant pool index, it is not valid
25788              to have 0 for both offsets.  */
25789           str_off = 0;
25790           vec_off = 0;
25791         }
25792
25793       output.append_data (MAYBE_SWAP (str_off));
25794       output.append_data (MAYBE_SWAP (vec_off));
25795     }
25796 }
25797
25798 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25799
25800 /* Helper struct for building the address table.  */
25801 struct addrmap_index_data
25802 {
25803   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25804     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25805   {}
25806
25807   struct objfile *objfile;
25808   data_buf &addr_vec;
25809   psym_index_map &cu_index_htab;
25810
25811   /* Non-zero if the previous_* fields are valid.
25812      We can't write an entry until we see the next entry (since it is only then
25813      that we know the end of the entry).  */
25814   int previous_valid;
25815   /* Index of the CU in the table of all CUs in the index file.  */
25816   unsigned int previous_cu_index;
25817   /* Start address of the CU.  */
25818   CORE_ADDR previous_cu_start;
25819 };
25820
25821 /* Write an address entry to ADDR_VEC.  */
25822
25823 static void
25824 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25825                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25826 {
25827   CORE_ADDR baseaddr;
25828
25829   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25830
25831   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25832   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25833   addr_vec.append_data (MAYBE_SWAP (cu_index));
25834 }
25835
25836 /* Worker function for traversing an addrmap to build the address table.  */
25837
25838 static int
25839 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25840 {
25841   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25842   struct partial_symtab *pst = (struct partial_symtab *) obj;
25843
25844   if (data->previous_valid)
25845     add_address_entry (data->objfile, data->addr_vec,
25846                        data->previous_cu_start, start_addr,
25847                        data->previous_cu_index);
25848
25849   data->previous_cu_start = start_addr;
25850   if (pst != NULL)
25851     {
25852       const auto it = data->cu_index_htab.find (pst);
25853       gdb_assert (it != data->cu_index_htab.cend ());
25854       data->previous_cu_index = it->second;
25855       data->previous_valid = 1;
25856     }
25857   else
25858     data->previous_valid = 0;
25859
25860   return 0;
25861 }
25862
25863 /* Write OBJFILE's address map to ADDR_VEC.
25864    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25865    in the index file.  */
25866
25867 static void
25868 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25869                    psym_index_map &cu_index_htab)
25870 {
25871   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25872
25873   /* When writing the address table, we have to cope with the fact that
25874      the addrmap iterator only provides the start of a region; we have to
25875      wait until the next invocation to get the start of the next region.  */
25876
25877   addrmap_index_data.objfile = objfile;
25878   addrmap_index_data.previous_valid = 0;
25879
25880   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25881                    &addrmap_index_data);
25882
25883   /* It's highly unlikely the last entry (end address = 0xff...ff)
25884      is valid, but we should still handle it.
25885      The end address is recorded as the start of the next region, but that
25886      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25887      anyway.  */
25888   if (addrmap_index_data.previous_valid)
25889     add_address_entry (objfile, addr_vec,
25890                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25891                        addrmap_index_data.previous_cu_index);
25892 }
25893
25894 /* Return the symbol kind of PSYM.  */
25895
25896 static gdb_index_symbol_kind
25897 symbol_kind (struct partial_symbol *psym)
25898 {
25899   domain_enum domain = PSYMBOL_DOMAIN (psym);
25900   enum address_class aclass = PSYMBOL_CLASS (psym);
25901
25902   switch (domain)
25903     {
25904     case VAR_DOMAIN:
25905       switch (aclass)
25906         {
25907         case LOC_BLOCK:
25908           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25909         case LOC_TYPEDEF:
25910           return GDB_INDEX_SYMBOL_KIND_TYPE;
25911         case LOC_COMPUTED:
25912         case LOC_CONST_BYTES:
25913         case LOC_OPTIMIZED_OUT:
25914         case LOC_STATIC:
25915           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25916         case LOC_CONST:
25917           /* Note: It's currently impossible to recognize psyms as enum values
25918              short of reading the type info.  For now punt.  */
25919           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25920         default:
25921           /* There are other LOC_FOO values that one might want to classify
25922              as variables, but dwarf2read.c doesn't currently use them.  */
25923           return GDB_INDEX_SYMBOL_KIND_OTHER;
25924         }
25925     case STRUCT_DOMAIN:
25926       return GDB_INDEX_SYMBOL_KIND_TYPE;
25927     default:
25928       return GDB_INDEX_SYMBOL_KIND_OTHER;
25929     }
25930 }
25931
25932 /* Add a list of partial symbols to SYMTAB.  */
25933
25934 static void
25935 write_psymbols (struct mapped_symtab *symtab,
25936                 std::unordered_set<partial_symbol *> &psyms_seen,
25937                 struct partial_symbol **psymp,
25938                 int count,
25939                 offset_type cu_index,
25940                 int is_static)
25941 {
25942   for (; count-- > 0; ++psymp)
25943     {
25944       struct partial_symbol *psym = *psymp;
25945
25946       if (SYMBOL_LANGUAGE (psym) == language_ada)
25947         error (_("Ada is not currently supported by the index"));
25948
25949       /* Only add a given psymbol once.  */
25950       if (psyms_seen.insert (psym).second)
25951         {
25952           gdb_index_symbol_kind kind = symbol_kind (psym);
25953
25954           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25955                            is_static, kind, cu_index);
25956         }
25957     }
25958 }
25959
25960 /* A helper struct used when iterating over debug_types.  */
25961 struct signatured_type_index_data
25962 {
25963   signatured_type_index_data (data_buf &types_list_,
25964                               std::unordered_set<partial_symbol *> &psyms_seen_)
25965     : types_list (types_list_), psyms_seen (psyms_seen_)
25966   {}
25967
25968   struct objfile *objfile;
25969   struct mapped_symtab *symtab;
25970   data_buf &types_list;
25971   std::unordered_set<partial_symbol *> &psyms_seen;
25972   int cu_index;
25973 };
25974
25975 /* A helper function that writes a single signatured_type to an
25976    obstack.  */
25977
25978 static int
25979 write_one_signatured_type (void **slot, void *d)
25980 {
25981   struct signatured_type_index_data *info
25982     = (struct signatured_type_index_data *) d;
25983   struct signatured_type *entry = (struct signatured_type *) *slot;
25984   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
25985
25986   write_psymbols (info->symtab,
25987                   info->psyms_seen,
25988                   &info->objfile->global_psymbols[psymtab->globals_offset],
25989                   psymtab->n_global_syms, info->cu_index,
25990                   0);
25991   write_psymbols (info->symtab,
25992                   info->psyms_seen,
25993                   &info->objfile->static_psymbols[psymtab->statics_offset],
25994                   psymtab->n_static_syms, info->cu_index,
25995                   1);
25996
25997   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25998                                 to_underlying (entry->per_cu.sect_off));
25999   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26000                                 to_underlying (entry->type_offset_in_tu));
26001   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26002
26003   ++info->cu_index;
26004
26005   return 1;
26006 }
26007
26008 /* Recurse into all "included" dependencies and count their symbols as
26009    if they appeared in this psymtab.  */
26010
26011 static void
26012 recursively_count_psymbols (struct partial_symtab *psymtab,
26013                             size_t &psyms_seen)
26014 {
26015   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26016     if (psymtab->dependencies[i]->user != NULL)
26017       recursively_count_psymbols (psymtab->dependencies[i],
26018                                   psyms_seen);
26019
26020   psyms_seen += psymtab->n_global_syms;
26021   psyms_seen += psymtab->n_static_syms;
26022 }
26023
26024 /* Recurse into all "included" dependencies and write their symbols as
26025    if they appeared in this psymtab.  */
26026
26027 static void
26028 recursively_write_psymbols (struct objfile *objfile,
26029                             struct partial_symtab *psymtab,
26030                             struct mapped_symtab *symtab,
26031                             std::unordered_set<partial_symbol *> &psyms_seen,
26032                             offset_type cu_index)
26033 {
26034   int i;
26035
26036   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26037     if (psymtab->dependencies[i]->user != NULL)
26038       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26039                                   symtab, psyms_seen, cu_index);
26040
26041   write_psymbols (symtab,
26042                   psyms_seen,
26043                   &objfile->global_psymbols[psymtab->globals_offset],
26044                   psymtab->n_global_syms, cu_index,
26045                   0);
26046   write_psymbols (symtab,
26047                   psyms_seen,
26048                   &objfile->static_psymbols[psymtab->statics_offset],
26049                   psymtab->n_static_syms, cu_index,
26050                   1);
26051 }
26052
26053 /* DWARF-5 .debug_names builder.  */
26054 class debug_names
26055 {
26056 public:
26057   debug_names (bool is_dwarf64, bfd_endian dwarf5_byte_order)
26058     : m_dwarf5_byte_order (dwarf5_byte_order),
26059       m_dwarf32 (dwarf5_byte_order),
26060       m_dwarf64 (dwarf5_byte_order),
26061       m_dwarf (is_dwarf64
26062                ? static_cast<dwarf &> (m_dwarf64)
26063                : static_cast<dwarf &> (m_dwarf32)),
26064       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26065       m_name_table_entry_offs (m_dwarf.name_table_entry_offs)
26066   {}
26067
26068   int dwarf5_offset_size () const
26069   {
26070     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26071     return dwarf5_is_dwarf64 ? 8 : 4;
26072   }
26073
26074   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26075   enum class unit_kind { cu, tu };
26076
26077   /* Insert one symbol.  */
26078   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26079                unit_kind kind)
26080   {
26081     const int dwarf_tag = psymbol_tag (psym);
26082     if (dwarf_tag == 0)
26083       return;
26084     const char *const name = SYMBOL_SEARCH_NAME (psym);
26085     const auto insertpair
26086       = m_name_to_value_set.emplace (c_str_view (name),
26087                                      std::set<symbol_value> ());
26088     std::set<symbol_value> &value_set = insertpair.first->second;
26089     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26090   }
26091
26092   /* Build all the tables.  All symbols must be already inserted.
26093      This function does not call file_write, caller has to do it
26094      afterwards.  */
26095   void build ()
26096   {
26097     /* Verify the build method has not be called twice.  */
26098     gdb_assert (m_abbrev_table.empty ());
26099     const size_t name_count = m_name_to_value_set.size ();
26100     m_bucket_table.resize
26101       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26102     m_hash_table.reserve (name_count);
26103     m_name_table_string_offs.reserve (name_count);
26104     m_name_table_entry_offs.reserve (name_count);
26105
26106     /* Map each hash of symbol to its name and value.  */
26107     struct hash_it_pair
26108     {
26109       uint32_t hash;
26110       decltype (m_name_to_value_set)::const_iterator it;
26111     };
26112     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26113     bucket_hash.resize (m_bucket_table.size ());
26114     for (decltype (m_name_to_value_set)::const_iterator it
26115            = m_name_to_value_set.cbegin ();
26116          it != m_name_to_value_set.cend ();
26117          ++it)
26118       {
26119         const char *const name = it->first.c_str ();
26120         const uint32_t hash = dwarf5_djb_hash (name);
26121         hash_it_pair hashitpair;
26122         hashitpair.hash = hash;
26123         hashitpair.it = it;
26124         auto &slot = bucket_hash[hash % bucket_hash.size()];
26125         slot.push_front (std::move (hashitpair));
26126       }
26127     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26128       {
26129         const std::forward_list<hash_it_pair> &hashitlist
26130           = bucket_hash[bucket_ix];
26131         if (hashitlist.empty ())
26132           continue;
26133         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26134         /* The hashes array is indexed starting at 1.  */
26135         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26136                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26137                                 m_hash_table.size () + 1);
26138         for (const hash_it_pair &hashitpair : hashitlist)
26139           {
26140             m_hash_table.push_back (0);
26141             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26142                                                         (&m_hash_table.back ()),
26143                                     sizeof (m_hash_table.back ()),
26144                                     m_dwarf5_byte_order, hashitpair.hash);
26145             const c_str_view &name = hashitpair.it->first;
26146             const std::set<symbol_value> &value_set = hashitpair.it->second;
26147             m_name_table_string_offs.push_back_reorder
26148               (m_debugstrlookup.lookup (name.c_str ()));
26149             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26150             gdb_assert (!value_set.empty ());
26151             for (const symbol_value &value : value_set)
26152               {
26153                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26154                                                         value.is_static,
26155                                                         value.kind)];
26156                 if (idx == 0)
26157                   {
26158                     idx = m_idx_next++;
26159                     m_abbrev_table.append_unsigned_leb128 (idx);
26160                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26161                     m_abbrev_table.append_unsigned_leb128
26162                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26163                                                            : DW_IDX_type_unit);
26164                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26165                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26166                                                            ? DW_IDX_GNU_internal
26167                                                            : DW_IDX_GNU_external);
26168                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26169
26170                     /* Terminate attributes list.  */
26171                     m_abbrev_table.append_unsigned_leb128 (0);
26172                     m_abbrev_table.append_unsigned_leb128 (0);
26173                   }
26174
26175                 m_entry_pool.append_unsigned_leb128 (idx);
26176                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26177               }
26178
26179             /* Terminate the list of CUs.  */
26180             m_entry_pool.append_unsigned_leb128 (0);
26181           }
26182       }
26183     gdb_assert (m_hash_table.size () == name_count);
26184
26185     /* Terminate tags list.  */
26186     m_abbrev_table.append_unsigned_leb128 (0);
26187   }
26188
26189   /* Return .debug_names bucket count.  This must be called only after
26190      calling the build method.  */
26191   uint32_t bucket_count () const
26192   {
26193     /* Verify the build method has been already called.  */
26194     gdb_assert (!m_abbrev_table.empty ());
26195     const uint32_t retval = m_bucket_table.size ();
26196
26197     /* Check for overflow.  */
26198     gdb_assert (retval == m_bucket_table.size ());
26199     return retval;
26200   }
26201
26202   /* Return .debug_names names count.  This must be called only after
26203      calling the build method.  */
26204   uint32_t name_count () const
26205   {
26206     /* Verify the build method has been already called.  */
26207     gdb_assert (!m_abbrev_table.empty ());
26208     const uint32_t retval = m_hash_table.size ();
26209
26210     /* Check for overflow.  */
26211     gdb_assert (retval == m_hash_table.size ());
26212     return retval;
26213   }
26214
26215   /* Return number of bytes of .debug_names abbreviation table.  This
26216      must be called only after calling the build method.  */
26217   uint32_t abbrev_table_bytes () const
26218   {
26219     gdb_assert (!m_abbrev_table.empty ());
26220     return m_abbrev_table.size ();
26221   }
26222
26223   /* Recurse into all "included" dependencies and store their symbols
26224      as if they appeared in this psymtab.  */
26225   void recursively_write_psymbols
26226     (struct objfile *objfile,
26227      struct partial_symtab *psymtab,
26228      std::unordered_set<partial_symbol *> &psyms_seen,
26229      int cu_index)
26230   {
26231     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26232       if (psymtab->dependencies[i]->user != NULL)
26233         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26234                                     psyms_seen, cu_index);
26235
26236     write_psymbols (psyms_seen,
26237                     &objfile->global_psymbols[psymtab->globals_offset],
26238                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26239     write_psymbols (psyms_seen,
26240                     &objfile->static_psymbols[psymtab->statics_offset],
26241                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26242   }
26243
26244   /* Return number of bytes the .debug_names section will have.  This
26245      must be called only after calling the build method.  */
26246   size_t bytes () const
26247   {
26248     /* Verify the build method has been already called.  */
26249     gdb_assert (!m_abbrev_table.empty ());
26250     size_t expected_bytes = 0;
26251     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26252     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26253     expected_bytes += m_name_table_string_offs.bytes ();
26254     expected_bytes += m_name_table_entry_offs.bytes ();
26255     expected_bytes += m_abbrev_table.size ();
26256     expected_bytes += m_entry_pool.size ();
26257     return expected_bytes;
26258   }
26259
26260   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26261      FILE_STR.  This must be called only after calling the build
26262      method.  */
26263   void file_write (FILE *file_names, FILE *file_str) const
26264   {
26265     /* Verify the build method has been already called.  */
26266     gdb_assert (!m_abbrev_table.empty ());
26267     ::file_write (file_names, m_bucket_table);
26268     ::file_write (file_names, m_hash_table);
26269     m_name_table_string_offs.file_write (file_names);
26270     m_name_table_entry_offs.file_write (file_names);
26271     m_abbrev_table.file_write (file_names);
26272     m_entry_pool.file_write (file_names);
26273     m_debugstrlookup.file_write (file_str);
26274   }
26275
26276   /* A helper user data for write_one_signatured_type.  */
26277   class write_one_signatured_type_data
26278   {
26279   public:
26280     write_one_signatured_type_data (debug_names &nametable_,
26281                                     signatured_type_index_data &&info_)
26282     : nametable (nametable_), info (std::move (info_))
26283     {}
26284     debug_names &nametable;
26285     struct signatured_type_index_data info;
26286   };
26287
26288   /* A helper function to pass write_one_signatured_type to
26289      htab_traverse_noresize.  */
26290   static int
26291   write_one_signatured_type (void **slot, void *d)
26292   {
26293     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26294     struct signatured_type_index_data *info = &data->info;
26295     struct signatured_type *entry = (struct signatured_type *) *slot;
26296
26297     data->nametable.write_one_signatured_type (entry, info);
26298
26299     return 1;
26300   }
26301
26302 private:
26303
26304   /* Storage for symbol names mapping them to their .debug_str section
26305      offsets.  */
26306   class debug_str_lookup
26307   {
26308   public:
26309
26310     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26311        All .debug_str section strings are automatically stored.  */
26312     debug_str_lookup ()
26313       : m_abfd (dwarf2_per_objfile->objfile->obfd)
26314     {
26315       dwarf2_read_section (dwarf2_per_objfile->objfile,
26316                            &dwarf2_per_objfile->str);
26317       if (dwarf2_per_objfile->str.buffer == NULL)
26318         return;
26319       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26320            data < (dwarf2_per_objfile->str.buffer
26321                    + dwarf2_per_objfile->str.size);)
26322         {
26323           const char *const s = reinterpret_cast<const char *> (data);
26324           const auto insertpair
26325             = m_str_table.emplace (c_str_view (s),
26326                                    data - dwarf2_per_objfile->str.buffer);
26327           if (!insertpair.second)
26328             complaint (&symfile_complaints,
26329                        _("Duplicate string \"%s\" in "
26330                          ".debug_str section [in module %s]"),
26331                        s, bfd_get_filename (m_abfd));
26332           data += strlen (s) + 1;
26333         }
26334     }
26335
26336     /* Return offset of symbol name S in the .debug_str section.  Add
26337        such symbol to the section's end if it does not exist there
26338        yet.  */
26339     size_t lookup (const char *s)
26340     {
26341       const auto it = m_str_table.find (c_str_view (s));
26342       if (it != m_str_table.end ())
26343         return it->second;
26344       const size_t offset = (dwarf2_per_objfile->str.size
26345                              + m_str_add_buf.size ());
26346       m_str_table.emplace (c_str_view (s), offset);
26347       m_str_add_buf.append_cstr0 (s);
26348       return offset;
26349     }
26350
26351     /* Append the end of the .debug_str section to FILE.  */
26352     void file_write (FILE *file) const
26353     {
26354       m_str_add_buf.file_write (file);
26355     }
26356
26357   private:
26358     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26359     bfd *const m_abfd;
26360
26361     /* Data to add at the end of .debug_str for new needed symbol names.  */
26362     data_buf m_str_add_buf;
26363   };
26364
26365   /* Container to map used DWARF tags to their .debug_names abbreviation
26366      tags.  */
26367   class index_key
26368   {
26369   public:
26370     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26371       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26372     {
26373     }
26374
26375     bool
26376     operator== (const index_key &other) const
26377     {
26378       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26379               && kind == other.kind);
26380     }
26381
26382     const int dwarf_tag;
26383     const bool is_static;
26384     const unit_kind kind;
26385   };
26386
26387   /* Provide std::unordered_map::hasher for index_key.  */
26388   class index_key_hasher
26389   {
26390   public:
26391     size_t
26392     operator () (const index_key &key) const
26393     {
26394       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26395     }
26396   };
26397
26398   /* Parameters of one symbol entry.  */
26399   class symbol_value
26400   {
26401   public:
26402     const int dwarf_tag, cu_index;
26403     const bool is_static;
26404     const unit_kind kind;
26405
26406     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26407                   unit_kind kind_)
26408       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26409         kind (kind_)
26410     {}
26411
26412     bool
26413     operator< (const symbol_value &other) const
26414     {
26415 #define X(n) \
26416   do \
26417     { \
26418       if (n < other.n) \
26419         return true; \
26420       if (n > other.n) \
26421         return false; \
26422     } \
26423   while (0)
26424       X (dwarf_tag);
26425       X (is_static);
26426       X (kind);
26427       X (cu_index);
26428 #undef X
26429       return false;
26430     }
26431   };
26432
26433   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26434      output.  */
26435   class offset_vec
26436   {
26437   protected:
26438     const bfd_endian dwarf5_byte_order;
26439   public:
26440     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26441       : dwarf5_byte_order (dwarf5_byte_order_)
26442     {}
26443
26444     /* Call std::vector::reserve for NELEM elements.  */
26445     virtual void reserve (size_t nelem) = 0;
26446
26447     /* Call std::vector::push_back with store_unsigned_integer byte
26448        reordering for ELEM.  */
26449     virtual void push_back_reorder (size_t elem) = 0;
26450
26451     /* Return expected output size in bytes.  */
26452     virtual size_t bytes () const = 0;
26453
26454     /* Write name table to FILE.  */
26455     virtual void file_write (FILE *file) const = 0;
26456   };
26457
26458   /* Template to unify DWARF-32 and DWARF-64 output.  */
26459   template<typename OffsetSize>
26460   class offset_vec_tmpl : public offset_vec
26461   {
26462   public:
26463     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26464       : offset_vec (dwarf5_byte_order_)
26465     {}
26466
26467     /* Implement offset_vec::reserve.  */
26468     void reserve (size_t nelem) override
26469     {
26470       m_vec.reserve (nelem);
26471     }
26472
26473     /* Implement offset_vec::push_back_reorder.  */
26474     void push_back_reorder (size_t elem) override
26475     {
26476       m_vec.push_back (elem);
26477       /* Check for overflow.  */
26478       gdb_assert (m_vec.back () == elem);
26479       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26480                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26481     }
26482
26483     /* Implement offset_vec::bytes.  */
26484     size_t bytes () const override
26485     {
26486       return m_vec.size () * sizeof (m_vec[0]);
26487     }
26488
26489     /* Implement offset_vec::file_write.  */
26490     void file_write (FILE *file) const override
26491     {
26492       ::file_write (file, m_vec);
26493     }
26494
26495   private:
26496     std::vector<OffsetSize> m_vec;
26497   };
26498
26499   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26500      respecting name table width.  */
26501   class dwarf
26502   {
26503   public:
26504     offset_vec &name_table_string_offs, &name_table_entry_offs;
26505
26506     dwarf (offset_vec &name_table_string_offs_,
26507            offset_vec &name_table_entry_offs_)
26508       : name_table_string_offs (name_table_string_offs_),
26509         name_table_entry_offs (name_table_entry_offs_)
26510     {
26511     }
26512   };
26513
26514   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26515      respecting name table width.  */
26516   template<typename OffsetSize>
26517   class dwarf_tmpl : public dwarf
26518   {
26519   public:
26520     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26521       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26522         m_name_table_string_offs (dwarf5_byte_order_),
26523         m_name_table_entry_offs (dwarf5_byte_order_)
26524     {}
26525
26526   private:
26527     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26528     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26529   };
26530
26531   /* Try to reconstruct original DWARF tag for given partial_symbol.
26532      This function is not DWARF-5 compliant but it is sufficient for
26533      GDB as a DWARF-5 index consumer.  */
26534   static int psymbol_tag (const struct partial_symbol *psym)
26535   {
26536     domain_enum domain = PSYMBOL_DOMAIN (psym);
26537     enum address_class aclass = PSYMBOL_CLASS (psym);
26538
26539     switch (domain)
26540       {
26541       case VAR_DOMAIN:
26542         switch (aclass)
26543           {
26544           case LOC_BLOCK:
26545             return DW_TAG_subprogram;
26546           case LOC_TYPEDEF:
26547             return DW_TAG_typedef;
26548           case LOC_COMPUTED:
26549           case LOC_CONST_BYTES:
26550           case LOC_OPTIMIZED_OUT:
26551           case LOC_STATIC:
26552             return DW_TAG_variable;
26553           case LOC_CONST:
26554             /* Note: It's currently impossible to recognize psyms as enum values
26555                short of reading the type info.  For now punt.  */
26556             return DW_TAG_variable;
26557           default:
26558             /* There are other LOC_FOO values that one might want to classify
26559                as variables, but dwarf2read.c doesn't currently use them.  */
26560             return DW_TAG_variable;
26561           }
26562       case STRUCT_DOMAIN:
26563         return DW_TAG_structure_type;
26564       default:
26565         return 0;
26566       }
26567   }
26568
26569   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26570   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26571                        struct partial_symbol **psymp, int count, int cu_index,
26572                        bool is_static, unit_kind kind)
26573   {
26574     for (; count-- > 0; ++psymp)
26575       {
26576         struct partial_symbol *psym = *psymp;
26577
26578         if (SYMBOL_LANGUAGE (psym) == language_ada)
26579           error (_("Ada is not currently supported by the index"));
26580
26581         /* Only add a given psymbol once.  */
26582         if (psyms_seen.insert (psym).second)
26583           insert (psym, cu_index, is_static, kind);
26584       }
26585   }
26586
26587   /* A helper function that writes a single signatured_type
26588      to a debug_names.  */
26589   void
26590   write_one_signatured_type (struct signatured_type *entry,
26591                              struct signatured_type_index_data *info)
26592   {
26593     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26594
26595     write_psymbols (info->psyms_seen,
26596                     &info->objfile->global_psymbols[psymtab->globals_offset],
26597                     psymtab->n_global_syms, info->cu_index, false,
26598                     unit_kind::tu);
26599     write_psymbols (info->psyms_seen,
26600                     &info->objfile->static_psymbols[psymtab->statics_offset],
26601                     psymtab->n_static_syms, info->cu_index, true,
26602                     unit_kind::tu);
26603
26604     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26605                                   to_underlying (entry->per_cu.sect_off));
26606
26607     ++info->cu_index;
26608   }
26609
26610   /* Store value of each symbol.  */
26611   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26612     m_name_to_value_set;
26613
26614   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26615      order.  */
26616   std::vector<uint32_t> m_bucket_table;
26617   std::vector<uint32_t> m_hash_table;
26618
26619   const bfd_endian m_dwarf5_byte_order;
26620   dwarf_tmpl<uint32_t> m_dwarf32;
26621   dwarf_tmpl<uint64_t> m_dwarf64;
26622   dwarf &m_dwarf;
26623   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26624   debug_str_lookup m_debugstrlookup;
26625
26626   /* Map each used .debug_names abbreviation tag parameter to its
26627      index value.  */
26628   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26629
26630   /* Next unused .debug_names abbreviation tag for
26631      m_indexkey_to_idx.  */
26632   int m_idx_next = 1;
26633
26634   /* .debug_names abbreviation table.  */
26635   data_buf m_abbrev_table;
26636
26637   /* .debug_names entry pool.  */
26638   data_buf m_entry_pool;
26639 };
26640
26641 /* Return iff any of the needed offsets does not fit into 32-bit
26642    .debug_names section.  */
26643
26644 static bool
26645 check_dwarf64_offsets ()
26646 {
26647   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26648     {
26649       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26650
26651       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26652         return true;
26653     }
26654   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26655     {
26656       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26657       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26658
26659       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26660         return true;
26661     }
26662   return false;
26663 }
26664
26665 /* The psyms_seen set is potentially going to be largish (~40k
26666    elements when indexing a -g3 build of GDB itself).  Estimate the
26667    number of elements in order to avoid too many rehashes, which
26668    require rebuilding buckets and thus many trips to
26669    malloc/free.  */
26670
26671 static size_t
26672 psyms_seen_size ()
26673 {
26674   size_t psyms_count = 0;
26675   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26676     {
26677       struct dwarf2_per_cu_data *per_cu
26678         = dwarf2_per_objfile->all_comp_units[i];
26679       struct partial_symtab *psymtab = per_cu->v.psymtab;
26680
26681       if (psymtab != NULL && psymtab->user == NULL)
26682         recursively_count_psymbols (psymtab, psyms_count);
26683     }
26684   /* Generating an index for gdb itself shows a ratio of
26685      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26686   return psyms_count / 4;
26687 }
26688
26689 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26690    Return how many bytes were expected to be written into OUT_FILE.  */
26691
26692 static size_t
26693 write_gdbindex (struct objfile *objfile, FILE *out_file)
26694 {
26695   mapped_symtab symtab;
26696   data_buf cu_list;
26697
26698   /* While we're scanning CU's create a table that maps a psymtab pointer
26699      (which is what addrmap records) to its index (which is what is recorded
26700      in the index file).  This will later be needed to write the address
26701      table.  */
26702   psym_index_map cu_index_htab;
26703   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26704
26705   /* The CU list is already sorted, so we don't need to do additional
26706      work here.  Also, the debug_types entries do not appear in
26707      all_comp_units, but only in their own hash table.  */
26708
26709   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26710   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26711     {
26712       struct dwarf2_per_cu_data *per_cu
26713         = dwarf2_per_objfile->all_comp_units[i];
26714       struct partial_symtab *psymtab = per_cu->v.psymtab;
26715
26716       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26717          It may be referenced from a local scope but in such case it does not
26718          need to be present in .gdb_index.  */
26719       if (psymtab == NULL)
26720         continue;
26721
26722       if (psymtab->user == NULL)
26723         recursively_write_psymbols (objfile, psymtab, &symtab,
26724                                     psyms_seen, i);
26725
26726       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26727       gdb_assert (insertpair.second);
26728
26729       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26730                            to_underlying (per_cu->sect_off));
26731       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26732     }
26733
26734   /* Dump the address map.  */
26735   data_buf addr_vec;
26736   write_address_map (objfile, addr_vec, cu_index_htab);
26737
26738   /* Write out the .debug_type entries, if any.  */
26739   data_buf types_cu_list;
26740   if (dwarf2_per_objfile->signatured_types)
26741     {
26742       signatured_type_index_data sig_data (types_cu_list,
26743                                            psyms_seen);
26744
26745       sig_data.objfile = objfile;
26746       sig_data.symtab = &symtab;
26747       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26748       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26749                               write_one_signatured_type, &sig_data);
26750     }
26751
26752   /* Now that we've processed all symbols we can shrink their cu_indices
26753      lists.  */
26754   uniquify_cu_indices (&symtab);
26755
26756   data_buf symtab_vec, constant_pool;
26757   write_hash_table (&symtab, symtab_vec, constant_pool);
26758
26759   data_buf contents;
26760   const offset_type size_of_contents = 6 * sizeof (offset_type);
26761   offset_type total_len = size_of_contents;
26762
26763   /* The version number.  */
26764   contents.append_data (MAYBE_SWAP (8));
26765
26766   /* The offset of the CU list from the start of the file.  */
26767   contents.append_data (MAYBE_SWAP (total_len));
26768   total_len += cu_list.size ();
26769
26770   /* The offset of the types CU list from the start of the file.  */
26771   contents.append_data (MAYBE_SWAP (total_len));
26772   total_len += types_cu_list.size ();
26773
26774   /* The offset of the address table from the start of the file.  */
26775   contents.append_data (MAYBE_SWAP (total_len));
26776   total_len += addr_vec.size ();
26777
26778   /* The offset of the symbol table from the start of the file.  */
26779   contents.append_data (MAYBE_SWAP (total_len));
26780   total_len += symtab_vec.size ();
26781
26782   /* The offset of the constant pool from the start of the file.  */
26783   contents.append_data (MAYBE_SWAP (total_len));
26784   total_len += constant_pool.size ();
26785
26786   gdb_assert (contents.size () == size_of_contents);
26787
26788   contents.file_write (out_file);
26789   cu_list.file_write (out_file);
26790   types_cu_list.file_write (out_file);
26791   addr_vec.file_write (out_file);
26792   symtab_vec.file_write (out_file);
26793   constant_pool.file_write (out_file);
26794
26795   return total_len;
26796 }
26797
26798 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26799 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26800
26801 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26802    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26803    many bytes were expected to be written into OUT_FILE.  */
26804
26805 static size_t
26806 write_debug_names (struct objfile *objfile, FILE *out_file, FILE *out_file_str)
26807 {
26808   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets ();
26809   const enum bfd_endian dwarf5_byte_order
26810     = gdbarch_byte_order (get_objfile_arch (objfile));
26811
26812   /* The CU list is already sorted, so we don't need to do additional
26813      work here.  Also, the debug_types entries do not appear in
26814      all_comp_units, but only in their own hash table.  */
26815   data_buf cu_list;
26816   debug_names nametable (dwarf5_is_dwarf64, dwarf5_byte_order);
26817   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26818   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26819     {
26820       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26821       partial_symtab *psymtab = per_cu->v.psymtab;
26822
26823       /* CU of a shared file from 'dwz -m' may be unused by this main
26824          file.  It may be referenced from a local scope but in such
26825          case it does not need to be present in .debug_names.  */
26826       if (psymtab == NULL)
26827         continue;
26828
26829       if (psymtab->user == NULL)
26830         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26831
26832       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26833                            to_underlying (per_cu->sect_off));
26834     }
26835
26836   /* Write out the .debug_type entries, if any.  */
26837   data_buf types_cu_list;
26838   if (dwarf2_per_objfile->signatured_types)
26839     {
26840       debug_names::write_one_signatured_type_data sig_data (nametable,
26841                         signatured_type_index_data (types_cu_list, psyms_seen));
26842
26843       sig_data.info.objfile = objfile;
26844       /* It is used only for gdb_index.  */
26845       sig_data.info.symtab = nullptr;
26846       sig_data.info.cu_index = 0;
26847       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26848                               debug_names::write_one_signatured_type,
26849                               &sig_data);
26850     }
26851
26852   nametable.build ();
26853
26854   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26855
26856   const offset_type bytes_of_header
26857     = ((dwarf5_is_dwarf64 ? 12 : 4)
26858        + 2 + 2 + 7 * 4
26859        + sizeof (dwarf5_gdb_augmentation));
26860   size_t expected_bytes = 0;
26861   expected_bytes += bytes_of_header;
26862   expected_bytes += cu_list.size ();
26863   expected_bytes += types_cu_list.size ();
26864   expected_bytes += nametable.bytes ();
26865   data_buf header;
26866
26867   if (!dwarf5_is_dwarf64)
26868     {
26869       const uint64_t size64 = expected_bytes - 4;
26870       gdb_assert (size64 < 0xfffffff0);
26871       header.append_uint (4, dwarf5_byte_order, size64);
26872     }
26873   else
26874     {
26875       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26876       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26877     }
26878
26879   /* The version number.  */
26880   header.append_uint (2, dwarf5_byte_order, 5);
26881
26882   /* Padding.  */
26883   header.append_uint (2, dwarf5_byte_order, 0);
26884
26885   /* comp_unit_count - The number of CUs in the CU list.  */
26886   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26887
26888   /* local_type_unit_count - The number of TUs in the local TU
26889      list.  */
26890   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26891
26892   /* foreign_type_unit_count - The number of TUs in the foreign TU
26893      list.  */
26894   header.append_uint (4, dwarf5_byte_order, 0);
26895
26896   /* bucket_count - The number of hash buckets in the hash lookup
26897      table.  */
26898   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26899
26900   /* name_count - The number of unique names in the index.  */
26901   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26902
26903   /* abbrev_table_size - The size in bytes of the abbreviations
26904      table.  */
26905   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26906
26907   /* augmentation_string_size - The size in bytes of the augmentation
26908      string.  This value is rounded up to a multiple of 4.  */
26909   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26910   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26911   header.append_data (dwarf5_gdb_augmentation);
26912
26913   gdb_assert (header.size () == bytes_of_header);
26914
26915   header.file_write (out_file);
26916   cu_list.file_write (out_file);
26917   types_cu_list.file_write (out_file);
26918   nametable.file_write (out_file, out_file_str);
26919
26920   return expected_bytes;
26921 }
26922
26923 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26924    position is at the end of the file.  */
26925
26926 static void
26927 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26928 {
26929   const auto file_size = ftell (file);
26930   if (file_size == -1)
26931     error (_("Can't get `%s' size"), filename);
26932   gdb_assert (file_size == expected_size);
26933 }
26934
26935 /* Create an index file for OBJFILE in the directory DIR.  */
26936
26937 static void
26938 write_psymtabs_to_index (struct objfile *objfile, const char *dir,
26939                          dw_index_kind index_kind)
26940 {
26941   if (dwarf2_per_objfile->using_index)
26942     error (_("Cannot use an index to create the index"));
26943
26944   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26945     error (_("Cannot make an index when the file has multiple .debug_types sections"));
26946
26947   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
26948     return;
26949
26950   struct stat st;
26951   if (stat (objfile_name (objfile), &st) < 0)
26952     perror_with_name (objfile_name (objfile));
26953
26954   std::string filename (std::string (dir) + SLASH_STRING
26955                         + lbasename (objfile_name (objfile))
26956                         + (index_kind == dw_index_kind::DEBUG_NAMES
26957                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
26958
26959   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
26960   if (!out_file)
26961     error (_("Can't open `%s' for writing"), filename.c_str ());
26962
26963   /* Order matters here; we want FILE to be closed before FILENAME is
26964      unlinked, because on MS-Windows one cannot delete a file that is
26965      still open.  (Don't call anything here that might throw until
26966      file_closer is created.)  */
26967   gdb::unlinker unlink_file (filename.c_str ());
26968   gdb_file_up close_out_file (out_file);
26969
26970   if (index_kind == dw_index_kind::DEBUG_NAMES)
26971     {
26972       std::string filename_str (std::string (dir) + SLASH_STRING
26973                                 + lbasename (objfile_name (objfile))
26974                                 + DEBUG_STR_SUFFIX);
26975       FILE *out_file_str
26976         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
26977       if (!out_file_str)
26978         error (_("Can't open `%s' for writing"), filename_str.c_str ());
26979       gdb::unlinker unlink_file_str (filename_str.c_str ());
26980       gdb_file_up close_out_file_str (out_file_str);
26981
26982       const size_t total_len
26983         = write_debug_names (objfile, out_file, out_file_str);
26984       assert_file_size (out_file, filename.c_str (), total_len);
26985
26986       /* We want to keep the file .debug_str file too.  */
26987       unlink_file_str.keep ();
26988     }
26989   else
26990     {
26991       const size_t total_len
26992         = write_gdbindex (objfile, out_file);
26993       assert_file_size (out_file, filename.c_str (), total_len);
26994     }
26995
26996   /* We want to keep the file.  */
26997   unlink_file.keep ();
26998 }
26999
27000 /* Implementation of the `save gdb-index' command.
27001    
27002    Note that the .gdb_index file format used by this command is
27003    documented in the GDB manual.  Any changes here must be documented
27004    there.  */
27005
27006 static void
27007 save_gdb_index_command (const char *arg, int from_tty)
27008 {
27009   struct objfile *objfile;
27010   const char dwarf5space[] = "-dwarf-5 ";
27011   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27012
27013   if (!arg)
27014     arg = "";
27015
27016   arg = skip_spaces (arg);
27017   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27018     {
27019       index_kind = dw_index_kind::DEBUG_NAMES;
27020       arg += strlen (dwarf5space);
27021       arg = skip_spaces (arg);
27022     }
27023
27024   if (!*arg)
27025     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27026
27027   ALL_OBJFILES (objfile)
27028   {
27029     struct stat st;
27030
27031     /* If the objfile does not correspond to an actual file, skip it.  */
27032     if (stat (objfile_name (objfile), &st) < 0)
27033       continue;
27034
27035     dwarf2_per_objfile
27036       = (struct dwarf2_per_objfile *) objfile_data (objfile,
27037                                                     dwarf2_objfile_data_key);
27038     if (dwarf2_per_objfile)
27039       {
27040
27041         TRY
27042           {
27043             write_psymtabs_to_index (objfile, arg, index_kind);
27044           }
27045         CATCH (except, RETURN_MASK_ERROR)
27046           {
27047             exception_fprintf (gdb_stderr, except,
27048                                _("Error while writing index for `%s': "),
27049                                objfile_name (objfile));
27050           }
27051         END_CATCH
27052       }
27053   }
27054 }
27055
27056 \f
27057
27058 int dwarf_always_disassemble;
27059
27060 static void
27061 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27062                                struct cmd_list_element *c, const char *value)
27063 {
27064   fprintf_filtered (file,
27065                     _("Whether to always disassemble "
27066                       "DWARF expressions is %s.\n"),
27067                     value);
27068 }
27069
27070 static void
27071 show_check_physname (struct ui_file *file, int from_tty,
27072                      struct cmd_list_element *c, const char *value)
27073 {
27074   fprintf_filtered (file,
27075                     _("Whether to check \"physname\" is %s.\n"),
27076                     value);
27077 }
27078
27079 void
27080 _initialize_dwarf2_read (void)
27081 {
27082   struct cmd_list_element *c;
27083
27084   dwarf2_objfile_data_key
27085     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
27086
27087   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27088 Set DWARF specific variables.\n\
27089 Configure DWARF variables such as the cache size"),
27090                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27091                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27092
27093   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27094 Show DWARF specific variables\n\
27095 Show DWARF variables such as the cache size"),
27096                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27097                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27098
27099   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27100                             &dwarf_max_cache_age, _("\
27101 Set the upper bound on the age of cached DWARF compilation units."), _("\
27102 Show the upper bound on the age of cached DWARF compilation units."), _("\
27103 A higher limit means that cached compilation units will be stored\n\
27104 in memory longer, and more total memory will be used.  Zero disables\n\
27105 caching, which can slow down startup."),
27106                             NULL,
27107                             show_dwarf_max_cache_age,
27108                             &set_dwarf_cmdlist,
27109                             &show_dwarf_cmdlist);
27110
27111   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27112                            &dwarf_always_disassemble, _("\
27113 Set whether `info address' always disassembles DWARF expressions."), _("\
27114 Show whether `info address' always disassembles DWARF expressions."), _("\
27115 When enabled, DWARF expressions are always printed in an assembly-like\n\
27116 syntax.  When disabled, expressions will be printed in a more\n\
27117 conversational style, when possible."),
27118                            NULL,
27119                            show_dwarf_always_disassemble,
27120                            &set_dwarf_cmdlist,
27121                            &show_dwarf_cmdlist);
27122
27123   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27124 Set debugging of the DWARF reader."), _("\
27125 Show debugging of the DWARF reader."), _("\
27126 When enabled (non-zero), debugging messages are printed during DWARF\n\
27127 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27128 information.  A value greater than 1 provides more verbose information."),
27129                             NULL,
27130                             NULL,
27131                             &setdebuglist, &showdebuglist);
27132
27133   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27134 Set debugging of the DWARF DIE reader."), _("\
27135 Show debugging of the DWARF DIE reader."), _("\
27136 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27137 The value is the maximum depth to print."),
27138                              NULL,
27139                              NULL,
27140                              &setdebuglist, &showdebuglist);
27141
27142   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27143 Set debugging of the dwarf line reader."), _("\
27144 Show debugging of the dwarf line reader."), _("\
27145 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27146 A value of 1 (one) provides basic information.\n\
27147 A value greater than 1 provides more verbose information."),
27148                              NULL,
27149                              NULL,
27150                              &setdebuglist, &showdebuglist);
27151
27152   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27153 Set cross-checking of \"physname\" code against demangler."), _("\
27154 Show cross-checking of \"physname\" code against demangler."), _("\
27155 When enabled, GDB's internal \"physname\" code is checked against\n\
27156 the demangler."),
27157                            NULL, show_check_physname,
27158                            &setdebuglist, &showdebuglist);
27159
27160   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27161                            no_class, &use_deprecated_index_sections, _("\
27162 Set whether to use deprecated gdb_index sections."), _("\
27163 Show whether to use deprecated gdb_index sections."), _("\
27164 When enabled, deprecated .gdb_index sections are used anyway.\n\
27165 Normally they are ignored either because of a missing feature or\n\
27166 performance issue.\n\
27167 Warning: This option must be enabled before gdb reads the file."),
27168                            NULL,
27169                            NULL,
27170                            &setlist, &showlist);
27171
27172   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27173                _("\
27174 Save a gdb-index file.\n\
27175 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27176 \n\
27177 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27178 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27179 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27180                &save_cmdlist);
27181   set_cmd_completer (c, filename_completer);
27182
27183   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27184                                                         &dwarf2_locexpr_funcs);
27185   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27186                                                         &dwarf2_loclist_funcs);
27187
27188   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27189                                         &dwarf2_block_frame_base_locexpr_funcs);
27190   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27191                                         &dwarf2_block_frame_base_loclist_funcs);
27192
27193 #if GDB_SELF_TEST
27194   selftests::register_test ("dw2_expand_symtabs_matching",
27195                             selftests::dw2_expand_symtabs_matching::run_test);
27196 #endif
27197 }