Convert Rust to use discriminated unions
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89 #include "rust-lang.h"
90
91 /* When == 1, print basic high level tracing messages.
92    When > 1, be more verbose.
93    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
94 static unsigned int dwarf_read_debug = 0;
95
96 /* When non-zero, dump DIEs after they are read in.  */
97 static unsigned int dwarf_die_debug = 0;
98
99 /* When non-zero, dump line number entries as they are read in.  */
100 static unsigned int dwarf_line_debug = 0;
101
102 /* When non-zero, cross-check physname against demangler.  */
103 static int check_physname = 0;
104
105 /* When non-zero, do not reject deprecated .gdb_index sections.  */
106 static int use_deprecated_index_sections = 0;
107
108 static const struct objfile_data *dwarf2_objfile_data_key;
109
110 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
111
112 static int dwarf2_locexpr_index;
113 static int dwarf2_loclist_index;
114 static int dwarf2_locexpr_block_index;
115 static int dwarf2_loclist_block_index;
116
117 /* A descriptor for dwarf sections.
118
119    S.ASECTION, SIZE are typically initialized when the objfile is first
120    scanned.  BUFFER, READIN are filled in later when the section is read.
121    If the section contained compressed data then SIZE is updated to record
122    the uncompressed size of the section.
123
124    DWP file format V2 introduces a wrinkle that is easiest to handle by
125    creating the concept of virtual sections contained within a real section.
126    In DWP V2 the sections of the input DWO files are concatenated together
127    into one section, but section offsets are kept relative to the original
128    input section.
129    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
130    the real section this "virtual" section is contained in, and BUFFER,SIZE
131    describe the virtual section.  */
132
133 struct dwarf2_section_info
134 {
135   union
136   {
137     /* If this is a real section, the bfd section.  */
138     asection *section;
139     /* If this is a virtual section, pointer to the containing ("real")
140        section.  */
141     struct dwarf2_section_info *containing_section;
142   } s;
143   /* Pointer to section data, only valid if readin.  */
144   const gdb_byte *buffer;
145   /* The size of the section, real or virtual.  */
146   bfd_size_type size;
147   /* If this is a virtual section, the offset in the real section.
148      Only valid if is_virtual.  */
149   bfd_size_type virtual_offset;
150   /* True if we have tried to read this section.  */
151   char readin;
152   /* True if this is a virtual section, False otherwise.
153      This specifies which of s.section and s.containing_section to use.  */
154   char is_virtual;
155 };
156
157 typedef struct dwarf2_section_info dwarf2_section_info_def;
158 DEF_VEC_O (dwarf2_section_info_def);
159
160 /* All offsets in the index are of this type.  It must be
161    architecture-independent.  */
162 typedef uint32_t offset_type;
163
164 DEF_VEC_I (offset_type);
165
166 /* Ensure only legit values are used.  */
167 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
168   do { \
169     gdb_assert ((unsigned int) (value) <= 1); \
170     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
171   } while (0)
172
173 /* Ensure only legit values are used.  */
174 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
175   do { \
176     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
177                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
178     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
179   } while (0)
180
181 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
182 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
183   do { \
184     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
185     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
186   } while (0)
187
188 #if WORDS_BIGENDIAN
189
190 /* Convert VALUE between big- and little-endian.  */
191
192 static offset_type
193 byte_swap (offset_type value)
194 {
195   offset_type result;
196
197   result = (value & 0xff) << 24;
198   result |= (value & 0xff00) << 8;
199   result |= (value & 0xff0000) >> 8;
200   result |= (value & 0xff000000) >> 24;
201   return result;
202 }
203
204 #define MAYBE_SWAP(V)  byte_swap (V)
205
206 #else
207 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
208 #endif /* WORDS_BIGENDIAN */
209
210 /* An index into a (C++) symbol name component in a symbol name as
211    recorded in the mapped_index's symbol table.  For each C++ symbol
212    in the symbol table, we record one entry for the start of each
213    component in the symbol in a table of name components, and then
214    sort the table, in order to be able to binary search symbol names,
215    ignoring leading namespaces, both completion and regular look up.
216    For example, for symbol "A::B::C", we'll have an entry that points
217    to "A::B::C", another that points to "B::C", and another for "C".
218    Note that function symbols in GDB index have no parameter
219    information, just the function/method names.  You can convert a
220    name_component to a "const char *" using the
221    'mapped_index::symbol_name_at(offset_type)' method.  */
222
223 struct name_component
224 {
225   /* Offset in the symbol name where the component starts.  Stored as
226      a (32-bit) offset instead of a pointer to save memory and improve
227      locality on 64-bit architectures.  */
228   offset_type name_offset;
229
230   /* The symbol's index in the symbol and constant pool tables of a
231      mapped_index.  */
232   offset_type idx;
233 };
234
235 /* Base class containing bits shared by both .gdb_index and
236    .debug_name indexes.  */
237
238 struct mapped_index_base
239 {
240   /* The name_component table (a sorted vector).  See name_component's
241      description above.  */
242   std::vector<name_component> name_components;
243
244   /* How NAME_COMPONENTS is sorted.  */
245   enum case_sensitivity name_components_casing;
246
247   /* Return the number of names in the symbol table.  */
248   virtual size_t symbol_name_count () const = 0;
249
250   /* Get the name of the symbol at IDX in the symbol table.  */
251   virtual const char *symbol_name_at (offset_type idx) const = 0;
252
253   /* Return whether the name at IDX in the symbol table should be
254      ignored.  */
255   virtual bool symbol_name_slot_invalid (offset_type idx) const
256   {
257     return false;
258   }
259
260   /* Build the symbol name component sorted vector, if we haven't
261      yet.  */
262   void build_name_components ();
263
264   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
265      possible matches for LN_NO_PARAMS in the name component
266      vector.  */
267   std::pair<std::vector<name_component>::const_iterator,
268             std::vector<name_component>::const_iterator>
269     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
270
271   /* Prevent deleting/destroying via a base class pointer.  */
272 protected:
273   ~mapped_index_base() = default;
274 };
275
276 /* A description of the mapped index.  The file format is described in
277    a comment by the code that writes the index.  */
278 struct mapped_index final : public mapped_index_base
279 {
280   /* A slot/bucket in the symbol table hash.  */
281   struct symbol_table_slot
282   {
283     const offset_type name;
284     const offset_type vec;
285   };
286
287   /* Index data format version.  */
288   int version;
289
290   /* The total length of the buffer.  */
291   off_t total_size;
292
293   /* The address table data.  */
294   gdb::array_view<const gdb_byte> address_table;
295
296   /* The symbol table, implemented as a hash table.  */
297   gdb::array_view<symbol_table_slot> symbol_table;
298
299   /* A pointer to the constant pool.  */
300   const char *constant_pool;
301
302   bool symbol_name_slot_invalid (offset_type idx) const override
303   {
304     const auto &bucket = this->symbol_table[idx];
305     return bucket.name == 0 && bucket.vec;
306   }
307
308   /* Convenience method to get at the name of the symbol at IDX in the
309      symbol table.  */
310   const char *symbol_name_at (offset_type idx) const override
311   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
312
313   size_t symbol_name_count () const override
314   { return this->symbol_table.size (); }
315 };
316
317 /* A description of the mapped .debug_names.
318    Uninitialized map has CU_COUNT 0.  */
319 struct mapped_debug_names final : public mapped_index_base
320 {
321   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
322   : dwarf2_per_objfile (dwarf2_per_objfile_)
323   {}
324
325   struct dwarf2_per_objfile *dwarf2_per_objfile;
326   bfd_endian dwarf5_byte_order;
327   bool dwarf5_is_dwarf64;
328   bool augmentation_is_gdb;
329   uint8_t offset_size;
330   uint32_t cu_count = 0;
331   uint32_t tu_count, bucket_count, name_count;
332   const gdb_byte *cu_table_reordered, *tu_table_reordered;
333   const uint32_t *bucket_table_reordered, *hash_table_reordered;
334   const gdb_byte *name_table_string_offs_reordered;
335   const gdb_byte *name_table_entry_offs_reordered;
336   const gdb_byte *entry_pool;
337
338   struct index_val
339   {
340     ULONGEST dwarf_tag;
341     struct attr
342     {
343       /* Attribute name DW_IDX_*.  */
344       ULONGEST dw_idx;
345
346       /* Attribute form DW_FORM_*.  */
347       ULONGEST form;
348
349       /* Value if FORM is DW_FORM_implicit_const.  */
350       LONGEST implicit_const;
351     };
352     std::vector<attr> attr_vec;
353   };
354
355   std::unordered_map<ULONGEST, index_val> abbrev_map;
356
357   const char *namei_to_name (uint32_t namei) const;
358
359   /* Implementation of the mapped_index_base virtual interface, for
360      the name_components cache.  */
361
362   const char *symbol_name_at (offset_type idx) const override
363   { return namei_to_name (idx); }
364
365   size_t symbol_name_count () const override
366   { return this->name_count; }
367 };
368
369 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
370 DEF_VEC_P (dwarf2_per_cu_ptr);
371
372 struct tu_stats
373 {
374   int nr_uniq_abbrev_tables;
375   int nr_symtabs;
376   int nr_symtab_sharers;
377   int nr_stmt_less_type_units;
378   int nr_all_type_units_reallocs;
379 };
380
381 /* Collection of data recorded per objfile.
382    This hangs off of dwarf2_objfile_data_key.  */
383
384 struct dwarf2_per_objfile : public allocate_on_obstack
385 {
386   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
387      dwarf2 section names, or is NULL if the standard ELF names are
388      used.  */
389   dwarf2_per_objfile (struct objfile *objfile,
390                       const dwarf2_debug_sections *names);
391
392   ~dwarf2_per_objfile ();
393
394   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
395
396   /* Free all cached compilation units.  */
397   void free_cached_comp_units ();
398 private:
399   /* This function is mapped across the sections and remembers the
400      offset and size of each of the debugging sections we are
401      interested in.  */
402   void locate_sections (bfd *abfd, asection *sectp,
403                         const dwarf2_debug_sections &names);
404
405 public:
406   dwarf2_section_info info {};
407   dwarf2_section_info abbrev {};
408   dwarf2_section_info line {};
409   dwarf2_section_info loc {};
410   dwarf2_section_info loclists {};
411   dwarf2_section_info macinfo {};
412   dwarf2_section_info macro {};
413   dwarf2_section_info str {};
414   dwarf2_section_info line_str {};
415   dwarf2_section_info ranges {};
416   dwarf2_section_info rnglists {};
417   dwarf2_section_info addr {};
418   dwarf2_section_info frame {};
419   dwarf2_section_info eh_frame {};
420   dwarf2_section_info gdb_index {};
421   dwarf2_section_info debug_names {};
422   dwarf2_section_info debug_aranges {};
423
424   VEC (dwarf2_section_info_def) *types = NULL;
425
426   /* Back link.  */
427   struct objfile *objfile = NULL;
428
429   /* Table of all the compilation units.  This is used to locate
430      the target compilation unit of a particular reference.  */
431   struct dwarf2_per_cu_data **all_comp_units = NULL;
432
433   /* The number of compilation units in ALL_COMP_UNITS.  */
434   int n_comp_units = 0;
435
436   /* The number of .debug_types-related CUs.  */
437   int n_type_units = 0;
438
439   /* The number of elements allocated in all_type_units.
440      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
441   int n_allocated_type_units = 0;
442
443   /* The .debug_types-related CUs (TUs).
444      This is stored in malloc space because we may realloc it.  */
445   struct signatured_type **all_type_units = NULL;
446
447   /* Table of struct type_unit_group objects.
448      The hash key is the DW_AT_stmt_list value.  */
449   htab_t type_unit_groups {};
450
451   /* A table mapping .debug_types signatures to its signatured_type entry.
452      This is NULL if the .debug_types section hasn't been read in yet.  */
453   htab_t signatured_types {};
454
455   /* Type unit statistics, to see how well the scaling improvements
456      are doing.  */
457   struct tu_stats tu_stats {};
458
459   /* A chain of compilation units that are currently read in, so that
460      they can be freed later.  */
461   dwarf2_per_cu_data *read_in_chain = NULL;
462
463   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
464      This is NULL if the table hasn't been allocated yet.  */
465   htab_t dwo_files {};
466
467   /* True if we've checked for whether there is a DWP file.  */
468   bool dwp_checked = false;
469
470   /* The DWP file if there is one, or NULL.  */
471   struct dwp_file *dwp_file = NULL;
472
473   /* The shared '.dwz' file, if one exists.  This is used when the
474      original data was compressed using 'dwz -m'.  */
475   struct dwz_file *dwz_file = NULL;
476
477   /* A flag indicating whether this objfile has a section loaded at a
478      VMA of 0.  */
479   bool has_section_at_zero = false;
480
481   /* True if we are using the mapped index,
482      or we are faking it for OBJF_READNOW's sake.  */
483   bool using_index = false;
484
485   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
486   mapped_index *index_table = NULL;
487
488   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
489   std::unique_ptr<mapped_debug_names> debug_names_table;
490
491   /* When using index_table, this keeps track of all quick_file_names entries.
492      TUs typically share line table entries with a CU, so we maintain a
493      separate table of all line table entries to support the sharing.
494      Note that while there can be way more TUs than CUs, we've already
495      sorted all the TUs into "type unit groups", grouped by their
496      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
497      CU and its associated TU group if there is one.  */
498   htab_t quick_file_names_table {};
499
500   /* Set during partial symbol reading, to prevent queueing of full
501      symbols.  */
502   bool reading_partial_symbols = false;
503
504   /* Table mapping type DIEs to their struct type *.
505      This is NULL if not allocated yet.
506      The mapping is done via (CU/TU + DIE offset) -> type.  */
507   htab_t die_type_hash {};
508
509   /* The CUs we recently read.  */
510   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
511
512   /* Table containing line_header indexed by offset and offset_in_dwz.  */
513   htab_t line_header_hash {};
514
515   /* Table containing all filenames.  This is an optional because the
516      table is lazily constructed on first access.  */
517   gdb::optional<filename_seen_cache> filenames_cache;
518 };
519
520 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
521
522 struct dwarf2_per_objfile *
523 get_dwarf2_per_objfile (struct objfile *objfile)
524 {
525   return ((struct dwarf2_per_objfile *)
526           objfile_data (objfile, dwarf2_objfile_data_key));
527 }
528
529 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
530
531 void
532 set_dwarf2_per_objfile (struct objfile *objfile,
533                         struct dwarf2_per_objfile *dwarf2_per_objfile)
534 {
535   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
536   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
537 }
538
539 /* Default names of the debugging sections.  */
540
541 /* Note that if the debugging section has been compressed, it might
542    have a name like .zdebug_info.  */
543
544 static const struct dwarf2_debug_sections dwarf2_elf_names =
545 {
546   { ".debug_info", ".zdebug_info" },
547   { ".debug_abbrev", ".zdebug_abbrev" },
548   { ".debug_line", ".zdebug_line" },
549   { ".debug_loc", ".zdebug_loc" },
550   { ".debug_loclists", ".zdebug_loclists" },
551   { ".debug_macinfo", ".zdebug_macinfo" },
552   { ".debug_macro", ".zdebug_macro" },
553   { ".debug_str", ".zdebug_str" },
554   { ".debug_line_str", ".zdebug_line_str" },
555   { ".debug_ranges", ".zdebug_ranges" },
556   { ".debug_rnglists", ".zdebug_rnglists" },
557   { ".debug_types", ".zdebug_types" },
558   { ".debug_addr", ".zdebug_addr" },
559   { ".debug_frame", ".zdebug_frame" },
560   { ".eh_frame", NULL },
561   { ".gdb_index", ".zgdb_index" },
562   { ".debug_names", ".zdebug_names" },
563   { ".debug_aranges", ".zdebug_aranges" },
564   23
565 };
566
567 /* List of DWO/DWP sections.  */
568
569 static const struct dwop_section_names
570 {
571   struct dwarf2_section_names abbrev_dwo;
572   struct dwarf2_section_names info_dwo;
573   struct dwarf2_section_names line_dwo;
574   struct dwarf2_section_names loc_dwo;
575   struct dwarf2_section_names loclists_dwo;
576   struct dwarf2_section_names macinfo_dwo;
577   struct dwarf2_section_names macro_dwo;
578   struct dwarf2_section_names str_dwo;
579   struct dwarf2_section_names str_offsets_dwo;
580   struct dwarf2_section_names types_dwo;
581   struct dwarf2_section_names cu_index;
582   struct dwarf2_section_names tu_index;
583 }
584 dwop_section_names =
585 {
586   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
587   { ".debug_info.dwo", ".zdebug_info.dwo" },
588   { ".debug_line.dwo", ".zdebug_line.dwo" },
589   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
590   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
591   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
592   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
593   { ".debug_str.dwo", ".zdebug_str.dwo" },
594   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
595   { ".debug_types.dwo", ".zdebug_types.dwo" },
596   { ".debug_cu_index", ".zdebug_cu_index" },
597   { ".debug_tu_index", ".zdebug_tu_index" },
598 };
599
600 /* local data types */
601
602 /* The data in a compilation unit header, after target2host
603    translation, looks like this.  */
604 struct comp_unit_head
605 {
606   unsigned int length;
607   short version;
608   unsigned char addr_size;
609   unsigned char signed_addr_p;
610   sect_offset abbrev_sect_off;
611
612   /* Size of file offsets; either 4 or 8.  */
613   unsigned int offset_size;
614
615   /* Size of the length field; either 4 or 12.  */
616   unsigned int initial_length_size;
617
618   enum dwarf_unit_type unit_type;
619
620   /* Offset to the first byte of this compilation unit header in the
621      .debug_info section, for resolving relative reference dies.  */
622   sect_offset sect_off;
623
624   /* Offset to first die in this cu from the start of the cu.
625      This will be the first byte following the compilation unit header.  */
626   cu_offset first_die_cu_offset;
627
628   /* 64-bit signature of this type unit - it is valid only for
629      UNIT_TYPE DW_UT_type.  */
630   ULONGEST signature;
631
632   /* For types, offset in the type's DIE of the type defined by this TU.  */
633   cu_offset type_cu_offset_in_tu;
634 };
635
636 /* Type used for delaying computation of method physnames.
637    See comments for compute_delayed_physnames.  */
638 struct delayed_method_info
639 {
640   /* The type to which the method is attached, i.e., its parent class.  */
641   struct type *type;
642
643   /* The index of the method in the type's function fieldlists.  */
644   int fnfield_index;
645
646   /* The index of the method in the fieldlist.  */
647   int index;
648
649   /* The name of the DIE.  */
650   const char *name;
651
652   /*  The DIE associated with this method.  */
653   struct die_info *die;
654 };
655
656 /* Internal state when decoding a particular compilation unit.  */
657 struct dwarf2_cu
658 {
659   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
660   ~dwarf2_cu ();
661
662   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
663
664   /* The header of the compilation unit.  */
665   struct comp_unit_head header {};
666
667   /* Base address of this compilation unit.  */
668   CORE_ADDR base_address = 0;
669
670   /* Non-zero if base_address has been set.  */
671   int base_known = 0;
672
673   /* The language we are debugging.  */
674   enum language language = language_unknown;
675   const struct language_defn *language_defn = nullptr;
676
677   const char *producer = nullptr;
678
679   /* The generic symbol table building routines have separate lists for
680      file scope symbols and all all other scopes (local scopes).  So
681      we need to select the right one to pass to add_symbol_to_list().
682      We do it by keeping a pointer to the correct list in list_in_scope.
683
684      FIXME: The original dwarf code just treated the file scope as the
685      first local scope, and all other local scopes as nested local
686      scopes, and worked fine.  Check to see if we really need to
687      distinguish these in buildsym.c.  */
688   struct pending **list_in_scope = nullptr;
689
690   /* Hash table holding all the loaded partial DIEs
691      with partial_die->offset.SECT_OFF as hash.  */
692   htab_t partial_dies = nullptr;
693
694   /* Storage for things with the same lifetime as this read-in compilation
695      unit, including partial DIEs.  */
696   auto_obstack comp_unit_obstack;
697
698   /* When multiple dwarf2_cu structures are living in memory, this field
699      chains them all together, so that they can be released efficiently.
700      We will probably also want a generation counter so that most-recently-used
701      compilation units are cached...  */
702   struct dwarf2_per_cu_data *read_in_chain = nullptr;
703
704   /* Backlink to our per_cu entry.  */
705   struct dwarf2_per_cu_data *per_cu;
706
707   /* How many compilation units ago was this CU last referenced?  */
708   int last_used = 0;
709
710   /* A hash table of DIE cu_offset for following references with
711      die_info->offset.sect_off as hash.  */
712   htab_t die_hash = nullptr;
713
714   /* Full DIEs if read in.  */
715   struct die_info *dies = nullptr;
716
717   /* A set of pointers to dwarf2_per_cu_data objects for compilation
718      units referenced by this one.  Only set during full symbol processing;
719      partial symbol tables do not have dependencies.  */
720   htab_t dependencies = nullptr;
721
722   /* Header data from the line table, during full symbol processing.  */
723   struct line_header *line_header = nullptr;
724   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
725      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
726      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
727      to the line header as long as this DIE is being processed.  See
728      process_die_scope.  */
729   die_info *line_header_die_owner = nullptr;
730
731   /* A list of methods which need to have physnames computed
732      after all type information has been read.  */
733   std::vector<delayed_method_info> method_list;
734
735   /* To be copied to symtab->call_site_htab.  */
736   htab_t call_site_htab = nullptr;
737
738   /* Non-NULL if this CU came from a DWO file.
739      There is an invariant here that is important to remember:
740      Except for attributes copied from the top level DIE in the "main"
741      (or "stub") file in preparation for reading the DWO file
742      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
743      Either there isn't a DWO file (in which case this is NULL and the point
744      is moot), or there is and either we're not going to read it (in which
745      case this is NULL) or there is and we are reading it (in which case this
746      is non-NULL).  */
747   struct dwo_unit *dwo_unit = nullptr;
748
749   /* The DW_AT_addr_base attribute if present, zero otherwise
750      (zero is a valid value though).
751      Note this value comes from the Fission stub CU/TU's DIE.  */
752   ULONGEST addr_base = 0;
753
754   /* The DW_AT_ranges_base attribute if present, zero otherwise
755      (zero is a valid value though).
756      Note this value comes from the Fission stub CU/TU's DIE.
757      Also note that the value is zero in the non-DWO case so this value can
758      be used without needing to know whether DWO files are in use or not.
759      N.B. This does not apply to DW_AT_ranges appearing in
760      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
761      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
762      DW_AT_ranges_base *would* have to be applied, and we'd have to care
763      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
764   ULONGEST ranges_base = 0;
765
766   /* When reading debug info generated by older versions of rustc, we
767      have to rewrite some union types to be struct types with a
768      variant part.  This rewriting must be done after the CU is fully
769      read in, because otherwise at the point of rewriting some struct
770      type might not have been fully processed.  So, we keep a list of
771      all such types here and process them after expansion.  */
772   std::vector<struct type *> rust_unions;
773
774   /* Mark used when releasing cached dies.  */
775   unsigned int mark : 1;
776
777   /* This CU references .debug_loc.  See the symtab->locations_valid field.
778      This test is imperfect as there may exist optimized debug code not using
779      any location list and still facing inlining issues if handled as
780      unoptimized code.  For a future better test see GCC PR other/32998.  */
781   unsigned int has_loclist : 1;
782
783   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
784      if all the producer_is_* fields are valid.  This information is cached
785      because profiling CU expansion showed excessive time spent in
786      producer_is_gxx_lt_4_6.  */
787   unsigned int checked_producer : 1;
788   unsigned int producer_is_gxx_lt_4_6 : 1;
789   unsigned int producer_is_gcc_lt_4_3 : 1;
790   unsigned int producer_is_icc_lt_14 : 1;
791
792   /* When set, the file that we're processing is known to have
793      debugging info for C++ namespaces.  GCC 3.3.x did not produce
794      this information, but later versions do.  */
795
796   unsigned int processing_has_namespace_info : 1;
797
798   struct partial_die_info *find_partial_die (sect_offset sect_off);
799 };
800
801 /* Persistent data held for a compilation unit, even when not
802    processing it.  We put a pointer to this structure in the
803    read_symtab_private field of the psymtab.  */
804
805 struct dwarf2_per_cu_data
806 {
807   /* The start offset and length of this compilation unit.
808      NOTE: Unlike comp_unit_head.length, this length includes
809      initial_length_size.
810      If the DIE refers to a DWO file, this is always of the original die,
811      not the DWO file.  */
812   sect_offset sect_off;
813   unsigned int length;
814
815   /* DWARF standard version this data has been read from (such as 4 or 5).  */
816   short dwarf_version;
817
818   /* Flag indicating this compilation unit will be read in before
819      any of the current compilation units are processed.  */
820   unsigned int queued : 1;
821
822   /* This flag will be set when reading partial DIEs if we need to load
823      absolutely all DIEs for this compilation unit, instead of just the ones
824      we think are interesting.  It gets set if we look for a DIE in the
825      hash table and don't find it.  */
826   unsigned int load_all_dies : 1;
827
828   /* Non-zero if this CU is from .debug_types.
829      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
830      this is non-zero.  */
831   unsigned int is_debug_types : 1;
832
833   /* Non-zero if this CU is from the .dwz file.  */
834   unsigned int is_dwz : 1;
835
836   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
837      This flag is only valid if is_debug_types is true.
838      We can't read a CU directly from a DWO file: There are required
839      attributes in the stub.  */
840   unsigned int reading_dwo_directly : 1;
841
842   /* Non-zero if the TU has been read.
843      This is used to assist the "Stay in DWO Optimization" for Fission:
844      When reading a DWO, it's faster to read TUs from the DWO instead of
845      fetching them from random other DWOs (due to comdat folding).
846      If the TU has already been read, the optimization is unnecessary
847      (and unwise - we don't want to change where gdb thinks the TU lives
848      "midflight").
849      This flag is only valid if is_debug_types is true.  */
850   unsigned int tu_read : 1;
851
852   /* The section this CU/TU lives in.
853      If the DIE refers to a DWO file, this is always the original die,
854      not the DWO file.  */
855   struct dwarf2_section_info *section;
856
857   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
858      of the CU cache it gets reset to NULL again.  This is left as NULL for
859      dummy CUs (a CU header, but nothing else).  */
860   struct dwarf2_cu *cu;
861
862   /* The corresponding dwarf2_per_objfile.  */
863   struct dwarf2_per_objfile *dwarf2_per_objfile;
864
865   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
866      is active.  Otherwise, the 'psymtab' field is active.  */
867   union
868   {
869     /* The partial symbol table associated with this compilation unit,
870        or NULL for unread partial units.  */
871     struct partial_symtab *psymtab;
872
873     /* Data needed by the "quick" functions.  */
874     struct dwarf2_per_cu_quick_data *quick;
875   } v;
876
877   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
878      while reading psymtabs, used to compute the psymtab dependencies,
879      and then cleared.  Then it is filled in again while reading full
880      symbols, and only deleted when the objfile is destroyed.
881
882      This is also used to work around a difference between the way gold
883      generates .gdb_index version <=7 and the way gdb does.  Arguably this
884      is a gold bug.  For symbols coming from TUs, gold records in the index
885      the CU that includes the TU instead of the TU itself.  This breaks
886      dw2_lookup_symbol: It assumes that if the index says symbol X lives
887      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
888      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
889      we need to look in TU Z to find X.  Fortunately, this is akin to
890      DW_TAG_imported_unit, so we just use the same mechanism: For
891      .gdb_index version <=7 this also records the TUs that the CU referred
892      to.  Concurrently with this change gdb was modified to emit version 8
893      indices so we only pay a price for gold generated indices.
894      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
895   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
896 };
897
898 /* Entry in the signatured_types hash table.  */
899
900 struct signatured_type
901 {
902   /* The "per_cu" object of this type.
903      This struct is used iff per_cu.is_debug_types.
904      N.B.: This is the first member so that it's easy to convert pointers
905      between them.  */
906   struct dwarf2_per_cu_data per_cu;
907
908   /* The type's signature.  */
909   ULONGEST signature;
910
911   /* Offset in the TU of the type's DIE, as read from the TU header.
912      If this TU is a DWO stub and the definition lives in a DWO file
913      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
914   cu_offset type_offset_in_tu;
915
916   /* Offset in the section of the type's DIE.
917      If the definition lives in a DWO file, this is the offset in the
918      .debug_types.dwo section.
919      The value is zero until the actual value is known.
920      Zero is otherwise not a valid section offset.  */
921   sect_offset type_offset_in_section;
922
923   /* Type units are grouped by their DW_AT_stmt_list entry so that they
924      can share them.  This points to the containing symtab.  */
925   struct type_unit_group *type_unit_group;
926
927   /* The type.
928      The first time we encounter this type we fully read it in and install it
929      in the symbol tables.  Subsequent times we only need the type.  */
930   struct type *type;
931
932   /* Containing DWO unit.
933      This field is valid iff per_cu.reading_dwo_directly.  */
934   struct dwo_unit *dwo_unit;
935 };
936
937 typedef struct signatured_type *sig_type_ptr;
938 DEF_VEC_P (sig_type_ptr);
939
940 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
941    This includes type_unit_group and quick_file_names.  */
942
943 struct stmt_list_hash
944 {
945   /* The DWO unit this table is from or NULL if there is none.  */
946   struct dwo_unit *dwo_unit;
947
948   /* Offset in .debug_line or .debug_line.dwo.  */
949   sect_offset line_sect_off;
950 };
951
952 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
953    an object of this type.  */
954
955 struct type_unit_group
956 {
957   /* dwarf2read.c's main "handle" on a TU symtab.
958      To simplify things we create an artificial CU that "includes" all the
959      type units using this stmt_list so that the rest of the code still has
960      a "per_cu" handle on the symtab.
961      This PER_CU is recognized by having no section.  */
962 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
963   struct dwarf2_per_cu_data per_cu;
964
965   /* The TUs that share this DW_AT_stmt_list entry.
966      This is added to while parsing type units to build partial symtabs,
967      and is deleted afterwards and not used again.  */
968   VEC (sig_type_ptr) *tus;
969
970   /* The compunit symtab.
971      Type units in a group needn't all be defined in the same source file,
972      so we create an essentially anonymous symtab as the compunit symtab.  */
973   struct compunit_symtab *compunit_symtab;
974
975   /* The data used to construct the hash key.  */
976   struct stmt_list_hash hash;
977
978   /* The number of symtabs from the line header.
979      The value here must match line_header.num_file_names.  */
980   unsigned int num_symtabs;
981
982   /* The symbol tables for this TU (obtained from the files listed in
983      DW_AT_stmt_list).
984      WARNING: The order of entries here must match the order of entries
985      in the line header.  After the first TU using this type_unit_group, the
986      line header for the subsequent TUs is recreated from this.  This is done
987      because we need to use the same symtabs for each TU using the same
988      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
989      there's no guarantee the line header doesn't have duplicate entries.  */
990   struct symtab **symtabs;
991 };
992
993 /* These sections are what may appear in a (real or virtual) DWO file.  */
994
995 struct dwo_sections
996 {
997   struct dwarf2_section_info abbrev;
998   struct dwarf2_section_info line;
999   struct dwarf2_section_info loc;
1000   struct dwarf2_section_info loclists;
1001   struct dwarf2_section_info macinfo;
1002   struct dwarf2_section_info macro;
1003   struct dwarf2_section_info str;
1004   struct dwarf2_section_info str_offsets;
1005   /* In the case of a virtual DWO file, these two are unused.  */
1006   struct dwarf2_section_info info;
1007   VEC (dwarf2_section_info_def) *types;
1008 };
1009
1010 /* CUs/TUs in DWP/DWO files.  */
1011
1012 struct dwo_unit
1013 {
1014   /* Backlink to the containing struct dwo_file.  */
1015   struct dwo_file *dwo_file;
1016
1017   /* The "id" that distinguishes this CU/TU.
1018      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1019      Since signatures came first, we stick with it for consistency.  */
1020   ULONGEST signature;
1021
1022   /* The section this CU/TU lives in, in the DWO file.  */
1023   struct dwarf2_section_info *section;
1024
1025   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1026   sect_offset sect_off;
1027   unsigned int length;
1028
1029   /* For types, offset in the type's DIE of the type defined by this TU.  */
1030   cu_offset type_offset_in_tu;
1031 };
1032
1033 /* include/dwarf2.h defines the DWP section codes.
1034    It defines a max value but it doesn't define a min value, which we
1035    use for error checking, so provide one.  */
1036
1037 enum dwp_v2_section_ids
1038 {
1039   DW_SECT_MIN = 1
1040 };
1041
1042 /* Data for one DWO file.
1043
1044    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1045    appears in a DWP file).  DWP files don't really have DWO files per se -
1046    comdat folding of types "loses" the DWO file they came from, and from
1047    a high level view DWP files appear to contain a mass of random types.
1048    However, to maintain consistency with the non-DWP case we pretend DWP
1049    files contain virtual DWO files, and we assign each TU with one virtual
1050    DWO file (generally based on the line and abbrev section offsets -
1051    a heuristic that seems to work in practice).  */
1052
1053 struct dwo_file
1054 {
1055   /* The DW_AT_GNU_dwo_name attribute.
1056      For virtual DWO files the name is constructed from the section offsets
1057      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1058      from related CU+TUs.  */
1059   const char *dwo_name;
1060
1061   /* The DW_AT_comp_dir attribute.  */
1062   const char *comp_dir;
1063
1064   /* The bfd, when the file is open.  Otherwise this is NULL.
1065      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1066   bfd *dbfd;
1067
1068   /* The sections that make up this DWO file.
1069      Remember that for virtual DWO files in DWP V2, these are virtual
1070      sections (for lack of a better name).  */
1071   struct dwo_sections sections;
1072
1073   /* The CUs in the file.
1074      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1075      an extension to handle LLVM's Link Time Optimization output (where
1076      multiple source files may be compiled into a single object/dwo pair). */
1077   htab_t cus;
1078
1079   /* Table of TUs in the file.
1080      Each element is a struct dwo_unit.  */
1081   htab_t tus;
1082 };
1083
1084 /* These sections are what may appear in a DWP file.  */
1085
1086 struct dwp_sections
1087 {
1088   /* These are used by both DWP version 1 and 2.  */
1089   struct dwarf2_section_info str;
1090   struct dwarf2_section_info cu_index;
1091   struct dwarf2_section_info tu_index;
1092
1093   /* These are only used by DWP version 2 files.
1094      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1095      sections are referenced by section number, and are not recorded here.
1096      In DWP version 2 there is at most one copy of all these sections, each
1097      section being (effectively) comprised of the concatenation of all of the
1098      individual sections that exist in the version 1 format.
1099      To keep the code simple we treat each of these concatenated pieces as a
1100      section itself (a virtual section?).  */
1101   struct dwarf2_section_info abbrev;
1102   struct dwarf2_section_info info;
1103   struct dwarf2_section_info line;
1104   struct dwarf2_section_info loc;
1105   struct dwarf2_section_info macinfo;
1106   struct dwarf2_section_info macro;
1107   struct dwarf2_section_info str_offsets;
1108   struct dwarf2_section_info types;
1109 };
1110
1111 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1112    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1113
1114 struct virtual_v1_dwo_sections
1115 {
1116   struct dwarf2_section_info abbrev;
1117   struct dwarf2_section_info line;
1118   struct dwarf2_section_info loc;
1119   struct dwarf2_section_info macinfo;
1120   struct dwarf2_section_info macro;
1121   struct dwarf2_section_info str_offsets;
1122   /* Each DWP hash table entry records one CU or one TU.
1123      That is recorded here, and copied to dwo_unit.section.  */
1124   struct dwarf2_section_info info_or_types;
1125 };
1126
1127 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1128    In version 2, the sections of the DWO files are concatenated together
1129    and stored in one section of that name.  Thus each ELF section contains
1130    several "virtual" sections.  */
1131
1132 struct virtual_v2_dwo_sections
1133 {
1134   bfd_size_type abbrev_offset;
1135   bfd_size_type abbrev_size;
1136
1137   bfd_size_type line_offset;
1138   bfd_size_type line_size;
1139
1140   bfd_size_type loc_offset;
1141   bfd_size_type loc_size;
1142
1143   bfd_size_type macinfo_offset;
1144   bfd_size_type macinfo_size;
1145
1146   bfd_size_type macro_offset;
1147   bfd_size_type macro_size;
1148
1149   bfd_size_type str_offsets_offset;
1150   bfd_size_type str_offsets_size;
1151
1152   /* Each DWP hash table entry records one CU or one TU.
1153      That is recorded here, and copied to dwo_unit.section.  */
1154   bfd_size_type info_or_types_offset;
1155   bfd_size_type info_or_types_size;
1156 };
1157
1158 /* Contents of DWP hash tables.  */
1159
1160 struct dwp_hash_table
1161 {
1162   uint32_t version, nr_columns;
1163   uint32_t nr_units, nr_slots;
1164   const gdb_byte *hash_table, *unit_table;
1165   union
1166   {
1167     struct
1168     {
1169       const gdb_byte *indices;
1170     } v1;
1171     struct
1172     {
1173       /* This is indexed by column number and gives the id of the section
1174          in that column.  */
1175 #define MAX_NR_V2_DWO_SECTIONS \
1176   (1 /* .debug_info or .debug_types */ \
1177    + 1 /* .debug_abbrev */ \
1178    + 1 /* .debug_line */ \
1179    + 1 /* .debug_loc */ \
1180    + 1 /* .debug_str_offsets */ \
1181    + 1 /* .debug_macro or .debug_macinfo */)
1182       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1183       const gdb_byte *offsets;
1184       const gdb_byte *sizes;
1185     } v2;
1186   } section_pool;
1187 };
1188
1189 /* Data for one DWP file.  */
1190
1191 struct dwp_file
1192 {
1193   /* Name of the file.  */
1194   const char *name;
1195
1196   /* File format version.  */
1197   int version;
1198
1199   /* The bfd.  */
1200   bfd *dbfd;
1201
1202   /* Section info for this file.  */
1203   struct dwp_sections sections;
1204
1205   /* Table of CUs in the file.  */
1206   const struct dwp_hash_table *cus;
1207
1208   /* Table of TUs in the file.  */
1209   const struct dwp_hash_table *tus;
1210
1211   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1212   htab_t loaded_cus;
1213   htab_t loaded_tus;
1214
1215   /* Table to map ELF section numbers to their sections.
1216      This is only needed for the DWP V1 file format.  */
1217   unsigned int num_sections;
1218   asection **elf_sections;
1219 };
1220
1221 /* This represents a '.dwz' file.  */
1222
1223 struct dwz_file
1224 {
1225   /* A dwz file can only contain a few sections.  */
1226   struct dwarf2_section_info abbrev;
1227   struct dwarf2_section_info info;
1228   struct dwarf2_section_info str;
1229   struct dwarf2_section_info line;
1230   struct dwarf2_section_info macro;
1231   struct dwarf2_section_info gdb_index;
1232   struct dwarf2_section_info debug_names;
1233
1234   /* The dwz's BFD.  */
1235   bfd *dwz_bfd;
1236 };
1237
1238 /* Struct used to pass misc. parameters to read_die_and_children, et
1239    al.  which are used for both .debug_info and .debug_types dies.
1240    All parameters here are unchanging for the life of the call.  This
1241    struct exists to abstract away the constant parameters of die reading.  */
1242
1243 struct die_reader_specs
1244 {
1245   /* The bfd of die_section.  */
1246   bfd* abfd;
1247
1248   /* The CU of the DIE we are parsing.  */
1249   struct dwarf2_cu *cu;
1250
1251   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1252   struct dwo_file *dwo_file;
1253
1254   /* The section the die comes from.
1255      This is either .debug_info or .debug_types, or the .dwo variants.  */
1256   struct dwarf2_section_info *die_section;
1257
1258   /* die_section->buffer.  */
1259   const gdb_byte *buffer;
1260
1261   /* The end of the buffer.  */
1262   const gdb_byte *buffer_end;
1263
1264   /* The value of the DW_AT_comp_dir attribute.  */
1265   const char *comp_dir;
1266
1267   /* The abbreviation table to use when reading the DIEs.  */
1268   struct abbrev_table *abbrev_table;
1269 };
1270
1271 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1272 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1273                                       const gdb_byte *info_ptr,
1274                                       struct die_info *comp_unit_die,
1275                                       int has_children,
1276                                       void *data);
1277
1278 /* A 1-based directory index.  This is a strong typedef to prevent
1279    accidentally using a directory index as a 0-based index into an
1280    array/vector.  */
1281 enum class dir_index : unsigned int {};
1282
1283 /* Likewise, a 1-based file name index.  */
1284 enum class file_name_index : unsigned int {};
1285
1286 struct file_entry
1287 {
1288   file_entry () = default;
1289
1290   file_entry (const char *name_, dir_index d_index_,
1291               unsigned int mod_time_, unsigned int length_)
1292     : name (name_),
1293       d_index (d_index_),
1294       mod_time (mod_time_),
1295       length (length_)
1296   {}
1297
1298   /* Return the include directory at D_INDEX stored in LH.  Returns
1299      NULL if D_INDEX is out of bounds.  */
1300   const char *include_dir (const line_header *lh) const;
1301
1302   /* The file name.  Note this is an observing pointer.  The memory is
1303      owned by debug_line_buffer.  */
1304   const char *name {};
1305
1306   /* The directory index (1-based).  */
1307   dir_index d_index {};
1308
1309   unsigned int mod_time {};
1310
1311   unsigned int length {};
1312
1313   /* True if referenced by the Line Number Program.  */
1314   bool included_p {};
1315
1316   /* The associated symbol table, if any.  */
1317   struct symtab *symtab {};
1318 };
1319
1320 /* The line number information for a compilation unit (found in the
1321    .debug_line section) begins with a "statement program header",
1322    which contains the following information.  */
1323 struct line_header
1324 {
1325   line_header ()
1326     : offset_in_dwz {}
1327   {}
1328
1329   /* Add an entry to the include directory table.  */
1330   void add_include_dir (const char *include_dir);
1331
1332   /* Add an entry to the file name table.  */
1333   void add_file_name (const char *name, dir_index d_index,
1334                       unsigned int mod_time, unsigned int length);
1335
1336   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1337      is out of bounds.  */
1338   const char *include_dir_at (dir_index index) const
1339   {
1340     /* Convert directory index number (1-based) to vector index
1341        (0-based).  */
1342     size_t vec_index = to_underlying (index) - 1;
1343
1344     if (vec_index >= include_dirs.size ())
1345       return NULL;
1346     return include_dirs[vec_index];
1347   }
1348
1349   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1350      is out of bounds.  */
1351   file_entry *file_name_at (file_name_index index)
1352   {
1353     /* Convert file name index number (1-based) to vector index
1354        (0-based).  */
1355     size_t vec_index = to_underlying (index) - 1;
1356
1357     if (vec_index >= file_names.size ())
1358       return NULL;
1359     return &file_names[vec_index];
1360   }
1361
1362   /* Const version of the above.  */
1363   const file_entry *file_name_at (unsigned int index) const
1364   {
1365     if (index >= file_names.size ())
1366       return NULL;
1367     return &file_names[index];
1368   }
1369
1370   /* Offset of line number information in .debug_line section.  */
1371   sect_offset sect_off {};
1372
1373   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1374   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1375
1376   unsigned int total_length {};
1377   unsigned short version {};
1378   unsigned int header_length {};
1379   unsigned char minimum_instruction_length {};
1380   unsigned char maximum_ops_per_instruction {};
1381   unsigned char default_is_stmt {};
1382   int line_base {};
1383   unsigned char line_range {};
1384   unsigned char opcode_base {};
1385
1386   /* standard_opcode_lengths[i] is the number of operands for the
1387      standard opcode whose value is i.  This means that
1388      standard_opcode_lengths[0] is unused, and the last meaningful
1389      element is standard_opcode_lengths[opcode_base - 1].  */
1390   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1391
1392   /* The include_directories table.  Note these are observing
1393      pointers.  The memory is owned by debug_line_buffer.  */
1394   std::vector<const char *> include_dirs;
1395
1396   /* The file_names table.  */
1397   std::vector<file_entry> file_names;
1398
1399   /* The start and end of the statement program following this
1400      header.  These point into dwarf2_per_objfile->line_buffer.  */
1401   const gdb_byte *statement_program_start {}, *statement_program_end {};
1402 };
1403
1404 typedef std::unique_ptr<line_header> line_header_up;
1405
1406 const char *
1407 file_entry::include_dir (const line_header *lh) const
1408 {
1409   return lh->include_dir_at (d_index);
1410 }
1411
1412 /* When we construct a partial symbol table entry we only
1413    need this much information.  */
1414 struct partial_die_info : public allocate_on_obstack
1415   {
1416     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1417
1418     /* Disable assign but still keep copy ctor, which is needed
1419        load_partial_dies.   */
1420     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1421
1422     /* Adjust the partial die before generating a symbol for it.  This
1423        function may set the is_external flag or change the DIE's
1424        name.  */
1425     void fixup (struct dwarf2_cu *cu);
1426
1427     /* Read a minimal amount of information into the minimal die
1428        structure.  */
1429     const gdb_byte *read (const struct die_reader_specs *reader,
1430                           const struct abbrev_info &abbrev,
1431                           const gdb_byte *info_ptr);
1432
1433     /* Offset of this DIE.  */
1434     const sect_offset sect_off;
1435
1436     /* DWARF-2 tag for this DIE.  */
1437     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1438
1439     /* Assorted flags describing the data found in this DIE.  */
1440     const unsigned int has_children : 1;
1441
1442     unsigned int is_external : 1;
1443     unsigned int is_declaration : 1;
1444     unsigned int has_type : 1;
1445     unsigned int has_specification : 1;
1446     unsigned int has_pc_info : 1;
1447     unsigned int may_be_inlined : 1;
1448
1449     /* This DIE has been marked DW_AT_main_subprogram.  */
1450     unsigned int main_subprogram : 1;
1451
1452     /* Flag set if the SCOPE field of this structure has been
1453        computed.  */
1454     unsigned int scope_set : 1;
1455
1456     /* Flag set if the DIE has a byte_size attribute.  */
1457     unsigned int has_byte_size : 1;
1458
1459     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1460     unsigned int has_const_value : 1;
1461
1462     /* Flag set if any of the DIE's children are template arguments.  */
1463     unsigned int has_template_arguments : 1;
1464
1465     /* Flag set if fixup has been called on this die.  */
1466     unsigned int fixup_called : 1;
1467
1468     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1469     unsigned int is_dwz : 1;
1470
1471     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1472     unsigned int spec_is_dwz : 1;
1473
1474     /* The name of this DIE.  Normally the value of DW_AT_name, but
1475        sometimes a default name for unnamed DIEs.  */
1476     const char *name = nullptr;
1477
1478     /* The linkage name, if present.  */
1479     const char *linkage_name = nullptr;
1480
1481     /* The scope to prepend to our children.  This is generally
1482        allocated on the comp_unit_obstack, so will disappear
1483        when this compilation unit leaves the cache.  */
1484     const char *scope = nullptr;
1485
1486     /* Some data associated with the partial DIE.  The tag determines
1487        which field is live.  */
1488     union
1489     {
1490       /* The location description associated with this DIE, if any.  */
1491       struct dwarf_block *locdesc;
1492       /* The offset of an import, for DW_TAG_imported_unit.  */
1493       sect_offset sect_off;
1494     } d {};
1495
1496     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1497     CORE_ADDR lowpc = 0;
1498     CORE_ADDR highpc = 0;
1499
1500     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1501        DW_AT_sibling, if any.  */
1502     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1503        could return DW_AT_sibling values to its caller load_partial_dies.  */
1504     const gdb_byte *sibling = nullptr;
1505
1506     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1507        DW_AT_specification (or DW_AT_abstract_origin or
1508        DW_AT_extension).  */
1509     sect_offset spec_offset {};
1510
1511     /* Pointers to this DIE's parent, first child, and next sibling,
1512        if any.  */
1513     struct partial_die_info *die_parent = nullptr;
1514     struct partial_die_info *die_child = nullptr;
1515     struct partial_die_info *die_sibling = nullptr;
1516
1517     friend struct partial_die_info *
1518     dwarf2_cu::find_partial_die (sect_offset sect_off);
1519
1520   private:
1521     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1522     partial_die_info (sect_offset sect_off)
1523       : partial_die_info (sect_off, DW_TAG_padding, 0)
1524     {
1525     }
1526
1527     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1528                       int has_children_)
1529       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1530     {
1531       is_external = 0;
1532       is_declaration = 0;
1533       has_type = 0;
1534       has_specification = 0;
1535       has_pc_info = 0;
1536       may_be_inlined = 0;
1537       main_subprogram = 0;
1538       scope_set = 0;
1539       has_byte_size = 0;
1540       has_const_value = 0;
1541       has_template_arguments = 0;
1542       fixup_called = 0;
1543       is_dwz = 0;
1544       spec_is_dwz = 0;
1545     }
1546   };
1547
1548 /* This data structure holds the information of an abbrev.  */
1549 struct abbrev_info
1550   {
1551     unsigned int number;        /* number identifying abbrev */
1552     enum dwarf_tag tag;         /* dwarf tag */
1553     unsigned short has_children;                /* boolean */
1554     unsigned short num_attrs;   /* number of attributes */
1555     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1556     struct abbrev_info *next;   /* next in chain */
1557   };
1558
1559 struct attr_abbrev
1560   {
1561     ENUM_BITFIELD(dwarf_attribute) name : 16;
1562     ENUM_BITFIELD(dwarf_form) form : 16;
1563
1564     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1565     LONGEST implicit_const;
1566   };
1567
1568 /* Size of abbrev_table.abbrev_hash_table.  */
1569 #define ABBREV_HASH_SIZE 121
1570
1571 /* Top level data structure to contain an abbreviation table.  */
1572
1573 struct abbrev_table
1574 {
1575   explicit abbrev_table (sect_offset off)
1576     : sect_off (off)
1577   {
1578     m_abbrevs =
1579       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1580     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1581   }
1582
1583   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1584
1585   /* Allocate space for a struct abbrev_info object in
1586      ABBREV_TABLE.  */
1587   struct abbrev_info *alloc_abbrev ();
1588
1589   /* Add an abbreviation to the table.  */
1590   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1591
1592   /* Look up an abbrev in the table.
1593      Returns NULL if the abbrev is not found.  */
1594
1595   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1596
1597
1598   /* Where the abbrev table came from.
1599      This is used as a sanity check when the table is used.  */
1600   const sect_offset sect_off;
1601
1602   /* Storage for the abbrev table.  */
1603   auto_obstack abbrev_obstack;
1604
1605 private:
1606
1607   /* Hash table of abbrevs.
1608      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1609      It could be statically allocated, but the previous code didn't so we
1610      don't either.  */
1611   struct abbrev_info **m_abbrevs;
1612 };
1613
1614 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1615
1616 /* Attributes have a name and a value.  */
1617 struct attribute
1618   {
1619     ENUM_BITFIELD(dwarf_attribute) name : 16;
1620     ENUM_BITFIELD(dwarf_form) form : 15;
1621
1622     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1623        field should be in u.str (existing only for DW_STRING) but it is kept
1624        here for better struct attribute alignment.  */
1625     unsigned int string_is_canonical : 1;
1626
1627     union
1628       {
1629         const char *str;
1630         struct dwarf_block *blk;
1631         ULONGEST unsnd;
1632         LONGEST snd;
1633         CORE_ADDR addr;
1634         ULONGEST signature;
1635       }
1636     u;
1637   };
1638
1639 /* This data structure holds a complete die structure.  */
1640 struct die_info
1641   {
1642     /* DWARF-2 tag for this DIE.  */
1643     ENUM_BITFIELD(dwarf_tag) tag : 16;
1644
1645     /* Number of attributes */
1646     unsigned char num_attrs;
1647
1648     /* True if we're presently building the full type name for the
1649        type derived from this DIE.  */
1650     unsigned char building_fullname : 1;
1651
1652     /* True if this die is in process.  PR 16581.  */
1653     unsigned char in_process : 1;
1654
1655     /* Abbrev number */
1656     unsigned int abbrev;
1657
1658     /* Offset in .debug_info or .debug_types section.  */
1659     sect_offset sect_off;
1660
1661     /* The dies in a compilation unit form an n-ary tree.  PARENT
1662        points to this die's parent; CHILD points to the first child of
1663        this node; and all the children of a given node are chained
1664        together via their SIBLING fields.  */
1665     struct die_info *child;     /* Its first child, if any.  */
1666     struct die_info *sibling;   /* Its next sibling, if any.  */
1667     struct die_info *parent;    /* Its parent, if any.  */
1668
1669     /* An array of attributes, with NUM_ATTRS elements.  There may be
1670        zero, but it's not common and zero-sized arrays are not
1671        sufficiently portable C.  */
1672     struct attribute attrs[1];
1673   };
1674
1675 /* Get at parts of an attribute structure.  */
1676
1677 #define DW_STRING(attr)    ((attr)->u.str)
1678 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1679 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1680 #define DW_BLOCK(attr)     ((attr)->u.blk)
1681 #define DW_SND(attr)       ((attr)->u.snd)
1682 #define DW_ADDR(attr)      ((attr)->u.addr)
1683 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1684
1685 /* Blocks are a bunch of untyped bytes.  */
1686 struct dwarf_block
1687   {
1688     size_t size;
1689
1690     /* Valid only if SIZE is not zero.  */
1691     const gdb_byte *data;
1692   };
1693
1694 #ifndef ATTR_ALLOC_CHUNK
1695 #define ATTR_ALLOC_CHUNK 4
1696 #endif
1697
1698 /* Allocate fields for structs, unions and enums in this size.  */
1699 #ifndef DW_FIELD_ALLOC_CHUNK
1700 #define DW_FIELD_ALLOC_CHUNK 4
1701 #endif
1702
1703 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1704    but this would require a corresponding change in unpack_field_as_long
1705    and friends.  */
1706 static int bits_per_byte = 8;
1707
1708 struct nextfield
1709 {
1710   struct nextfield *next;
1711   int accessibility;
1712   int virtuality;
1713   struct field field;
1714 };
1715
1716 struct nextfnfield
1717 {
1718   struct nextfnfield *next;
1719   struct fn_field fnfield;
1720 };
1721
1722 struct fnfieldlist
1723 {
1724   const char *name;
1725   int length;
1726   struct nextfnfield *head;
1727 };
1728
1729 struct decl_field_list
1730 {
1731   struct decl_field field;
1732   struct decl_field_list *next;
1733 };
1734
1735 /* The routines that read and process dies for a C struct or C++ class
1736    pass lists of data member fields and lists of member function fields
1737    in an instance of a field_info structure, as defined below.  */
1738 struct field_info
1739   {
1740     /* List of data member and baseclasses fields.  */
1741     struct nextfield *fields, *baseclasses;
1742
1743     /* Number of fields (including baseclasses).  */
1744     int nfields;
1745
1746     /* Number of baseclasses.  */
1747     int nbaseclasses;
1748
1749     /* Set if the accesibility of one of the fields is not public.  */
1750     int non_public_fields;
1751
1752     /* Member function fieldlist array, contains name of possibly overloaded
1753        member function, number of overloaded member functions and a pointer
1754        to the head of the member function field chain.  */
1755     struct fnfieldlist *fnfieldlists;
1756
1757     /* Number of entries in the fnfieldlists array.  */
1758     int nfnfields;
1759
1760     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1761        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1762     struct decl_field_list *typedef_field_list;
1763     unsigned typedef_field_list_count;
1764
1765     /* Nested types defined by this class and the number of elements in this
1766        list.  */
1767     struct decl_field_list *nested_types_list;
1768     unsigned nested_types_list_count;
1769   };
1770
1771 /* One item on the queue of compilation units to read in full symbols
1772    for.  */
1773 struct dwarf2_queue_item
1774 {
1775   struct dwarf2_per_cu_data *per_cu;
1776   enum language pretend_language;
1777   struct dwarf2_queue_item *next;
1778 };
1779
1780 /* The current queue.  */
1781 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1782
1783 /* Loaded secondary compilation units are kept in memory until they
1784    have not been referenced for the processing of this many
1785    compilation units.  Set this to zero to disable caching.  Cache
1786    sizes of up to at least twenty will improve startup time for
1787    typical inter-CU-reference binaries, at an obvious memory cost.  */
1788 static int dwarf_max_cache_age = 5;
1789 static void
1790 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1791                           struct cmd_list_element *c, const char *value)
1792 {
1793   fprintf_filtered (file, _("The upper bound on the age of cached "
1794                             "DWARF compilation units is %s.\n"),
1795                     value);
1796 }
1797 \f
1798 /* local function prototypes */
1799
1800 static const char *get_section_name (const struct dwarf2_section_info *);
1801
1802 static const char *get_section_file_name (const struct dwarf2_section_info *);
1803
1804 static void dwarf2_find_base_address (struct die_info *die,
1805                                       struct dwarf2_cu *cu);
1806
1807 static struct partial_symtab *create_partial_symtab
1808   (struct dwarf2_per_cu_data *per_cu, const char *name);
1809
1810 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1811                                         const gdb_byte *info_ptr,
1812                                         struct die_info *type_unit_die,
1813                                         int has_children, void *data);
1814
1815 static void dwarf2_build_psymtabs_hard
1816   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1817
1818 static void scan_partial_symbols (struct partial_die_info *,
1819                                   CORE_ADDR *, CORE_ADDR *,
1820                                   int, struct dwarf2_cu *);
1821
1822 static void add_partial_symbol (struct partial_die_info *,
1823                                 struct dwarf2_cu *);
1824
1825 static void add_partial_namespace (struct partial_die_info *pdi,
1826                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1827                                    int set_addrmap, struct dwarf2_cu *cu);
1828
1829 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1830                                 CORE_ADDR *highpc, int set_addrmap,
1831                                 struct dwarf2_cu *cu);
1832
1833 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1834                                      struct dwarf2_cu *cu);
1835
1836 static void add_partial_subprogram (struct partial_die_info *pdi,
1837                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1838                                     int need_pc, struct dwarf2_cu *cu);
1839
1840 static void dwarf2_read_symtab (struct partial_symtab *,
1841                                 struct objfile *);
1842
1843 static void psymtab_to_symtab_1 (struct partial_symtab *);
1844
1845 static abbrev_table_up abbrev_table_read_table
1846   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1847    sect_offset);
1848
1849 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1850
1851 static struct partial_die_info *load_partial_dies
1852   (const struct die_reader_specs *, const gdb_byte *, int);
1853
1854 static struct partial_die_info *find_partial_die (sect_offset, int,
1855                                                   struct dwarf2_cu *);
1856
1857 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1858                                        struct attribute *, struct attr_abbrev *,
1859                                        const gdb_byte *);
1860
1861 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1862
1863 static int read_1_signed_byte (bfd *, const gdb_byte *);
1864
1865 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1866
1867 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1868
1869 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1870
1871 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1872                                unsigned int *);
1873
1874 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1875
1876 static LONGEST read_checked_initial_length_and_offset
1877   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1878    unsigned int *, unsigned int *);
1879
1880 static LONGEST read_offset (bfd *, const gdb_byte *,
1881                             const struct comp_unit_head *,
1882                             unsigned int *);
1883
1884 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1885
1886 static sect_offset read_abbrev_offset
1887   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1888    struct dwarf2_section_info *, sect_offset);
1889
1890 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1891
1892 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1893
1894 static const char *read_indirect_string
1895   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1896    const struct comp_unit_head *, unsigned int *);
1897
1898 static const char *read_indirect_line_string
1899   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1900    const struct comp_unit_head *, unsigned int *);
1901
1902 static const char *read_indirect_string_at_offset
1903   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1904    LONGEST str_offset);
1905
1906 static const char *read_indirect_string_from_dwz
1907   (struct objfile *objfile, struct dwz_file *, LONGEST);
1908
1909 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1910
1911 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1912                                               const gdb_byte *,
1913                                               unsigned int *);
1914
1915 static const char *read_str_index (const struct die_reader_specs *reader,
1916                                    ULONGEST str_index);
1917
1918 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1919
1920 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1921                                       struct dwarf2_cu *);
1922
1923 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1924                                                 unsigned int);
1925
1926 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1927                                        struct dwarf2_cu *cu);
1928
1929 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1930                                struct dwarf2_cu *cu);
1931
1932 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1933
1934 static struct die_info *die_specification (struct die_info *die,
1935                                            struct dwarf2_cu **);
1936
1937 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1938                                                 struct dwarf2_cu *cu);
1939
1940 static void dwarf_decode_lines (struct line_header *, const char *,
1941                                 struct dwarf2_cu *, struct partial_symtab *,
1942                                 CORE_ADDR, int decode_mapping);
1943
1944 static void dwarf2_start_subfile (const char *, const char *);
1945
1946 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1947                                                     const char *, const char *,
1948                                                     CORE_ADDR);
1949
1950 static struct symbol *new_symbol (struct die_info *, struct type *,
1951                                   struct dwarf2_cu *, struct symbol * = NULL);
1952
1953 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1954                                 struct dwarf2_cu *);
1955
1956 static void dwarf2_const_value_attr (const struct attribute *attr,
1957                                      struct type *type,
1958                                      const char *name,
1959                                      struct obstack *obstack,
1960                                      struct dwarf2_cu *cu, LONGEST *value,
1961                                      const gdb_byte **bytes,
1962                                      struct dwarf2_locexpr_baton **baton);
1963
1964 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1965
1966 static int need_gnat_info (struct dwarf2_cu *);
1967
1968 static struct type *die_descriptive_type (struct die_info *,
1969                                           struct dwarf2_cu *);
1970
1971 static void set_descriptive_type (struct type *, struct die_info *,
1972                                   struct dwarf2_cu *);
1973
1974 static struct type *die_containing_type (struct die_info *,
1975                                          struct dwarf2_cu *);
1976
1977 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1978                                      struct dwarf2_cu *);
1979
1980 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1981
1982 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1983
1984 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1985
1986 static char *typename_concat (struct obstack *obs, const char *prefix,
1987                               const char *suffix, int physname,
1988                               struct dwarf2_cu *cu);
1989
1990 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1991
1992 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1993
1994 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1995
1996 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1997
1998 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1999
2000 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
2001
2002 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
2003                                struct dwarf2_cu *, struct partial_symtab *);
2004
2005 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
2006    values.  Keep the items ordered with increasing constraints compliance.  */
2007 enum pc_bounds_kind
2008 {
2009   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
2010   PC_BOUNDS_NOT_PRESENT,
2011
2012   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
2013      were present but they do not form a valid range of PC addresses.  */
2014   PC_BOUNDS_INVALID,
2015
2016   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
2017   PC_BOUNDS_RANGES,
2018
2019   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
2020   PC_BOUNDS_HIGH_LOW,
2021 };
2022
2023 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
2024                                                  CORE_ADDR *, CORE_ADDR *,
2025                                                  struct dwarf2_cu *,
2026                                                  struct partial_symtab *);
2027
2028 static void get_scope_pc_bounds (struct die_info *,
2029                                  CORE_ADDR *, CORE_ADDR *,
2030                                  struct dwarf2_cu *);
2031
2032 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
2033                                         CORE_ADDR, struct dwarf2_cu *);
2034
2035 static void dwarf2_add_field (struct field_info *, struct die_info *,
2036                               struct dwarf2_cu *);
2037
2038 static void dwarf2_attach_fields_to_type (struct field_info *,
2039                                           struct type *, struct dwarf2_cu *);
2040
2041 static void dwarf2_add_member_fn (struct field_info *,
2042                                   struct die_info *, struct type *,
2043                                   struct dwarf2_cu *);
2044
2045 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
2046                                              struct type *,
2047                                              struct dwarf2_cu *);
2048
2049 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
2050
2051 static void read_common_block (struct die_info *, struct dwarf2_cu *);
2052
2053 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2054
2055 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2056
2057 static struct using_direct **using_directives (enum language);
2058
2059 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2060
2061 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2062
2063 static struct type *read_module_type (struct die_info *die,
2064                                       struct dwarf2_cu *cu);
2065
2066 static const char *namespace_name (struct die_info *die,
2067                                    int *is_anonymous, struct dwarf2_cu *);
2068
2069 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2070
2071 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2072
2073 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2074                                                        struct dwarf2_cu *);
2075
2076 static struct die_info *read_die_and_siblings_1
2077   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2078    struct die_info *);
2079
2080 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2081                                                const gdb_byte *info_ptr,
2082                                                const gdb_byte **new_info_ptr,
2083                                                struct die_info *parent);
2084
2085 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2086                                         struct die_info **, const gdb_byte *,
2087                                         int *, int);
2088
2089 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2090                                       struct die_info **, const gdb_byte *,
2091                                       int *);
2092
2093 static void process_die (struct die_info *, struct dwarf2_cu *);
2094
2095 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2096                                              struct obstack *);
2097
2098 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2099
2100 static const char *dwarf2_full_name (const char *name,
2101                                      struct die_info *die,
2102                                      struct dwarf2_cu *cu);
2103
2104 static const char *dwarf2_physname (const char *name, struct die_info *die,
2105                                     struct dwarf2_cu *cu);
2106
2107 static struct die_info *dwarf2_extension (struct die_info *die,
2108                                           struct dwarf2_cu **);
2109
2110 static const char *dwarf_tag_name (unsigned int);
2111
2112 static const char *dwarf_attr_name (unsigned int);
2113
2114 static const char *dwarf_form_name (unsigned int);
2115
2116 static const char *dwarf_bool_name (unsigned int);
2117
2118 static const char *dwarf_type_encoding_name (unsigned int);
2119
2120 static struct die_info *sibling_die (struct die_info *);
2121
2122 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2123
2124 static void dump_die_for_error (struct die_info *);
2125
2126 static void dump_die_1 (struct ui_file *, int level, int max_level,
2127                         struct die_info *);
2128
2129 /*static*/ void dump_die (struct die_info *, int max_level);
2130
2131 static void store_in_ref_table (struct die_info *,
2132                                 struct dwarf2_cu *);
2133
2134 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2135
2136 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2137
2138 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2139                                                const struct attribute *,
2140                                                struct dwarf2_cu **);
2141
2142 static struct die_info *follow_die_ref (struct die_info *,
2143                                         const struct attribute *,
2144                                         struct dwarf2_cu **);
2145
2146 static struct die_info *follow_die_sig (struct die_info *,
2147                                         const struct attribute *,
2148                                         struct dwarf2_cu **);
2149
2150 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2151                                          struct dwarf2_cu *);
2152
2153 static struct type *get_DW_AT_signature_type (struct die_info *,
2154                                               const struct attribute *,
2155                                               struct dwarf2_cu *);
2156
2157 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2158
2159 static void read_signatured_type (struct signatured_type *);
2160
2161 static int attr_to_dynamic_prop (const struct attribute *attr,
2162                                  struct die_info *die, struct dwarf2_cu *cu,
2163                                  struct dynamic_prop *prop);
2164
2165 /* memory allocation interface */
2166
2167 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2168
2169 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2170
2171 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2172
2173 static int attr_form_is_block (const struct attribute *);
2174
2175 static int attr_form_is_section_offset (const struct attribute *);
2176
2177 static int attr_form_is_constant (const struct attribute *);
2178
2179 static int attr_form_is_ref (const struct attribute *);
2180
2181 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2182                                    struct dwarf2_loclist_baton *baton,
2183                                    const struct attribute *attr);
2184
2185 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2186                                          struct symbol *sym,
2187                                          struct dwarf2_cu *cu,
2188                                          int is_block);
2189
2190 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2191                                      const gdb_byte *info_ptr,
2192                                      struct abbrev_info *abbrev);
2193
2194 static hashval_t partial_die_hash (const void *item);
2195
2196 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2197
2198 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2199   (sect_offset sect_off, unsigned int offset_in_dwz,
2200    struct dwarf2_per_objfile *dwarf2_per_objfile);
2201
2202 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2203                                    struct die_info *comp_unit_die,
2204                                    enum language pretend_language);
2205
2206 static void free_cached_comp_units (void *);
2207
2208 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2209
2210 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2211
2212 static struct type *set_die_type (struct die_info *, struct type *,
2213                                   struct dwarf2_cu *);
2214
2215 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2216
2217 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2218
2219 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2220                                  enum language);
2221
2222 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2223                                     enum language);
2224
2225 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2226                                     enum language);
2227
2228 static void dwarf2_add_dependence (struct dwarf2_cu *,
2229                                    struct dwarf2_per_cu_data *);
2230
2231 static void dwarf2_mark (struct dwarf2_cu *);
2232
2233 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2234
2235 static struct type *get_die_type_at_offset (sect_offset,
2236                                             struct dwarf2_per_cu_data *);
2237
2238 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2239
2240 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2241                              enum language pretend_language);
2242
2243 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2244
2245 /* Class, the destructor of which frees all allocated queue entries.  This
2246    will only have work to do if an error was thrown while processing the
2247    dwarf.  If no error was thrown then the queue entries should have all
2248    been processed, and freed, as we went along.  */
2249
2250 class dwarf2_queue_guard
2251 {
2252 public:
2253   dwarf2_queue_guard () = default;
2254
2255   /* Free any entries remaining on the queue.  There should only be
2256      entries left if we hit an error while processing the dwarf.  */
2257   ~dwarf2_queue_guard ()
2258   {
2259     struct dwarf2_queue_item *item, *last;
2260
2261     item = dwarf2_queue;
2262     while (item)
2263       {
2264         /* Anything still marked queued is likely to be in an
2265            inconsistent state, so discard it.  */
2266         if (item->per_cu->queued)
2267           {
2268             if (item->per_cu->cu != NULL)
2269               free_one_cached_comp_unit (item->per_cu);
2270             item->per_cu->queued = 0;
2271           }
2272
2273         last = item;
2274         item = item->next;
2275         xfree (last);
2276       }
2277
2278     dwarf2_queue = dwarf2_queue_tail = NULL;
2279   }
2280 };
2281
2282 /* The return type of find_file_and_directory.  Note, the enclosed
2283    string pointers are only valid while this object is valid.  */
2284
2285 struct file_and_directory
2286 {
2287   /* The filename.  This is never NULL.  */
2288   const char *name;
2289
2290   /* The compilation directory.  NULL if not known.  If we needed to
2291      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2292      points directly to the DW_AT_comp_dir string attribute owned by
2293      the obstack that owns the DIE.  */
2294   const char *comp_dir;
2295
2296   /* If we needed to build a new string for comp_dir, this is what
2297      owns the storage.  */
2298   std::string comp_dir_storage;
2299 };
2300
2301 static file_and_directory find_file_and_directory (struct die_info *die,
2302                                                    struct dwarf2_cu *cu);
2303
2304 static char *file_full_name (int file, struct line_header *lh,
2305                              const char *comp_dir);
2306
2307 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2308 enum class rcuh_kind { COMPILE, TYPE };
2309
2310 static const gdb_byte *read_and_check_comp_unit_head
2311   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2312    struct comp_unit_head *header,
2313    struct dwarf2_section_info *section,
2314    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2315    rcuh_kind section_kind);
2316
2317 static void init_cutu_and_read_dies
2318   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2319    int use_existing_cu, int keep,
2320    die_reader_func_ftype *die_reader_func, void *data);
2321
2322 static void init_cutu_and_read_dies_simple
2323   (struct dwarf2_per_cu_data *this_cu,
2324    die_reader_func_ftype *die_reader_func, void *data);
2325
2326 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2327
2328 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2329
2330 static struct dwo_unit *lookup_dwo_unit_in_dwp
2331   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2332    struct dwp_file *dwp_file, const char *comp_dir,
2333    ULONGEST signature, int is_debug_types);
2334
2335 static struct dwp_file *get_dwp_file
2336   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2337
2338 static struct dwo_unit *lookup_dwo_comp_unit
2339   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2340
2341 static struct dwo_unit *lookup_dwo_type_unit
2342   (struct signatured_type *, const char *, const char *);
2343
2344 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2345
2346 static void free_dwo_file_cleanup (void *);
2347
2348 struct free_dwo_file_cleanup_data
2349 {
2350   struct dwo_file *dwo_file;
2351   struct dwarf2_per_objfile *dwarf2_per_objfile;
2352 };
2353
2354 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2355
2356 static void check_producer (struct dwarf2_cu *cu);
2357
2358 static void free_line_header_voidp (void *arg);
2359 \f
2360 /* Various complaints about symbol reading that don't abort the process.  */
2361
2362 static void
2363 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2364 {
2365   complaint (&symfile_complaints,
2366              _("statement list doesn't fit in .debug_line section"));
2367 }
2368
2369 static void
2370 dwarf2_debug_line_missing_file_complaint (void)
2371 {
2372   complaint (&symfile_complaints,
2373              _(".debug_line section has line data without a file"));
2374 }
2375
2376 static void
2377 dwarf2_debug_line_missing_end_sequence_complaint (void)
2378 {
2379   complaint (&symfile_complaints,
2380              _(".debug_line section has line "
2381                "program sequence without an end"));
2382 }
2383
2384 static void
2385 dwarf2_complex_location_expr_complaint (void)
2386 {
2387   complaint (&symfile_complaints, _("location expression too complex"));
2388 }
2389
2390 static void
2391 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2392                                               int arg3)
2393 {
2394   complaint (&symfile_complaints,
2395              _("const value length mismatch for '%s', got %d, expected %d"),
2396              arg1, arg2, arg3);
2397 }
2398
2399 static void
2400 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2401 {
2402   complaint (&symfile_complaints,
2403              _("debug info runs off end of %s section"
2404                " [in module %s]"),
2405              get_section_name (section),
2406              get_section_file_name (section));
2407 }
2408
2409 static void
2410 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2411 {
2412   complaint (&symfile_complaints,
2413              _("macro debug info contains a "
2414                "malformed macro definition:\n`%s'"),
2415              arg1);
2416 }
2417
2418 static void
2419 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2420 {
2421   complaint (&symfile_complaints,
2422              _("invalid attribute class or form for '%s' in '%s'"),
2423              arg1, arg2);
2424 }
2425
2426 /* Hash function for line_header_hash.  */
2427
2428 static hashval_t
2429 line_header_hash (const struct line_header *ofs)
2430 {
2431   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2432 }
2433
2434 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2435
2436 static hashval_t
2437 line_header_hash_voidp (const void *item)
2438 {
2439   const struct line_header *ofs = (const struct line_header *) item;
2440
2441   return line_header_hash (ofs);
2442 }
2443
2444 /* Equality function for line_header_hash.  */
2445
2446 static int
2447 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2448 {
2449   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2450   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2451
2452   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2453           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2454 }
2455
2456 \f
2457
2458 /* Read the given attribute value as an address, taking the attribute's
2459    form into account.  */
2460
2461 static CORE_ADDR
2462 attr_value_as_address (struct attribute *attr)
2463 {
2464   CORE_ADDR addr;
2465
2466   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2467     {
2468       /* Aside from a few clearly defined exceptions, attributes that
2469          contain an address must always be in DW_FORM_addr form.
2470          Unfortunately, some compilers happen to be violating this
2471          requirement by encoding addresses using other forms, such
2472          as DW_FORM_data4 for example.  For those broken compilers,
2473          we try to do our best, without any guarantee of success,
2474          to interpret the address correctly.  It would also be nice
2475          to generate a complaint, but that would require us to maintain
2476          a list of legitimate cases where a non-address form is allowed,
2477          as well as update callers to pass in at least the CU's DWARF
2478          version.  This is more overhead than what we're willing to
2479          expand for a pretty rare case.  */
2480       addr = DW_UNSND (attr);
2481     }
2482   else
2483     addr = DW_ADDR (attr);
2484
2485   return addr;
2486 }
2487
2488 /* The suffix for an index file.  */
2489 #define INDEX4_SUFFIX ".gdb-index"
2490 #define INDEX5_SUFFIX ".debug_names"
2491 #define DEBUG_STR_SUFFIX ".debug_str"
2492
2493 /* See declaration.  */
2494
2495 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2496                                         const dwarf2_debug_sections *names)
2497   : objfile (objfile_)
2498 {
2499   if (names == NULL)
2500     names = &dwarf2_elf_names;
2501
2502   bfd *obfd = objfile->obfd;
2503
2504   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2505     locate_sections (obfd, sec, *names);
2506 }
2507
2508 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2509
2510 dwarf2_per_objfile::~dwarf2_per_objfile ()
2511 {
2512   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2513   free_cached_comp_units ();
2514
2515   if (quick_file_names_table)
2516     htab_delete (quick_file_names_table);
2517
2518   if (line_header_hash)
2519     htab_delete (line_header_hash);
2520
2521   for (int ix = 0; ix < n_comp_units; ++ix)
2522    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2523
2524   for (int ix = 0; ix < n_type_units; ++ix)
2525     VEC_free (dwarf2_per_cu_ptr,
2526               all_type_units[ix]->per_cu.imported_symtabs);
2527   xfree (all_type_units);
2528
2529   VEC_free (dwarf2_section_info_def, types);
2530
2531   if (dwo_files != NULL)
2532     free_dwo_files (dwo_files, objfile);
2533   if (dwp_file != NULL)
2534     gdb_bfd_unref (dwp_file->dbfd);
2535
2536   if (dwz_file != NULL && dwz_file->dwz_bfd)
2537     gdb_bfd_unref (dwz_file->dwz_bfd);
2538
2539   if (index_table != NULL)
2540     index_table->~mapped_index ();
2541
2542   /* Everything else should be on the objfile obstack.  */
2543 }
2544
2545 /* See declaration.  */
2546
2547 void
2548 dwarf2_per_objfile::free_cached_comp_units ()
2549 {
2550   dwarf2_per_cu_data *per_cu = read_in_chain;
2551   dwarf2_per_cu_data **last_chain = &read_in_chain;
2552   while (per_cu != NULL)
2553     {
2554       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2555
2556       delete per_cu->cu;
2557       *last_chain = next_cu;
2558       per_cu = next_cu;
2559     }
2560 }
2561
2562 /* Try to locate the sections we need for DWARF 2 debugging
2563    information and return true if we have enough to do something.
2564    NAMES points to the dwarf2 section names, or is NULL if the standard
2565    ELF names are used.  */
2566
2567 int
2568 dwarf2_has_info (struct objfile *objfile,
2569                  const struct dwarf2_debug_sections *names)
2570 {
2571   if (objfile->flags & OBJF_READNEVER)
2572     return 0;
2573
2574   struct dwarf2_per_objfile *dwarf2_per_objfile
2575     = get_dwarf2_per_objfile (objfile);
2576
2577   if (dwarf2_per_objfile == NULL)
2578     {
2579       /* Initialize per-objfile state.  */
2580       dwarf2_per_objfile
2581         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2582                                                                      names);
2583       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2584     }
2585   return (!dwarf2_per_objfile->info.is_virtual
2586           && dwarf2_per_objfile->info.s.section != NULL
2587           && !dwarf2_per_objfile->abbrev.is_virtual
2588           && dwarf2_per_objfile->abbrev.s.section != NULL);
2589 }
2590
2591 /* Return the containing section of virtual section SECTION.  */
2592
2593 static struct dwarf2_section_info *
2594 get_containing_section (const struct dwarf2_section_info *section)
2595 {
2596   gdb_assert (section->is_virtual);
2597   return section->s.containing_section;
2598 }
2599
2600 /* Return the bfd owner of SECTION.  */
2601
2602 static struct bfd *
2603 get_section_bfd_owner (const struct dwarf2_section_info *section)
2604 {
2605   if (section->is_virtual)
2606     {
2607       section = get_containing_section (section);
2608       gdb_assert (!section->is_virtual);
2609     }
2610   return section->s.section->owner;
2611 }
2612
2613 /* Return the bfd section of SECTION.
2614    Returns NULL if the section is not present.  */
2615
2616 static asection *
2617 get_section_bfd_section (const struct dwarf2_section_info *section)
2618 {
2619   if (section->is_virtual)
2620     {
2621       section = get_containing_section (section);
2622       gdb_assert (!section->is_virtual);
2623     }
2624   return section->s.section;
2625 }
2626
2627 /* Return the name of SECTION.  */
2628
2629 static const char *
2630 get_section_name (const struct dwarf2_section_info *section)
2631 {
2632   asection *sectp = get_section_bfd_section (section);
2633
2634   gdb_assert (sectp != NULL);
2635   return bfd_section_name (get_section_bfd_owner (section), sectp);
2636 }
2637
2638 /* Return the name of the file SECTION is in.  */
2639
2640 static const char *
2641 get_section_file_name (const struct dwarf2_section_info *section)
2642 {
2643   bfd *abfd = get_section_bfd_owner (section);
2644
2645   return bfd_get_filename (abfd);
2646 }
2647
2648 /* Return the id of SECTION.
2649    Returns 0 if SECTION doesn't exist.  */
2650
2651 static int
2652 get_section_id (const struct dwarf2_section_info *section)
2653 {
2654   asection *sectp = get_section_bfd_section (section);
2655
2656   if (sectp == NULL)
2657     return 0;
2658   return sectp->id;
2659 }
2660
2661 /* Return the flags of SECTION.
2662    SECTION (or containing section if this is a virtual section) must exist.  */
2663
2664 static int
2665 get_section_flags (const struct dwarf2_section_info *section)
2666 {
2667   asection *sectp = get_section_bfd_section (section);
2668
2669   gdb_assert (sectp != NULL);
2670   return bfd_get_section_flags (sectp->owner, sectp);
2671 }
2672
2673 /* When loading sections, we look either for uncompressed section or for
2674    compressed section names.  */
2675
2676 static int
2677 section_is_p (const char *section_name,
2678               const struct dwarf2_section_names *names)
2679 {
2680   if (names->normal != NULL
2681       && strcmp (section_name, names->normal) == 0)
2682     return 1;
2683   if (names->compressed != NULL
2684       && strcmp (section_name, names->compressed) == 0)
2685     return 1;
2686   return 0;
2687 }
2688
2689 /* See declaration.  */
2690
2691 void
2692 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2693                                      const dwarf2_debug_sections &names)
2694 {
2695   flagword aflag = bfd_get_section_flags (abfd, sectp);
2696
2697   if ((aflag & SEC_HAS_CONTENTS) == 0)
2698     {
2699     }
2700   else if (section_is_p (sectp->name, &names.info))
2701     {
2702       this->info.s.section = sectp;
2703       this->info.size = bfd_get_section_size (sectp);
2704     }
2705   else if (section_is_p (sectp->name, &names.abbrev))
2706     {
2707       this->abbrev.s.section = sectp;
2708       this->abbrev.size = bfd_get_section_size (sectp);
2709     }
2710   else if (section_is_p (sectp->name, &names.line))
2711     {
2712       this->line.s.section = sectp;
2713       this->line.size = bfd_get_section_size (sectp);
2714     }
2715   else if (section_is_p (sectp->name, &names.loc))
2716     {
2717       this->loc.s.section = sectp;
2718       this->loc.size = bfd_get_section_size (sectp);
2719     }
2720   else if (section_is_p (sectp->name, &names.loclists))
2721     {
2722       this->loclists.s.section = sectp;
2723       this->loclists.size = bfd_get_section_size (sectp);
2724     }
2725   else if (section_is_p (sectp->name, &names.macinfo))
2726     {
2727       this->macinfo.s.section = sectp;
2728       this->macinfo.size = bfd_get_section_size (sectp);
2729     }
2730   else if (section_is_p (sectp->name, &names.macro))
2731     {
2732       this->macro.s.section = sectp;
2733       this->macro.size = bfd_get_section_size (sectp);
2734     }
2735   else if (section_is_p (sectp->name, &names.str))
2736     {
2737       this->str.s.section = sectp;
2738       this->str.size = bfd_get_section_size (sectp);
2739     }
2740   else if (section_is_p (sectp->name, &names.line_str))
2741     {
2742       this->line_str.s.section = sectp;
2743       this->line_str.size = bfd_get_section_size (sectp);
2744     }
2745   else if (section_is_p (sectp->name, &names.addr))
2746     {
2747       this->addr.s.section = sectp;
2748       this->addr.size = bfd_get_section_size (sectp);
2749     }
2750   else if (section_is_p (sectp->name, &names.frame))
2751     {
2752       this->frame.s.section = sectp;
2753       this->frame.size = bfd_get_section_size (sectp);
2754     }
2755   else if (section_is_p (sectp->name, &names.eh_frame))
2756     {
2757       this->eh_frame.s.section = sectp;
2758       this->eh_frame.size = bfd_get_section_size (sectp);
2759     }
2760   else if (section_is_p (sectp->name, &names.ranges))
2761     {
2762       this->ranges.s.section = sectp;
2763       this->ranges.size = bfd_get_section_size (sectp);
2764     }
2765   else if (section_is_p (sectp->name, &names.rnglists))
2766     {
2767       this->rnglists.s.section = sectp;
2768       this->rnglists.size = bfd_get_section_size (sectp);
2769     }
2770   else if (section_is_p (sectp->name, &names.types))
2771     {
2772       struct dwarf2_section_info type_section;
2773
2774       memset (&type_section, 0, sizeof (type_section));
2775       type_section.s.section = sectp;
2776       type_section.size = bfd_get_section_size (sectp);
2777
2778       VEC_safe_push (dwarf2_section_info_def, this->types,
2779                      &type_section);
2780     }
2781   else if (section_is_p (sectp->name, &names.gdb_index))
2782     {
2783       this->gdb_index.s.section = sectp;
2784       this->gdb_index.size = bfd_get_section_size (sectp);
2785     }
2786   else if (section_is_p (sectp->name, &names.debug_names))
2787     {
2788       this->debug_names.s.section = sectp;
2789       this->debug_names.size = bfd_get_section_size (sectp);
2790     }
2791   else if (section_is_p (sectp->name, &names.debug_aranges))
2792     {
2793       this->debug_aranges.s.section = sectp;
2794       this->debug_aranges.size = bfd_get_section_size (sectp);
2795     }
2796
2797   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2798       && bfd_section_vma (abfd, sectp) == 0)
2799     this->has_section_at_zero = true;
2800 }
2801
2802 /* A helper function that decides whether a section is empty,
2803    or not present.  */
2804
2805 static int
2806 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2807 {
2808   if (section->is_virtual)
2809     return section->size == 0;
2810   return section->s.section == NULL || section->size == 0;
2811 }
2812
2813 /* Read the contents of the section INFO.
2814    OBJFILE is the main object file, but not necessarily the file where
2815    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2816    of the DWO file.
2817    If the section is compressed, uncompress it before returning.  */
2818
2819 static void
2820 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2821 {
2822   asection *sectp;
2823   bfd *abfd;
2824   gdb_byte *buf, *retbuf;
2825
2826   if (info->readin)
2827     return;
2828   info->buffer = NULL;
2829   info->readin = 1;
2830
2831   if (dwarf2_section_empty_p (info))
2832     return;
2833
2834   sectp = get_section_bfd_section (info);
2835
2836   /* If this is a virtual section we need to read in the real one first.  */
2837   if (info->is_virtual)
2838     {
2839       struct dwarf2_section_info *containing_section =
2840         get_containing_section (info);
2841
2842       gdb_assert (sectp != NULL);
2843       if ((sectp->flags & SEC_RELOC) != 0)
2844         {
2845           error (_("Dwarf Error: DWP format V2 with relocations is not"
2846                    " supported in section %s [in module %s]"),
2847                  get_section_name (info), get_section_file_name (info));
2848         }
2849       dwarf2_read_section (objfile, containing_section);
2850       /* Other code should have already caught virtual sections that don't
2851          fit.  */
2852       gdb_assert (info->virtual_offset + info->size
2853                   <= containing_section->size);
2854       /* If the real section is empty or there was a problem reading the
2855          section we shouldn't get here.  */
2856       gdb_assert (containing_section->buffer != NULL);
2857       info->buffer = containing_section->buffer + info->virtual_offset;
2858       return;
2859     }
2860
2861   /* If the section has relocations, we must read it ourselves.
2862      Otherwise we attach it to the BFD.  */
2863   if ((sectp->flags & SEC_RELOC) == 0)
2864     {
2865       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2866       return;
2867     }
2868
2869   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2870   info->buffer = buf;
2871
2872   /* When debugging .o files, we may need to apply relocations; see
2873      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2874      We never compress sections in .o files, so we only need to
2875      try this when the section is not compressed.  */
2876   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2877   if (retbuf != NULL)
2878     {
2879       info->buffer = retbuf;
2880       return;
2881     }
2882
2883   abfd = get_section_bfd_owner (info);
2884   gdb_assert (abfd != NULL);
2885
2886   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2887       || bfd_bread (buf, info->size, abfd) != info->size)
2888     {
2889       error (_("Dwarf Error: Can't read DWARF data"
2890                " in section %s [in module %s]"),
2891              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2892     }
2893 }
2894
2895 /* A helper function that returns the size of a section in a safe way.
2896    If you are positive that the section has been read before using the
2897    size, then it is safe to refer to the dwarf2_section_info object's
2898    "size" field directly.  In other cases, you must call this
2899    function, because for compressed sections the size field is not set
2900    correctly until the section has been read.  */
2901
2902 static bfd_size_type
2903 dwarf2_section_size (struct objfile *objfile,
2904                      struct dwarf2_section_info *info)
2905 {
2906   if (!info->readin)
2907     dwarf2_read_section (objfile, info);
2908   return info->size;
2909 }
2910
2911 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2912    SECTION_NAME.  */
2913
2914 void
2915 dwarf2_get_section_info (struct objfile *objfile,
2916                          enum dwarf2_section_enum sect,
2917                          asection **sectp, const gdb_byte **bufp,
2918                          bfd_size_type *sizep)
2919 {
2920   struct dwarf2_per_objfile *data
2921     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2922                                                   dwarf2_objfile_data_key);
2923   struct dwarf2_section_info *info;
2924
2925   /* We may see an objfile without any DWARF, in which case we just
2926      return nothing.  */
2927   if (data == NULL)
2928     {
2929       *sectp = NULL;
2930       *bufp = NULL;
2931       *sizep = 0;
2932       return;
2933     }
2934   switch (sect)
2935     {
2936     case DWARF2_DEBUG_FRAME:
2937       info = &data->frame;
2938       break;
2939     case DWARF2_EH_FRAME:
2940       info = &data->eh_frame;
2941       break;
2942     default:
2943       gdb_assert_not_reached ("unexpected section");
2944     }
2945
2946   dwarf2_read_section (objfile, info);
2947
2948   *sectp = get_section_bfd_section (info);
2949   *bufp = info->buffer;
2950   *sizep = info->size;
2951 }
2952
2953 /* A helper function to find the sections for a .dwz file.  */
2954
2955 static void
2956 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2957 {
2958   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2959
2960   /* Note that we only support the standard ELF names, because .dwz
2961      is ELF-only (at the time of writing).  */
2962   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2963     {
2964       dwz_file->abbrev.s.section = sectp;
2965       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2966     }
2967   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2968     {
2969       dwz_file->info.s.section = sectp;
2970       dwz_file->info.size = bfd_get_section_size (sectp);
2971     }
2972   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2973     {
2974       dwz_file->str.s.section = sectp;
2975       dwz_file->str.size = bfd_get_section_size (sectp);
2976     }
2977   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2978     {
2979       dwz_file->line.s.section = sectp;
2980       dwz_file->line.size = bfd_get_section_size (sectp);
2981     }
2982   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2983     {
2984       dwz_file->macro.s.section = sectp;
2985       dwz_file->macro.size = bfd_get_section_size (sectp);
2986     }
2987   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2988     {
2989       dwz_file->gdb_index.s.section = sectp;
2990       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2991     }
2992   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2993     {
2994       dwz_file->debug_names.s.section = sectp;
2995       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2996     }
2997 }
2998
2999 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
3000    there is no .gnu_debugaltlink section in the file.  Error if there
3001    is such a section but the file cannot be found.  */
3002
3003 static struct dwz_file *
3004 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
3005 {
3006   const char *filename;
3007   struct dwz_file *result;
3008   bfd_size_type buildid_len_arg;
3009   size_t buildid_len;
3010   bfd_byte *buildid;
3011
3012   if (dwarf2_per_objfile->dwz_file != NULL)
3013     return dwarf2_per_objfile->dwz_file;
3014
3015   bfd_set_error (bfd_error_no_error);
3016   gdb::unique_xmalloc_ptr<char> data
3017     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
3018                                   &buildid_len_arg, &buildid));
3019   if (data == NULL)
3020     {
3021       if (bfd_get_error () == bfd_error_no_error)
3022         return NULL;
3023       error (_("could not read '.gnu_debugaltlink' section: %s"),
3024              bfd_errmsg (bfd_get_error ()));
3025     }
3026
3027   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
3028
3029   buildid_len = (size_t) buildid_len_arg;
3030
3031   filename = data.get ();
3032
3033   std::string abs_storage;
3034   if (!IS_ABSOLUTE_PATH (filename))
3035     {
3036       gdb::unique_xmalloc_ptr<char> abs
3037         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
3038
3039       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
3040       filename = abs_storage.c_str ();
3041     }
3042
3043   /* First try the file name given in the section.  If that doesn't
3044      work, try to use the build-id instead.  */
3045   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
3046   if (dwz_bfd != NULL)
3047     {
3048       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
3049         dwz_bfd.release ();
3050     }
3051
3052   if (dwz_bfd == NULL)
3053     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
3054
3055   if (dwz_bfd == NULL)
3056     error (_("could not find '.gnu_debugaltlink' file for %s"),
3057            objfile_name (dwarf2_per_objfile->objfile));
3058
3059   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
3060                            struct dwz_file);
3061   result->dwz_bfd = dwz_bfd.release ();
3062
3063   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
3064
3065   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
3066   dwarf2_per_objfile->dwz_file = result;
3067   return result;
3068 }
3069 \f
3070 /* DWARF quick_symbols_functions support.  */
3071
3072 /* TUs can share .debug_line entries, and there can be a lot more TUs than
3073    unique line tables, so we maintain a separate table of all .debug_line
3074    derived entries to support the sharing.
3075    All the quick functions need is the list of file names.  We discard the
3076    line_header when we're done and don't need to record it here.  */
3077 struct quick_file_names
3078 {
3079   /* The data used to construct the hash key.  */
3080   struct stmt_list_hash hash;
3081
3082   /* The number of entries in file_names, real_names.  */
3083   unsigned int num_file_names;
3084
3085   /* The file names from the line table, after being run through
3086      file_full_name.  */
3087   const char **file_names;
3088
3089   /* The file names from the line table after being run through
3090      gdb_realpath.  These are computed lazily.  */
3091   const char **real_names;
3092 };
3093
3094 /* When using the index (and thus not using psymtabs), each CU has an
3095    object of this type.  This is used to hold information needed by
3096    the various "quick" methods.  */
3097 struct dwarf2_per_cu_quick_data
3098 {
3099   /* The file table.  This can be NULL if there was no file table
3100      or it's currently not read in.
3101      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
3102   struct quick_file_names *file_names;
3103
3104   /* The corresponding symbol table.  This is NULL if symbols for this
3105      CU have not yet been read.  */
3106   struct compunit_symtab *compunit_symtab;
3107
3108   /* A temporary mark bit used when iterating over all CUs in
3109      expand_symtabs_matching.  */
3110   unsigned int mark : 1;
3111
3112   /* True if we've tried to read the file table and found there isn't one.
3113      There will be no point in trying to read it again next time.  */
3114   unsigned int no_file_data : 1;
3115 };
3116
3117 /* Utility hash function for a stmt_list_hash.  */
3118
3119 static hashval_t
3120 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3121 {
3122   hashval_t v = 0;
3123
3124   if (stmt_list_hash->dwo_unit != NULL)
3125     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3126   v += to_underlying (stmt_list_hash->line_sect_off);
3127   return v;
3128 }
3129
3130 /* Utility equality function for a stmt_list_hash.  */
3131
3132 static int
3133 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3134                     const struct stmt_list_hash *rhs)
3135 {
3136   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3137     return 0;
3138   if (lhs->dwo_unit != NULL
3139       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3140     return 0;
3141
3142   return lhs->line_sect_off == rhs->line_sect_off;
3143 }
3144
3145 /* Hash function for a quick_file_names.  */
3146
3147 static hashval_t
3148 hash_file_name_entry (const void *e)
3149 {
3150   const struct quick_file_names *file_data
3151     = (const struct quick_file_names *) e;
3152
3153   return hash_stmt_list_entry (&file_data->hash);
3154 }
3155
3156 /* Equality function for a quick_file_names.  */
3157
3158 static int
3159 eq_file_name_entry (const void *a, const void *b)
3160 {
3161   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3162   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3163
3164   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3165 }
3166
3167 /* Delete function for a quick_file_names.  */
3168
3169 static void
3170 delete_file_name_entry (void *e)
3171 {
3172   struct quick_file_names *file_data = (struct quick_file_names *) e;
3173   int i;
3174
3175   for (i = 0; i < file_data->num_file_names; ++i)
3176     {
3177       xfree ((void*) file_data->file_names[i]);
3178       if (file_data->real_names)
3179         xfree ((void*) file_data->real_names[i]);
3180     }
3181
3182   /* The space for the struct itself lives on objfile_obstack,
3183      so we don't free it here.  */
3184 }
3185
3186 /* Create a quick_file_names hash table.  */
3187
3188 static htab_t
3189 create_quick_file_names_table (unsigned int nr_initial_entries)
3190 {
3191   return htab_create_alloc (nr_initial_entries,
3192                             hash_file_name_entry, eq_file_name_entry,
3193                             delete_file_name_entry, xcalloc, xfree);
3194 }
3195
3196 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3197    have to be created afterwards.  You should call age_cached_comp_units after
3198    processing PER_CU->CU.  dw2_setup must have been already called.  */
3199
3200 static void
3201 load_cu (struct dwarf2_per_cu_data *per_cu)
3202 {
3203   if (per_cu->is_debug_types)
3204     load_full_type_unit (per_cu);
3205   else
3206     load_full_comp_unit (per_cu, language_minimal);
3207
3208   if (per_cu->cu == NULL)
3209     return;  /* Dummy CU.  */
3210
3211   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3212 }
3213
3214 /* Read in the symbols for PER_CU.  */
3215
3216 static void
3217 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3218 {
3219   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3220
3221   /* Skip type_unit_groups, reading the type units they contain
3222      is handled elsewhere.  */
3223   if (IS_TYPE_UNIT_GROUP (per_cu))
3224     return;
3225
3226   /* The destructor of dwarf2_queue_guard frees any entries left on
3227      the queue.  After this point we're guaranteed to leave this function
3228      with the dwarf queue empty.  */
3229   dwarf2_queue_guard q_guard;
3230
3231   if (dwarf2_per_objfile->using_index
3232       ? per_cu->v.quick->compunit_symtab == NULL
3233       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3234     {
3235       queue_comp_unit (per_cu, language_minimal);
3236       load_cu (per_cu);
3237
3238       /* If we just loaded a CU from a DWO, and we're working with an index
3239          that may badly handle TUs, load all the TUs in that DWO as well.
3240          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3241       if (!per_cu->is_debug_types
3242           && per_cu->cu != NULL
3243           && per_cu->cu->dwo_unit != NULL
3244           && dwarf2_per_objfile->index_table != NULL
3245           && dwarf2_per_objfile->index_table->version <= 7
3246           /* DWP files aren't supported yet.  */
3247           && get_dwp_file (dwarf2_per_objfile) == NULL)
3248         queue_and_load_all_dwo_tus (per_cu);
3249     }
3250
3251   process_queue (dwarf2_per_objfile);
3252
3253   /* Age the cache, releasing compilation units that have not
3254      been used recently.  */
3255   age_cached_comp_units (dwarf2_per_objfile);
3256 }
3257
3258 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3259    the objfile from which this CU came.  Returns the resulting symbol
3260    table.  */
3261
3262 static struct compunit_symtab *
3263 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3264 {
3265   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3266
3267   gdb_assert (dwarf2_per_objfile->using_index);
3268   if (!per_cu->v.quick->compunit_symtab)
3269     {
3270       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3271                                               dwarf2_per_objfile);
3272       scoped_restore decrementer = increment_reading_symtab ();
3273       dw2_do_instantiate_symtab (per_cu);
3274       process_cu_includes (dwarf2_per_objfile);
3275       do_cleanups (back_to);
3276     }
3277
3278   return per_cu->v.quick->compunit_symtab;
3279 }
3280
3281 /* Return the CU/TU given its index.
3282
3283    This is intended for loops like:
3284
3285    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3286                     + dwarf2_per_objfile->n_type_units); ++i)
3287      {
3288        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3289
3290        ...;
3291      }
3292 */
3293
3294 static struct dwarf2_per_cu_data *
3295 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3296               int index)
3297 {
3298   if (index >= dwarf2_per_objfile->n_comp_units)
3299     {
3300       index -= dwarf2_per_objfile->n_comp_units;
3301       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3302       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3303     }
3304
3305   return dwarf2_per_objfile->all_comp_units[index];
3306 }
3307
3308 /* Return the CU given its index.
3309    This differs from dw2_get_cutu in that it's for when you know INDEX
3310    refers to a CU.  */
3311
3312 static struct dwarf2_per_cu_data *
3313 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3314 {
3315   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3316
3317   return dwarf2_per_objfile->all_comp_units[index];
3318 }
3319
3320 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3321    objfile_obstack, and constructed with the specified field
3322    values.  */
3323
3324 static dwarf2_per_cu_data *
3325 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3326                           struct dwarf2_section_info *section,
3327                           int is_dwz,
3328                           sect_offset sect_off, ULONGEST length)
3329 {
3330   struct objfile *objfile = dwarf2_per_objfile->objfile;
3331   dwarf2_per_cu_data *the_cu
3332     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3333                      struct dwarf2_per_cu_data);
3334   the_cu->sect_off = sect_off;
3335   the_cu->length = length;
3336   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3337   the_cu->section = section;
3338   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3339                                    struct dwarf2_per_cu_quick_data);
3340   the_cu->is_dwz = is_dwz;
3341   return the_cu;
3342 }
3343
3344 /* A helper for create_cus_from_index that handles a given list of
3345    CUs.  */
3346
3347 static void
3348 create_cus_from_index_list (struct objfile *objfile,
3349                             const gdb_byte *cu_list, offset_type n_elements,
3350                             struct dwarf2_section_info *section,
3351                             int is_dwz,
3352                             int base_offset)
3353 {
3354   offset_type i;
3355   struct dwarf2_per_objfile *dwarf2_per_objfile
3356     = get_dwarf2_per_objfile (objfile);
3357
3358   for (i = 0; i < n_elements; i += 2)
3359     {
3360       gdb_static_assert (sizeof (ULONGEST) >= 8);
3361
3362       sect_offset sect_off
3363         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3364       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3365       cu_list += 2 * 8;
3366
3367       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3368         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3369                                      sect_off, length);
3370     }
3371 }
3372
3373 /* Read the CU list from the mapped index, and use it to create all
3374    the CU objects for this objfile.  */
3375
3376 static void
3377 create_cus_from_index (struct objfile *objfile,
3378                        const gdb_byte *cu_list, offset_type cu_list_elements,
3379                        const gdb_byte *dwz_list, offset_type dwz_elements)
3380 {
3381   struct dwz_file *dwz;
3382   struct dwarf2_per_objfile *dwarf2_per_objfile
3383     = get_dwarf2_per_objfile (objfile);
3384
3385   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3386   dwarf2_per_objfile->all_comp_units =
3387     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3388                dwarf2_per_objfile->n_comp_units);
3389
3390   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3391                               &dwarf2_per_objfile->info, 0, 0);
3392
3393   if (dwz_elements == 0)
3394     return;
3395
3396   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3397   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3398                               cu_list_elements / 2);
3399 }
3400
3401 /* Create the signatured type hash table from the index.  */
3402
3403 static void
3404 create_signatured_type_table_from_index (struct objfile *objfile,
3405                                          struct dwarf2_section_info *section,
3406                                          const gdb_byte *bytes,
3407                                          offset_type elements)
3408 {
3409   offset_type i;
3410   htab_t sig_types_hash;
3411   struct dwarf2_per_objfile *dwarf2_per_objfile
3412     = get_dwarf2_per_objfile (objfile);
3413
3414   dwarf2_per_objfile->n_type_units
3415     = dwarf2_per_objfile->n_allocated_type_units
3416     = elements / 3;
3417   dwarf2_per_objfile->all_type_units =
3418     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3419
3420   sig_types_hash = allocate_signatured_type_table (objfile);
3421
3422   for (i = 0; i < elements; i += 3)
3423     {
3424       struct signatured_type *sig_type;
3425       ULONGEST signature;
3426       void **slot;
3427       cu_offset type_offset_in_tu;
3428
3429       gdb_static_assert (sizeof (ULONGEST) >= 8);
3430       sect_offset sect_off
3431         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3432       type_offset_in_tu
3433         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3434                                                 BFD_ENDIAN_LITTLE);
3435       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3436       bytes += 3 * 8;
3437
3438       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3439                                  struct signatured_type);
3440       sig_type->signature = signature;
3441       sig_type->type_offset_in_tu = type_offset_in_tu;
3442       sig_type->per_cu.is_debug_types = 1;
3443       sig_type->per_cu.section = section;
3444       sig_type->per_cu.sect_off = sect_off;
3445       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3446       sig_type->per_cu.v.quick
3447         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3448                           struct dwarf2_per_cu_quick_data);
3449
3450       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3451       *slot = sig_type;
3452
3453       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3454     }
3455
3456   dwarf2_per_objfile->signatured_types = sig_types_hash;
3457 }
3458
3459 /* Create the signatured type hash table from .debug_names.  */
3460
3461 static void
3462 create_signatured_type_table_from_debug_names
3463   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3464    const mapped_debug_names &map,
3465    struct dwarf2_section_info *section,
3466    struct dwarf2_section_info *abbrev_section)
3467 {
3468   struct objfile *objfile = dwarf2_per_objfile->objfile;
3469
3470   dwarf2_read_section (objfile, section);
3471   dwarf2_read_section (objfile, abbrev_section);
3472
3473   dwarf2_per_objfile->n_type_units
3474     = dwarf2_per_objfile->n_allocated_type_units
3475     = map.tu_count;
3476   dwarf2_per_objfile->all_type_units
3477     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3478
3479   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3480
3481   for (uint32_t i = 0; i < map.tu_count; ++i)
3482     {
3483       struct signatured_type *sig_type;
3484       ULONGEST signature;
3485       void **slot;
3486       cu_offset type_offset_in_tu;
3487
3488       sect_offset sect_off
3489         = (sect_offset) (extract_unsigned_integer
3490                          (map.tu_table_reordered + i * map.offset_size,
3491                           map.offset_size,
3492                           map.dwarf5_byte_order));
3493
3494       comp_unit_head cu_header;
3495       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3496                                      abbrev_section,
3497                                      section->buffer + to_underlying (sect_off),
3498                                      rcuh_kind::TYPE);
3499
3500       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3501                                  struct signatured_type);
3502       sig_type->signature = cu_header.signature;
3503       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3504       sig_type->per_cu.is_debug_types = 1;
3505       sig_type->per_cu.section = section;
3506       sig_type->per_cu.sect_off = sect_off;
3507       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3508       sig_type->per_cu.v.quick
3509         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3510                           struct dwarf2_per_cu_quick_data);
3511
3512       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3513       *slot = sig_type;
3514
3515       dwarf2_per_objfile->all_type_units[i] = sig_type;
3516     }
3517
3518   dwarf2_per_objfile->signatured_types = sig_types_hash;
3519 }
3520
3521 /* Read the address map data from the mapped index, and use it to
3522    populate the objfile's psymtabs_addrmap.  */
3523
3524 static void
3525 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3526                            struct mapped_index *index)
3527 {
3528   struct objfile *objfile = dwarf2_per_objfile->objfile;
3529   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3530   const gdb_byte *iter, *end;
3531   struct addrmap *mutable_map;
3532   CORE_ADDR baseaddr;
3533
3534   auto_obstack temp_obstack;
3535
3536   mutable_map = addrmap_create_mutable (&temp_obstack);
3537
3538   iter = index->address_table.data ();
3539   end = iter + index->address_table.size ();
3540
3541   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3542
3543   while (iter < end)
3544     {
3545       ULONGEST hi, lo, cu_index;
3546       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3547       iter += 8;
3548       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3549       iter += 8;
3550       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3551       iter += 4;
3552
3553       if (lo > hi)
3554         {
3555           complaint (&symfile_complaints,
3556                      _(".gdb_index address table has invalid range (%s - %s)"),
3557                      hex_string (lo), hex_string (hi));
3558           continue;
3559         }
3560
3561       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3562         {
3563           complaint (&symfile_complaints,
3564                      _(".gdb_index address table has invalid CU number %u"),
3565                      (unsigned) cu_index);
3566           continue;
3567         }
3568
3569       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3570       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3571       addrmap_set_empty (mutable_map, lo, hi - 1,
3572                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3573     }
3574
3575   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3576                                                     &objfile->objfile_obstack);
3577 }
3578
3579 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3580    populate the objfile's psymtabs_addrmap.  */
3581
3582 static void
3583 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3584                              struct dwarf2_section_info *section)
3585 {
3586   struct objfile *objfile = dwarf2_per_objfile->objfile;
3587   bfd *abfd = objfile->obfd;
3588   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3589   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3590                                        SECT_OFF_TEXT (objfile));
3591
3592   auto_obstack temp_obstack;
3593   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3594
3595   std::unordered_map<sect_offset,
3596                      dwarf2_per_cu_data *,
3597                      gdb::hash_enum<sect_offset>>
3598     debug_info_offset_to_per_cu;
3599   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3600     {
3601       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3602       const auto insertpair
3603         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3604       if (!insertpair.second)
3605         {
3606           warning (_("Section .debug_aranges in %s has duplicate "
3607                      "debug_info_offset %s, ignoring .debug_aranges."),
3608                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3609           return;
3610         }
3611     }
3612
3613   dwarf2_read_section (objfile, section);
3614
3615   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3616
3617   const gdb_byte *addr = section->buffer;
3618
3619   while (addr < section->buffer + section->size)
3620     {
3621       const gdb_byte *const entry_addr = addr;
3622       unsigned int bytes_read;
3623
3624       const LONGEST entry_length = read_initial_length (abfd, addr,
3625                                                         &bytes_read);
3626       addr += bytes_read;
3627
3628       const gdb_byte *const entry_end = addr + entry_length;
3629       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3630       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3631       if (addr + entry_length > section->buffer + section->size)
3632         {
3633           warning (_("Section .debug_aranges in %s entry at offset %zu "
3634                      "length %s exceeds section length %s, "
3635                      "ignoring .debug_aranges."),
3636                    objfile_name (objfile), entry_addr - section->buffer,
3637                    plongest (bytes_read + entry_length),
3638                    pulongest (section->size));
3639           return;
3640         }
3641
3642       /* The version number.  */
3643       const uint16_t version = read_2_bytes (abfd, addr);
3644       addr += 2;
3645       if (version != 2)
3646         {
3647           warning (_("Section .debug_aranges in %s entry at offset %zu "
3648                      "has unsupported version %d, ignoring .debug_aranges."),
3649                    objfile_name (objfile), entry_addr - section->buffer,
3650                    version);
3651           return;
3652         }
3653
3654       const uint64_t debug_info_offset
3655         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3656       addr += offset_size;
3657       const auto per_cu_it
3658         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3659       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3660         {
3661           warning (_("Section .debug_aranges in %s entry at offset %zu "
3662                      "debug_info_offset %s does not exists, "
3663                      "ignoring .debug_aranges."),
3664                    objfile_name (objfile), entry_addr - section->buffer,
3665                    pulongest (debug_info_offset));
3666           return;
3667         }
3668       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3669
3670       const uint8_t address_size = *addr++;
3671       if (address_size < 1 || address_size > 8)
3672         {
3673           warning (_("Section .debug_aranges in %s entry at offset %zu "
3674                      "address_size %u is invalid, ignoring .debug_aranges."),
3675                    objfile_name (objfile), entry_addr - section->buffer,
3676                    address_size);
3677           return;
3678         }
3679
3680       const uint8_t segment_selector_size = *addr++;
3681       if (segment_selector_size != 0)
3682         {
3683           warning (_("Section .debug_aranges in %s entry at offset %zu "
3684                      "segment_selector_size %u is not supported, "
3685                      "ignoring .debug_aranges."),
3686                    objfile_name (objfile), entry_addr - section->buffer,
3687                    segment_selector_size);
3688           return;
3689         }
3690
3691       /* Must pad to an alignment boundary that is twice the address
3692          size.  It is undocumented by the DWARF standard but GCC does
3693          use it.  */
3694       for (size_t padding = ((-(addr - section->buffer))
3695                              & (2 * address_size - 1));
3696            padding > 0; padding--)
3697         if (*addr++ != 0)
3698           {
3699             warning (_("Section .debug_aranges in %s entry at offset %zu "
3700                        "padding is not zero, ignoring .debug_aranges."),
3701                      objfile_name (objfile), entry_addr - section->buffer);
3702             return;
3703           }
3704
3705       for (;;)
3706         {
3707           if (addr + 2 * address_size > entry_end)
3708             {
3709               warning (_("Section .debug_aranges in %s entry at offset %zu "
3710                          "address list is not properly terminated, "
3711                          "ignoring .debug_aranges."),
3712                        objfile_name (objfile), entry_addr - section->buffer);
3713               return;
3714             }
3715           ULONGEST start = extract_unsigned_integer (addr, address_size,
3716                                                      dwarf5_byte_order);
3717           addr += address_size;
3718           ULONGEST length = extract_unsigned_integer (addr, address_size,
3719                                                       dwarf5_byte_order);
3720           addr += address_size;
3721           if (start == 0 && length == 0)
3722             break;
3723           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3724             {
3725               /* Symbol was eliminated due to a COMDAT group.  */
3726               continue;
3727             }
3728           ULONGEST end = start + length;
3729           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3730           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3731           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3732         }
3733     }
3734
3735   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3736                                                     &objfile->objfile_obstack);
3737 }
3738
3739 /* The hash function for strings in the mapped index.  This is the same as
3740    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3741    implementation.  This is necessary because the hash function is tied to the
3742    format of the mapped index file.  The hash values do not have to match with
3743    SYMBOL_HASH_NEXT.
3744    
3745    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3746
3747 static hashval_t
3748 mapped_index_string_hash (int index_version, const void *p)
3749 {
3750   const unsigned char *str = (const unsigned char *) p;
3751   hashval_t r = 0;
3752   unsigned char c;
3753
3754   while ((c = *str++) != 0)
3755     {
3756       if (index_version >= 5)
3757         c = tolower (c);
3758       r = r * 67 + c - 113;
3759     }
3760
3761   return r;
3762 }
3763
3764 /* Find a slot in the mapped index INDEX for the object named NAME.
3765    If NAME is found, set *VEC_OUT to point to the CU vector in the
3766    constant pool and return true.  If NAME cannot be found, return
3767    false.  */
3768
3769 static bool
3770 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3771                           offset_type **vec_out)
3772 {
3773   offset_type hash;
3774   offset_type slot, step;
3775   int (*cmp) (const char *, const char *);
3776
3777   gdb::unique_xmalloc_ptr<char> without_params;
3778   if (current_language->la_language == language_cplus
3779       || current_language->la_language == language_fortran
3780       || current_language->la_language == language_d)
3781     {
3782       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3783          not contain any.  */
3784
3785       if (strchr (name, '(') != NULL)
3786         {
3787           without_params = cp_remove_params (name);
3788
3789           if (without_params != NULL)
3790             name = without_params.get ();
3791         }
3792     }
3793
3794   /* Index version 4 did not support case insensitive searches.  But the
3795      indices for case insensitive languages are built in lowercase, therefore
3796      simulate our NAME being searched is also lowercased.  */
3797   hash = mapped_index_string_hash ((index->version == 4
3798                                     && case_sensitivity == case_sensitive_off
3799                                     ? 5 : index->version),
3800                                    name);
3801
3802   slot = hash & (index->symbol_table.size () - 1);
3803   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3804   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3805
3806   for (;;)
3807     {
3808       const char *str;
3809
3810       const auto &bucket = index->symbol_table[slot];
3811       if (bucket.name == 0 && bucket.vec == 0)
3812         return false;
3813
3814       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3815       if (!cmp (name, str))
3816         {
3817           *vec_out = (offset_type *) (index->constant_pool
3818                                       + MAYBE_SWAP (bucket.vec));
3819           return true;
3820         }
3821
3822       slot = (slot + step) & (index->symbol_table.size () - 1);
3823     }
3824 }
3825
3826 /* A helper function that reads the .gdb_index from SECTION and fills
3827    in MAP.  FILENAME is the name of the file containing the section;
3828    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3829    ok to use deprecated sections.
3830
3831    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3832    out parameters that are filled in with information about the CU and
3833    TU lists in the section.
3834
3835    Returns 1 if all went well, 0 otherwise.  */
3836
3837 static int
3838 read_index_from_section (struct objfile *objfile,
3839                          const char *filename,
3840                          int deprecated_ok,
3841                          struct dwarf2_section_info *section,
3842                          struct mapped_index *map,
3843                          const gdb_byte **cu_list,
3844                          offset_type *cu_list_elements,
3845                          const gdb_byte **types_list,
3846                          offset_type *types_list_elements)
3847 {
3848   const gdb_byte *addr;
3849   offset_type version;
3850   offset_type *metadata;
3851   int i;
3852
3853   if (dwarf2_section_empty_p (section))
3854     return 0;
3855
3856   /* Older elfutils strip versions could keep the section in the main
3857      executable while splitting it for the separate debug info file.  */
3858   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3859     return 0;
3860
3861   dwarf2_read_section (objfile, section);
3862
3863   addr = section->buffer;
3864   /* Version check.  */
3865   version = MAYBE_SWAP (*(offset_type *) addr);
3866   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3867      causes the index to behave very poorly for certain requests.  Version 3
3868      contained incomplete addrmap.  So, it seems better to just ignore such
3869      indices.  */
3870   if (version < 4)
3871     {
3872       static int warning_printed = 0;
3873       if (!warning_printed)
3874         {
3875           warning (_("Skipping obsolete .gdb_index section in %s."),
3876                    filename);
3877           warning_printed = 1;
3878         }
3879       return 0;
3880     }
3881   /* Index version 4 uses a different hash function than index version
3882      5 and later.
3883
3884      Versions earlier than 6 did not emit psymbols for inlined
3885      functions.  Using these files will cause GDB not to be able to
3886      set breakpoints on inlined functions by name, so we ignore these
3887      indices unless the user has done
3888      "set use-deprecated-index-sections on".  */
3889   if (version < 6 && !deprecated_ok)
3890     {
3891       static int warning_printed = 0;
3892       if (!warning_printed)
3893         {
3894           warning (_("\
3895 Skipping deprecated .gdb_index section in %s.\n\
3896 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3897 to use the section anyway."),
3898                    filename);
3899           warning_printed = 1;
3900         }
3901       return 0;
3902     }
3903   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3904      of the TU (for symbols coming from TUs),
3905      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3906      Plus gold-generated indices can have duplicate entries for global symbols,
3907      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3908      These are just performance bugs, and we can't distinguish gdb-generated
3909      indices from gold-generated ones, so issue no warning here.  */
3910
3911   /* Indexes with higher version than the one supported by GDB may be no
3912      longer backward compatible.  */
3913   if (version > 8)
3914     return 0;
3915
3916   map->version = version;
3917   map->total_size = section->size;
3918
3919   metadata = (offset_type *) (addr + sizeof (offset_type));
3920
3921   i = 0;
3922   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3923   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3924                        / 8);
3925   ++i;
3926
3927   *types_list = addr + MAYBE_SWAP (metadata[i]);
3928   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3929                            - MAYBE_SWAP (metadata[i]))
3930                           / 8);
3931   ++i;
3932
3933   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3934   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3935   map->address_table
3936     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3937   ++i;
3938
3939   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3940   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3941   map->symbol_table
3942     = gdb::array_view<mapped_index::symbol_table_slot>
3943        ((mapped_index::symbol_table_slot *) symbol_table,
3944         (mapped_index::symbol_table_slot *) symbol_table_end);
3945
3946   ++i;
3947   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3948
3949   return 1;
3950 }
3951
3952 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3953    elements of all the CUs and return 1.  Otherwise, return 0.  */
3954
3955 static int
3956 dwarf2_read_index (struct objfile *objfile)
3957 {
3958   struct mapped_index local_map, *map;
3959   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3960   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3961   struct dwz_file *dwz;
3962   struct dwarf2_per_objfile *dwarf2_per_objfile
3963     = get_dwarf2_per_objfile (objfile);
3964
3965   if (!read_index_from_section (objfile, objfile_name (objfile),
3966                                 use_deprecated_index_sections,
3967                                 &dwarf2_per_objfile->gdb_index, &local_map,
3968                                 &cu_list, &cu_list_elements,
3969                                 &types_list, &types_list_elements))
3970     return 0;
3971
3972   /* Don't use the index if it's empty.  */
3973   if (local_map.symbol_table.empty ())
3974     return 0;
3975
3976   /* If there is a .dwz file, read it so we can get its CU list as
3977      well.  */
3978   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3979   if (dwz != NULL)
3980     {
3981       struct mapped_index dwz_map;
3982       const gdb_byte *dwz_types_ignore;
3983       offset_type dwz_types_elements_ignore;
3984
3985       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3986                                     1,
3987                                     &dwz->gdb_index, &dwz_map,
3988                                     &dwz_list, &dwz_list_elements,
3989                                     &dwz_types_ignore,
3990                                     &dwz_types_elements_ignore))
3991         {
3992           warning (_("could not read '.gdb_index' section from %s; skipping"),
3993                    bfd_get_filename (dwz->dwz_bfd));
3994           return 0;
3995         }
3996     }
3997
3998   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3999                          dwz_list_elements);
4000
4001   if (types_list_elements)
4002     {
4003       struct dwarf2_section_info *section;
4004
4005       /* We can only handle a single .debug_types when we have an
4006          index.  */
4007       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
4008         return 0;
4009
4010       section = VEC_index (dwarf2_section_info_def,
4011                            dwarf2_per_objfile->types, 0);
4012
4013       create_signatured_type_table_from_index (objfile, section, types_list,
4014                                                types_list_elements);
4015     }
4016
4017   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
4018
4019   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
4020   map = new (map) mapped_index ();
4021   *map = local_map;
4022
4023   dwarf2_per_objfile->index_table = map;
4024   dwarf2_per_objfile->using_index = 1;
4025   dwarf2_per_objfile->quick_file_names_table =
4026     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4027
4028   return 1;
4029 }
4030
4031 /* die_reader_func for dw2_get_file_names.  */
4032
4033 static void
4034 dw2_get_file_names_reader (const struct die_reader_specs *reader,
4035                            const gdb_byte *info_ptr,
4036                            struct die_info *comp_unit_die,
4037                            int has_children,
4038                            void *data)
4039 {
4040   struct dwarf2_cu *cu = reader->cu;
4041   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
4042   struct dwarf2_per_objfile *dwarf2_per_objfile
4043     = cu->per_cu->dwarf2_per_objfile;
4044   struct objfile *objfile = dwarf2_per_objfile->objfile;
4045   struct dwarf2_per_cu_data *lh_cu;
4046   struct attribute *attr;
4047   int i;
4048   void **slot;
4049   struct quick_file_names *qfn;
4050
4051   gdb_assert (! this_cu->is_debug_types);
4052
4053   /* Our callers never want to match partial units -- instead they
4054      will match the enclosing full CU.  */
4055   if (comp_unit_die->tag == DW_TAG_partial_unit)
4056     {
4057       this_cu->v.quick->no_file_data = 1;
4058       return;
4059     }
4060
4061   lh_cu = this_cu;
4062   slot = NULL;
4063
4064   line_header_up lh;
4065   sect_offset line_offset {};
4066
4067   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4068   if (attr)
4069     {
4070       struct quick_file_names find_entry;
4071
4072       line_offset = (sect_offset) DW_UNSND (attr);
4073
4074       /* We may have already read in this line header (TU line header sharing).
4075          If we have we're done.  */
4076       find_entry.hash.dwo_unit = cu->dwo_unit;
4077       find_entry.hash.line_sect_off = line_offset;
4078       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
4079                              &find_entry, INSERT);
4080       if (*slot != NULL)
4081         {
4082           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
4083           return;
4084         }
4085
4086       lh = dwarf_decode_line_header (line_offset, cu);
4087     }
4088   if (lh == NULL)
4089     {
4090       lh_cu->v.quick->no_file_data = 1;
4091       return;
4092     }
4093
4094   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
4095   qfn->hash.dwo_unit = cu->dwo_unit;
4096   qfn->hash.line_sect_off = line_offset;
4097   gdb_assert (slot != NULL);
4098   *slot = qfn;
4099
4100   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
4101
4102   qfn->num_file_names = lh->file_names.size ();
4103   qfn->file_names =
4104     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4105   for (i = 0; i < lh->file_names.size (); ++i)
4106     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4107   qfn->real_names = NULL;
4108
4109   lh_cu->v.quick->file_names = qfn;
4110 }
4111
4112 /* A helper for the "quick" functions which attempts to read the line
4113    table for THIS_CU.  */
4114
4115 static struct quick_file_names *
4116 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4117 {
4118   /* This should never be called for TUs.  */
4119   gdb_assert (! this_cu->is_debug_types);
4120   /* Nor type unit groups.  */
4121   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4122
4123   if (this_cu->v.quick->file_names != NULL)
4124     return this_cu->v.quick->file_names;
4125   /* If we know there is no line data, no point in looking again.  */
4126   if (this_cu->v.quick->no_file_data)
4127     return NULL;
4128
4129   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4130
4131   if (this_cu->v.quick->no_file_data)
4132     return NULL;
4133   return this_cu->v.quick->file_names;
4134 }
4135
4136 /* A helper for the "quick" functions which computes and caches the
4137    real path for a given file name from the line table.  */
4138
4139 static const char *
4140 dw2_get_real_path (struct objfile *objfile,
4141                    struct quick_file_names *qfn, int index)
4142 {
4143   if (qfn->real_names == NULL)
4144     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4145                                       qfn->num_file_names, const char *);
4146
4147   if (qfn->real_names[index] == NULL)
4148     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4149
4150   return qfn->real_names[index];
4151 }
4152
4153 static struct symtab *
4154 dw2_find_last_source_symtab (struct objfile *objfile)
4155 {
4156   struct dwarf2_per_objfile *dwarf2_per_objfile
4157     = get_dwarf2_per_objfile (objfile);
4158   int index = dwarf2_per_objfile->n_comp_units - 1;
4159   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4160   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4161
4162   if (cust == NULL)
4163     return NULL;
4164
4165   return compunit_primary_filetab (cust);
4166 }
4167
4168 /* Traversal function for dw2_forget_cached_source_info.  */
4169
4170 static int
4171 dw2_free_cached_file_names (void **slot, void *info)
4172 {
4173   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4174
4175   if (file_data->real_names)
4176     {
4177       int i;
4178
4179       for (i = 0; i < file_data->num_file_names; ++i)
4180         {
4181           xfree ((void*) file_data->real_names[i]);
4182           file_data->real_names[i] = NULL;
4183         }
4184     }
4185
4186   return 1;
4187 }
4188
4189 static void
4190 dw2_forget_cached_source_info (struct objfile *objfile)
4191 {
4192   struct dwarf2_per_objfile *dwarf2_per_objfile
4193     = get_dwarf2_per_objfile (objfile);
4194
4195   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4196                           dw2_free_cached_file_names, NULL);
4197 }
4198
4199 /* Helper function for dw2_map_symtabs_matching_filename that expands
4200    the symtabs and calls the iterator.  */
4201
4202 static int
4203 dw2_map_expand_apply (struct objfile *objfile,
4204                       struct dwarf2_per_cu_data *per_cu,
4205                       const char *name, const char *real_path,
4206                       gdb::function_view<bool (symtab *)> callback)
4207 {
4208   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4209
4210   /* Don't visit already-expanded CUs.  */
4211   if (per_cu->v.quick->compunit_symtab)
4212     return 0;
4213
4214   /* This may expand more than one symtab, and we want to iterate over
4215      all of them.  */
4216   dw2_instantiate_symtab (per_cu);
4217
4218   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4219                                     last_made, callback);
4220 }
4221
4222 /* Implementation of the map_symtabs_matching_filename method.  */
4223
4224 static bool
4225 dw2_map_symtabs_matching_filename
4226   (struct objfile *objfile, const char *name, const char *real_path,
4227    gdb::function_view<bool (symtab *)> callback)
4228 {
4229   int i;
4230   const char *name_basename = lbasename (name);
4231   struct dwarf2_per_objfile *dwarf2_per_objfile
4232     = get_dwarf2_per_objfile (objfile);
4233
4234   /* The rule is CUs specify all the files, including those used by
4235      any TU, so there's no need to scan TUs here.  */
4236
4237   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4238     {
4239       int j;
4240       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4241       struct quick_file_names *file_data;
4242
4243       /* We only need to look at symtabs not already expanded.  */
4244       if (per_cu->v.quick->compunit_symtab)
4245         continue;
4246
4247       file_data = dw2_get_file_names (per_cu);
4248       if (file_data == NULL)
4249         continue;
4250
4251       for (j = 0; j < file_data->num_file_names; ++j)
4252         {
4253           const char *this_name = file_data->file_names[j];
4254           const char *this_real_name;
4255
4256           if (compare_filenames_for_search (this_name, name))
4257             {
4258               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4259                                         callback))
4260                 return true;
4261               continue;
4262             }
4263
4264           /* Before we invoke realpath, which can get expensive when many
4265              files are involved, do a quick comparison of the basenames.  */
4266           if (! basenames_may_differ
4267               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4268             continue;
4269
4270           this_real_name = dw2_get_real_path (objfile, file_data, j);
4271           if (compare_filenames_for_search (this_real_name, name))
4272             {
4273               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4274                                         callback))
4275                 return true;
4276               continue;
4277             }
4278
4279           if (real_path != NULL)
4280             {
4281               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4282               gdb_assert (IS_ABSOLUTE_PATH (name));
4283               if (this_real_name != NULL
4284                   && FILENAME_CMP (real_path, this_real_name) == 0)
4285                 {
4286                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4287                                             callback))
4288                     return true;
4289                   continue;
4290                 }
4291             }
4292         }
4293     }
4294
4295   return false;
4296 }
4297
4298 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4299
4300 struct dw2_symtab_iterator
4301 {
4302   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4303   struct dwarf2_per_objfile *dwarf2_per_objfile;
4304   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4305   int want_specific_block;
4306   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4307      Unused if !WANT_SPECIFIC_BLOCK.  */
4308   int block_index;
4309   /* The kind of symbol we're looking for.  */
4310   domain_enum domain;
4311   /* The list of CUs from the index entry of the symbol,
4312      or NULL if not found.  */
4313   offset_type *vec;
4314   /* The next element in VEC to look at.  */
4315   int next;
4316   /* The number of elements in VEC, or zero if there is no match.  */
4317   int length;
4318   /* Have we seen a global version of the symbol?
4319      If so we can ignore all further global instances.
4320      This is to work around gold/15646, inefficient gold-generated
4321      indices.  */
4322   int global_seen;
4323 };
4324
4325 /* Initialize the index symtab iterator ITER.
4326    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4327    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4328
4329 static void
4330 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4331                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4332                       int want_specific_block,
4333                       int block_index,
4334                       domain_enum domain,
4335                       const char *name)
4336 {
4337   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4338   iter->want_specific_block = want_specific_block;
4339   iter->block_index = block_index;
4340   iter->domain = domain;
4341   iter->next = 0;
4342   iter->global_seen = 0;
4343
4344   mapped_index *index = dwarf2_per_objfile->index_table;
4345
4346   /* index is NULL if OBJF_READNOW.  */
4347   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4348     iter->length = MAYBE_SWAP (*iter->vec);
4349   else
4350     {
4351       iter->vec = NULL;
4352       iter->length = 0;
4353     }
4354 }
4355
4356 /* Return the next matching CU or NULL if there are no more.  */
4357
4358 static struct dwarf2_per_cu_data *
4359 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4360 {
4361   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4362
4363   for ( ; iter->next < iter->length; ++iter->next)
4364     {
4365       offset_type cu_index_and_attrs =
4366         MAYBE_SWAP (iter->vec[iter->next + 1]);
4367       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4368       struct dwarf2_per_cu_data *per_cu;
4369       int want_static = iter->block_index != GLOBAL_BLOCK;
4370       /* This value is only valid for index versions >= 7.  */
4371       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4372       gdb_index_symbol_kind symbol_kind =
4373         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4374       /* Only check the symbol attributes if they're present.
4375          Indices prior to version 7 don't record them,
4376          and indices >= 7 may elide them for certain symbols
4377          (gold does this).  */
4378       int attrs_valid =
4379         (dwarf2_per_objfile->index_table->version >= 7
4380          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4381
4382       /* Don't crash on bad data.  */
4383       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4384                        + dwarf2_per_objfile->n_type_units))
4385         {
4386           complaint (&symfile_complaints,
4387                      _(".gdb_index entry has bad CU index"
4388                        " [in module %s]"),
4389                      objfile_name (dwarf2_per_objfile->objfile));
4390           continue;
4391         }
4392
4393       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4394
4395       /* Skip if already read in.  */
4396       if (per_cu->v.quick->compunit_symtab)
4397         continue;
4398
4399       /* Check static vs global.  */
4400       if (attrs_valid)
4401         {
4402           if (iter->want_specific_block
4403               && want_static != is_static)
4404             continue;
4405           /* Work around gold/15646.  */
4406           if (!is_static && iter->global_seen)
4407             continue;
4408           if (!is_static)
4409             iter->global_seen = 1;
4410         }
4411
4412       /* Only check the symbol's kind if it has one.  */
4413       if (attrs_valid)
4414         {
4415           switch (iter->domain)
4416             {
4417             case VAR_DOMAIN:
4418               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4419                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4420                   /* Some types are also in VAR_DOMAIN.  */
4421                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4422                 continue;
4423               break;
4424             case STRUCT_DOMAIN:
4425               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4426                 continue;
4427               break;
4428             case LABEL_DOMAIN:
4429               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4430                 continue;
4431               break;
4432             default:
4433               break;
4434             }
4435         }
4436
4437       ++iter->next;
4438       return per_cu;
4439     }
4440
4441   return NULL;
4442 }
4443
4444 static struct compunit_symtab *
4445 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4446                    const char *name, domain_enum domain)
4447 {
4448   struct compunit_symtab *stab_best = NULL;
4449   struct dwarf2_per_objfile *dwarf2_per_objfile
4450     = get_dwarf2_per_objfile (objfile);
4451
4452   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4453
4454   struct dw2_symtab_iterator iter;
4455   struct dwarf2_per_cu_data *per_cu;
4456
4457   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4458
4459   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4460     {
4461       struct symbol *sym, *with_opaque = NULL;
4462       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4463       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4464       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4465
4466       sym = block_find_symbol (block, name, domain,
4467                                block_find_non_opaque_type_preferred,
4468                                &with_opaque);
4469
4470       /* Some caution must be observed with overloaded functions
4471          and methods, since the index will not contain any overload
4472          information (but NAME might contain it).  */
4473
4474       if (sym != NULL
4475           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4476         return stab;
4477       if (with_opaque != NULL
4478           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4479         stab_best = stab;
4480
4481       /* Keep looking through other CUs.  */
4482     }
4483
4484   return stab_best;
4485 }
4486
4487 static void
4488 dw2_print_stats (struct objfile *objfile)
4489 {
4490   struct dwarf2_per_objfile *dwarf2_per_objfile
4491     = get_dwarf2_per_objfile (objfile);
4492   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4493   int count = 0;
4494
4495   for (int i = 0; i < total; ++i)
4496     {
4497       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4498
4499       if (!per_cu->v.quick->compunit_symtab)
4500         ++count;
4501     }
4502   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4503   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4504 }
4505
4506 /* This dumps minimal information about the index.
4507    It is called via "mt print objfiles".
4508    One use is to verify .gdb_index has been loaded by the
4509    gdb.dwarf2/gdb-index.exp testcase.  */
4510
4511 static void
4512 dw2_dump (struct objfile *objfile)
4513 {
4514   struct dwarf2_per_objfile *dwarf2_per_objfile
4515     = get_dwarf2_per_objfile (objfile);
4516
4517   gdb_assert (dwarf2_per_objfile->using_index);
4518   printf_filtered (".gdb_index:");
4519   if (dwarf2_per_objfile->index_table != NULL)
4520     {
4521       printf_filtered (" version %d\n",
4522                        dwarf2_per_objfile->index_table->version);
4523     }
4524   else
4525     printf_filtered (" faked for \"readnow\"\n");
4526   printf_filtered ("\n");
4527 }
4528
4529 static void
4530 dw2_relocate (struct objfile *objfile,
4531               const struct section_offsets *new_offsets,
4532               const struct section_offsets *delta)
4533 {
4534   /* There's nothing to relocate here.  */
4535 }
4536
4537 static void
4538 dw2_expand_symtabs_for_function (struct objfile *objfile,
4539                                  const char *func_name)
4540 {
4541   struct dwarf2_per_objfile *dwarf2_per_objfile
4542     = get_dwarf2_per_objfile (objfile);
4543
4544   struct dw2_symtab_iterator iter;
4545   struct dwarf2_per_cu_data *per_cu;
4546
4547   /* Note: It doesn't matter what we pass for block_index here.  */
4548   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4549                         func_name);
4550
4551   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4552     dw2_instantiate_symtab (per_cu);
4553
4554 }
4555
4556 static void
4557 dw2_expand_all_symtabs (struct objfile *objfile)
4558 {
4559   struct dwarf2_per_objfile *dwarf2_per_objfile
4560     = get_dwarf2_per_objfile (objfile);
4561   int total_units = (dwarf2_per_objfile->n_comp_units
4562                      + dwarf2_per_objfile->n_type_units);
4563
4564   for (int i = 0; i < total_units; ++i)
4565     {
4566       struct dwarf2_per_cu_data *per_cu
4567         = dw2_get_cutu (dwarf2_per_objfile, i);
4568
4569       dw2_instantiate_symtab (per_cu);
4570     }
4571 }
4572
4573 static void
4574 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4575                                   const char *fullname)
4576 {
4577   struct dwarf2_per_objfile *dwarf2_per_objfile
4578     = get_dwarf2_per_objfile (objfile);
4579
4580   /* We don't need to consider type units here.
4581      This is only called for examining code, e.g. expand_line_sal.
4582      There can be an order of magnitude (or more) more type units
4583      than comp units, and we avoid them if we can.  */
4584
4585   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4586     {
4587       int j;
4588       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4589       struct quick_file_names *file_data;
4590
4591       /* We only need to look at symtabs not already expanded.  */
4592       if (per_cu->v.quick->compunit_symtab)
4593         continue;
4594
4595       file_data = dw2_get_file_names (per_cu);
4596       if (file_data == NULL)
4597         continue;
4598
4599       for (j = 0; j < file_data->num_file_names; ++j)
4600         {
4601           const char *this_fullname = file_data->file_names[j];
4602
4603           if (filename_cmp (this_fullname, fullname) == 0)
4604             {
4605               dw2_instantiate_symtab (per_cu);
4606               break;
4607             }
4608         }
4609     }
4610 }
4611
4612 static void
4613 dw2_map_matching_symbols (struct objfile *objfile,
4614                           const char * name, domain_enum domain,
4615                           int global,
4616                           int (*callback) (struct block *,
4617                                            struct symbol *, void *),
4618                           void *data, symbol_name_match_type match,
4619                           symbol_compare_ftype *ordered_compare)
4620 {
4621   /* Currently unimplemented; used for Ada.  The function can be called if the
4622      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4623      does not look for non-Ada symbols this function should just return.  */
4624 }
4625
4626 /* Symbol name matcher for .gdb_index names.
4627
4628    Symbol names in .gdb_index have a few particularities:
4629
4630    - There's no indication of which is the language of each symbol.
4631
4632      Since each language has its own symbol name matching algorithm,
4633      and we don't know which language is the right one, we must match
4634      each symbol against all languages.  This would be a potential
4635      performance problem if it were not mitigated by the
4636      mapped_index::name_components lookup table, which significantly
4637      reduces the number of times we need to call into this matcher,
4638      making it a non-issue.
4639
4640    - Symbol names in the index have no overload (parameter)
4641      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4642      appear as "foo" in the index, for example.
4643
4644      This means that the lookup names passed to the symbol name
4645      matcher functions must have no parameter information either
4646      because (e.g.) symbol search name "foo" does not match
4647      lookup-name "foo(int)" [while swapping search name for lookup
4648      name would match].
4649 */
4650 class gdb_index_symbol_name_matcher
4651 {
4652 public:
4653   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4654   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4655
4656   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4657      Returns true if any matcher matches.  */
4658   bool matches (const char *symbol_name);
4659
4660 private:
4661   /* A reference to the lookup name we're matching against.  */
4662   const lookup_name_info &m_lookup_name;
4663
4664   /* A vector holding all the different symbol name matchers, for all
4665      languages.  */
4666   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4667 };
4668
4669 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4670   (const lookup_name_info &lookup_name)
4671     : m_lookup_name (lookup_name)
4672 {
4673   /* Prepare the vector of comparison functions upfront, to avoid
4674      doing the same work for each symbol.  Care is taken to avoid
4675      matching with the same matcher more than once if/when multiple
4676      languages use the same matcher function.  */
4677   auto &matchers = m_symbol_name_matcher_funcs;
4678   matchers.reserve (nr_languages);
4679
4680   matchers.push_back (default_symbol_name_matcher);
4681
4682   for (int i = 0; i < nr_languages; i++)
4683     {
4684       const language_defn *lang = language_def ((enum language) i);
4685       symbol_name_matcher_ftype *name_matcher
4686         = get_symbol_name_matcher (lang, m_lookup_name);
4687
4688       /* Don't insert the same comparison routine more than once.
4689          Note that we do this linear walk instead of a seemingly
4690          cheaper sorted insert, or use a std::set or something like
4691          that, because relative order of function addresses is not
4692          stable.  This is not a problem in practice because the number
4693          of supported languages is low, and the cost here is tiny
4694          compared to the number of searches we'll do afterwards using
4695          this object.  */
4696       if (name_matcher != default_symbol_name_matcher
4697           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4698               == matchers.end ()))
4699         matchers.push_back (name_matcher);
4700     }
4701 }
4702
4703 bool
4704 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4705 {
4706   for (auto matches_name : m_symbol_name_matcher_funcs)
4707     if (matches_name (symbol_name, m_lookup_name, NULL))
4708       return true;
4709
4710   return false;
4711 }
4712
4713 /* Starting from a search name, return the string that finds the upper
4714    bound of all strings that start with SEARCH_NAME in a sorted name
4715    list.  Returns the empty string to indicate that the upper bound is
4716    the end of the list.  */
4717
4718 static std::string
4719 make_sort_after_prefix_name (const char *search_name)
4720 {
4721   /* When looking to complete "func", we find the upper bound of all
4722      symbols that start with "func" by looking for where we'd insert
4723      the closest string that would follow "func" in lexicographical
4724      order.  Usually, that's "func"-with-last-character-incremented,
4725      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4726      will be UTF-8 multi-byte sequences, but we can't be certain.
4727      Especially mind the 0xff character, which is a valid character in
4728      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4729      rule out compilers allowing it in identifiers.  Note that
4730      conveniently, strcmp/strcasecmp are specified to compare
4731      characters interpreted as unsigned char.  So what we do is treat
4732      the whole string as a base 256 number composed of a sequence of
4733      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4734      to 0, and carries 1 to the following more-significant position.
4735      If the very first character in SEARCH_NAME ends up incremented
4736      and carries/overflows, then the upper bound is the end of the
4737      list.  The string after the empty string is also the empty
4738      string.
4739
4740      Some examples of this operation:
4741
4742        SEARCH_NAME  => "+1" RESULT
4743
4744        "abc"              => "abd"
4745        "ab\xff"           => "ac"
4746        "\xff" "a" "\xff"  => "\xff" "b"
4747        "\xff"             => ""
4748        "\xff\xff"         => ""
4749        ""                 => ""
4750
4751      Then, with these symbols for example:
4752
4753       func
4754       func1
4755       fund
4756
4757      completing "func" looks for symbols between "func" and
4758      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4759      which finds "func" and "func1", but not "fund".
4760
4761      And with:
4762
4763       funcÿ     (Latin1 'ÿ' [0xff])
4764       funcÿ1
4765       fund
4766
4767      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4768      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4769
4770      And with:
4771
4772       ÿÿ        (Latin1 'ÿ' [0xff])
4773       ÿÿ1
4774
4775      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4776      the end of the list.
4777   */
4778   std::string after = search_name;
4779   while (!after.empty () && (unsigned char) after.back () == 0xff)
4780     after.pop_back ();
4781   if (!after.empty ())
4782     after.back () = (unsigned char) after.back () + 1;
4783   return after;
4784 }
4785
4786 /* See declaration.  */
4787
4788 std::pair<std::vector<name_component>::const_iterator,
4789           std::vector<name_component>::const_iterator>
4790 mapped_index_base::find_name_components_bounds
4791   (const lookup_name_info &lookup_name_without_params) const
4792 {
4793   auto *name_cmp
4794     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4795
4796   const char *cplus
4797     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4798
4799   /* Comparison function object for lower_bound that matches against a
4800      given symbol name.  */
4801   auto lookup_compare_lower = [&] (const name_component &elem,
4802                                    const char *name)
4803     {
4804       const char *elem_qualified = this->symbol_name_at (elem.idx);
4805       const char *elem_name = elem_qualified + elem.name_offset;
4806       return name_cmp (elem_name, name) < 0;
4807     };
4808
4809   /* Comparison function object for upper_bound that matches against a
4810      given symbol name.  */
4811   auto lookup_compare_upper = [&] (const char *name,
4812                                    const name_component &elem)
4813     {
4814       const char *elem_qualified = this->symbol_name_at (elem.idx);
4815       const char *elem_name = elem_qualified + elem.name_offset;
4816       return name_cmp (name, elem_name) < 0;
4817     };
4818
4819   auto begin = this->name_components.begin ();
4820   auto end = this->name_components.end ();
4821
4822   /* Find the lower bound.  */
4823   auto lower = [&] ()
4824     {
4825       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4826         return begin;
4827       else
4828         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4829     } ();
4830
4831   /* Find the upper bound.  */
4832   auto upper = [&] ()
4833     {
4834       if (lookup_name_without_params.completion_mode ())
4835         {
4836           /* In completion mode, we want UPPER to point past all
4837              symbols names that have the same prefix.  I.e., with
4838              these symbols, and completing "func":
4839
4840               function        << lower bound
4841               function1
4842               other_function  << upper bound
4843
4844              We find the upper bound by looking for the insertion
4845              point of "func"-with-last-character-incremented,
4846              i.e. "fund".  */
4847           std::string after = make_sort_after_prefix_name (cplus);
4848           if (after.empty ())
4849             return end;
4850           return std::lower_bound (lower, end, after.c_str (),
4851                                    lookup_compare_lower);
4852         }
4853       else
4854         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4855     } ();
4856
4857   return {lower, upper};
4858 }
4859
4860 /* See declaration.  */
4861
4862 void
4863 mapped_index_base::build_name_components ()
4864 {
4865   if (!this->name_components.empty ())
4866     return;
4867
4868   this->name_components_casing = case_sensitivity;
4869   auto *name_cmp
4870     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4871
4872   /* The code below only knows how to break apart components of C++
4873      symbol names (and other languages that use '::' as
4874      namespace/module separator).  If we add support for wild matching
4875      to some language that uses some other operator (E.g., Ada, Go and
4876      D use '.'), then we'll need to try splitting the symbol name
4877      according to that language too.  Note that Ada does support wild
4878      matching, but doesn't currently support .gdb_index.  */
4879   auto count = this->symbol_name_count ();
4880   for (offset_type idx = 0; idx < count; idx++)
4881     {
4882       if (this->symbol_name_slot_invalid (idx))
4883         continue;
4884
4885       const char *name = this->symbol_name_at (idx);
4886
4887       /* Add each name component to the name component table.  */
4888       unsigned int previous_len = 0;
4889       for (unsigned int current_len = cp_find_first_component (name);
4890            name[current_len] != '\0';
4891            current_len += cp_find_first_component (name + current_len))
4892         {
4893           gdb_assert (name[current_len] == ':');
4894           this->name_components.push_back ({previous_len, idx});
4895           /* Skip the '::'.  */
4896           current_len += 2;
4897           previous_len = current_len;
4898         }
4899       this->name_components.push_back ({previous_len, idx});
4900     }
4901
4902   /* Sort name_components elements by name.  */
4903   auto name_comp_compare = [&] (const name_component &left,
4904                                 const name_component &right)
4905     {
4906       const char *left_qualified = this->symbol_name_at (left.idx);
4907       const char *right_qualified = this->symbol_name_at (right.idx);
4908
4909       const char *left_name = left_qualified + left.name_offset;
4910       const char *right_name = right_qualified + right.name_offset;
4911
4912       return name_cmp (left_name, right_name) < 0;
4913     };
4914
4915   std::sort (this->name_components.begin (),
4916              this->name_components.end (),
4917              name_comp_compare);
4918 }
4919
4920 /* Helper for dw2_expand_symtabs_matching that works with a
4921    mapped_index_base instead of the containing objfile.  This is split
4922    to a separate function in order to be able to unit test the
4923    name_components matching using a mock mapped_index_base.  For each
4924    symbol name that matches, calls MATCH_CALLBACK, passing it the
4925    symbol's index in the mapped_index_base symbol table.  */
4926
4927 static void
4928 dw2_expand_symtabs_matching_symbol
4929   (mapped_index_base &index,
4930    const lookup_name_info &lookup_name_in,
4931    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4932    enum search_domain kind,
4933    gdb::function_view<void (offset_type)> match_callback)
4934 {
4935   lookup_name_info lookup_name_without_params
4936     = lookup_name_in.make_ignore_params ();
4937   gdb_index_symbol_name_matcher lookup_name_matcher
4938     (lookup_name_without_params);
4939
4940   /* Build the symbol name component sorted vector, if we haven't
4941      yet.  */
4942   index.build_name_components ();
4943
4944   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4945
4946   /* Now for each symbol name in range, check to see if we have a name
4947      match, and if so, call the MATCH_CALLBACK callback.  */
4948
4949   /* The same symbol may appear more than once in the range though.
4950      E.g., if we're looking for symbols that complete "w", and we have
4951      a symbol named "w1::w2", we'll find the two name components for
4952      that same symbol in the range.  To be sure we only call the
4953      callback once per symbol, we first collect the symbol name
4954      indexes that matched in a temporary vector and ignore
4955      duplicates.  */
4956   std::vector<offset_type> matches;
4957   matches.reserve (std::distance (bounds.first, bounds.second));
4958
4959   for (; bounds.first != bounds.second; ++bounds.first)
4960     {
4961       const char *qualified = index.symbol_name_at (bounds.first->idx);
4962
4963       if (!lookup_name_matcher.matches (qualified)
4964           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4965         continue;
4966
4967       matches.push_back (bounds.first->idx);
4968     }
4969
4970   std::sort (matches.begin (), matches.end ());
4971
4972   /* Finally call the callback, once per match.  */
4973   ULONGEST prev = -1;
4974   for (offset_type idx : matches)
4975     {
4976       if (prev != idx)
4977         {
4978           match_callback (idx);
4979           prev = idx;
4980         }
4981     }
4982
4983   /* Above we use a type wider than idx's for 'prev', since 0 and
4984      (offset_type)-1 are both possible values.  */
4985   static_assert (sizeof (prev) > sizeof (offset_type), "");
4986 }
4987
4988 #if GDB_SELF_TEST
4989
4990 namespace selftests { namespace dw2_expand_symtabs_matching {
4991
4992 /* A mock .gdb_index/.debug_names-like name index table, enough to
4993    exercise dw2_expand_symtabs_matching_symbol, which works with the
4994    mapped_index_base interface.  Builds an index from the symbol list
4995    passed as parameter to the constructor.  */
4996 class mock_mapped_index : public mapped_index_base
4997 {
4998 public:
4999   mock_mapped_index (gdb::array_view<const char *> symbols)
5000     : m_symbol_table (symbols)
5001   {}
5002
5003   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
5004
5005   /* Return the number of names in the symbol table.  */
5006   virtual size_t symbol_name_count () const
5007   {
5008     return m_symbol_table.size ();
5009   }
5010
5011   /* Get the name of the symbol at IDX in the symbol table.  */
5012   virtual const char *symbol_name_at (offset_type idx) const
5013   {
5014     return m_symbol_table[idx];
5015   }
5016
5017 private:
5018   gdb::array_view<const char *> m_symbol_table;
5019 };
5020
5021 /* Convenience function that converts a NULL pointer to a "<null>"
5022    string, to pass to print routines.  */
5023
5024 static const char *
5025 string_or_null (const char *str)
5026 {
5027   return str != NULL ? str : "<null>";
5028 }
5029
5030 /* Check if a lookup_name_info built from
5031    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
5032    index.  EXPECTED_LIST is the list of expected matches, in expected
5033    matching order.  If no match expected, then an empty list is
5034    specified.  Returns true on success.  On failure prints a warning
5035    indicating the file:line that failed, and returns false.  */
5036
5037 static bool
5038 check_match (const char *file, int line,
5039              mock_mapped_index &mock_index,
5040              const char *name, symbol_name_match_type match_type,
5041              bool completion_mode,
5042              std::initializer_list<const char *> expected_list)
5043 {
5044   lookup_name_info lookup_name (name, match_type, completion_mode);
5045
5046   bool matched = true;
5047
5048   auto mismatch = [&] (const char *expected_str,
5049                        const char *got)
5050   {
5051     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
5052                "expected=\"%s\", got=\"%s\"\n"),
5053              file, line,
5054              (match_type == symbol_name_match_type::FULL
5055               ? "FULL" : "WILD"),
5056              name, string_or_null (expected_str), string_or_null (got));
5057     matched = false;
5058   };
5059
5060   auto expected_it = expected_list.begin ();
5061   auto expected_end = expected_list.end ();
5062
5063   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
5064                                       NULL, ALL_DOMAIN,
5065                                       [&] (offset_type idx)
5066   {
5067     const char *matched_name = mock_index.symbol_name_at (idx);
5068     const char *expected_str
5069       = expected_it == expected_end ? NULL : *expected_it++;
5070
5071     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
5072       mismatch (expected_str, matched_name);
5073   });
5074
5075   const char *expected_str
5076   = expected_it == expected_end ? NULL : *expected_it++;
5077   if (expected_str != NULL)
5078     mismatch (expected_str, NULL);
5079
5080   return matched;
5081 }
5082
5083 /* The symbols added to the mock mapped_index for testing (in
5084    canonical form).  */
5085 static const char *test_symbols[] = {
5086   "function",
5087   "std::bar",
5088   "std::zfunction",
5089   "std::zfunction2",
5090   "w1::w2",
5091   "ns::foo<char*>",
5092   "ns::foo<int>",
5093   "ns::foo<long>",
5094   "ns2::tmpl<int>::foo2",
5095   "(anonymous namespace)::A::B::C",
5096
5097   /* These are used to check that the increment-last-char in the
5098      matching algorithm for completion doesn't match "t1_fund" when
5099      completing "t1_func".  */
5100   "t1_func",
5101   "t1_func1",
5102   "t1_fund",
5103   "t1_fund1",
5104
5105   /* A UTF-8 name with multi-byte sequences to make sure that
5106      cp-name-parser understands this as a single identifier ("função"
5107      is "function" in PT).  */
5108   u8"u8função",
5109
5110   /* \377 (0xff) is Latin1 'ÿ'.  */
5111   "yfunc\377",
5112
5113   /* \377 (0xff) is Latin1 'ÿ'.  */
5114   "\377",
5115   "\377\377123",
5116
5117   /* A name with all sorts of complications.  Starts with "z" to make
5118      it easier for the completion tests below.  */
5119 #define Z_SYM_NAME \
5120   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5121     "::tuple<(anonymous namespace)::ui*, " \
5122     "std::default_delete<(anonymous namespace)::ui>, void>"
5123
5124   Z_SYM_NAME
5125 };
5126
5127 /* Returns true if the mapped_index_base::find_name_component_bounds
5128    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5129    in completion mode.  */
5130
5131 static bool
5132 check_find_bounds_finds (mapped_index_base &index,
5133                          const char *search_name,
5134                          gdb::array_view<const char *> expected_syms)
5135 {
5136   lookup_name_info lookup_name (search_name,
5137                                 symbol_name_match_type::FULL, true);
5138
5139   auto bounds = index.find_name_components_bounds (lookup_name);
5140
5141   size_t distance = std::distance (bounds.first, bounds.second);
5142   if (distance != expected_syms.size ())
5143     return false;
5144
5145   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5146     {
5147       auto nc_elem = bounds.first + exp_elem;
5148       const char *qualified = index.symbol_name_at (nc_elem->idx);
5149       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5150         return false;
5151     }
5152
5153   return true;
5154 }
5155
5156 /* Test the lower-level mapped_index::find_name_component_bounds
5157    method.  */
5158
5159 static void
5160 test_mapped_index_find_name_component_bounds ()
5161 {
5162   mock_mapped_index mock_index (test_symbols);
5163
5164   mock_index.build_name_components ();
5165
5166   /* Test the lower-level mapped_index::find_name_component_bounds
5167      method in completion mode.  */
5168   {
5169     static const char *expected_syms[] = {
5170       "t1_func",
5171       "t1_func1",
5172     };
5173
5174     SELF_CHECK (check_find_bounds_finds (mock_index,
5175                                          "t1_func", expected_syms));
5176   }
5177
5178   /* Check that the increment-last-char in the name matching algorithm
5179      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5180   {
5181     static const char *expected_syms1[] = {
5182       "\377",
5183       "\377\377123",
5184     };
5185     SELF_CHECK (check_find_bounds_finds (mock_index,
5186                                          "\377", expected_syms1));
5187
5188     static const char *expected_syms2[] = {
5189       "\377\377123",
5190     };
5191     SELF_CHECK (check_find_bounds_finds (mock_index,
5192                                          "\377\377", expected_syms2));
5193   }
5194 }
5195
5196 /* Test dw2_expand_symtabs_matching_symbol.  */
5197
5198 static void
5199 test_dw2_expand_symtabs_matching_symbol ()
5200 {
5201   mock_mapped_index mock_index (test_symbols);
5202
5203   /* We let all tests run until the end even if some fails, for debug
5204      convenience.  */
5205   bool any_mismatch = false;
5206
5207   /* Create the expected symbols list (an initializer_list).  Needed
5208      because lists have commas, and we need to pass them to CHECK,
5209      which is a macro.  */
5210 #define EXPECT(...) { __VA_ARGS__ }
5211
5212   /* Wrapper for check_match that passes down the current
5213      __FILE__/__LINE__.  */
5214 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5215   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5216                                 mock_index,                             \
5217                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5218                                 EXPECTED_LIST)
5219
5220   /* Identity checks.  */
5221   for (const char *sym : test_symbols)
5222     {
5223       /* Should be able to match all existing symbols.  */
5224       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5225                    EXPECT (sym));
5226
5227       /* Should be able to match all existing symbols with
5228          parameters.  */
5229       std::string with_params = std::string (sym) + "(int)";
5230       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5231                    EXPECT (sym));
5232
5233       /* Should be able to match all existing symbols with
5234          parameters and qualifiers.  */
5235       with_params = std::string (sym) + " ( int ) const";
5236       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5237                    EXPECT (sym));
5238
5239       /* This should really find sym, but cp-name-parser.y doesn't
5240          know about lvalue/rvalue qualifiers yet.  */
5241       with_params = std::string (sym) + " ( int ) &&";
5242       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5243                    {});
5244     }
5245
5246   /* Check that the name matching algorithm for completion doesn't get
5247      confused with Latin1 'ÿ' / 0xff.  */
5248   {
5249     static const char str[] = "\377";
5250     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5251                  EXPECT ("\377", "\377\377123"));
5252   }
5253
5254   /* Check that the increment-last-char in the matching algorithm for
5255      completion doesn't match "t1_fund" when completing "t1_func".  */
5256   {
5257     static const char str[] = "t1_func";
5258     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5259                  EXPECT ("t1_func", "t1_func1"));
5260   }
5261
5262   /* Check that completion mode works at each prefix of the expected
5263      symbol name.  */
5264   {
5265     static const char str[] = "function(int)";
5266     size_t len = strlen (str);
5267     std::string lookup;
5268
5269     for (size_t i = 1; i < len; i++)
5270       {
5271         lookup.assign (str, i);
5272         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5273                      EXPECT ("function"));
5274       }
5275   }
5276
5277   /* While "w" is a prefix of both components, the match function
5278      should still only be called once.  */
5279   {
5280     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5281                  EXPECT ("w1::w2"));
5282     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5283                  EXPECT ("w1::w2"));
5284   }
5285
5286   /* Same, with a "complicated" symbol.  */
5287   {
5288     static const char str[] = Z_SYM_NAME;
5289     size_t len = strlen (str);
5290     std::string lookup;
5291
5292     for (size_t i = 1; i < len; i++)
5293       {
5294         lookup.assign (str, i);
5295         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5296                      EXPECT (Z_SYM_NAME));
5297       }
5298   }
5299
5300   /* In FULL mode, an incomplete symbol doesn't match.  */
5301   {
5302     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5303                  {});
5304   }
5305
5306   /* A complete symbol with parameters matches any overload, since the
5307      index has no overload info.  */
5308   {
5309     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5310                  EXPECT ("std::zfunction", "std::zfunction2"));
5311     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5312                  EXPECT ("std::zfunction", "std::zfunction2"));
5313     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5314                  EXPECT ("std::zfunction", "std::zfunction2"));
5315   }
5316
5317   /* Check that whitespace is ignored appropriately.  A symbol with a
5318      template argument list. */
5319   {
5320     static const char expected[] = "ns::foo<int>";
5321     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5322                  EXPECT (expected));
5323     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5324                  EXPECT (expected));
5325   }
5326
5327   /* Check that whitespace is ignored appropriately.  A symbol with a
5328      template argument list that includes a pointer.  */
5329   {
5330     static const char expected[] = "ns::foo<char*>";
5331     /* Try both completion and non-completion modes.  */
5332     static const bool completion_mode[2] = {false, true};
5333     for (size_t i = 0; i < 2; i++)
5334       {
5335         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5336                      completion_mode[i], EXPECT (expected));
5337         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5338                      completion_mode[i], EXPECT (expected));
5339
5340         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5341                      completion_mode[i], EXPECT (expected));
5342         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5343                      completion_mode[i], EXPECT (expected));
5344       }
5345   }
5346
5347   {
5348     /* Check method qualifiers are ignored.  */
5349     static const char expected[] = "ns::foo<char*>";
5350     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5351                  symbol_name_match_type::FULL, true, EXPECT (expected));
5352     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5353                  symbol_name_match_type::FULL, true, EXPECT (expected));
5354     CHECK_MATCH ("foo < char * >  ( int ) const",
5355                  symbol_name_match_type::WILD, true, EXPECT (expected));
5356     CHECK_MATCH ("foo < char * >  ( int ) &&",
5357                  symbol_name_match_type::WILD, true, EXPECT (expected));
5358   }
5359
5360   /* Test lookup names that don't match anything.  */
5361   {
5362     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5363                  {});
5364
5365     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5366                  {});
5367   }
5368
5369   /* Some wild matching tests, exercising "(anonymous namespace)",
5370      which should not be confused with a parameter list.  */
5371   {
5372     static const char *syms[] = {
5373       "A::B::C",
5374       "B::C",
5375       "C",
5376       "A :: B :: C ( int )",
5377       "B :: C ( int )",
5378       "C ( int )",
5379     };
5380
5381     for (const char *s : syms)
5382       {
5383         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5384                      EXPECT ("(anonymous namespace)::A::B::C"));
5385       }
5386   }
5387
5388   {
5389     static const char expected[] = "ns2::tmpl<int>::foo2";
5390     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5391                  EXPECT (expected));
5392     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5393                  EXPECT (expected));
5394   }
5395
5396   SELF_CHECK (!any_mismatch);
5397
5398 #undef EXPECT
5399 #undef CHECK_MATCH
5400 }
5401
5402 static void
5403 run_test ()
5404 {
5405   test_mapped_index_find_name_component_bounds ();
5406   test_dw2_expand_symtabs_matching_symbol ();
5407 }
5408
5409 }} // namespace selftests::dw2_expand_symtabs_matching
5410
5411 #endif /* GDB_SELF_TEST */
5412
5413 /* If FILE_MATCHER is NULL or if PER_CU has
5414    dwarf2_per_cu_quick_data::MARK set (see
5415    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5416    EXPANSION_NOTIFY on it.  */
5417
5418 static void
5419 dw2_expand_symtabs_matching_one
5420   (struct dwarf2_per_cu_data *per_cu,
5421    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5422    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5423 {
5424   if (file_matcher == NULL || per_cu->v.quick->mark)
5425     {
5426       bool symtab_was_null
5427         = (per_cu->v.quick->compunit_symtab == NULL);
5428
5429       dw2_instantiate_symtab (per_cu);
5430
5431       if (expansion_notify != NULL
5432           && symtab_was_null
5433           && per_cu->v.quick->compunit_symtab != NULL)
5434         expansion_notify (per_cu->v.quick->compunit_symtab);
5435     }
5436 }
5437
5438 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5439    matched, to expand corresponding CUs that were marked.  IDX is the
5440    index of the symbol name that matched.  */
5441
5442 static void
5443 dw2_expand_marked_cus
5444   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5445    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5446    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5447    search_domain kind)
5448 {
5449   offset_type *vec, vec_len, vec_idx;
5450   bool global_seen = false;
5451   mapped_index &index = *dwarf2_per_objfile->index_table;
5452
5453   vec = (offset_type *) (index.constant_pool
5454                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5455   vec_len = MAYBE_SWAP (vec[0]);
5456   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5457     {
5458       struct dwarf2_per_cu_data *per_cu;
5459       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5460       /* This value is only valid for index versions >= 7.  */
5461       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5462       gdb_index_symbol_kind symbol_kind =
5463         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5464       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5465       /* Only check the symbol attributes if they're present.
5466          Indices prior to version 7 don't record them,
5467          and indices >= 7 may elide them for certain symbols
5468          (gold does this).  */
5469       int attrs_valid =
5470         (index.version >= 7
5471          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5472
5473       /* Work around gold/15646.  */
5474       if (attrs_valid)
5475         {
5476           if (!is_static && global_seen)
5477             continue;
5478           if (!is_static)
5479             global_seen = true;
5480         }
5481
5482       /* Only check the symbol's kind if it has one.  */
5483       if (attrs_valid)
5484         {
5485           switch (kind)
5486             {
5487             case VARIABLES_DOMAIN:
5488               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5489                 continue;
5490               break;
5491             case FUNCTIONS_DOMAIN:
5492               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5493                 continue;
5494               break;
5495             case TYPES_DOMAIN:
5496               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5497                 continue;
5498               break;
5499             default:
5500               break;
5501             }
5502         }
5503
5504       /* Don't crash on bad data.  */
5505       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5506                        + dwarf2_per_objfile->n_type_units))
5507         {
5508           complaint (&symfile_complaints,
5509                      _(".gdb_index entry has bad CU index"
5510                        " [in module %s]"),
5511                        objfile_name (dwarf2_per_objfile->objfile));
5512           continue;
5513         }
5514
5515       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5516       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5517                                        expansion_notify);
5518     }
5519 }
5520
5521 /* If FILE_MATCHER is non-NULL, set all the
5522    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5523    that match FILE_MATCHER.  */
5524
5525 static void
5526 dw_expand_symtabs_matching_file_matcher
5527   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5528    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5529 {
5530   if (file_matcher == NULL)
5531     return;
5532
5533   objfile *const objfile = dwarf2_per_objfile->objfile;
5534
5535   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5536                                             htab_eq_pointer,
5537                                             NULL, xcalloc, xfree));
5538   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5539                                                 htab_eq_pointer,
5540                                                 NULL, xcalloc, xfree));
5541
5542   /* The rule is CUs specify all the files, including those used by
5543      any TU, so there's no need to scan TUs here.  */
5544
5545   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5546     {
5547       int j;
5548       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5549       struct quick_file_names *file_data;
5550       void **slot;
5551
5552       QUIT;
5553
5554       per_cu->v.quick->mark = 0;
5555
5556       /* We only need to look at symtabs not already expanded.  */
5557       if (per_cu->v.quick->compunit_symtab)
5558         continue;
5559
5560       file_data = dw2_get_file_names (per_cu);
5561       if (file_data == NULL)
5562         continue;
5563
5564       if (htab_find (visited_not_found.get (), file_data) != NULL)
5565         continue;
5566       else if (htab_find (visited_found.get (), file_data) != NULL)
5567         {
5568           per_cu->v.quick->mark = 1;
5569           continue;
5570         }
5571
5572       for (j = 0; j < file_data->num_file_names; ++j)
5573         {
5574           const char *this_real_name;
5575
5576           if (file_matcher (file_data->file_names[j], false))
5577             {
5578               per_cu->v.quick->mark = 1;
5579               break;
5580             }
5581
5582           /* Before we invoke realpath, which can get expensive when many
5583              files are involved, do a quick comparison of the basenames.  */
5584           if (!basenames_may_differ
5585               && !file_matcher (lbasename (file_data->file_names[j]),
5586                                 true))
5587             continue;
5588
5589           this_real_name = dw2_get_real_path (objfile, file_data, j);
5590           if (file_matcher (this_real_name, false))
5591             {
5592               per_cu->v.quick->mark = 1;
5593               break;
5594             }
5595         }
5596
5597       slot = htab_find_slot (per_cu->v.quick->mark
5598                              ? visited_found.get ()
5599                              : visited_not_found.get (),
5600                              file_data, INSERT);
5601       *slot = file_data;
5602     }
5603 }
5604
5605 static void
5606 dw2_expand_symtabs_matching
5607   (struct objfile *objfile,
5608    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5609    const lookup_name_info &lookup_name,
5610    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5611    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5612    enum search_domain kind)
5613 {
5614   struct dwarf2_per_objfile *dwarf2_per_objfile
5615     = get_dwarf2_per_objfile (objfile);
5616
5617   /* index_table is NULL if OBJF_READNOW.  */
5618   if (!dwarf2_per_objfile->index_table)
5619     return;
5620
5621   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5622
5623   mapped_index &index = *dwarf2_per_objfile->index_table;
5624
5625   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5626                                       symbol_matcher,
5627                                       kind, [&] (offset_type idx)
5628     {
5629       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5630                              expansion_notify, kind);
5631     });
5632 }
5633
5634 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5635    symtab.  */
5636
5637 static struct compunit_symtab *
5638 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5639                                           CORE_ADDR pc)
5640 {
5641   int i;
5642
5643   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5644       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5645     return cust;
5646
5647   if (cust->includes == NULL)
5648     return NULL;
5649
5650   for (i = 0; cust->includes[i]; ++i)
5651     {
5652       struct compunit_symtab *s = cust->includes[i];
5653
5654       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5655       if (s != NULL)
5656         return s;
5657     }
5658
5659   return NULL;
5660 }
5661
5662 static struct compunit_symtab *
5663 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5664                                   struct bound_minimal_symbol msymbol,
5665                                   CORE_ADDR pc,
5666                                   struct obj_section *section,
5667                                   int warn_if_readin)
5668 {
5669   struct dwarf2_per_cu_data *data;
5670   struct compunit_symtab *result;
5671
5672   if (!objfile->psymtabs_addrmap)
5673     return NULL;
5674
5675   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5676                                                      pc);
5677   if (!data)
5678     return NULL;
5679
5680   if (warn_if_readin && data->v.quick->compunit_symtab)
5681     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5682              paddress (get_objfile_arch (objfile), pc));
5683
5684   result
5685     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5686                                                 pc);
5687   gdb_assert (result != NULL);
5688   return result;
5689 }
5690
5691 static void
5692 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5693                           void *data, int need_fullname)
5694 {
5695   struct dwarf2_per_objfile *dwarf2_per_objfile
5696     = get_dwarf2_per_objfile (objfile);
5697
5698   if (!dwarf2_per_objfile->filenames_cache)
5699     {
5700       dwarf2_per_objfile->filenames_cache.emplace ();
5701
5702       htab_up visited (htab_create_alloc (10,
5703                                           htab_hash_pointer, htab_eq_pointer,
5704                                           NULL, xcalloc, xfree));
5705
5706       /* The rule is CUs specify all the files, including those used
5707          by any TU, so there's no need to scan TUs here.  We can
5708          ignore file names coming from already-expanded CUs.  */
5709
5710       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5711         {
5712           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5713
5714           if (per_cu->v.quick->compunit_symtab)
5715             {
5716               void **slot = htab_find_slot (visited.get (),
5717                                             per_cu->v.quick->file_names,
5718                                             INSERT);
5719
5720               *slot = per_cu->v.quick->file_names;
5721             }
5722         }
5723
5724       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5725         {
5726           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5727           struct quick_file_names *file_data;
5728           void **slot;
5729
5730           /* We only need to look at symtabs not already expanded.  */
5731           if (per_cu->v.quick->compunit_symtab)
5732             continue;
5733
5734           file_data = dw2_get_file_names (per_cu);
5735           if (file_data == NULL)
5736             continue;
5737
5738           slot = htab_find_slot (visited.get (), file_data, INSERT);
5739           if (*slot)
5740             {
5741               /* Already visited.  */
5742               continue;
5743             }
5744           *slot = file_data;
5745
5746           for (int j = 0; j < file_data->num_file_names; ++j)
5747             {
5748               const char *filename = file_data->file_names[j];
5749               dwarf2_per_objfile->filenames_cache->seen (filename);
5750             }
5751         }
5752     }
5753
5754   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5755     {
5756       gdb::unique_xmalloc_ptr<char> this_real_name;
5757
5758       if (need_fullname)
5759         this_real_name = gdb_realpath (filename);
5760       (*fun) (filename, this_real_name.get (), data);
5761     });
5762 }
5763
5764 static int
5765 dw2_has_symbols (struct objfile *objfile)
5766 {
5767   return 1;
5768 }
5769
5770 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5771 {
5772   dw2_has_symbols,
5773   dw2_find_last_source_symtab,
5774   dw2_forget_cached_source_info,
5775   dw2_map_symtabs_matching_filename,
5776   dw2_lookup_symbol,
5777   dw2_print_stats,
5778   dw2_dump,
5779   dw2_relocate,
5780   dw2_expand_symtabs_for_function,
5781   dw2_expand_all_symtabs,
5782   dw2_expand_symtabs_with_fullname,
5783   dw2_map_matching_symbols,
5784   dw2_expand_symtabs_matching,
5785   dw2_find_pc_sect_compunit_symtab,
5786   NULL,
5787   dw2_map_symbol_filenames
5788 };
5789
5790 /* DWARF-5 debug_names reader.  */
5791
5792 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5793 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5794
5795 /* A helper function that reads the .debug_names section in SECTION
5796    and fills in MAP.  FILENAME is the name of the file containing the
5797    section; it is used for error reporting.
5798
5799    Returns true if all went well, false otherwise.  */
5800
5801 static bool
5802 read_debug_names_from_section (struct objfile *objfile,
5803                                const char *filename,
5804                                struct dwarf2_section_info *section,
5805                                mapped_debug_names &map)
5806 {
5807   if (dwarf2_section_empty_p (section))
5808     return false;
5809
5810   /* Older elfutils strip versions could keep the section in the main
5811      executable while splitting it for the separate debug info file.  */
5812   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5813     return false;
5814
5815   dwarf2_read_section (objfile, section);
5816
5817   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5818
5819   const gdb_byte *addr = section->buffer;
5820
5821   bfd *const abfd = get_section_bfd_owner (section);
5822
5823   unsigned int bytes_read;
5824   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5825   addr += bytes_read;
5826
5827   map.dwarf5_is_dwarf64 = bytes_read != 4;
5828   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5829   if (bytes_read + length != section->size)
5830     {
5831       /* There may be multiple per-CU indices.  */
5832       warning (_("Section .debug_names in %s length %s does not match "
5833                  "section length %s, ignoring .debug_names."),
5834                filename, plongest (bytes_read + length),
5835                pulongest (section->size));
5836       return false;
5837     }
5838
5839   /* The version number.  */
5840   uint16_t version = read_2_bytes (abfd, addr);
5841   addr += 2;
5842   if (version != 5)
5843     {
5844       warning (_("Section .debug_names in %s has unsupported version %d, "
5845                  "ignoring .debug_names."),
5846                filename, version);
5847       return false;
5848     }
5849
5850   /* Padding.  */
5851   uint16_t padding = read_2_bytes (abfd, addr);
5852   addr += 2;
5853   if (padding != 0)
5854     {
5855       warning (_("Section .debug_names in %s has unsupported padding %d, "
5856                  "ignoring .debug_names."),
5857                filename, padding);
5858       return false;
5859     }
5860
5861   /* comp_unit_count - The number of CUs in the CU list.  */
5862   map.cu_count = read_4_bytes (abfd, addr);
5863   addr += 4;
5864
5865   /* local_type_unit_count - The number of TUs in the local TU
5866      list.  */
5867   map.tu_count = read_4_bytes (abfd, addr);
5868   addr += 4;
5869
5870   /* foreign_type_unit_count - The number of TUs in the foreign TU
5871      list.  */
5872   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5873   addr += 4;
5874   if (foreign_tu_count != 0)
5875     {
5876       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5877                  "ignoring .debug_names."),
5878                filename, static_cast<unsigned long> (foreign_tu_count));
5879       return false;
5880     }
5881
5882   /* bucket_count - The number of hash buckets in the hash lookup
5883      table.  */
5884   map.bucket_count = read_4_bytes (abfd, addr);
5885   addr += 4;
5886
5887   /* name_count - The number of unique names in the index.  */
5888   map.name_count = read_4_bytes (abfd, addr);
5889   addr += 4;
5890
5891   /* abbrev_table_size - The size in bytes of the abbreviations
5892      table.  */
5893   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5894   addr += 4;
5895
5896   /* augmentation_string_size - The size in bytes of the augmentation
5897      string.  This value is rounded up to a multiple of 4.  */
5898   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5899   addr += 4;
5900   map.augmentation_is_gdb = ((augmentation_string_size
5901                               == sizeof (dwarf5_augmentation))
5902                              && memcmp (addr, dwarf5_augmentation,
5903                                         sizeof (dwarf5_augmentation)) == 0);
5904   augmentation_string_size += (-augmentation_string_size) & 3;
5905   addr += augmentation_string_size;
5906
5907   /* List of CUs */
5908   map.cu_table_reordered = addr;
5909   addr += map.cu_count * map.offset_size;
5910
5911   /* List of Local TUs */
5912   map.tu_table_reordered = addr;
5913   addr += map.tu_count * map.offset_size;
5914
5915   /* Hash Lookup Table */
5916   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5917   addr += map.bucket_count * 4;
5918   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5919   addr += map.name_count * 4;
5920
5921   /* Name Table */
5922   map.name_table_string_offs_reordered = addr;
5923   addr += map.name_count * map.offset_size;
5924   map.name_table_entry_offs_reordered = addr;
5925   addr += map.name_count * map.offset_size;
5926
5927   const gdb_byte *abbrev_table_start = addr;
5928   for (;;)
5929     {
5930       unsigned int bytes_read;
5931       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5932       addr += bytes_read;
5933       if (index_num == 0)
5934         break;
5935
5936       const auto insertpair
5937         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5938       if (!insertpair.second)
5939         {
5940           warning (_("Section .debug_names in %s has duplicate index %s, "
5941                      "ignoring .debug_names."),
5942                    filename, pulongest (index_num));
5943           return false;
5944         }
5945       mapped_debug_names::index_val &indexval = insertpair.first->second;
5946       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5947       addr += bytes_read;
5948
5949       for (;;)
5950         {
5951           mapped_debug_names::index_val::attr attr;
5952           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5953           addr += bytes_read;
5954           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5955           addr += bytes_read;
5956           if (attr.form == DW_FORM_implicit_const)
5957             {
5958               attr.implicit_const = read_signed_leb128 (abfd, addr,
5959                                                         &bytes_read);
5960               addr += bytes_read;
5961             }
5962           if (attr.dw_idx == 0 && attr.form == 0)
5963             break;
5964           indexval.attr_vec.push_back (std::move (attr));
5965         }
5966     }
5967   if (addr != abbrev_table_start + abbrev_table_size)
5968     {
5969       warning (_("Section .debug_names in %s has abbreviation_table "
5970                  "of size %zu vs. written as %u, ignoring .debug_names."),
5971                filename, addr - abbrev_table_start, abbrev_table_size);
5972       return false;
5973     }
5974   map.entry_pool = addr;
5975
5976   return true;
5977 }
5978
5979 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5980    list.  */
5981
5982 static void
5983 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5984                                   const mapped_debug_names &map,
5985                                   dwarf2_section_info &section,
5986                                   bool is_dwz, int base_offset)
5987 {
5988   sect_offset sect_off_prev;
5989   for (uint32_t i = 0; i <= map.cu_count; ++i)
5990     {
5991       sect_offset sect_off_next;
5992       if (i < map.cu_count)
5993         {
5994           sect_off_next
5995             = (sect_offset) (extract_unsigned_integer
5996                              (map.cu_table_reordered + i * map.offset_size,
5997                               map.offset_size,
5998                               map.dwarf5_byte_order));
5999         }
6000       else
6001         sect_off_next = (sect_offset) section.size;
6002       if (i >= 1)
6003         {
6004           const ULONGEST length = sect_off_next - sect_off_prev;
6005           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
6006             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
6007                                          sect_off_prev, length);
6008         }
6009       sect_off_prev = sect_off_next;
6010     }
6011 }
6012
6013 /* Read the CU list from the mapped index, and use it to create all
6014    the CU objects for this dwarf2_per_objfile.  */
6015
6016 static void
6017 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
6018                              const mapped_debug_names &map,
6019                              const mapped_debug_names &dwz_map)
6020 {
6021   struct objfile *objfile = dwarf2_per_objfile->objfile;
6022
6023   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
6024   dwarf2_per_objfile->all_comp_units
6025     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
6026                  dwarf2_per_objfile->n_comp_units);
6027
6028   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
6029                                     dwarf2_per_objfile->info,
6030                                     false /* is_dwz */,
6031                                     0 /* base_offset */);
6032
6033   if (dwz_map.cu_count == 0)
6034     return;
6035
6036   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6037   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
6038                                     true /* is_dwz */,
6039                                     map.cu_count /* base_offset */);
6040 }
6041
6042 /* Read .debug_names.  If everything went ok, initialize the "quick"
6043    elements of all the CUs and return true.  Otherwise, return false.  */
6044
6045 static bool
6046 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
6047 {
6048   mapped_debug_names local_map (dwarf2_per_objfile);
6049   mapped_debug_names dwz_map (dwarf2_per_objfile);
6050   struct objfile *objfile = dwarf2_per_objfile->objfile;
6051
6052   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
6053                                       &dwarf2_per_objfile->debug_names,
6054                                       local_map))
6055     return false;
6056
6057   /* Don't use the index if it's empty.  */
6058   if (local_map.name_count == 0)
6059     return false;
6060
6061   /* If there is a .dwz file, read it so we can get its CU list as
6062      well.  */
6063   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
6064   if (dwz != NULL)
6065     {
6066       if (!read_debug_names_from_section (objfile,
6067                                           bfd_get_filename (dwz->dwz_bfd),
6068                                           &dwz->debug_names, dwz_map))
6069         {
6070           warning (_("could not read '.debug_names' section from %s; skipping"),
6071                    bfd_get_filename (dwz->dwz_bfd));
6072           return false;
6073         }
6074     }
6075
6076   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
6077
6078   if (local_map.tu_count != 0)
6079     {
6080       /* We can only handle a single .debug_types when we have an
6081          index.  */
6082       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
6083         return false;
6084
6085       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
6086                                                 dwarf2_per_objfile->types, 0);
6087
6088       create_signatured_type_table_from_debug_names
6089         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
6090     }
6091
6092   create_addrmap_from_aranges (dwarf2_per_objfile,
6093                                &dwarf2_per_objfile->debug_aranges);
6094
6095   dwarf2_per_objfile->debug_names_table.reset
6096     (new mapped_debug_names (dwarf2_per_objfile));
6097   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
6098   dwarf2_per_objfile->using_index = 1;
6099   dwarf2_per_objfile->quick_file_names_table =
6100     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6101
6102   return true;
6103 }
6104
6105 /* Symbol name hashing function as specified by DWARF-5.  */
6106
6107 static uint32_t
6108 dwarf5_djb_hash (const char *str_)
6109 {
6110   const unsigned char *str = (const unsigned char *) str_;
6111
6112   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6113      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6114
6115   uint32_t hash = 5381;
6116   while (int c = *str++)
6117     hash = hash * 33 + tolower (c);
6118   return hash;
6119 }
6120
6121 /* Type used to manage iterating over all CUs looking for a symbol for
6122    .debug_names.  */
6123
6124 class dw2_debug_names_iterator
6125 {
6126 public:
6127   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6128      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6129   dw2_debug_names_iterator (const mapped_debug_names &map,
6130                             bool want_specific_block,
6131                             block_enum block_index, domain_enum domain,
6132                             const char *name)
6133     : m_map (map), m_want_specific_block (want_specific_block),
6134       m_block_index (block_index), m_domain (domain),
6135       m_addr (find_vec_in_debug_names (map, name))
6136   {}
6137
6138   dw2_debug_names_iterator (const mapped_debug_names &map,
6139                             search_domain search, uint32_t namei)
6140     : m_map (map),
6141       m_search (search),
6142       m_addr (find_vec_in_debug_names (map, namei))
6143   {}
6144
6145   /* Return the next matching CU or NULL if there are no more.  */
6146   dwarf2_per_cu_data *next ();
6147
6148 private:
6149   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6150                                                   const char *name);
6151   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6152                                                   uint32_t namei);
6153
6154   /* The internalized form of .debug_names.  */
6155   const mapped_debug_names &m_map;
6156
6157   /* If true, only look for symbols that match BLOCK_INDEX.  */
6158   const bool m_want_specific_block = false;
6159
6160   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6161      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6162      value.  */
6163   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6164
6165   /* The kind of symbol we're looking for.  */
6166   const domain_enum m_domain = UNDEF_DOMAIN;
6167   const search_domain m_search = ALL_DOMAIN;
6168
6169   /* The list of CUs from the index entry of the symbol, or NULL if
6170      not found.  */
6171   const gdb_byte *m_addr;
6172 };
6173
6174 const char *
6175 mapped_debug_names::namei_to_name (uint32_t namei) const
6176 {
6177   const ULONGEST namei_string_offs
6178     = extract_unsigned_integer ((name_table_string_offs_reordered
6179                                  + namei * offset_size),
6180                                 offset_size,
6181                                 dwarf5_byte_order);
6182   return read_indirect_string_at_offset
6183     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6184 }
6185
6186 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6187    found, return pointer to its pool data.  If NAME cannot be found,
6188    return NULL.  */
6189
6190 const gdb_byte *
6191 dw2_debug_names_iterator::find_vec_in_debug_names
6192   (const mapped_debug_names &map, const char *name)
6193 {
6194   int (*cmp) (const char *, const char *);
6195
6196   if (current_language->la_language == language_cplus
6197       || current_language->la_language == language_fortran
6198       || current_language->la_language == language_d)
6199     {
6200       /* NAME is already canonical.  Drop any qualifiers as
6201          .debug_names does not contain any.  */
6202
6203       if (strchr (name, '(') != NULL)
6204         {
6205           gdb::unique_xmalloc_ptr<char> without_params
6206             = cp_remove_params (name);
6207
6208           if (without_params != NULL)
6209             {
6210               name = without_params.get();
6211             }
6212         }
6213     }
6214
6215   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6216
6217   const uint32_t full_hash = dwarf5_djb_hash (name);
6218   uint32_t namei
6219     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6220                                 (map.bucket_table_reordered
6221                                  + (full_hash % map.bucket_count)), 4,
6222                                 map.dwarf5_byte_order);
6223   if (namei == 0)
6224     return NULL;
6225   --namei;
6226   if (namei >= map.name_count)
6227     {
6228       complaint (&symfile_complaints,
6229                  _("Wrong .debug_names with name index %u but name_count=%u "
6230                    "[in module %s]"),
6231                  namei, map.name_count,
6232                  objfile_name (map.dwarf2_per_objfile->objfile));
6233       return NULL;
6234     }
6235
6236   for (;;)
6237     {
6238       const uint32_t namei_full_hash
6239         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6240                                     (map.hash_table_reordered + namei), 4,
6241                                     map.dwarf5_byte_order);
6242       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6243         return NULL;
6244
6245       if (full_hash == namei_full_hash)
6246         {
6247           const char *const namei_string = map.namei_to_name (namei);
6248
6249 #if 0 /* An expensive sanity check.  */
6250           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6251             {
6252               complaint (&symfile_complaints,
6253                          _("Wrong .debug_names hash for string at index %u "
6254                            "[in module %s]"),
6255                          namei, objfile_name (dwarf2_per_objfile->objfile));
6256               return NULL;
6257             }
6258 #endif
6259
6260           if (cmp (namei_string, name) == 0)
6261             {
6262               const ULONGEST namei_entry_offs
6263                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6264                                              + namei * map.offset_size),
6265                                             map.offset_size, map.dwarf5_byte_order);
6266               return map.entry_pool + namei_entry_offs;
6267             }
6268         }
6269
6270       ++namei;
6271       if (namei >= map.name_count)
6272         return NULL;
6273     }
6274 }
6275
6276 const gdb_byte *
6277 dw2_debug_names_iterator::find_vec_in_debug_names
6278   (const mapped_debug_names &map, uint32_t namei)
6279 {
6280   if (namei >= map.name_count)
6281     {
6282       complaint (&symfile_complaints,
6283                  _("Wrong .debug_names with name index %u but name_count=%u "
6284                    "[in module %s]"),
6285                  namei, map.name_count,
6286                  objfile_name (map.dwarf2_per_objfile->objfile));
6287       return NULL;
6288     }
6289
6290   const ULONGEST namei_entry_offs
6291     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6292                                  + namei * map.offset_size),
6293                                 map.offset_size, map.dwarf5_byte_order);
6294   return map.entry_pool + namei_entry_offs;
6295 }
6296
6297 /* See dw2_debug_names_iterator.  */
6298
6299 dwarf2_per_cu_data *
6300 dw2_debug_names_iterator::next ()
6301 {
6302   if (m_addr == NULL)
6303     return NULL;
6304
6305   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6306   struct objfile *objfile = dwarf2_per_objfile->objfile;
6307   bfd *const abfd = objfile->obfd;
6308
6309  again:
6310
6311   unsigned int bytes_read;
6312   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6313   m_addr += bytes_read;
6314   if (abbrev == 0)
6315     return NULL;
6316
6317   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6318   if (indexval_it == m_map.abbrev_map.cend ())
6319     {
6320       complaint (&symfile_complaints,
6321                  _("Wrong .debug_names undefined abbrev code %s "
6322                    "[in module %s]"),
6323                  pulongest (abbrev), objfile_name (objfile));
6324       return NULL;
6325     }
6326   const mapped_debug_names::index_val &indexval = indexval_it->second;
6327   bool have_is_static = false;
6328   bool is_static;
6329   dwarf2_per_cu_data *per_cu = NULL;
6330   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6331     {
6332       ULONGEST ull;
6333       switch (attr.form)
6334         {
6335         case DW_FORM_implicit_const:
6336           ull = attr.implicit_const;
6337           break;
6338         case DW_FORM_flag_present:
6339           ull = 1;
6340           break;
6341         case DW_FORM_udata:
6342           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6343           m_addr += bytes_read;
6344           break;
6345         default:
6346           complaint (&symfile_complaints,
6347                      _("Unsupported .debug_names form %s [in module %s]"),
6348                      dwarf_form_name (attr.form),
6349                      objfile_name (objfile));
6350           return NULL;
6351         }
6352       switch (attr.dw_idx)
6353         {
6354         case DW_IDX_compile_unit:
6355           /* Don't crash on bad data.  */
6356           if (ull >= dwarf2_per_objfile->n_comp_units)
6357             {
6358               complaint (&symfile_complaints,
6359                          _(".debug_names entry has bad CU index %s"
6360                            " [in module %s]"),
6361                          pulongest (ull),
6362                          objfile_name (dwarf2_per_objfile->objfile));
6363               continue;
6364             }
6365           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6366           break;
6367         case DW_IDX_type_unit:
6368           /* Don't crash on bad data.  */
6369           if (ull >= dwarf2_per_objfile->n_type_units)
6370             {
6371               complaint (&symfile_complaints,
6372                          _(".debug_names entry has bad TU index %s"
6373                            " [in module %s]"),
6374                          pulongest (ull),
6375                          objfile_name (dwarf2_per_objfile->objfile));
6376               continue;
6377             }
6378           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6379                                  dwarf2_per_objfile->n_comp_units + ull);
6380           break;
6381         case DW_IDX_GNU_internal:
6382           if (!m_map.augmentation_is_gdb)
6383             break;
6384           have_is_static = true;
6385           is_static = true;
6386           break;
6387         case DW_IDX_GNU_external:
6388           if (!m_map.augmentation_is_gdb)
6389             break;
6390           have_is_static = true;
6391           is_static = false;
6392           break;
6393         }
6394     }
6395
6396   /* Skip if already read in.  */
6397   if (per_cu->v.quick->compunit_symtab)
6398     goto again;
6399
6400   /* Check static vs global.  */
6401   if (have_is_static)
6402     {
6403       const bool want_static = m_block_index != GLOBAL_BLOCK;
6404       if (m_want_specific_block && want_static != is_static)
6405         goto again;
6406     }
6407
6408   /* Match dw2_symtab_iter_next, symbol_kind
6409      and debug_names::psymbol_tag.  */
6410   switch (m_domain)
6411     {
6412     case VAR_DOMAIN:
6413       switch (indexval.dwarf_tag)
6414         {
6415         case DW_TAG_variable:
6416         case DW_TAG_subprogram:
6417         /* Some types are also in VAR_DOMAIN.  */
6418         case DW_TAG_typedef:
6419         case DW_TAG_structure_type:
6420           break;
6421         default:
6422           goto again;
6423         }
6424       break;
6425     case STRUCT_DOMAIN:
6426       switch (indexval.dwarf_tag)
6427         {
6428         case DW_TAG_typedef:
6429         case DW_TAG_structure_type:
6430           break;
6431         default:
6432           goto again;
6433         }
6434       break;
6435     case LABEL_DOMAIN:
6436       switch (indexval.dwarf_tag)
6437         {
6438         case 0:
6439         case DW_TAG_variable:
6440           break;
6441         default:
6442           goto again;
6443         }
6444       break;
6445     default:
6446       break;
6447     }
6448
6449   /* Match dw2_expand_symtabs_matching, symbol_kind and
6450      debug_names::psymbol_tag.  */
6451   switch (m_search)
6452     {
6453     case VARIABLES_DOMAIN:
6454       switch (indexval.dwarf_tag)
6455         {
6456         case DW_TAG_variable:
6457           break;
6458         default:
6459           goto again;
6460         }
6461       break;
6462     case FUNCTIONS_DOMAIN:
6463       switch (indexval.dwarf_tag)
6464         {
6465         case DW_TAG_subprogram:
6466           break;
6467         default:
6468           goto again;
6469         }
6470       break;
6471     case TYPES_DOMAIN:
6472       switch (indexval.dwarf_tag)
6473         {
6474         case DW_TAG_typedef:
6475         case DW_TAG_structure_type:
6476           break;
6477         default:
6478           goto again;
6479         }
6480       break;
6481     default:
6482       break;
6483     }
6484
6485   return per_cu;
6486 }
6487
6488 static struct compunit_symtab *
6489 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6490                                const char *name, domain_enum domain)
6491 {
6492   const block_enum block_index = static_cast<block_enum> (block_index_int);
6493   struct dwarf2_per_objfile *dwarf2_per_objfile
6494     = get_dwarf2_per_objfile (objfile);
6495
6496   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6497   if (!mapp)
6498     {
6499       /* index is NULL if OBJF_READNOW.  */
6500       return NULL;
6501     }
6502   const auto &map = *mapp;
6503
6504   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6505                                  block_index, domain, name);
6506
6507   struct compunit_symtab *stab_best = NULL;
6508   struct dwarf2_per_cu_data *per_cu;
6509   while ((per_cu = iter.next ()) != NULL)
6510     {
6511       struct symbol *sym, *with_opaque = NULL;
6512       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6513       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6514       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6515
6516       sym = block_find_symbol (block, name, domain,
6517                                block_find_non_opaque_type_preferred,
6518                                &with_opaque);
6519
6520       /* Some caution must be observed with overloaded functions and
6521          methods, since the index will not contain any overload
6522          information (but NAME might contain it).  */
6523
6524       if (sym != NULL
6525           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6526         return stab;
6527       if (with_opaque != NULL
6528           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6529         stab_best = stab;
6530
6531       /* Keep looking through other CUs.  */
6532     }
6533
6534   return stab_best;
6535 }
6536
6537 /* This dumps minimal information about .debug_names.  It is called
6538    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6539    uses this to verify that .debug_names has been loaded.  */
6540
6541 static void
6542 dw2_debug_names_dump (struct objfile *objfile)
6543 {
6544   struct dwarf2_per_objfile *dwarf2_per_objfile
6545     = get_dwarf2_per_objfile (objfile);
6546
6547   gdb_assert (dwarf2_per_objfile->using_index);
6548   printf_filtered (".debug_names:");
6549   if (dwarf2_per_objfile->debug_names_table)
6550     printf_filtered (" exists\n");
6551   else
6552     printf_filtered (" faked for \"readnow\"\n");
6553   printf_filtered ("\n");
6554 }
6555
6556 static void
6557 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6558                                              const char *func_name)
6559 {
6560   struct dwarf2_per_objfile *dwarf2_per_objfile
6561     = get_dwarf2_per_objfile (objfile);
6562
6563   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6564   if (dwarf2_per_objfile->debug_names_table)
6565     {
6566       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6567
6568       /* Note: It doesn't matter what we pass for block_index here.  */
6569       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6570                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6571
6572       struct dwarf2_per_cu_data *per_cu;
6573       while ((per_cu = iter.next ()) != NULL)
6574         dw2_instantiate_symtab (per_cu);
6575     }
6576 }
6577
6578 static void
6579 dw2_debug_names_expand_symtabs_matching
6580   (struct objfile *objfile,
6581    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6582    const lookup_name_info &lookup_name,
6583    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6584    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6585    enum search_domain kind)
6586 {
6587   struct dwarf2_per_objfile *dwarf2_per_objfile
6588     = get_dwarf2_per_objfile (objfile);
6589
6590   /* debug_names_table is NULL if OBJF_READNOW.  */
6591   if (!dwarf2_per_objfile->debug_names_table)
6592     return;
6593
6594   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6595
6596   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6597
6598   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6599                                       symbol_matcher,
6600                                       kind, [&] (offset_type namei)
6601     {
6602       /* The name was matched, now expand corresponding CUs that were
6603          marked.  */
6604       dw2_debug_names_iterator iter (map, kind, namei);
6605
6606       struct dwarf2_per_cu_data *per_cu;
6607       while ((per_cu = iter.next ()) != NULL)
6608         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6609                                          expansion_notify);
6610     });
6611 }
6612
6613 const struct quick_symbol_functions dwarf2_debug_names_functions =
6614 {
6615   dw2_has_symbols,
6616   dw2_find_last_source_symtab,
6617   dw2_forget_cached_source_info,
6618   dw2_map_symtabs_matching_filename,
6619   dw2_debug_names_lookup_symbol,
6620   dw2_print_stats,
6621   dw2_debug_names_dump,
6622   dw2_relocate,
6623   dw2_debug_names_expand_symtabs_for_function,
6624   dw2_expand_all_symtabs,
6625   dw2_expand_symtabs_with_fullname,
6626   dw2_map_matching_symbols,
6627   dw2_debug_names_expand_symtabs_matching,
6628   dw2_find_pc_sect_compunit_symtab,
6629   NULL,
6630   dw2_map_symbol_filenames
6631 };
6632
6633 /* See symfile.h.  */
6634
6635 bool
6636 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6637 {
6638   struct dwarf2_per_objfile *dwarf2_per_objfile
6639     = get_dwarf2_per_objfile (objfile);
6640
6641   /* If we're about to read full symbols, don't bother with the
6642      indices.  In this case we also don't care if some other debug
6643      format is making psymtabs, because they are all about to be
6644      expanded anyway.  */
6645   if ((objfile->flags & OBJF_READNOW))
6646     {
6647       int i;
6648
6649       dwarf2_per_objfile->using_index = 1;
6650       create_all_comp_units (dwarf2_per_objfile);
6651       create_all_type_units (dwarf2_per_objfile);
6652       dwarf2_per_objfile->quick_file_names_table =
6653         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6654
6655       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6656                        + dwarf2_per_objfile->n_type_units); ++i)
6657         {
6658           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6659
6660           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6661                                             struct dwarf2_per_cu_quick_data);
6662         }
6663
6664       /* Return 1 so that gdb sees the "quick" functions.  However,
6665          these functions will be no-ops because we will have expanded
6666          all symtabs.  */
6667       *index_kind = dw_index_kind::GDB_INDEX;
6668       return true;
6669     }
6670
6671   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6672     {
6673       *index_kind = dw_index_kind::DEBUG_NAMES;
6674       return true;
6675     }
6676
6677   if (dwarf2_read_index (objfile))
6678     {
6679       *index_kind = dw_index_kind::GDB_INDEX;
6680       return true;
6681     }
6682
6683   return false;
6684 }
6685
6686 \f
6687
6688 /* Build a partial symbol table.  */
6689
6690 void
6691 dwarf2_build_psymtabs (struct objfile *objfile)
6692 {
6693   struct dwarf2_per_objfile *dwarf2_per_objfile
6694     = get_dwarf2_per_objfile (objfile);
6695
6696   if (objfile->global_psymbols.capacity () == 0
6697       && objfile->static_psymbols.capacity () == 0)
6698     init_psymbol_list (objfile, 1024);
6699
6700   TRY
6701     {
6702       /* This isn't really ideal: all the data we allocate on the
6703          objfile's obstack is still uselessly kept around.  However,
6704          freeing it seems unsafe.  */
6705       psymtab_discarder psymtabs (objfile);
6706       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6707       psymtabs.keep ();
6708     }
6709   CATCH (except, RETURN_MASK_ERROR)
6710     {
6711       exception_print (gdb_stderr, except);
6712     }
6713   END_CATCH
6714 }
6715
6716 /* Return the total length of the CU described by HEADER.  */
6717
6718 static unsigned int
6719 get_cu_length (const struct comp_unit_head *header)
6720 {
6721   return header->initial_length_size + header->length;
6722 }
6723
6724 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6725
6726 static inline bool
6727 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6728 {
6729   sect_offset bottom = cu_header->sect_off;
6730   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6731
6732   return sect_off >= bottom && sect_off < top;
6733 }
6734
6735 /* Find the base address of the compilation unit for range lists and
6736    location lists.  It will normally be specified by DW_AT_low_pc.
6737    In DWARF-3 draft 4, the base address could be overridden by
6738    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6739    compilation units with discontinuous ranges.  */
6740
6741 static void
6742 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6743 {
6744   struct attribute *attr;
6745
6746   cu->base_known = 0;
6747   cu->base_address = 0;
6748
6749   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6750   if (attr)
6751     {
6752       cu->base_address = attr_value_as_address (attr);
6753       cu->base_known = 1;
6754     }
6755   else
6756     {
6757       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6758       if (attr)
6759         {
6760           cu->base_address = attr_value_as_address (attr);
6761           cu->base_known = 1;
6762         }
6763     }
6764 }
6765
6766 /* Read in the comp unit header information from the debug_info at info_ptr.
6767    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6768    NOTE: This leaves members offset, first_die_offset to be filled in
6769    by the caller.  */
6770
6771 static const gdb_byte *
6772 read_comp_unit_head (struct comp_unit_head *cu_header,
6773                      const gdb_byte *info_ptr,
6774                      struct dwarf2_section_info *section,
6775                      rcuh_kind section_kind)
6776 {
6777   int signed_addr;
6778   unsigned int bytes_read;
6779   const char *filename = get_section_file_name (section);
6780   bfd *abfd = get_section_bfd_owner (section);
6781
6782   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6783   cu_header->initial_length_size = bytes_read;
6784   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6785   info_ptr += bytes_read;
6786   cu_header->version = read_2_bytes (abfd, info_ptr);
6787   info_ptr += 2;
6788   if (cu_header->version < 5)
6789     switch (section_kind)
6790       {
6791       case rcuh_kind::COMPILE:
6792         cu_header->unit_type = DW_UT_compile;
6793         break;
6794       case rcuh_kind::TYPE:
6795         cu_header->unit_type = DW_UT_type;
6796         break;
6797       default:
6798         internal_error (__FILE__, __LINE__,
6799                         _("read_comp_unit_head: invalid section_kind"));
6800       }
6801   else
6802     {
6803       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6804                                                  (read_1_byte (abfd, info_ptr));
6805       info_ptr += 1;
6806       switch (cu_header->unit_type)
6807         {
6808         case DW_UT_compile:
6809           if (section_kind != rcuh_kind::COMPILE)
6810             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6811                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6812                    filename);
6813           break;
6814         case DW_UT_type:
6815           section_kind = rcuh_kind::TYPE;
6816           break;
6817         default:
6818           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6819                  "(is %d, should be %d or %d) [in module %s]"),
6820                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6821         }
6822
6823       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6824       info_ptr += 1;
6825     }
6826   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6827                                                           cu_header,
6828                                                           &bytes_read);
6829   info_ptr += bytes_read;
6830   if (cu_header->version < 5)
6831     {
6832       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6833       info_ptr += 1;
6834     }
6835   signed_addr = bfd_get_sign_extend_vma (abfd);
6836   if (signed_addr < 0)
6837     internal_error (__FILE__, __LINE__,
6838                     _("read_comp_unit_head: dwarf from non elf file"));
6839   cu_header->signed_addr_p = signed_addr;
6840
6841   if (section_kind == rcuh_kind::TYPE)
6842     {
6843       LONGEST type_offset;
6844
6845       cu_header->signature = read_8_bytes (abfd, info_ptr);
6846       info_ptr += 8;
6847
6848       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6849       info_ptr += bytes_read;
6850       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6851       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6852         error (_("Dwarf Error: Too big type_offset in compilation unit "
6853                "header (is %s) [in module %s]"), plongest (type_offset),
6854                filename);
6855     }
6856
6857   return info_ptr;
6858 }
6859
6860 /* Helper function that returns the proper abbrev section for
6861    THIS_CU.  */
6862
6863 static struct dwarf2_section_info *
6864 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6865 {
6866   struct dwarf2_section_info *abbrev;
6867   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6868
6869   if (this_cu->is_dwz)
6870     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6871   else
6872     abbrev = &dwarf2_per_objfile->abbrev;
6873
6874   return abbrev;
6875 }
6876
6877 /* Subroutine of read_and_check_comp_unit_head and
6878    read_and_check_type_unit_head to simplify them.
6879    Perform various error checking on the header.  */
6880
6881 static void
6882 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6883                             struct comp_unit_head *header,
6884                             struct dwarf2_section_info *section,
6885                             struct dwarf2_section_info *abbrev_section)
6886 {
6887   const char *filename = get_section_file_name (section);
6888
6889   if (header->version < 2 || header->version > 5)
6890     error (_("Dwarf Error: wrong version in compilation unit header "
6891            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6892            filename);
6893
6894   if (to_underlying (header->abbrev_sect_off)
6895       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6896     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6897            "(offset %s + 6) [in module %s]"),
6898            sect_offset_str (header->abbrev_sect_off),
6899            sect_offset_str (header->sect_off),
6900            filename);
6901
6902   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6903      avoid potential 32-bit overflow.  */
6904   if (((ULONGEST) header->sect_off + get_cu_length (header))
6905       > section->size)
6906     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6907            "(offset %s + 0) [in module %s]"),
6908            header->length, sect_offset_str (header->sect_off),
6909            filename);
6910 }
6911
6912 /* Read in a CU/TU header and perform some basic error checking.
6913    The contents of the header are stored in HEADER.
6914    The result is a pointer to the start of the first DIE.  */
6915
6916 static const gdb_byte *
6917 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6918                                struct comp_unit_head *header,
6919                                struct dwarf2_section_info *section,
6920                                struct dwarf2_section_info *abbrev_section,
6921                                const gdb_byte *info_ptr,
6922                                rcuh_kind section_kind)
6923 {
6924   const gdb_byte *beg_of_comp_unit = info_ptr;
6925
6926   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6927
6928   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6929
6930   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6931
6932   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6933                               abbrev_section);
6934
6935   return info_ptr;
6936 }
6937
6938 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6939
6940 static sect_offset
6941 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6942                     struct dwarf2_section_info *section,
6943                     sect_offset sect_off)
6944 {
6945   bfd *abfd = get_section_bfd_owner (section);
6946   const gdb_byte *info_ptr;
6947   unsigned int initial_length_size, offset_size;
6948   uint16_t version;
6949
6950   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6951   info_ptr = section->buffer + to_underlying (sect_off);
6952   read_initial_length (abfd, info_ptr, &initial_length_size);
6953   offset_size = initial_length_size == 4 ? 4 : 8;
6954   info_ptr += initial_length_size;
6955
6956   version = read_2_bytes (abfd, info_ptr);
6957   info_ptr += 2;
6958   if (version >= 5)
6959     {
6960       /* Skip unit type and address size.  */
6961       info_ptr += 2;
6962     }
6963
6964   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6965 }
6966
6967 /* Allocate a new partial symtab for file named NAME and mark this new
6968    partial symtab as being an include of PST.  */
6969
6970 static void
6971 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6972                                struct objfile *objfile)
6973 {
6974   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6975
6976   if (!IS_ABSOLUTE_PATH (subpst->filename))
6977     {
6978       /* It shares objfile->objfile_obstack.  */
6979       subpst->dirname = pst->dirname;
6980     }
6981
6982   subpst->textlow = 0;
6983   subpst->texthigh = 0;
6984
6985   subpst->dependencies
6986     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6987   subpst->dependencies[0] = pst;
6988   subpst->number_of_dependencies = 1;
6989
6990   subpst->globals_offset = 0;
6991   subpst->n_global_syms = 0;
6992   subpst->statics_offset = 0;
6993   subpst->n_static_syms = 0;
6994   subpst->compunit_symtab = NULL;
6995   subpst->read_symtab = pst->read_symtab;
6996   subpst->readin = 0;
6997
6998   /* No private part is necessary for include psymtabs.  This property
6999      can be used to differentiate between such include psymtabs and
7000      the regular ones.  */
7001   subpst->read_symtab_private = NULL;
7002 }
7003
7004 /* Read the Line Number Program data and extract the list of files
7005    included by the source file represented by PST.  Build an include
7006    partial symtab for each of these included files.  */
7007
7008 static void
7009 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
7010                                struct die_info *die,
7011                                struct partial_symtab *pst)
7012 {
7013   line_header_up lh;
7014   struct attribute *attr;
7015
7016   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7017   if (attr)
7018     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
7019   if (lh == NULL)
7020     return;  /* No linetable, so no includes.  */
7021
7022   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
7023   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
7024 }
7025
7026 static hashval_t
7027 hash_signatured_type (const void *item)
7028 {
7029   const struct signatured_type *sig_type
7030     = (const struct signatured_type *) item;
7031
7032   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
7033   return sig_type->signature;
7034 }
7035
7036 static int
7037 eq_signatured_type (const void *item_lhs, const void *item_rhs)
7038 {
7039   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
7040   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
7041
7042   return lhs->signature == rhs->signature;
7043 }
7044
7045 /* Allocate a hash table for signatured types.  */
7046
7047 static htab_t
7048 allocate_signatured_type_table (struct objfile *objfile)
7049 {
7050   return htab_create_alloc_ex (41,
7051                                hash_signatured_type,
7052                                eq_signatured_type,
7053                                NULL,
7054                                &objfile->objfile_obstack,
7055                                hashtab_obstack_allocate,
7056                                dummy_obstack_deallocate);
7057 }
7058
7059 /* A helper function to add a signatured type CU to a table.  */
7060
7061 static int
7062 add_signatured_type_cu_to_table (void **slot, void *datum)
7063 {
7064   struct signatured_type *sigt = (struct signatured_type *) *slot;
7065   struct signatured_type ***datap = (struct signatured_type ***) datum;
7066
7067   **datap = sigt;
7068   ++*datap;
7069
7070   return 1;
7071 }
7072
7073 /* A helper for create_debug_types_hash_table.  Read types from SECTION
7074    and fill them into TYPES_HTAB.  It will process only type units,
7075    therefore DW_UT_type.  */
7076
7077 static void
7078 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7079                               struct dwo_file *dwo_file,
7080                               dwarf2_section_info *section, htab_t &types_htab,
7081                               rcuh_kind section_kind)
7082 {
7083   struct objfile *objfile = dwarf2_per_objfile->objfile;
7084   struct dwarf2_section_info *abbrev_section;
7085   bfd *abfd;
7086   const gdb_byte *info_ptr, *end_ptr;
7087
7088   abbrev_section = (dwo_file != NULL
7089                     ? &dwo_file->sections.abbrev
7090                     : &dwarf2_per_objfile->abbrev);
7091
7092   if (dwarf_read_debug)
7093     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
7094                         get_section_name (section),
7095                         get_section_file_name (abbrev_section));
7096
7097   dwarf2_read_section (objfile, section);
7098   info_ptr = section->buffer;
7099
7100   if (info_ptr == NULL)
7101     return;
7102
7103   /* We can't set abfd until now because the section may be empty or
7104      not present, in which case the bfd is unknown.  */
7105   abfd = get_section_bfd_owner (section);
7106
7107   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7108      because we don't need to read any dies: the signature is in the
7109      header.  */
7110
7111   end_ptr = info_ptr + section->size;
7112   while (info_ptr < end_ptr)
7113     {
7114       struct signatured_type *sig_type;
7115       struct dwo_unit *dwo_tu;
7116       void **slot;
7117       const gdb_byte *ptr = info_ptr;
7118       struct comp_unit_head header;
7119       unsigned int length;
7120
7121       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7122
7123       /* Initialize it due to a false compiler warning.  */
7124       header.signature = -1;
7125       header.type_cu_offset_in_tu = (cu_offset) -1;
7126
7127       /* We need to read the type's signature in order to build the hash
7128          table, but we don't need anything else just yet.  */
7129
7130       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7131                                            abbrev_section, ptr, section_kind);
7132
7133       length = get_cu_length (&header);
7134
7135       /* Skip dummy type units.  */
7136       if (ptr >= info_ptr + length
7137           || peek_abbrev_code (abfd, ptr) == 0
7138           || header.unit_type != DW_UT_type)
7139         {
7140           info_ptr += length;
7141           continue;
7142         }
7143
7144       if (types_htab == NULL)
7145         {
7146           if (dwo_file)
7147             types_htab = allocate_dwo_unit_table (objfile);
7148           else
7149             types_htab = allocate_signatured_type_table (objfile);
7150         }
7151
7152       if (dwo_file)
7153         {
7154           sig_type = NULL;
7155           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7156                                    struct dwo_unit);
7157           dwo_tu->dwo_file = dwo_file;
7158           dwo_tu->signature = header.signature;
7159           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7160           dwo_tu->section = section;
7161           dwo_tu->sect_off = sect_off;
7162           dwo_tu->length = length;
7163         }
7164       else
7165         {
7166           /* N.B.: type_offset is not usable if this type uses a DWO file.
7167              The real type_offset is in the DWO file.  */
7168           dwo_tu = NULL;
7169           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7170                                      struct signatured_type);
7171           sig_type->signature = header.signature;
7172           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7173           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7174           sig_type->per_cu.is_debug_types = 1;
7175           sig_type->per_cu.section = section;
7176           sig_type->per_cu.sect_off = sect_off;
7177           sig_type->per_cu.length = length;
7178         }
7179
7180       slot = htab_find_slot (types_htab,
7181                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7182                              INSERT);
7183       gdb_assert (slot != NULL);
7184       if (*slot != NULL)
7185         {
7186           sect_offset dup_sect_off;
7187
7188           if (dwo_file)
7189             {
7190               const struct dwo_unit *dup_tu
7191                 = (const struct dwo_unit *) *slot;
7192
7193               dup_sect_off = dup_tu->sect_off;
7194             }
7195           else
7196             {
7197               const struct signatured_type *dup_tu
7198                 = (const struct signatured_type *) *slot;
7199
7200               dup_sect_off = dup_tu->per_cu.sect_off;
7201             }
7202
7203           complaint (&symfile_complaints,
7204                      _("debug type entry at offset %s is duplicate to"
7205                        " the entry at offset %s, signature %s"),
7206                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
7207                      hex_string (header.signature));
7208         }
7209       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7210
7211       if (dwarf_read_debug > 1)
7212         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
7213                             sect_offset_str (sect_off),
7214                             hex_string (header.signature));
7215
7216       info_ptr += length;
7217     }
7218 }
7219
7220 /* Create the hash table of all entries in the .debug_types
7221    (or .debug_types.dwo) section(s).
7222    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7223    otherwise it is NULL.
7224
7225    The result is a pointer to the hash table or NULL if there are no types.
7226
7227    Note: This function processes DWO files only, not DWP files.  */
7228
7229 static void
7230 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7231                                struct dwo_file *dwo_file,
7232                                VEC (dwarf2_section_info_def) *types,
7233                                htab_t &types_htab)
7234 {
7235   int ix;
7236   struct dwarf2_section_info *section;
7237
7238   if (VEC_empty (dwarf2_section_info_def, types))
7239     return;
7240
7241   for (ix = 0;
7242        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7243        ++ix)
7244     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7245                                   types_htab, rcuh_kind::TYPE);
7246 }
7247
7248 /* Create the hash table of all entries in the .debug_types section,
7249    and initialize all_type_units.
7250    The result is zero if there is an error (e.g. missing .debug_types section),
7251    otherwise non-zero.  */
7252
7253 static int
7254 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7255 {
7256   htab_t types_htab = NULL;
7257   struct signatured_type **iter;
7258
7259   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7260                                 &dwarf2_per_objfile->info, types_htab,
7261                                 rcuh_kind::COMPILE);
7262   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7263                                  dwarf2_per_objfile->types, types_htab);
7264   if (types_htab == NULL)
7265     {
7266       dwarf2_per_objfile->signatured_types = NULL;
7267       return 0;
7268     }
7269
7270   dwarf2_per_objfile->signatured_types = types_htab;
7271
7272   dwarf2_per_objfile->n_type_units
7273     = dwarf2_per_objfile->n_allocated_type_units
7274     = htab_elements (types_htab);
7275   dwarf2_per_objfile->all_type_units =
7276     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7277   iter = &dwarf2_per_objfile->all_type_units[0];
7278   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7279   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7280               == dwarf2_per_objfile->n_type_units);
7281
7282   return 1;
7283 }
7284
7285 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7286    If SLOT is non-NULL, it is the entry to use in the hash table.
7287    Otherwise we find one.  */
7288
7289 static struct signatured_type *
7290 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7291                void **slot)
7292 {
7293   struct objfile *objfile = dwarf2_per_objfile->objfile;
7294   int n_type_units = dwarf2_per_objfile->n_type_units;
7295   struct signatured_type *sig_type;
7296
7297   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7298   ++n_type_units;
7299   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7300     {
7301       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7302         dwarf2_per_objfile->n_allocated_type_units = 1;
7303       dwarf2_per_objfile->n_allocated_type_units *= 2;
7304       dwarf2_per_objfile->all_type_units
7305         = XRESIZEVEC (struct signatured_type *,
7306                       dwarf2_per_objfile->all_type_units,
7307                       dwarf2_per_objfile->n_allocated_type_units);
7308       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7309     }
7310   dwarf2_per_objfile->n_type_units = n_type_units;
7311
7312   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7313                              struct signatured_type);
7314   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7315   sig_type->signature = sig;
7316   sig_type->per_cu.is_debug_types = 1;
7317   if (dwarf2_per_objfile->using_index)
7318     {
7319       sig_type->per_cu.v.quick =
7320         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7321                         struct dwarf2_per_cu_quick_data);
7322     }
7323
7324   if (slot == NULL)
7325     {
7326       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7327                              sig_type, INSERT);
7328     }
7329   gdb_assert (*slot == NULL);
7330   *slot = sig_type;
7331   /* The rest of sig_type must be filled in by the caller.  */
7332   return sig_type;
7333 }
7334
7335 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7336    Fill in SIG_ENTRY with DWO_ENTRY.  */
7337
7338 static void
7339 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7340                                   struct signatured_type *sig_entry,
7341                                   struct dwo_unit *dwo_entry)
7342 {
7343   /* Make sure we're not clobbering something we don't expect to.  */
7344   gdb_assert (! sig_entry->per_cu.queued);
7345   gdb_assert (sig_entry->per_cu.cu == NULL);
7346   if (dwarf2_per_objfile->using_index)
7347     {
7348       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7349       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7350     }
7351   else
7352       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7353   gdb_assert (sig_entry->signature == dwo_entry->signature);
7354   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7355   gdb_assert (sig_entry->type_unit_group == NULL);
7356   gdb_assert (sig_entry->dwo_unit == NULL);
7357
7358   sig_entry->per_cu.section = dwo_entry->section;
7359   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7360   sig_entry->per_cu.length = dwo_entry->length;
7361   sig_entry->per_cu.reading_dwo_directly = 1;
7362   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7363   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7364   sig_entry->dwo_unit = dwo_entry;
7365 }
7366
7367 /* Subroutine of lookup_signatured_type.
7368    If we haven't read the TU yet, create the signatured_type data structure
7369    for a TU to be read in directly from a DWO file, bypassing the stub.
7370    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7371    using .gdb_index, then when reading a CU we want to stay in the DWO file
7372    containing that CU.  Otherwise we could end up reading several other DWO
7373    files (due to comdat folding) to process the transitive closure of all the
7374    mentioned TUs, and that can be slow.  The current DWO file will have every
7375    type signature that it needs.
7376    We only do this for .gdb_index because in the psymtab case we already have
7377    to read all the DWOs to build the type unit groups.  */
7378
7379 static struct signatured_type *
7380 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7381 {
7382   struct dwarf2_per_objfile *dwarf2_per_objfile
7383     = cu->per_cu->dwarf2_per_objfile;
7384   struct objfile *objfile = dwarf2_per_objfile->objfile;
7385   struct dwo_file *dwo_file;
7386   struct dwo_unit find_dwo_entry, *dwo_entry;
7387   struct signatured_type find_sig_entry, *sig_entry;
7388   void **slot;
7389
7390   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7391
7392   /* If TU skeletons have been removed then we may not have read in any
7393      TUs yet.  */
7394   if (dwarf2_per_objfile->signatured_types == NULL)
7395     {
7396       dwarf2_per_objfile->signatured_types
7397         = allocate_signatured_type_table (objfile);
7398     }
7399
7400   /* We only ever need to read in one copy of a signatured type.
7401      Use the global signatured_types array to do our own comdat-folding
7402      of types.  If this is the first time we're reading this TU, and
7403      the TU has an entry in .gdb_index, replace the recorded data from
7404      .gdb_index with this TU.  */
7405
7406   find_sig_entry.signature = sig;
7407   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7408                          &find_sig_entry, INSERT);
7409   sig_entry = (struct signatured_type *) *slot;
7410
7411   /* We can get here with the TU already read, *or* in the process of being
7412      read.  Don't reassign the global entry to point to this DWO if that's
7413      the case.  Also note that if the TU is already being read, it may not
7414      have come from a DWO, the program may be a mix of Fission-compiled
7415      code and non-Fission-compiled code.  */
7416
7417   /* Have we already tried to read this TU?
7418      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7419      needn't exist in the global table yet).  */
7420   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7421     return sig_entry;
7422
7423   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7424      dwo_unit of the TU itself.  */
7425   dwo_file = cu->dwo_unit->dwo_file;
7426
7427   /* Ok, this is the first time we're reading this TU.  */
7428   if (dwo_file->tus == NULL)
7429     return NULL;
7430   find_dwo_entry.signature = sig;
7431   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7432   if (dwo_entry == NULL)
7433     return NULL;
7434
7435   /* If the global table doesn't have an entry for this TU, add one.  */
7436   if (sig_entry == NULL)
7437     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7438
7439   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7440   sig_entry->per_cu.tu_read = 1;
7441   return sig_entry;
7442 }
7443
7444 /* Subroutine of lookup_signatured_type.
7445    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7446    then try the DWP file.  If the TU stub (skeleton) has been removed then
7447    it won't be in .gdb_index.  */
7448
7449 static struct signatured_type *
7450 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7451 {
7452   struct dwarf2_per_objfile *dwarf2_per_objfile
7453     = cu->per_cu->dwarf2_per_objfile;
7454   struct objfile *objfile = dwarf2_per_objfile->objfile;
7455   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7456   struct dwo_unit *dwo_entry;
7457   struct signatured_type find_sig_entry, *sig_entry;
7458   void **slot;
7459
7460   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7461   gdb_assert (dwp_file != NULL);
7462
7463   /* If TU skeletons have been removed then we may not have read in any
7464      TUs yet.  */
7465   if (dwarf2_per_objfile->signatured_types == NULL)
7466     {
7467       dwarf2_per_objfile->signatured_types
7468         = allocate_signatured_type_table (objfile);
7469     }
7470
7471   find_sig_entry.signature = sig;
7472   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7473                          &find_sig_entry, INSERT);
7474   sig_entry = (struct signatured_type *) *slot;
7475
7476   /* Have we already tried to read this TU?
7477      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7478      needn't exist in the global table yet).  */
7479   if (sig_entry != NULL)
7480     return sig_entry;
7481
7482   if (dwp_file->tus == NULL)
7483     return NULL;
7484   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7485                                       sig, 1 /* is_debug_types */);
7486   if (dwo_entry == NULL)
7487     return NULL;
7488
7489   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7490   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7491
7492   return sig_entry;
7493 }
7494
7495 /* Lookup a signature based type for DW_FORM_ref_sig8.
7496    Returns NULL if signature SIG is not present in the table.
7497    It is up to the caller to complain about this.  */
7498
7499 static struct signatured_type *
7500 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7501 {
7502   struct dwarf2_per_objfile *dwarf2_per_objfile
7503     = cu->per_cu->dwarf2_per_objfile;
7504
7505   if (cu->dwo_unit
7506       && dwarf2_per_objfile->using_index)
7507     {
7508       /* We're in a DWO/DWP file, and we're using .gdb_index.
7509          These cases require special processing.  */
7510       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7511         return lookup_dwo_signatured_type (cu, sig);
7512       else
7513         return lookup_dwp_signatured_type (cu, sig);
7514     }
7515   else
7516     {
7517       struct signatured_type find_entry, *entry;
7518
7519       if (dwarf2_per_objfile->signatured_types == NULL)
7520         return NULL;
7521       find_entry.signature = sig;
7522       entry = ((struct signatured_type *)
7523                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7524       return entry;
7525     }
7526 }
7527 \f
7528 /* Low level DIE reading support.  */
7529
7530 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7531
7532 static void
7533 init_cu_die_reader (struct die_reader_specs *reader,
7534                     struct dwarf2_cu *cu,
7535                     struct dwarf2_section_info *section,
7536                     struct dwo_file *dwo_file,
7537                     struct abbrev_table *abbrev_table)
7538 {
7539   gdb_assert (section->readin && section->buffer != NULL);
7540   reader->abfd = get_section_bfd_owner (section);
7541   reader->cu = cu;
7542   reader->dwo_file = dwo_file;
7543   reader->die_section = section;
7544   reader->buffer = section->buffer;
7545   reader->buffer_end = section->buffer + section->size;
7546   reader->comp_dir = NULL;
7547   reader->abbrev_table = abbrev_table;
7548 }
7549
7550 /* Subroutine of init_cutu_and_read_dies to simplify it.
7551    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7552    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7553    already.
7554
7555    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7556    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7557    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7558    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7559    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7560    STUB_COMP_DIR may be non-NULL.
7561    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7562    are filled in with the info of the DIE from the DWO file.
7563    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7564    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7565    kept around for at least as long as *RESULT_READER.
7566
7567    The result is non-zero if a valid (non-dummy) DIE was found.  */
7568
7569 static int
7570 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7571                         struct dwo_unit *dwo_unit,
7572                         struct die_info *stub_comp_unit_die,
7573                         const char *stub_comp_dir,
7574                         struct die_reader_specs *result_reader,
7575                         const gdb_byte **result_info_ptr,
7576                         struct die_info **result_comp_unit_die,
7577                         int *result_has_children,
7578                         abbrev_table_up *result_dwo_abbrev_table)
7579 {
7580   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7581   struct objfile *objfile = dwarf2_per_objfile->objfile;
7582   struct dwarf2_cu *cu = this_cu->cu;
7583   bfd *abfd;
7584   const gdb_byte *begin_info_ptr, *info_ptr;
7585   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7586   int i,num_extra_attrs;
7587   struct dwarf2_section_info *dwo_abbrev_section;
7588   struct attribute *attr;
7589   struct die_info *comp_unit_die;
7590
7591   /* At most one of these may be provided.  */
7592   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7593
7594   /* These attributes aren't processed until later:
7595      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7596      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7597      referenced later.  However, these attributes are found in the stub
7598      which we won't have later.  In order to not impose this complication
7599      on the rest of the code, we read them here and copy them to the
7600      DWO CU/TU die.  */
7601
7602   stmt_list = NULL;
7603   low_pc = NULL;
7604   high_pc = NULL;
7605   ranges = NULL;
7606   comp_dir = NULL;
7607
7608   if (stub_comp_unit_die != NULL)
7609     {
7610       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7611          DWO file.  */
7612       if (! this_cu->is_debug_types)
7613         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7614       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7615       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7616       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7617       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7618
7619       /* There should be a DW_AT_addr_base attribute here (if needed).
7620          We need the value before we can process DW_FORM_GNU_addr_index.  */
7621       cu->addr_base = 0;
7622       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7623       if (attr)
7624         cu->addr_base = DW_UNSND (attr);
7625
7626       /* There should be a DW_AT_ranges_base attribute here (if needed).
7627          We need the value before we can process DW_AT_ranges.  */
7628       cu->ranges_base = 0;
7629       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7630       if (attr)
7631         cu->ranges_base = DW_UNSND (attr);
7632     }
7633   else if (stub_comp_dir != NULL)
7634     {
7635       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7636       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7637       comp_dir->name = DW_AT_comp_dir;
7638       comp_dir->form = DW_FORM_string;
7639       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7640       DW_STRING (comp_dir) = stub_comp_dir;
7641     }
7642
7643   /* Set up for reading the DWO CU/TU.  */
7644   cu->dwo_unit = dwo_unit;
7645   dwarf2_section_info *section = dwo_unit->section;
7646   dwarf2_read_section (objfile, section);
7647   abfd = get_section_bfd_owner (section);
7648   begin_info_ptr = info_ptr = (section->buffer
7649                                + to_underlying (dwo_unit->sect_off));
7650   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7651
7652   if (this_cu->is_debug_types)
7653     {
7654       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7655
7656       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7657                                                 &cu->header, section,
7658                                                 dwo_abbrev_section,
7659                                                 info_ptr, rcuh_kind::TYPE);
7660       /* This is not an assert because it can be caused by bad debug info.  */
7661       if (sig_type->signature != cu->header.signature)
7662         {
7663           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7664                    " TU at offset %s [in module %s]"),
7665                  hex_string (sig_type->signature),
7666                  hex_string (cu->header.signature),
7667                  sect_offset_str (dwo_unit->sect_off),
7668                  bfd_get_filename (abfd));
7669         }
7670       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7671       /* For DWOs coming from DWP files, we don't know the CU length
7672          nor the type's offset in the TU until now.  */
7673       dwo_unit->length = get_cu_length (&cu->header);
7674       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7675
7676       /* Establish the type offset that can be used to lookup the type.
7677          For DWO files, we don't know it until now.  */
7678       sig_type->type_offset_in_section
7679         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7680     }
7681   else
7682     {
7683       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7684                                                 &cu->header, section,
7685                                                 dwo_abbrev_section,
7686                                                 info_ptr, rcuh_kind::COMPILE);
7687       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7688       /* For DWOs coming from DWP files, we don't know the CU length
7689          until now.  */
7690       dwo_unit->length = get_cu_length (&cu->header);
7691     }
7692
7693   *result_dwo_abbrev_table
7694     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7695                                cu->header.abbrev_sect_off);
7696   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7697                       result_dwo_abbrev_table->get ());
7698
7699   /* Read in the die, but leave space to copy over the attributes
7700      from the stub.  This has the benefit of simplifying the rest of
7701      the code - all the work to maintain the illusion of a single
7702      DW_TAG_{compile,type}_unit DIE is done here.  */
7703   num_extra_attrs = ((stmt_list != NULL)
7704                      + (low_pc != NULL)
7705                      + (high_pc != NULL)
7706                      + (ranges != NULL)
7707                      + (comp_dir != NULL));
7708   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7709                               result_has_children, num_extra_attrs);
7710
7711   /* Copy over the attributes from the stub to the DIE we just read in.  */
7712   comp_unit_die = *result_comp_unit_die;
7713   i = comp_unit_die->num_attrs;
7714   if (stmt_list != NULL)
7715     comp_unit_die->attrs[i++] = *stmt_list;
7716   if (low_pc != NULL)
7717     comp_unit_die->attrs[i++] = *low_pc;
7718   if (high_pc != NULL)
7719     comp_unit_die->attrs[i++] = *high_pc;
7720   if (ranges != NULL)
7721     comp_unit_die->attrs[i++] = *ranges;
7722   if (comp_dir != NULL)
7723     comp_unit_die->attrs[i++] = *comp_dir;
7724   comp_unit_die->num_attrs += num_extra_attrs;
7725
7726   if (dwarf_die_debug)
7727     {
7728       fprintf_unfiltered (gdb_stdlog,
7729                           "Read die from %s@0x%x of %s:\n",
7730                           get_section_name (section),
7731                           (unsigned) (begin_info_ptr - section->buffer),
7732                           bfd_get_filename (abfd));
7733       dump_die (comp_unit_die, dwarf_die_debug);
7734     }
7735
7736   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7737      TUs by skipping the stub and going directly to the entry in the DWO file.
7738      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7739      to get it via circuitous means.  Blech.  */
7740   if (comp_dir != NULL)
7741     result_reader->comp_dir = DW_STRING (comp_dir);
7742
7743   /* Skip dummy compilation units.  */
7744   if (info_ptr >= begin_info_ptr + dwo_unit->length
7745       || peek_abbrev_code (abfd, info_ptr) == 0)
7746     return 0;
7747
7748   *result_info_ptr = info_ptr;
7749   return 1;
7750 }
7751
7752 /* Subroutine of init_cutu_and_read_dies to simplify it.
7753    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7754    Returns NULL if the specified DWO unit cannot be found.  */
7755
7756 static struct dwo_unit *
7757 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7758                  struct die_info *comp_unit_die)
7759 {
7760   struct dwarf2_cu *cu = this_cu->cu;
7761   ULONGEST signature;
7762   struct dwo_unit *dwo_unit;
7763   const char *comp_dir, *dwo_name;
7764
7765   gdb_assert (cu != NULL);
7766
7767   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7768   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7769   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7770
7771   if (this_cu->is_debug_types)
7772     {
7773       struct signatured_type *sig_type;
7774
7775       /* Since this_cu is the first member of struct signatured_type,
7776          we can go from a pointer to one to a pointer to the other.  */
7777       sig_type = (struct signatured_type *) this_cu;
7778       signature = sig_type->signature;
7779       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7780     }
7781   else
7782     {
7783       struct attribute *attr;
7784
7785       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7786       if (! attr)
7787         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7788                  " [in module %s]"),
7789                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7790       signature = DW_UNSND (attr);
7791       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7792                                        signature);
7793     }
7794
7795   return dwo_unit;
7796 }
7797
7798 /* Subroutine of init_cutu_and_read_dies to simplify it.
7799    See it for a description of the parameters.
7800    Read a TU directly from a DWO file, bypassing the stub.  */
7801
7802 static void
7803 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7804                            int use_existing_cu, int keep,
7805                            die_reader_func_ftype *die_reader_func,
7806                            void *data)
7807 {
7808   std::unique_ptr<dwarf2_cu> new_cu;
7809   struct signatured_type *sig_type;
7810   struct die_reader_specs reader;
7811   const gdb_byte *info_ptr;
7812   struct die_info *comp_unit_die;
7813   int has_children;
7814   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7815
7816   /* Verify we can do the following downcast, and that we have the
7817      data we need.  */
7818   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7819   sig_type = (struct signatured_type *) this_cu;
7820   gdb_assert (sig_type->dwo_unit != NULL);
7821
7822   if (use_existing_cu && this_cu->cu != NULL)
7823     {
7824       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7825       /* There's no need to do the rereading_dwo_cu handling that
7826          init_cutu_and_read_dies does since we don't read the stub.  */
7827     }
7828   else
7829     {
7830       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7831       gdb_assert (this_cu->cu == NULL);
7832       new_cu.reset (new dwarf2_cu (this_cu));
7833     }
7834
7835   /* A future optimization, if needed, would be to use an existing
7836      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7837      could share abbrev tables.  */
7838
7839   /* The abbreviation table used by READER, this must live at least as long as
7840      READER.  */
7841   abbrev_table_up dwo_abbrev_table;
7842
7843   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7844                               NULL /* stub_comp_unit_die */,
7845                               sig_type->dwo_unit->dwo_file->comp_dir,
7846                               &reader, &info_ptr,
7847                               &comp_unit_die, &has_children,
7848                               &dwo_abbrev_table) == 0)
7849     {
7850       /* Dummy die.  */
7851       return;
7852     }
7853
7854   /* All the "real" work is done here.  */
7855   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7856
7857   /* This duplicates the code in init_cutu_and_read_dies,
7858      but the alternative is making the latter more complex.
7859      This function is only for the special case of using DWO files directly:
7860      no point in overly complicating the general case just to handle this.  */
7861   if (new_cu != NULL && keep)
7862     {
7863       /* Link this CU into read_in_chain.  */
7864       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7865       dwarf2_per_objfile->read_in_chain = this_cu;
7866       /* The chain owns it now.  */
7867       new_cu.release ();
7868     }
7869 }
7870
7871 /* Initialize a CU (or TU) and read its DIEs.
7872    If the CU defers to a DWO file, read the DWO file as well.
7873
7874    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7875    Otherwise the table specified in the comp unit header is read in and used.
7876    This is an optimization for when we already have the abbrev table.
7877
7878    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7879    Otherwise, a new CU is allocated with xmalloc.
7880
7881    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7882    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7883
7884    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7885    linker) then DIE_READER_FUNC will not get called.  */
7886
7887 static void
7888 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7889                          struct abbrev_table *abbrev_table,
7890                          int use_existing_cu, int keep,
7891                          die_reader_func_ftype *die_reader_func,
7892                          void *data)
7893 {
7894   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7895   struct objfile *objfile = dwarf2_per_objfile->objfile;
7896   struct dwarf2_section_info *section = this_cu->section;
7897   bfd *abfd = get_section_bfd_owner (section);
7898   struct dwarf2_cu *cu;
7899   const gdb_byte *begin_info_ptr, *info_ptr;
7900   struct die_reader_specs reader;
7901   struct die_info *comp_unit_die;
7902   int has_children;
7903   struct attribute *attr;
7904   struct signatured_type *sig_type = NULL;
7905   struct dwarf2_section_info *abbrev_section;
7906   /* Non-zero if CU currently points to a DWO file and we need to
7907      reread it.  When this happens we need to reread the skeleton die
7908      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7909   int rereading_dwo_cu = 0;
7910
7911   if (dwarf_die_debug)
7912     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7913                         this_cu->is_debug_types ? "type" : "comp",
7914                         sect_offset_str (this_cu->sect_off));
7915
7916   if (use_existing_cu)
7917     gdb_assert (keep);
7918
7919   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7920      file (instead of going through the stub), short-circuit all of this.  */
7921   if (this_cu->reading_dwo_directly)
7922     {
7923       /* Narrow down the scope of possibilities to have to understand.  */
7924       gdb_assert (this_cu->is_debug_types);
7925       gdb_assert (abbrev_table == NULL);
7926       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7927                                  die_reader_func, data);
7928       return;
7929     }
7930
7931   /* This is cheap if the section is already read in.  */
7932   dwarf2_read_section (objfile, section);
7933
7934   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7935
7936   abbrev_section = get_abbrev_section_for_cu (this_cu);
7937
7938   std::unique_ptr<dwarf2_cu> new_cu;
7939   if (use_existing_cu && this_cu->cu != NULL)
7940     {
7941       cu = this_cu->cu;
7942       /* If this CU is from a DWO file we need to start over, we need to
7943          refetch the attributes from the skeleton CU.
7944          This could be optimized by retrieving those attributes from when we
7945          were here the first time: the previous comp_unit_die was stored in
7946          comp_unit_obstack.  But there's no data yet that we need this
7947          optimization.  */
7948       if (cu->dwo_unit != NULL)
7949         rereading_dwo_cu = 1;
7950     }
7951   else
7952     {
7953       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7954       gdb_assert (this_cu->cu == NULL);
7955       new_cu.reset (new dwarf2_cu (this_cu));
7956       cu = new_cu.get ();
7957     }
7958
7959   /* Get the header.  */
7960   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7961     {
7962       /* We already have the header, there's no need to read it in again.  */
7963       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7964     }
7965   else
7966     {
7967       if (this_cu->is_debug_types)
7968         {
7969           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7970                                                     &cu->header, section,
7971                                                     abbrev_section, info_ptr,
7972                                                     rcuh_kind::TYPE);
7973
7974           /* Since per_cu is the first member of struct signatured_type,
7975              we can go from a pointer to one to a pointer to the other.  */
7976           sig_type = (struct signatured_type *) this_cu;
7977           gdb_assert (sig_type->signature == cu->header.signature);
7978           gdb_assert (sig_type->type_offset_in_tu
7979                       == cu->header.type_cu_offset_in_tu);
7980           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7981
7982           /* LENGTH has not been set yet for type units if we're
7983              using .gdb_index.  */
7984           this_cu->length = get_cu_length (&cu->header);
7985
7986           /* Establish the type offset that can be used to lookup the type.  */
7987           sig_type->type_offset_in_section =
7988             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7989
7990           this_cu->dwarf_version = cu->header.version;
7991         }
7992       else
7993         {
7994           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7995                                                     &cu->header, section,
7996                                                     abbrev_section,
7997                                                     info_ptr,
7998                                                     rcuh_kind::COMPILE);
7999
8000           gdb_assert (this_cu->sect_off == cu->header.sect_off);
8001           gdb_assert (this_cu->length == get_cu_length (&cu->header));
8002           this_cu->dwarf_version = cu->header.version;
8003         }
8004     }
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     return;
8010
8011   /* If we don't have them yet, read the abbrevs for this compilation unit.
8012      And if we need to read them now, make sure they're freed when we're
8013      done (own the table through ABBREV_TABLE_HOLDER).  */
8014   abbrev_table_up abbrev_table_holder;
8015   if (abbrev_table != NULL)
8016     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
8017   else
8018     {
8019       abbrev_table_holder
8020         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8021                                    cu->header.abbrev_sect_off);
8022       abbrev_table = abbrev_table_holder.get ();
8023     }
8024
8025   /* Read the top level CU/TU die.  */
8026   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
8027   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8028
8029   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
8030      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
8031      table from the DWO file and pass the ownership over to us.  It will be
8032      referenced from READER, so we must make sure to free it after we're done
8033      with READER.
8034
8035      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
8036      DWO CU, that this test will fail (the attribute will not be present).  */
8037   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
8038   abbrev_table_up dwo_abbrev_table;
8039   if (attr)
8040     {
8041       struct dwo_unit *dwo_unit;
8042       struct die_info *dwo_comp_unit_die;
8043
8044       if (has_children)
8045         {
8046           complaint (&symfile_complaints,
8047                      _("compilation unit with DW_AT_GNU_dwo_name"
8048                        " has children (offset %s) [in module %s]"),
8049                      sect_offset_str (this_cu->sect_off),
8050                      bfd_get_filename (abfd));
8051         }
8052       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
8053       if (dwo_unit != NULL)
8054         {
8055           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
8056                                       comp_unit_die, NULL,
8057                                       &reader, &info_ptr,
8058                                       &dwo_comp_unit_die, &has_children,
8059                                       &dwo_abbrev_table) == 0)
8060             {
8061               /* Dummy die.  */
8062               return;
8063             }
8064           comp_unit_die = dwo_comp_unit_die;
8065         }
8066       else
8067         {
8068           /* Yikes, we couldn't find the rest of the DIE, we only have
8069              the stub.  A complaint has already been logged.  There's
8070              not much more we can do except pass on the stub DIE to
8071              die_reader_func.  We don't want to throw an error on bad
8072              debug info.  */
8073         }
8074     }
8075
8076   /* All of the above is setup for this call.  Yikes.  */
8077   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8078
8079   /* Done, clean up.  */
8080   if (new_cu != NULL && keep)
8081     {
8082       /* Link this CU into read_in_chain.  */
8083       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8084       dwarf2_per_objfile->read_in_chain = this_cu;
8085       /* The chain owns it now.  */
8086       new_cu.release ();
8087     }
8088 }
8089
8090 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8091    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8092    to have already done the lookup to find the DWO file).
8093
8094    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8095    THIS_CU->is_debug_types, but nothing else.
8096
8097    We fill in THIS_CU->length.
8098
8099    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8100    linker) then DIE_READER_FUNC will not get called.
8101
8102    THIS_CU->cu is always freed when done.
8103    This is done in order to not leave THIS_CU->cu in a state where we have
8104    to care whether it refers to the "main" CU or the DWO CU.  */
8105
8106 static void
8107 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8108                                    struct dwo_file *dwo_file,
8109                                    die_reader_func_ftype *die_reader_func,
8110                                    void *data)
8111 {
8112   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8113   struct objfile *objfile = dwarf2_per_objfile->objfile;
8114   struct dwarf2_section_info *section = this_cu->section;
8115   bfd *abfd = get_section_bfd_owner (section);
8116   struct dwarf2_section_info *abbrev_section;
8117   const gdb_byte *begin_info_ptr, *info_ptr;
8118   struct die_reader_specs reader;
8119   struct die_info *comp_unit_die;
8120   int has_children;
8121
8122   if (dwarf_die_debug)
8123     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
8124                         this_cu->is_debug_types ? "type" : "comp",
8125                         sect_offset_str (this_cu->sect_off));
8126
8127   gdb_assert (this_cu->cu == NULL);
8128
8129   abbrev_section = (dwo_file != NULL
8130                     ? &dwo_file->sections.abbrev
8131                     : get_abbrev_section_for_cu (this_cu));
8132
8133   /* This is cheap if the section is already read in.  */
8134   dwarf2_read_section (objfile, section);
8135
8136   struct dwarf2_cu cu (this_cu);
8137
8138   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8139   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8140                                             &cu.header, section,
8141                                             abbrev_section, info_ptr,
8142                                             (this_cu->is_debug_types
8143                                              ? rcuh_kind::TYPE
8144                                              : rcuh_kind::COMPILE));
8145
8146   this_cu->length = get_cu_length (&cu.header);
8147
8148   /* Skip dummy compilation units.  */
8149   if (info_ptr >= begin_info_ptr + this_cu->length
8150       || peek_abbrev_code (abfd, info_ptr) == 0)
8151     return;
8152
8153   abbrev_table_up abbrev_table
8154     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8155                                cu.header.abbrev_sect_off);
8156
8157   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8158   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8159
8160   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8161 }
8162
8163 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8164    does not lookup the specified DWO file.
8165    This cannot be used to read DWO files.
8166
8167    THIS_CU->cu is always freed when done.
8168    This is done in order to not leave THIS_CU->cu in a state where we have
8169    to care whether it refers to the "main" CU or the DWO CU.
8170    We can revisit this if the data shows there's a performance issue.  */
8171
8172 static void
8173 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8174                                 die_reader_func_ftype *die_reader_func,
8175                                 void *data)
8176 {
8177   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8178 }
8179 \f
8180 /* Type Unit Groups.
8181
8182    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8183    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8184    so that all types coming from the same compilation (.o file) are grouped
8185    together.  A future step could be to put the types in the same symtab as
8186    the CU the types ultimately came from.  */
8187
8188 static hashval_t
8189 hash_type_unit_group (const void *item)
8190 {
8191   const struct type_unit_group *tu_group
8192     = (const struct type_unit_group *) item;
8193
8194   return hash_stmt_list_entry (&tu_group->hash);
8195 }
8196
8197 static int
8198 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8199 {
8200   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8201   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8202
8203   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8204 }
8205
8206 /* Allocate a hash table for type unit groups.  */
8207
8208 static htab_t
8209 allocate_type_unit_groups_table (struct objfile *objfile)
8210 {
8211   return htab_create_alloc_ex (3,
8212                                hash_type_unit_group,
8213                                eq_type_unit_group,
8214                                NULL,
8215                                &objfile->objfile_obstack,
8216                                hashtab_obstack_allocate,
8217                                dummy_obstack_deallocate);
8218 }
8219
8220 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8221    partial symtabs.  We combine several TUs per psymtab to not let the size
8222    of any one psymtab grow too big.  */
8223 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8224 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8225
8226 /* Helper routine for get_type_unit_group.
8227    Create the type_unit_group object used to hold one or more TUs.  */
8228
8229 static struct type_unit_group *
8230 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8231 {
8232   struct dwarf2_per_objfile *dwarf2_per_objfile
8233     = cu->per_cu->dwarf2_per_objfile;
8234   struct objfile *objfile = dwarf2_per_objfile->objfile;
8235   struct dwarf2_per_cu_data *per_cu;
8236   struct type_unit_group *tu_group;
8237
8238   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8239                              struct type_unit_group);
8240   per_cu = &tu_group->per_cu;
8241   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8242
8243   if (dwarf2_per_objfile->using_index)
8244     {
8245       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8246                                         struct dwarf2_per_cu_quick_data);
8247     }
8248   else
8249     {
8250       unsigned int line_offset = to_underlying (line_offset_struct);
8251       struct partial_symtab *pst;
8252       char *name;
8253
8254       /* Give the symtab a useful name for debug purposes.  */
8255       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8256         name = xstrprintf ("<type_units_%d>",
8257                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8258       else
8259         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8260
8261       pst = create_partial_symtab (per_cu, name);
8262       pst->anonymous = 1;
8263
8264       xfree (name);
8265     }
8266
8267   tu_group->hash.dwo_unit = cu->dwo_unit;
8268   tu_group->hash.line_sect_off = line_offset_struct;
8269
8270   return tu_group;
8271 }
8272
8273 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8274    STMT_LIST is a DW_AT_stmt_list attribute.  */
8275
8276 static struct type_unit_group *
8277 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8278 {
8279   struct dwarf2_per_objfile *dwarf2_per_objfile
8280     = cu->per_cu->dwarf2_per_objfile;
8281   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8282   struct type_unit_group *tu_group;
8283   void **slot;
8284   unsigned int line_offset;
8285   struct type_unit_group type_unit_group_for_lookup;
8286
8287   if (dwarf2_per_objfile->type_unit_groups == NULL)
8288     {
8289       dwarf2_per_objfile->type_unit_groups =
8290         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8291     }
8292
8293   /* Do we need to create a new group, or can we use an existing one?  */
8294
8295   if (stmt_list)
8296     {
8297       line_offset = DW_UNSND (stmt_list);
8298       ++tu_stats->nr_symtab_sharers;
8299     }
8300   else
8301     {
8302       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8303          We can do various things here like create one group per TU or
8304          spread them over multiple groups to split up the expansion work.
8305          To avoid worst case scenarios (too many groups or too large groups)
8306          we, umm, group them in bunches.  */
8307       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8308                      | (tu_stats->nr_stmt_less_type_units
8309                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8310       ++tu_stats->nr_stmt_less_type_units;
8311     }
8312
8313   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8314   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8315   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8316                          &type_unit_group_for_lookup, INSERT);
8317   if (*slot != NULL)
8318     {
8319       tu_group = (struct type_unit_group *) *slot;
8320       gdb_assert (tu_group != NULL);
8321     }
8322   else
8323     {
8324       sect_offset line_offset_struct = (sect_offset) line_offset;
8325       tu_group = create_type_unit_group (cu, line_offset_struct);
8326       *slot = tu_group;
8327       ++tu_stats->nr_symtabs;
8328     }
8329
8330   return tu_group;
8331 }
8332 \f
8333 /* Partial symbol tables.  */
8334
8335 /* Create a psymtab named NAME and assign it to PER_CU.
8336
8337    The caller must fill in the following details:
8338    dirname, textlow, texthigh.  */
8339
8340 static struct partial_symtab *
8341 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8342 {
8343   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8344   struct partial_symtab *pst;
8345
8346   pst = start_psymtab_common (objfile, name, 0,
8347                               objfile->global_psymbols,
8348                               objfile->static_psymbols);
8349
8350   pst->psymtabs_addrmap_supported = 1;
8351
8352   /* This is the glue that links PST into GDB's symbol API.  */
8353   pst->read_symtab_private = per_cu;
8354   pst->read_symtab = dwarf2_read_symtab;
8355   per_cu->v.psymtab = pst;
8356
8357   return pst;
8358 }
8359
8360 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8361    type.  */
8362
8363 struct process_psymtab_comp_unit_data
8364 {
8365   /* True if we are reading a DW_TAG_partial_unit.  */
8366
8367   int want_partial_unit;
8368
8369   /* The "pretend" language that is used if the CU doesn't declare a
8370      language.  */
8371
8372   enum language pretend_language;
8373 };
8374
8375 /* die_reader_func for process_psymtab_comp_unit.  */
8376
8377 static void
8378 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8379                                   const gdb_byte *info_ptr,
8380                                   struct die_info *comp_unit_die,
8381                                   int has_children,
8382                                   void *data)
8383 {
8384   struct dwarf2_cu *cu = reader->cu;
8385   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8386   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8387   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8388   CORE_ADDR baseaddr;
8389   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8390   struct partial_symtab *pst;
8391   enum pc_bounds_kind cu_bounds_kind;
8392   const char *filename;
8393   struct process_psymtab_comp_unit_data *info
8394     = (struct process_psymtab_comp_unit_data *) data;
8395
8396   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8397     return;
8398
8399   gdb_assert (! per_cu->is_debug_types);
8400
8401   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8402
8403   cu->list_in_scope = &file_symbols;
8404
8405   /* Allocate a new partial symbol table structure.  */
8406   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8407   if (filename == NULL)
8408     filename = "";
8409
8410   pst = create_partial_symtab (per_cu, filename);
8411
8412   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8413   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8414
8415   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8416
8417   dwarf2_find_base_address (comp_unit_die, cu);
8418
8419   /* Possibly set the default values of LOWPC and HIGHPC from
8420      `DW_AT_ranges'.  */
8421   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8422                                          &best_highpc, cu, pst);
8423   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8424     /* Store the contiguous range if it is not empty; it can be empty for
8425        CUs with no code.  */
8426     addrmap_set_empty (objfile->psymtabs_addrmap,
8427                        gdbarch_adjust_dwarf2_addr (gdbarch,
8428                                                    best_lowpc + baseaddr),
8429                        gdbarch_adjust_dwarf2_addr (gdbarch,
8430                                                    best_highpc + baseaddr) - 1,
8431                        pst);
8432
8433   /* Check if comp unit has_children.
8434      If so, read the rest of the partial symbols from this comp unit.
8435      If not, there's no more debug_info for this comp unit.  */
8436   if (has_children)
8437     {
8438       struct partial_die_info *first_die;
8439       CORE_ADDR lowpc, highpc;
8440
8441       lowpc = ((CORE_ADDR) -1);
8442       highpc = ((CORE_ADDR) 0);
8443
8444       first_die = load_partial_dies (reader, info_ptr, 1);
8445
8446       scan_partial_symbols (first_die, &lowpc, &highpc,
8447                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8448
8449       /* If we didn't find a lowpc, set it to highpc to avoid
8450          complaints from `maint check'.  */
8451       if (lowpc == ((CORE_ADDR) -1))
8452         lowpc = highpc;
8453
8454       /* If the compilation unit didn't have an explicit address range,
8455          then use the information extracted from its child dies.  */
8456       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8457         {
8458           best_lowpc = lowpc;
8459           best_highpc = highpc;
8460         }
8461     }
8462   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8463   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8464
8465   end_psymtab_common (objfile, pst);
8466
8467   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8468     {
8469       int i;
8470       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8471       struct dwarf2_per_cu_data *iter;
8472
8473       /* Fill in 'dependencies' here; we fill in 'users' in a
8474          post-pass.  */
8475       pst->number_of_dependencies = len;
8476       pst->dependencies =
8477         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8478       for (i = 0;
8479            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8480                         i, iter);
8481            ++i)
8482         pst->dependencies[i] = iter->v.psymtab;
8483
8484       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8485     }
8486
8487   /* Get the list of files included in the current compilation unit,
8488      and build a psymtab for each of them.  */
8489   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8490
8491   if (dwarf_read_debug)
8492     {
8493       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8494
8495       fprintf_unfiltered (gdb_stdlog,
8496                           "Psymtab for %s unit @%s: %s - %s"
8497                           ", %d global, %d static syms\n",
8498                           per_cu->is_debug_types ? "type" : "comp",
8499                           sect_offset_str (per_cu->sect_off),
8500                           paddress (gdbarch, pst->textlow),
8501                           paddress (gdbarch, pst->texthigh),
8502                           pst->n_global_syms, pst->n_static_syms);
8503     }
8504 }
8505
8506 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8507    Process compilation unit THIS_CU for a psymtab.  */
8508
8509 static void
8510 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8511                            int want_partial_unit,
8512                            enum language pretend_language)
8513 {
8514   /* If this compilation unit was already read in, free the
8515      cached copy in order to read it in again.  This is
8516      necessary because we skipped some symbols when we first
8517      read in the compilation unit (see load_partial_dies).
8518      This problem could be avoided, but the benefit is unclear.  */
8519   if (this_cu->cu != NULL)
8520     free_one_cached_comp_unit (this_cu);
8521
8522   if (this_cu->is_debug_types)
8523     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8524                              NULL);
8525   else
8526     {
8527       process_psymtab_comp_unit_data info;
8528       info.want_partial_unit = want_partial_unit;
8529       info.pretend_language = pretend_language;
8530       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8531                                process_psymtab_comp_unit_reader, &info);
8532     }
8533
8534   /* Age out any secondary CUs.  */
8535   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8536 }
8537
8538 /* Reader function for build_type_psymtabs.  */
8539
8540 static void
8541 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8542                             const gdb_byte *info_ptr,
8543                             struct die_info *type_unit_die,
8544                             int has_children,
8545                             void *data)
8546 {
8547   struct dwarf2_per_objfile *dwarf2_per_objfile
8548     = reader->cu->per_cu->dwarf2_per_objfile;
8549   struct objfile *objfile = dwarf2_per_objfile->objfile;
8550   struct dwarf2_cu *cu = reader->cu;
8551   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8552   struct signatured_type *sig_type;
8553   struct type_unit_group *tu_group;
8554   struct attribute *attr;
8555   struct partial_die_info *first_die;
8556   CORE_ADDR lowpc, highpc;
8557   struct partial_symtab *pst;
8558
8559   gdb_assert (data == NULL);
8560   gdb_assert (per_cu->is_debug_types);
8561   sig_type = (struct signatured_type *) per_cu;
8562
8563   if (! has_children)
8564     return;
8565
8566   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8567   tu_group = get_type_unit_group (cu, attr);
8568
8569   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8570
8571   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8572   cu->list_in_scope = &file_symbols;
8573   pst = create_partial_symtab (per_cu, "");
8574   pst->anonymous = 1;
8575
8576   first_die = load_partial_dies (reader, info_ptr, 1);
8577
8578   lowpc = (CORE_ADDR) -1;
8579   highpc = (CORE_ADDR) 0;
8580   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8581
8582   end_psymtab_common (objfile, pst);
8583 }
8584
8585 /* Struct used to sort TUs by their abbreviation table offset.  */
8586
8587 struct tu_abbrev_offset
8588 {
8589   struct signatured_type *sig_type;
8590   sect_offset abbrev_offset;
8591 };
8592
8593 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8594
8595 static int
8596 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8597 {
8598   const struct tu_abbrev_offset * const *a
8599     = (const struct tu_abbrev_offset * const*) ap;
8600   const struct tu_abbrev_offset * const *b
8601     = (const struct tu_abbrev_offset * const*) bp;
8602   sect_offset aoff = (*a)->abbrev_offset;
8603   sect_offset boff = (*b)->abbrev_offset;
8604
8605   return (aoff > boff) - (aoff < boff);
8606 }
8607
8608 /* Efficiently read all the type units.
8609    This does the bulk of the work for build_type_psymtabs.
8610
8611    The efficiency is because we sort TUs by the abbrev table they use and
8612    only read each abbrev table once.  In one program there are 200K TUs
8613    sharing 8K abbrev tables.
8614
8615    The main purpose of this function is to support building the
8616    dwarf2_per_objfile->type_unit_groups table.
8617    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8618    can collapse the search space by grouping them by stmt_list.
8619    The savings can be significant, in the same program from above the 200K TUs
8620    share 8K stmt_list tables.
8621
8622    FUNC is expected to call get_type_unit_group, which will create the
8623    struct type_unit_group if necessary and add it to
8624    dwarf2_per_objfile->type_unit_groups.  */
8625
8626 static void
8627 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8628 {
8629   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8630   struct cleanup *cleanups;
8631   abbrev_table_up abbrev_table;
8632   sect_offset abbrev_offset;
8633   struct tu_abbrev_offset *sorted_by_abbrev;
8634   int i;
8635
8636   /* It's up to the caller to not call us multiple times.  */
8637   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8638
8639   if (dwarf2_per_objfile->n_type_units == 0)
8640     return;
8641
8642   /* TUs typically share abbrev tables, and there can be way more TUs than
8643      abbrev tables.  Sort by abbrev table to reduce the number of times we
8644      read each abbrev table in.
8645      Alternatives are to punt or to maintain a cache of abbrev tables.
8646      This is simpler and efficient enough for now.
8647
8648      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8649      symtab to use).  Typically TUs with the same abbrev offset have the same
8650      stmt_list value too so in practice this should work well.
8651
8652      The basic algorithm here is:
8653
8654       sort TUs by abbrev table
8655       for each TU with same abbrev table:
8656         read abbrev table if first user
8657         read TU top level DIE
8658           [IWBN if DWO skeletons had DW_AT_stmt_list]
8659         call FUNC  */
8660
8661   if (dwarf_read_debug)
8662     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8663
8664   /* Sort in a separate table to maintain the order of all_type_units
8665      for .gdb_index: TU indices directly index all_type_units.  */
8666   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8667                               dwarf2_per_objfile->n_type_units);
8668   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8669     {
8670       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8671
8672       sorted_by_abbrev[i].sig_type = sig_type;
8673       sorted_by_abbrev[i].abbrev_offset =
8674         read_abbrev_offset (dwarf2_per_objfile,
8675                             sig_type->per_cu.section,
8676                             sig_type->per_cu.sect_off);
8677     }
8678   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8679   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8680          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8681
8682   abbrev_offset = (sect_offset) ~(unsigned) 0;
8683
8684   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8685     {
8686       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8687
8688       /* Switch to the next abbrev table if necessary.  */
8689       if (abbrev_table == NULL
8690           || tu->abbrev_offset != abbrev_offset)
8691         {
8692           abbrev_offset = tu->abbrev_offset;
8693           abbrev_table =
8694             abbrev_table_read_table (dwarf2_per_objfile,
8695                                      &dwarf2_per_objfile->abbrev,
8696                                      abbrev_offset);
8697           ++tu_stats->nr_uniq_abbrev_tables;
8698         }
8699
8700       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8701                                0, 0, build_type_psymtabs_reader, NULL);
8702     }
8703
8704   do_cleanups (cleanups);
8705 }
8706
8707 /* Print collected type unit statistics.  */
8708
8709 static void
8710 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8711 {
8712   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8713
8714   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8715   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8716                       dwarf2_per_objfile->n_type_units);
8717   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8718                       tu_stats->nr_uniq_abbrev_tables);
8719   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8720                       tu_stats->nr_symtabs);
8721   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8722                       tu_stats->nr_symtab_sharers);
8723   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8724                       tu_stats->nr_stmt_less_type_units);
8725   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8726                       tu_stats->nr_all_type_units_reallocs);
8727 }
8728
8729 /* Traversal function for build_type_psymtabs.  */
8730
8731 static int
8732 build_type_psymtab_dependencies (void **slot, void *info)
8733 {
8734   struct dwarf2_per_objfile *dwarf2_per_objfile
8735     = (struct dwarf2_per_objfile *) info;
8736   struct objfile *objfile = dwarf2_per_objfile->objfile;
8737   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8738   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8739   struct partial_symtab *pst = per_cu->v.psymtab;
8740   int len = VEC_length (sig_type_ptr, tu_group->tus);
8741   struct signatured_type *iter;
8742   int i;
8743
8744   gdb_assert (len > 0);
8745   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8746
8747   pst->number_of_dependencies = len;
8748   pst->dependencies =
8749     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8750   for (i = 0;
8751        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8752        ++i)
8753     {
8754       gdb_assert (iter->per_cu.is_debug_types);
8755       pst->dependencies[i] = iter->per_cu.v.psymtab;
8756       iter->type_unit_group = tu_group;
8757     }
8758
8759   VEC_free (sig_type_ptr, tu_group->tus);
8760
8761   return 1;
8762 }
8763
8764 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8765    Build partial symbol tables for the .debug_types comp-units.  */
8766
8767 static void
8768 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8769 {
8770   if (! create_all_type_units (dwarf2_per_objfile))
8771     return;
8772
8773   build_type_psymtabs_1 (dwarf2_per_objfile);
8774 }
8775
8776 /* Traversal function for process_skeletonless_type_unit.
8777    Read a TU in a DWO file and build partial symbols for it.  */
8778
8779 static int
8780 process_skeletonless_type_unit (void **slot, void *info)
8781 {
8782   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8783   struct dwarf2_per_objfile *dwarf2_per_objfile
8784     = (struct dwarf2_per_objfile *) info;
8785   struct signatured_type find_entry, *entry;
8786
8787   /* If this TU doesn't exist in the global table, add it and read it in.  */
8788
8789   if (dwarf2_per_objfile->signatured_types == NULL)
8790     {
8791       dwarf2_per_objfile->signatured_types
8792         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8793     }
8794
8795   find_entry.signature = dwo_unit->signature;
8796   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8797                          INSERT);
8798   /* If we've already seen this type there's nothing to do.  What's happening
8799      is we're doing our own version of comdat-folding here.  */
8800   if (*slot != NULL)
8801     return 1;
8802
8803   /* This does the job that create_all_type_units would have done for
8804      this TU.  */
8805   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8806   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8807   *slot = entry;
8808
8809   /* This does the job that build_type_psymtabs_1 would have done.  */
8810   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8811                            build_type_psymtabs_reader, NULL);
8812
8813   return 1;
8814 }
8815
8816 /* Traversal function for process_skeletonless_type_units.  */
8817
8818 static int
8819 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8820 {
8821   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8822
8823   if (dwo_file->tus != NULL)
8824     {
8825       htab_traverse_noresize (dwo_file->tus,
8826                               process_skeletonless_type_unit, info);
8827     }
8828
8829   return 1;
8830 }
8831
8832 /* Scan all TUs of DWO files, verifying we've processed them.
8833    This is needed in case a TU was emitted without its skeleton.
8834    Note: This can't be done until we know what all the DWO files are.  */
8835
8836 static void
8837 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8838 {
8839   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8840   if (get_dwp_file (dwarf2_per_objfile) == NULL
8841       && dwarf2_per_objfile->dwo_files != NULL)
8842     {
8843       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8844                               process_dwo_file_for_skeletonless_type_units,
8845                               dwarf2_per_objfile);
8846     }
8847 }
8848
8849 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8850
8851 static void
8852 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8853 {
8854   int i;
8855
8856   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8857     {
8858       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8859       struct partial_symtab *pst = per_cu->v.psymtab;
8860       int j;
8861
8862       if (pst == NULL)
8863         continue;
8864
8865       for (j = 0; j < pst->number_of_dependencies; ++j)
8866         {
8867           /* Set the 'user' field only if it is not already set.  */
8868           if (pst->dependencies[j]->user == NULL)
8869             pst->dependencies[j]->user = pst;
8870         }
8871     }
8872 }
8873
8874 /* Build the partial symbol table by doing a quick pass through the
8875    .debug_info and .debug_abbrev sections.  */
8876
8877 static void
8878 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8879 {
8880   struct cleanup *back_to;
8881   int i;
8882   struct objfile *objfile = dwarf2_per_objfile->objfile;
8883
8884   if (dwarf_read_debug)
8885     {
8886       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8887                           objfile_name (objfile));
8888     }
8889
8890   dwarf2_per_objfile->reading_partial_symbols = 1;
8891
8892   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8893
8894   /* Any cached compilation units will be linked by the per-objfile
8895      read_in_chain.  Make sure to free them when we're done.  */
8896   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8897
8898   build_type_psymtabs (dwarf2_per_objfile);
8899
8900   create_all_comp_units (dwarf2_per_objfile);
8901
8902   /* Create a temporary address map on a temporary obstack.  We later
8903      copy this to the final obstack.  */
8904   auto_obstack temp_obstack;
8905
8906   scoped_restore save_psymtabs_addrmap
8907     = make_scoped_restore (&objfile->psymtabs_addrmap,
8908                            addrmap_create_mutable (&temp_obstack));
8909
8910   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8911     {
8912       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8913
8914       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8915     }
8916
8917   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8918   process_skeletonless_type_units (dwarf2_per_objfile);
8919
8920   /* Now that all TUs have been processed we can fill in the dependencies.  */
8921   if (dwarf2_per_objfile->type_unit_groups != NULL)
8922     {
8923       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8924                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8925     }
8926
8927   if (dwarf_read_debug)
8928     print_tu_stats (dwarf2_per_objfile);
8929
8930   set_partial_user (dwarf2_per_objfile);
8931
8932   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8933                                                     &objfile->objfile_obstack);
8934   /* At this point we want to keep the address map.  */
8935   save_psymtabs_addrmap.release ();
8936
8937   do_cleanups (back_to);
8938
8939   if (dwarf_read_debug)
8940     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8941                         objfile_name (objfile));
8942 }
8943
8944 /* die_reader_func for load_partial_comp_unit.  */
8945
8946 static void
8947 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8948                                const gdb_byte *info_ptr,
8949                                struct die_info *comp_unit_die,
8950                                int has_children,
8951                                void *data)
8952 {
8953   struct dwarf2_cu *cu = reader->cu;
8954
8955   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8956
8957   /* Check if comp unit has_children.
8958      If so, read the rest of the partial symbols from this comp unit.
8959      If not, there's no more debug_info for this comp unit.  */
8960   if (has_children)
8961     load_partial_dies (reader, info_ptr, 0);
8962 }
8963
8964 /* Load the partial DIEs for a secondary CU into memory.
8965    This is also used when rereading a primary CU with load_all_dies.  */
8966
8967 static void
8968 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8969 {
8970   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8971                            load_partial_comp_unit_reader, NULL);
8972 }
8973
8974 static void
8975 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8976                               struct dwarf2_section_info *section,
8977                               struct dwarf2_section_info *abbrev_section,
8978                               unsigned int is_dwz,
8979                               int *n_allocated,
8980                               int *n_comp_units,
8981                               struct dwarf2_per_cu_data ***all_comp_units)
8982 {
8983   const gdb_byte *info_ptr;
8984   struct objfile *objfile = dwarf2_per_objfile->objfile;
8985
8986   if (dwarf_read_debug)
8987     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8988                         get_section_name (section),
8989                         get_section_file_name (section));
8990
8991   dwarf2_read_section (objfile, section);
8992
8993   info_ptr = section->buffer;
8994
8995   while (info_ptr < section->buffer + section->size)
8996     {
8997       struct dwarf2_per_cu_data *this_cu;
8998
8999       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
9000
9001       comp_unit_head cu_header;
9002       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
9003                                      abbrev_section, info_ptr,
9004                                      rcuh_kind::COMPILE);
9005
9006       /* Save the compilation unit for later lookup.  */
9007       if (cu_header.unit_type != DW_UT_type)
9008         {
9009           this_cu = XOBNEW (&objfile->objfile_obstack,
9010                             struct dwarf2_per_cu_data);
9011           memset (this_cu, 0, sizeof (*this_cu));
9012         }
9013       else
9014         {
9015           auto sig_type = XOBNEW (&objfile->objfile_obstack,
9016                                   struct signatured_type);
9017           memset (sig_type, 0, sizeof (*sig_type));
9018           sig_type->signature = cu_header.signature;
9019           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
9020           this_cu = &sig_type->per_cu;
9021         }
9022       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
9023       this_cu->sect_off = sect_off;
9024       this_cu->length = cu_header.length + cu_header.initial_length_size;
9025       this_cu->is_dwz = is_dwz;
9026       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
9027       this_cu->section = section;
9028
9029       if (*n_comp_units == *n_allocated)
9030         {
9031           *n_allocated *= 2;
9032           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
9033                                         *all_comp_units, *n_allocated);
9034         }
9035       (*all_comp_units)[*n_comp_units] = this_cu;
9036       ++*n_comp_units;
9037
9038       info_ptr = info_ptr + this_cu->length;
9039     }
9040 }
9041
9042 /* Create a list of all compilation units in OBJFILE.
9043    This is only done for -readnow and building partial symtabs.  */
9044
9045 static void
9046 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
9047 {
9048   int n_allocated;
9049   int n_comp_units;
9050   struct dwarf2_per_cu_data **all_comp_units;
9051   struct dwz_file *dwz;
9052   struct objfile *objfile = dwarf2_per_objfile->objfile;
9053
9054   n_comp_units = 0;
9055   n_allocated = 10;
9056   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9057
9058   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9059                                 &dwarf2_per_objfile->abbrev, 0,
9060                                 &n_allocated, &n_comp_units, &all_comp_units);
9061
9062   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9063   if (dwz != NULL)
9064     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9065                                   1, &n_allocated, &n_comp_units,
9066                                   &all_comp_units);
9067
9068   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9069                                                   struct dwarf2_per_cu_data *,
9070                                                   n_comp_units);
9071   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9072           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9073   xfree (all_comp_units);
9074   dwarf2_per_objfile->n_comp_units = n_comp_units;
9075 }
9076
9077 /* Process all loaded DIEs for compilation unit CU, starting at
9078    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9079    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9080    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9081    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9082
9083 static void
9084 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9085                       CORE_ADDR *highpc, int set_addrmap,
9086                       struct dwarf2_cu *cu)
9087 {
9088   struct partial_die_info *pdi;
9089
9090   /* Now, march along the PDI's, descending into ones which have
9091      interesting children but skipping the children of the other ones,
9092      until we reach the end of the compilation unit.  */
9093
9094   pdi = first_die;
9095
9096   while (pdi != NULL)
9097     {
9098       pdi->fixup (cu);
9099
9100       /* Anonymous namespaces or modules have no name but have interesting
9101          children, so we need to look at them.  Ditto for anonymous
9102          enums.  */
9103
9104       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9105           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9106           || pdi->tag == DW_TAG_imported_unit
9107           || pdi->tag == DW_TAG_inlined_subroutine)
9108         {
9109           switch (pdi->tag)
9110             {
9111             case DW_TAG_subprogram:
9112             case DW_TAG_inlined_subroutine:
9113               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9114               break;
9115             case DW_TAG_constant:
9116             case DW_TAG_variable:
9117             case DW_TAG_typedef:
9118             case DW_TAG_union_type:
9119               if (!pdi->is_declaration)
9120                 {
9121                   add_partial_symbol (pdi, cu);
9122                 }
9123               break;
9124             case DW_TAG_class_type:
9125             case DW_TAG_interface_type:
9126             case DW_TAG_structure_type:
9127               if (!pdi->is_declaration)
9128                 {
9129                   add_partial_symbol (pdi, cu);
9130                 }
9131               if (cu->language == language_rust && pdi->has_children)
9132                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9133                                       set_addrmap, cu);
9134               break;
9135             case DW_TAG_enumeration_type:
9136               if (!pdi->is_declaration)
9137                 add_partial_enumeration (pdi, cu);
9138               break;
9139             case DW_TAG_base_type:
9140             case DW_TAG_subrange_type:
9141               /* File scope base type definitions are added to the partial
9142                  symbol table.  */
9143               add_partial_symbol (pdi, cu);
9144               break;
9145             case DW_TAG_namespace:
9146               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9147               break;
9148             case DW_TAG_module:
9149               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9150               break;
9151             case DW_TAG_imported_unit:
9152               {
9153                 struct dwarf2_per_cu_data *per_cu;
9154
9155                 /* For now we don't handle imported units in type units.  */
9156                 if (cu->per_cu->is_debug_types)
9157                   {
9158                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9159                              " supported in type units [in module %s]"),
9160                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9161                   }
9162
9163                 per_cu = dwarf2_find_containing_comp_unit
9164                            (pdi->d.sect_off, pdi->is_dwz,
9165                             cu->per_cu->dwarf2_per_objfile);
9166
9167                 /* Go read the partial unit, if needed.  */
9168                 if (per_cu->v.psymtab == NULL)
9169                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9170
9171                 VEC_safe_push (dwarf2_per_cu_ptr,
9172                                cu->per_cu->imported_symtabs, per_cu);
9173               }
9174               break;
9175             case DW_TAG_imported_declaration:
9176               add_partial_symbol (pdi, cu);
9177               break;
9178             default:
9179               break;
9180             }
9181         }
9182
9183       /* If the die has a sibling, skip to the sibling.  */
9184
9185       pdi = pdi->die_sibling;
9186     }
9187 }
9188
9189 /* Functions used to compute the fully scoped name of a partial DIE.
9190
9191    Normally, this is simple.  For C++, the parent DIE's fully scoped
9192    name is concatenated with "::" and the partial DIE's name.
9193    Enumerators are an exception; they use the scope of their parent
9194    enumeration type, i.e. the name of the enumeration type is not
9195    prepended to the enumerator.
9196
9197    There are two complexities.  One is DW_AT_specification; in this
9198    case "parent" means the parent of the target of the specification,
9199    instead of the direct parent of the DIE.  The other is compilers
9200    which do not emit DW_TAG_namespace; in this case we try to guess
9201    the fully qualified name of structure types from their members'
9202    linkage names.  This must be done using the DIE's children rather
9203    than the children of any DW_AT_specification target.  We only need
9204    to do this for structures at the top level, i.e. if the target of
9205    any DW_AT_specification (if any; otherwise the DIE itself) does not
9206    have a parent.  */
9207
9208 /* Compute the scope prefix associated with PDI's parent, in
9209    compilation unit CU.  The result will be allocated on CU's
9210    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9211    field.  NULL is returned if no prefix is necessary.  */
9212 static const char *
9213 partial_die_parent_scope (struct partial_die_info *pdi,
9214                           struct dwarf2_cu *cu)
9215 {
9216   const char *grandparent_scope;
9217   struct partial_die_info *parent, *real_pdi;
9218
9219   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9220      then this means the parent of the specification DIE.  */
9221
9222   real_pdi = pdi;
9223   while (real_pdi->has_specification)
9224     real_pdi = find_partial_die (real_pdi->spec_offset,
9225                                  real_pdi->spec_is_dwz, cu);
9226
9227   parent = real_pdi->die_parent;
9228   if (parent == NULL)
9229     return NULL;
9230
9231   if (parent->scope_set)
9232     return parent->scope;
9233
9234   parent->fixup (cu);
9235
9236   grandparent_scope = partial_die_parent_scope (parent, cu);
9237
9238   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9239      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9240      Work around this problem here.  */
9241   if (cu->language == language_cplus
9242       && parent->tag == DW_TAG_namespace
9243       && strcmp (parent->name, "::") == 0
9244       && grandparent_scope == NULL)
9245     {
9246       parent->scope = NULL;
9247       parent->scope_set = 1;
9248       return NULL;
9249     }
9250
9251   if (pdi->tag == DW_TAG_enumerator)
9252     /* Enumerators should not get the name of the enumeration as a prefix.  */
9253     parent->scope = grandparent_scope;
9254   else if (parent->tag == DW_TAG_namespace
9255       || parent->tag == DW_TAG_module
9256       || parent->tag == DW_TAG_structure_type
9257       || parent->tag == DW_TAG_class_type
9258       || parent->tag == DW_TAG_interface_type
9259       || parent->tag == DW_TAG_union_type
9260       || parent->tag == DW_TAG_enumeration_type)
9261     {
9262       if (grandparent_scope == NULL)
9263         parent->scope = parent->name;
9264       else
9265         parent->scope = typename_concat (&cu->comp_unit_obstack,
9266                                          grandparent_scope,
9267                                          parent->name, 0, cu);
9268     }
9269   else
9270     {
9271       /* FIXME drow/2004-04-01: What should we be doing with
9272          function-local names?  For partial symbols, we should probably be
9273          ignoring them.  */
9274       complaint (&symfile_complaints,
9275                  _("unhandled containing DIE tag %d for DIE at %s"),
9276                  parent->tag, sect_offset_str (pdi->sect_off));
9277       parent->scope = grandparent_scope;
9278     }
9279
9280   parent->scope_set = 1;
9281   return parent->scope;
9282 }
9283
9284 /* Return the fully scoped name associated with PDI, from compilation unit
9285    CU.  The result will be allocated with malloc.  */
9286
9287 static char *
9288 partial_die_full_name (struct partial_die_info *pdi,
9289                        struct dwarf2_cu *cu)
9290 {
9291   const char *parent_scope;
9292
9293   /* If this is a template instantiation, we can not work out the
9294      template arguments from partial DIEs.  So, unfortunately, we have
9295      to go through the full DIEs.  At least any work we do building
9296      types here will be reused if full symbols are loaded later.  */
9297   if (pdi->has_template_arguments)
9298     {
9299       pdi->fixup (cu);
9300
9301       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9302         {
9303           struct die_info *die;
9304           struct attribute attr;
9305           struct dwarf2_cu *ref_cu = cu;
9306
9307           /* DW_FORM_ref_addr is using section offset.  */
9308           attr.name = (enum dwarf_attribute) 0;
9309           attr.form = DW_FORM_ref_addr;
9310           attr.u.unsnd = to_underlying (pdi->sect_off);
9311           die = follow_die_ref (NULL, &attr, &ref_cu);
9312
9313           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9314         }
9315     }
9316
9317   parent_scope = partial_die_parent_scope (pdi, cu);
9318   if (parent_scope == NULL)
9319     return NULL;
9320   else
9321     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9322 }
9323
9324 static void
9325 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9326 {
9327   struct dwarf2_per_objfile *dwarf2_per_objfile
9328     = cu->per_cu->dwarf2_per_objfile;
9329   struct objfile *objfile = dwarf2_per_objfile->objfile;
9330   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9331   CORE_ADDR addr = 0;
9332   const char *actual_name = NULL;
9333   CORE_ADDR baseaddr;
9334   char *built_actual_name;
9335
9336   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9337
9338   built_actual_name = partial_die_full_name (pdi, cu);
9339   if (built_actual_name != NULL)
9340     actual_name = built_actual_name;
9341
9342   if (actual_name == NULL)
9343     actual_name = pdi->name;
9344
9345   switch (pdi->tag)
9346     {
9347     case DW_TAG_inlined_subroutine:
9348     case DW_TAG_subprogram:
9349       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9350       if (pdi->is_external || cu->language == language_ada)
9351         {
9352           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9353              of the global scope.  But in Ada, we want to be able to access
9354              nested procedures globally.  So all Ada subprograms are stored
9355              in the global scope.  */
9356           add_psymbol_to_list (actual_name, strlen (actual_name),
9357                                built_actual_name != NULL,
9358                                VAR_DOMAIN, LOC_BLOCK,
9359                                &objfile->global_psymbols,
9360                                addr, cu->language, objfile);
9361         }
9362       else
9363         {
9364           add_psymbol_to_list (actual_name, strlen (actual_name),
9365                                built_actual_name != NULL,
9366                                VAR_DOMAIN, LOC_BLOCK,
9367                                &objfile->static_psymbols,
9368                                addr, cu->language, objfile);
9369         }
9370
9371       if (pdi->main_subprogram && actual_name != NULL)
9372         set_objfile_main_name (objfile, actual_name, cu->language);
9373       break;
9374     case DW_TAG_constant:
9375       {
9376         std::vector<partial_symbol *> *list;
9377
9378         if (pdi->is_external)
9379           list = &objfile->global_psymbols;
9380         else
9381           list = &objfile->static_psymbols;
9382         add_psymbol_to_list (actual_name, strlen (actual_name),
9383                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9384                              list, 0, cu->language, objfile);
9385       }
9386       break;
9387     case DW_TAG_variable:
9388       if (pdi->d.locdesc)
9389         addr = decode_locdesc (pdi->d.locdesc, cu);
9390
9391       if (pdi->d.locdesc
9392           && addr == 0
9393           && !dwarf2_per_objfile->has_section_at_zero)
9394         {
9395           /* A global or static variable may also have been stripped
9396              out by the linker if unused, in which case its address
9397              will be nullified; do not add such variables into partial
9398              symbol table then.  */
9399         }
9400       else if (pdi->is_external)
9401         {
9402           /* Global Variable.
9403              Don't enter into the minimal symbol tables as there is
9404              a minimal symbol table entry from the ELF symbols already.
9405              Enter into partial symbol table if it has a location
9406              descriptor or a type.
9407              If the location descriptor is missing, new_symbol will create
9408              a LOC_UNRESOLVED symbol, the address of the variable will then
9409              be determined from the minimal symbol table whenever the variable
9410              is referenced.
9411              The address for the partial symbol table entry is not
9412              used by GDB, but it comes in handy for debugging partial symbol
9413              table building.  */
9414
9415           if (pdi->d.locdesc || pdi->has_type)
9416             add_psymbol_to_list (actual_name, strlen (actual_name),
9417                                  built_actual_name != NULL,
9418                                  VAR_DOMAIN, LOC_STATIC,
9419                                  &objfile->global_psymbols,
9420                                  addr + baseaddr,
9421                                  cu->language, objfile);
9422         }
9423       else
9424         {
9425           int has_loc = pdi->d.locdesc != NULL;
9426
9427           /* Static Variable.  Skip symbols whose value we cannot know (those
9428              without location descriptors or constant values).  */
9429           if (!has_loc && !pdi->has_const_value)
9430             {
9431               xfree (built_actual_name);
9432               return;
9433             }
9434
9435           add_psymbol_to_list (actual_name, strlen (actual_name),
9436                                built_actual_name != NULL,
9437                                VAR_DOMAIN, LOC_STATIC,
9438                                &objfile->static_psymbols,
9439                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9440                                cu->language, objfile);
9441         }
9442       break;
9443     case DW_TAG_typedef:
9444     case DW_TAG_base_type:
9445     case DW_TAG_subrange_type:
9446       add_psymbol_to_list (actual_name, strlen (actual_name),
9447                            built_actual_name != NULL,
9448                            VAR_DOMAIN, LOC_TYPEDEF,
9449                            &objfile->static_psymbols,
9450                            0, cu->language, objfile);
9451       break;
9452     case DW_TAG_imported_declaration:
9453     case DW_TAG_namespace:
9454       add_psymbol_to_list (actual_name, strlen (actual_name),
9455                            built_actual_name != NULL,
9456                            VAR_DOMAIN, LOC_TYPEDEF,
9457                            &objfile->global_psymbols,
9458                            0, cu->language, objfile);
9459       break;
9460     case DW_TAG_module:
9461       add_psymbol_to_list (actual_name, strlen (actual_name),
9462                            built_actual_name != NULL,
9463                            MODULE_DOMAIN, LOC_TYPEDEF,
9464                            &objfile->global_psymbols,
9465                            0, cu->language, objfile);
9466       break;
9467     case DW_TAG_class_type:
9468     case DW_TAG_interface_type:
9469     case DW_TAG_structure_type:
9470     case DW_TAG_union_type:
9471     case DW_TAG_enumeration_type:
9472       /* Skip external references.  The DWARF standard says in the section
9473          about "Structure, Union, and Class Type Entries": "An incomplete
9474          structure, union or class type is represented by a structure,
9475          union or class entry that does not have a byte size attribute
9476          and that has a DW_AT_declaration attribute."  */
9477       if (!pdi->has_byte_size && pdi->is_declaration)
9478         {
9479           xfree (built_actual_name);
9480           return;
9481         }
9482
9483       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9484          static vs. global.  */
9485       add_psymbol_to_list (actual_name, strlen (actual_name),
9486                            built_actual_name != NULL,
9487                            STRUCT_DOMAIN, LOC_TYPEDEF,
9488                            cu->language == language_cplus
9489                            ? &objfile->global_psymbols
9490                            : &objfile->static_psymbols,
9491                            0, cu->language, objfile);
9492
9493       break;
9494     case DW_TAG_enumerator:
9495       add_psymbol_to_list (actual_name, strlen (actual_name),
9496                            built_actual_name != NULL,
9497                            VAR_DOMAIN, LOC_CONST,
9498                            cu->language == language_cplus
9499                            ? &objfile->global_psymbols
9500                            : &objfile->static_psymbols,
9501                            0, cu->language, objfile);
9502       break;
9503     default:
9504       break;
9505     }
9506
9507   xfree (built_actual_name);
9508 }
9509
9510 /* Read a partial die corresponding to a namespace; also, add a symbol
9511    corresponding to that namespace to the symbol table.  NAMESPACE is
9512    the name of the enclosing namespace.  */
9513
9514 static void
9515 add_partial_namespace (struct partial_die_info *pdi,
9516                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9517                        int set_addrmap, struct dwarf2_cu *cu)
9518 {
9519   /* Add a symbol for the namespace.  */
9520
9521   add_partial_symbol (pdi, cu);
9522
9523   /* Now scan partial symbols in that namespace.  */
9524
9525   if (pdi->has_children)
9526     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9527 }
9528
9529 /* Read a partial die corresponding to a Fortran module.  */
9530
9531 static void
9532 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9533                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9534 {
9535   /* Add a symbol for the namespace.  */
9536
9537   add_partial_symbol (pdi, cu);
9538
9539   /* Now scan partial symbols in that module.  */
9540
9541   if (pdi->has_children)
9542     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9543 }
9544
9545 /* Read a partial die corresponding to a subprogram or an inlined
9546    subprogram and create a partial symbol for that subprogram.
9547    When the CU language allows it, this routine also defines a partial
9548    symbol for each nested subprogram that this subprogram contains.
9549    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9550    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9551
9552    PDI may also be a lexical block, in which case we simply search
9553    recursively for subprograms defined inside that lexical block.
9554    Again, this is only performed when the CU language allows this
9555    type of definitions.  */
9556
9557 static void
9558 add_partial_subprogram (struct partial_die_info *pdi,
9559                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9560                         int set_addrmap, struct dwarf2_cu *cu)
9561 {
9562   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9563     {
9564       if (pdi->has_pc_info)
9565         {
9566           if (pdi->lowpc < *lowpc)
9567             *lowpc = pdi->lowpc;
9568           if (pdi->highpc > *highpc)
9569             *highpc = pdi->highpc;
9570           if (set_addrmap)
9571             {
9572               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9573               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9574               CORE_ADDR baseaddr;
9575               CORE_ADDR highpc;
9576               CORE_ADDR lowpc;
9577
9578               baseaddr = ANOFFSET (objfile->section_offsets,
9579                                    SECT_OFF_TEXT (objfile));
9580               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9581                                                   pdi->lowpc + baseaddr);
9582               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9583                                                    pdi->highpc + baseaddr);
9584               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9585                                  cu->per_cu->v.psymtab);
9586             }
9587         }
9588
9589       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9590         {
9591           if (!pdi->is_declaration)
9592             /* Ignore subprogram DIEs that do not have a name, they are
9593                illegal.  Do not emit a complaint at this point, we will
9594                do so when we convert this psymtab into a symtab.  */
9595             if (pdi->name)
9596               add_partial_symbol (pdi, cu);
9597         }
9598     }
9599
9600   if (! pdi->has_children)
9601     return;
9602
9603   if (cu->language == language_ada)
9604     {
9605       pdi = pdi->die_child;
9606       while (pdi != NULL)
9607         {
9608           pdi->fixup (cu);
9609           if (pdi->tag == DW_TAG_subprogram
9610               || pdi->tag == DW_TAG_inlined_subroutine
9611               || pdi->tag == DW_TAG_lexical_block)
9612             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9613           pdi = pdi->die_sibling;
9614         }
9615     }
9616 }
9617
9618 /* Read a partial die corresponding to an enumeration type.  */
9619
9620 static void
9621 add_partial_enumeration (struct partial_die_info *enum_pdi,
9622                          struct dwarf2_cu *cu)
9623 {
9624   struct partial_die_info *pdi;
9625
9626   if (enum_pdi->name != NULL)
9627     add_partial_symbol (enum_pdi, cu);
9628
9629   pdi = enum_pdi->die_child;
9630   while (pdi)
9631     {
9632       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9633         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9634       else
9635         add_partial_symbol (pdi, cu);
9636       pdi = pdi->die_sibling;
9637     }
9638 }
9639
9640 /* Return the initial uleb128 in the die at INFO_PTR.  */
9641
9642 static unsigned int
9643 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9644 {
9645   unsigned int bytes_read;
9646
9647   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9648 }
9649
9650 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9651    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9652
9653    Return the corresponding abbrev, or NULL if the number is zero (indicating
9654    an empty DIE).  In either case *BYTES_READ will be set to the length of
9655    the initial number.  */
9656
9657 static struct abbrev_info *
9658 peek_die_abbrev (const die_reader_specs &reader,
9659                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9660 {
9661   dwarf2_cu *cu = reader.cu;
9662   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9663   unsigned int abbrev_number
9664     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9665
9666   if (abbrev_number == 0)
9667     return NULL;
9668
9669   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9670   if (!abbrev)
9671     {
9672       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9673                " at offset %s [in module %s]"),
9674              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9675              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9676     }
9677
9678   return abbrev;
9679 }
9680
9681 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9682    Returns a pointer to the end of a series of DIEs, terminated by an empty
9683    DIE.  Any children of the skipped DIEs will also be skipped.  */
9684
9685 static const gdb_byte *
9686 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9687 {
9688   while (1)
9689     {
9690       unsigned int bytes_read;
9691       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9692
9693       if (abbrev == NULL)
9694         return info_ptr + bytes_read;
9695       else
9696         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9697     }
9698 }
9699
9700 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9701    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9702    abbrev corresponding to that skipped uleb128 should be passed in
9703    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9704    children.  */
9705
9706 static const gdb_byte *
9707 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9708               struct abbrev_info *abbrev)
9709 {
9710   unsigned int bytes_read;
9711   struct attribute attr;
9712   bfd *abfd = reader->abfd;
9713   struct dwarf2_cu *cu = reader->cu;
9714   const gdb_byte *buffer = reader->buffer;
9715   const gdb_byte *buffer_end = reader->buffer_end;
9716   unsigned int form, i;
9717
9718   for (i = 0; i < abbrev->num_attrs; i++)
9719     {
9720       /* The only abbrev we care about is DW_AT_sibling.  */
9721       if (abbrev->attrs[i].name == DW_AT_sibling)
9722         {
9723           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9724           if (attr.form == DW_FORM_ref_addr)
9725             complaint (&symfile_complaints,
9726                        _("ignoring absolute DW_AT_sibling"));
9727           else
9728             {
9729               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9730               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9731
9732               if (sibling_ptr < info_ptr)
9733                 complaint (&symfile_complaints,
9734                            _("DW_AT_sibling points backwards"));
9735               else if (sibling_ptr > reader->buffer_end)
9736                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9737               else
9738                 return sibling_ptr;
9739             }
9740         }
9741
9742       /* If it isn't DW_AT_sibling, skip this attribute.  */
9743       form = abbrev->attrs[i].form;
9744     skip_attribute:
9745       switch (form)
9746         {
9747         case DW_FORM_ref_addr:
9748           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9749              and later it is offset sized.  */
9750           if (cu->header.version == 2)
9751             info_ptr += cu->header.addr_size;
9752           else
9753             info_ptr += cu->header.offset_size;
9754           break;
9755         case DW_FORM_GNU_ref_alt:
9756           info_ptr += cu->header.offset_size;
9757           break;
9758         case DW_FORM_addr:
9759           info_ptr += cu->header.addr_size;
9760           break;
9761         case DW_FORM_data1:
9762         case DW_FORM_ref1:
9763         case DW_FORM_flag:
9764           info_ptr += 1;
9765           break;
9766         case DW_FORM_flag_present:
9767         case DW_FORM_implicit_const:
9768           break;
9769         case DW_FORM_data2:
9770         case DW_FORM_ref2:
9771           info_ptr += 2;
9772           break;
9773         case DW_FORM_data4:
9774         case DW_FORM_ref4:
9775           info_ptr += 4;
9776           break;
9777         case DW_FORM_data8:
9778         case DW_FORM_ref8:
9779         case DW_FORM_ref_sig8:
9780           info_ptr += 8;
9781           break;
9782         case DW_FORM_data16:
9783           info_ptr += 16;
9784           break;
9785         case DW_FORM_string:
9786           read_direct_string (abfd, info_ptr, &bytes_read);
9787           info_ptr += bytes_read;
9788           break;
9789         case DW_FORM_sec_offset:
9790         case DW_FORM_strp:
9791         case DW_FORM_GNU_strp_alt:
9792           info_ptr += cu->header.offset_size;
9793           break;
9794         case DW_FORM_exprloc:
9795         case DW_FORM_block:
9796           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9797           info_ptr += bytes_read;
9798           break;
9799         case DW_FORM_block1:
9800           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9801           break;
9802         case DW_FORM_block2:
9803           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9804           break;
9805         case DW_FORM_block4:
9806           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9807           break;
9808         case DW_FORM_sdata:
9809         case DW_FORM_udata:
9810         case DW_FORM_ref_udata:
9811         case DW_FORM_GNU_addr_index:
9812         case DW_FORM_GNU_str_index:
9813           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9814           break;
9815         case DW_FORM_indirect:
9816           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9817           info_ptr += bytes_read;
9818           /* We need to continue parsing from here, so just go back to
9819              the top.  */
9820           goto skip_attribute;
9821
9822         default:
9823           error (_("Dwarf Error: Cannot handle %s "
9824                    "in DWARF reader [in module %s]"),
9825                  dwarf_form_name (form),
9826                  bfd_get_filename (abfd));
9827         }
9828     }
9829
9830   if (abbrev->has_children)
9831     return skip_children (reader, info_ptr);
9832   else
9833     return info_ptr;
9834 }
9835
9836 /* Locate ORIG_PDI's sibling.
9837    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9838
9839 static const gdb_byte *
9840 locate_pdi_sibling (const struct die_reader_specs *reader,
9841                     struct partial_die_info *orig_pdi,
9842                     const gdb_byte *info_ptr)
9843 {
9844   /* Do we know the sibling already?  */
9845
9846   if (orig_pdi->sibling)
9847     return orig_pdi->sibling;
9848
9849   /* Are there any children to deal with?  */
9850
9851   if (!orig_pdi->has_children)
9852     return info_ptr;
9853
9854   /* Skip the children the long way.  */
9855
9856   return skip_children (reader, info_ptr);
9857 }
9858
9859 /* Expand this partial symbol table into a full symbol table.  SELF is
9860    not NULL.  */
9861
9862 static void
9863 dwarf2_read_symtab (struct partial_symtab *self,
9864                     struct objfile *objfile)
9865 {
9866   struct dwarf2_per_objfile *dwarf2_per_objfile
9867     = get_dwarf2_per_objfile (objfile);
9868
9869   if (self->readin)
9870     {
9871       warning (_("bug: psymtab for %s is already read in."),
9872                self->filename);
9873     }
9874   else
9875     {
9876       if (info_verbose)
9877         {
9878           printf_filtered (_("Reading in symbols for %s..."),
9879                            self->filename);
9880           gdb_flush (gdb_stdout);
9881         }
9882
9883       /* If this psymtab is constructed from a debug-only objfile, the
9884          has_section_at_zero flag will not necessarily be correct.  We
9885          can get the correct value for this flag by looking at the data
9886          associated with the (presumably stripped) associated objfile.  */
9887       if (objfile->separate_debug_objfile_backlink)
9888         {
9889           struct dwarf2_per_objfile *dpo_backlink
9890             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9891
9892           dwarf2_per_objfile->has_section_at_zero
9893             = dpo_backlink->has_section_at_zero;
9894         }
9895
9896       dwarf2_per_objfile->reading_partial_symbols = 0;
9897
9898       psymtab_to_symtab_1 (self);
9899
9900       /* Finish up the debug error message.  */
9901       if (info_verbose)
9902         printf_filtered (_("done.\n"));
9903     }
9904
9905   process_cu_includes (dwarf2_per_objfile);
9906 }
9907 \f
9908 /* Reading in full CUs.  */
9909
9910 /* Add PER_CU to the queue.  */
9911
9912 static void
9913 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9914                  enum language pretend_language)
9915 {
9916   struct dwarf2_queue_item *item;
9917
9918   per_cu->queued = 1;
9919   item = XNEW (struct dwarf2_queue_item);
9920   item->per_cu = per_cu;
9921   item->pretend_language = pretend_language;
9922   item->next = NULL;
9923
9924   if (dwarf2_queue == NULL)
9925     dwarf2_queue = item;
9926   else
9927     dwarf2_queue_tail->next = item;
9928
9929   dwarf2_queue_tail = item;
9930 }
9931
9932 /* If PER_CU is not yet queued, add it to the queue.
9933    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9934    dependency.
9935    The result is non-zero if PER_CU was queued, otherwise the result is zero
9936    meaning either PER_CU is already queued or it is already loaded.
9937
9938    N.B. There is an invariant here that if a CU is queued then it is loaded.
9939    The caller is required to load PER_CU if we return non-zero.  */
9940
9941 static int
9942 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9943                        struct dwarf2_per_cu_data *per_cu,
9944                        enum language pretend_language)
9945 {
9946   /* We may arrive here during partial symbol reading, if we need full
9947      DIEs to process an unusual case (e.g. template arguments).  Do
9948      not queue PER_CU, just tell our caller to load its DIEs.  */
9949   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9950     {
9951       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9952         return 1;
9953       return 0;
9954     }
9955
9956   /* Mark the dependence relation so that we don't flush PER_CU
9957      too early.  */
9958   if (dependent_cu != NULL)
9959     dwarf2_add_dependence (dependent_cu, per_cu);
9960
9961   /* If it's already on the queue, we have nothing to do.  */
9962   if (per_cu->queued)
9963     return 0;
9964
9965   /* If the compilation unit is already loaded, just mark it as
9966      used.  */
9967   if (per_cu->cu != NULL)
9968     {
9969       per_cu->cu->last_used = 0;
9970       return 0;
9971     }
9972
9973   /* Add it to the queue.  */
9974   queue_comp_unit (per_cu, pretend_language);
9975
9976   return 1;
9977 }
9978
9979 /* Process the queue.  */
9980
9981 static void
9982 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9983 {
9984   struct dwarf2_queue_item *item, *next_item;
9985
9986   if (dwarf_read_debug)
9987     {
9988       fprintf_unfiltered (gdb_stdlog,
9989                           "Expanding one or more symtabs of objfile %s ...\n",
9990                           objfile_name (dwarf2_per_objfile->objfile));
9991     }
9992
9993   /* The queue starts out with one item, but following a DIE reference
9994      may load a new CU, adding it to the end of the queue.  */
9995   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9996     {
9997       if ((dwarf2_per_objfile->using_index
9998            ? !item->per_cu->v.quick->compunit_symtab
9999            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
10000           /* Skip dummy CUs.  */
10001           && item->per_cu->cu != NULL)
10002         {
10003           struct dwarf2_per_cu_data *per_cu = item->per_cu;
10004           unsigned int debug_print_threshold;
10005           char buf[100];
10006
10007           if (per_cu->is_debug_types)
10008             {
10009               struct signatured_type *sig_type =
10010                 (struct signatured_type *) per_cu;
10011
10012               sprintf (buf, "TU %s at offset %s",
10013                        hex_string (sig_type->signature),
10014                        sect_offset_str (per_cu->sect_off));
10015               /* There can be 100s of TUs.
10016                  Only print them in verbose mode.  */
10017               debug_print_threshold = 2;
10018             }
10019           else
10020             {
10021               sprintf (buf, "CU at offset %s",
10022                        sect_offset_str (per_cu->sect_off));
10023               debug_print_threshold = 1;
10024             }
10025
10026           if (dwarf_read_debug >= debug_print_threshold)
10027             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
10028
10029           if (per_cu->is_debug_types)
10030             process_full_type_unit (per_cu, item->pretend_language);
10031           else
10032             process_full_comp_unit (per_cu, item->pretend_language);
10033
10034           if (dwarf_read_debug >= debug_print_threshold)
10035             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
10036         }
10037
10038       item->per_cu->queued = 0;
10039       next_item = item->next;
10040       xfree (item);
10041     }
10042
10043   dwarf2_queue_tail = NULL;
10044
10045   if (dwarf_read_debug)
10046     {
10047       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
10048                           objfile_name (dwarf2_per_objfile->objfile));
10049     }
10050 }
10051
10052 /* Read in full symbols for PST, and anything it depends on.  */
10053
10054 static void
10055 psymtab_to_symtab_1 (struct partial_symtab *pst)
10056 {
10057   struct dwarf2_per_cu_data *per_cu;
10058   int i;
10059
10060   if (pst->readin)
10061     return;
10062
10063   for (i = 0; i < pst->number_of_dependencies; i++)
10064     if (!pst->dependencies[i]->readin
10065         && pst->dependencies[i]->user == NULL)
10066       {
10067         /* Inform about additional files that need to be read in.  */
10068         if (info_verbose)
10069           {
10070             /* FIXME: i18n: Need to make this a single string.  */
10071             fputs_filtered (" ", gdb_stdout);
10072             wrap_here ("");
10073             fputs_filtered ("and ", gdb_stdout);
10074             wrap_here ("");
10075             printf_filtered ("%s...", pst->dependencies[i]->filename);
10076             wrap_here ("");     /* Flush output.  */
10077             gdb_flush (gdb_stdout);
10078           }
10079         psymtab_to_symtab_1 (pst->dependencies[i]);
10080       }
10081
10082   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10083
10084   if (per_cu == NULL)
10085     {
10086       /* It's an include file, no symbols to read for it.
10087          Everything is in the parent symtab.  */
10088       pst->readin = 1;
10089       return;
10090     }
10091
10092   dw2_do_instantiate_symtab (per_cu);
10093 }
10094
10095 /* Trivial hash function for die_info: the hash value of a DIE
10096    is its offset in .debug_info for this objfile.  */
10097
10098 static hashval_t
10099 die_hash (const void *item)
10100 {
10101   const struct die_info *die = (const struct die_info *) item;
10102
10103   return to_underlying (die->sect_off);
10104 }
10105
10106 /* Trivial comparison function for die_info structures: two DIEs
10107    are equal if they have the same offset.  */
10108
10109 static int
10110 die_eq (const void *item_lhs, const void *item_rhs)
10111 {
10112   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10113   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10114
10115   return die_lhs->sect_off == die_rhs->sect_off;
10116 }
10117
10118 /* die_reader_func for load_full_comp_unit.
10119    This is identical to read_signatured_type_reader,
10120    but is kept separate for now.  */
10121
10122 static void
10123 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10124                             const gdb_byte *info_ptr,
10125                             struct die_info *comp_unit_die,
10126                             int has_children,
10127                             void *data)
10128 {
10129   struct dwarf2_cu *cu = reader->cu;
10130   enum language *language_ptr = (enum language *) data;
10131
10132   gdb_assert (cu->die_hash == NULL);
10133   cu->die_hash =
10134     htab_create_alloc_ex (cu->header.length / 12,
10135                           die_hash,
10136                           die_eq,
10137                           NULL,
10138                           &cu->comp_unit_obstack,
10139                           hashtab_obstack_allocate,
10140                           dummy_obstack_deallocate);
10141
10142   if (has_children)
10143     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10144                                                   &info_ptr, comp_unit_die);
10145   cu->dies = comp_unit_die;
10146   /* comp_unit_die is not stored in die_hash, no need.  */
10147
10148   /* We try not to read any attributes in this function, because not
10149      all CUs needed for references have been loaded yet, and symbol
10150      table processing isn't initialized.  But we have to set the CU language,
10151      or we won't be able to build types correctly.
10152      Similarly, if we do not read the producer, we can not apply
10153      producer-specific interpretation.  */
10154   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10155 }
10156
10157 /* Load the DIEs associated with PER_CU into memory.  */
10158
10159 static void
10160 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10161                      enum language pretend_language)
10162 {
10163   gdb_assert (! this_cu->is_debug_types);
10164
10165   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10166                            load_full_comp_unit_reader, &pretend_language);
10167 }
10168
10169 /* Add a DIE to the delayed physname list.  */
10170
10171 static void
10172 add_to_method_list (struct type *type, int fnfield_index, int index,
10173                     const char *name, struct die_info *die,
10174                     struct dwarf2_cu *cu)
10175 {
10176   struct delayed_method_info mi;
10177   mi.type = type;
10178   mi.fnfield_index = fnfield_index;
10179   mi.index = index;
10180   mi.name = name;
10181   mi.die = die;
10182   cu->method_list.push_back (mi);
10183 }
10184
10185 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10186    "const" / "volatile".  If so, decrements LEN by the length of the
10187    modifier and return true.  Otherwise return false.  */
10188
10189 template<size_t N>
10190 static bool
10191 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10192 {
10193   size_t mod_len = sizeof (mod) - 1;
10194   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10195     {
10196       len -= mod_len;
10197       return true;
10198     }
10199   return false;
10200 }
10201
10202 /* Compute the physnames of any methods on the CU's method list.
10203
10204    The computation of method physnames is delayed in order to avoid the
10205    (bad) condition that one of the method's formal parameters is of an as yet
10206    incomplete type.  */
10207
10208 static void
10209 compute_delayed_physnames (struct dwarf2_cu *cu)
10210 {
10211   /* Only C++ delays computing physnames.  */
10212   if (cu->method_list.empty ())
10213     return;
10214   gdb_assert (cu->language == language_cplus);
10215
10216   for (struct delayed_method_info &mi : cu->method_list)
10217     {
10218       const char *physname;
10219       struct fn_fieldlist *fn_flp
10220         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
10221       physname = dwarf2_physname (mi.name, mi.die, cu);
10222       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
10223         = physname ? physname : "";
10224
10225       /* Since there's no tag to indicate whether a method is a
10226          const/volatile overload, extract that information out of the
10227          demangled name.  */
10228       if (physname != NULL)
10229         {
10230           size_t len = strlen (physname);
10231
10232           while (1)
10233             {
10234               if (physname[len] == ')') /* shortcut */
10235                 break;
10236               else if (check_modifier (physname, len, " const"))
10237                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
10238               else if (check_modifier (physname, len, " volatile"))
10239                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
10240               else
10241                 break;
10242             }
10243         }
10244     }
10245
10246   /* The list is no longer needed.  */
10247   cu->method_list.clear ();
10248 }
10249
10250 /* Go objects should be embedded in a DW_TAG_module DIE,
10251    and it's not clear if/how imported objects will appear.
10252    To keep Go support simple until that's worked out,
10253    go back through what we've read and create something usable.
10254    We could do this while processing each DIE, and feels kinda cleaner,
10255    but that way is more invasive.
10256    This is to, for example, allow the user to type "p var" or "b main"
10257    without having to specify the package name, and allow lookups
10258    of module.object to work in contexts that use the expression
10259    parser.  */
10260
10261 static void
10262 fixup_go_packaging (struct dwarf2_cu *cu)
10263 {
10264   char *package_name = NULL;
10265   struct pending *list;
10266   int i;
10267
10268   for (list = global_symbols; list != NULL; list = list->next)
10269     {
10270       for (i = 0; i < list->nsyms; ++i)
10271         {
10272           struct symbol *sym = list->symbol[i];
10273
10274           if (SYMBOL_LANGUAGE (sym) == language_go
10275               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10276             {
10277               char *this_package_name = go_symbol_package_name (sym);
10278
10279               if (this_package_name == NULL)
10280                 continue;
10281               if (package_name == NULL)
10282                 package_name = this_package_name;
10283               else
10284                 {
10285                   struct objfile *objfile
10286                     = cu->per_cu->dwarf2_per_objfile->objfile;
10287                   if (strcmp (package_name, this_package_name) != 0)
10288                     complaint (&symfile_complaints,
10289                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10290                                (symbol_symtab (sym) != NULL
10291                                 ? symtab_to_filename_for_display
10292                                     (symbol_symtab (sym))
10293                                 : objfile_name (objfile)),
10294                                this_package_name, package_name);
10295                   xfree (this_package_name);
10296                 }
10297             }
10298         }
10299     }
10300
10301   if (package_name != NULL)
10302     {
10303       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10304       const char *saved_package_name
10305         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10306                                         package_name,
10307                                         strlen (package_name));
10308       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10309                                      saved_package_name);
10310       struct symbol *sym;
10311
10312       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10313
10314       sym = allocate_symbol (objfile);
10315       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10316       SYMBOL_SET_NAMES (sym, saved_package_name,
10317                         strlen (saved_package_name), 0, objfile);
10318       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10319          e.g., "main" finds the "main" module and not C's main().  */
10320       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10321       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10322       SYMBOL_TYPE (sym) = type;
10323
10324       add_symbol_to_list (sym, &global_symbols);
10325
10326       xfree (package_name);
10327     }
10328 }
10329
10330 /* Allocate a fully-qualified name consisting of the two parts on the
10331    obstack.  */
10332
10333 static const char *
10334 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
10335 {
10336   return obconcat (obstack, p1, "::", p2, (char *) NULL);
10337 }
10338
10339 /* A helper that allocates a struct discriminant_info to attach to a
10340    union type.  */
10341
10342 static struct discriminant_info *
10343 alloc_discriminant_info (struct type *type, int discriminant_index,
10344                          int default_index)
10345 {
10346   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
10347   gdb_assert (default_index == -1
10348               || (default_index > 0 && default_index < TYPE_NFIELDS (type)));
10349
10350   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
10351
10352   struct discriminant_info *disc
10353     = ((struct discriminant_info *)
10354        TYPE_ZALLOC (type,
10355                     offsetof (struct discriminant_info, discriminants)
10356                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
10357   disc->default_index = default_index;
10358   disc->discriminant_index = discriminant_index;
10359
10360   struct dynamic_prop prop;
10361   prop.kind = PROP_UNDEFINED;
10362   prop.data.baton = disc;
10363
10364   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
10365
10366   return disc;
10367 }
10368
10369 /* Some versions of rustc emitted enums in an unusual way.
10370
10371    Ordinary enums were emitted as unions.  The first element of each
10372    structure in the union was named "RUST$ENUM$DISR".  This element
10373    held the discriminant.
10374
10375    These versions of Rust also implemented the "non-zero"
10376    optimization.  When the enum had two values, and one is empty and
10377    the other holds a pointer that cannot be zero, the pointer is used
10378    as the discriminant, with a zero value meaning the empty variant.
10379    Here, the union's first member is of the form
10380    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
10381    where the fieldnos are the indices of the fields that should be
10382    traversed in order to find the field (which may be several fields deep)
10383    and the variantname is the name of the variant of the case when the
10384    field is zero.
10385
10386    This function recognizes whether TYPE is of one of these forms,
10387    and, if so, smashes it to be a variant type.  */
10388
10389 static void
10390 quirk_rust_enum (struct type *type, struct objfile *objfile)
10391 {
10392   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
10393
10394   /* We don't need to deal with empty enums.  */
10395   if (TYPE_NFIELDS (type) == 0)
10396     return;
10397
10398 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
10399   if (TYPE_NFIELDS (type) == 1
10400       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
10401     {
10402       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
10403
10404       /* Decode the field name to find the offset of the
10405          discriminant.  */
10406       ULONGEST bit_offset = 0;
10407       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
10408       while (name[0] >= '0' && name[0] <= '9')
10409         {
10410           char *tail;
10411           unsigned long index = strtoul (name, &tail, 10);
10412           name = tail;
10413           if (*name != '$'
10414               || index >= TYPE_NFIELDS (field_type)
10415               || (TYPE_FIELD_LOC_KIND (field_type, index)
10416                   != FIELD_LOC_KIND_BITPOS))
10417             {
10418               complaint (&symfile_complaints,
10419                          _("Could not parse Rust enum encoding string \"%s\""
10420                            "[in module %s]"),
10421                          TYPE_FIELD_NAME (type, 0),
10422                          objfile_name (objfile));
10423               return;
10424             }
10425           ++name;
10426
10427           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
10428           field_type = TYPE_FIELD_TYPE (field_type, index);
10429         }
10430
10431       /* Make a union to hold the variants.  */
10432       struct type *union_type = alloc_type (objfile);
10433       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10434       TYPE_NFIELDS (union_type) = 3;
10435       TYPE_FIELDS (union_type)
10436         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
10437       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10438
10439       /* Put the discriminant must at index 0.  */
10440       TYPE_FIELD_TYPE (union_type, 0) = field_type;
10441       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10442       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10443       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
10444
10445       /* The order of fields doesn't really matter, so put the real
10446          field at index 1 and the data-less field at index 2.  */
10447       struct discriminant_info *disc
10448         = alloc_discriminant_info (union_type, 0, 1);
10449       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
10450       TYPE_FIELD_NAME (union_type, 1)
10451         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
10452       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
10453         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10454                               TYPE_FIELD_NAME (union_type, 1));
10455
10456       const char *dataless_name
10457         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10458                               name);
10459       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10460                                               dataless_name);
10461       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10462       /* NAME points into the original discriminant name, which
10463          already has the correct lifetime.  */
10464       TYPE_FIELD_NAME (union_type, 2) = name;
10465       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10466       disc->discriminants[2] = 0;
10467
10468       /* Smash this type to be a structure type.  We have to do this
10469          because the type has already been recorded.  */
10470       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10471       TYPE_NFIELDS (type) = 1;
10472       TYPE_FIELDS (type)
10473         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10474
10475       /* Install the variant part.  */
10476       TYPE_FIELD_TYPE (type, 0) = union_type;
10477       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10478       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10479     }
10480   else if (TYPE_NFIELDS (type) == 1)
10481     {
10482       /* We assume that a union with a single field is a univariant
10483          enum.  */
10484       /* Smash this type to be a structure type.  We have to do this
10485          because the type has already been recorded.  */
10486       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10487
10488       /* Make a union to hold the variants.  */
10489       struct type *union_type = alloc_type (objfile);
10490       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10491       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10492       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10493       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10494
10495       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10496       const char *variant_name
10497         = rust_last_path_segment (TYPE_NAME (field_type));
10498       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10499       TYPE_NAME (field_type)
10500         = rust_fully_qualify (&objfile->objfile_obstack,
10501                               TYPE_NAME (field_type), variant_name);
10502
10503       /* Install the union in the outer struct type.  */
10504       TYPE_NFIELDS (type) = 1;
10505       TYPE_FIELDS (type)
10506         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10507       TYPE_FIELD_TYPE (type, 0) = union_type;
10508       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10509       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10510
10511       alloc_discriminant_info (union_type, -1, 0);
10512     }
10513   else
10514     {
10515       struct type *disr_type = nullptr;
10516       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10517         {
10518           disr_type = TYPE_FIELD_TYPE (type, i);
10519
10520           if (TYPE_NFIELDS (disr_type) == 0)
10521             {
10522               /* Could be data-less variant, so keep going.  */
10523             }
10524           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10525                            "RUST$ENUM$DISR") != 0)
10526             {
10527               /* Not a Rust enum.  */
10528               return;
10529             }
10530           else
10531             {
10532               /* Found one.  */
10533               break;
10534             }
10535         }
10536
10537       /* If we got here without a discriminant, then it's probably
10538          just a union.  */
10539       if (disr_type == nullptr)
10540         return;
10541
10542       /* Smash this type to be a structure type.  We have to do this
10543          because the type has already been recorded.  */
10544       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10545
10546       /* Make a union to hold the variants.  */
10547       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10548       struct type *union_type = alloc_type (objfile);
10549       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10550       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10551       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10552       TYPE_FIELDS (union_type)
10553         = (struct field *) TYPE_ZALLOC (union_type,
10554                                         (TYPE_NFIELDS (union_type)
10555                                          * sizeof (struct field)));
10556
10557       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10558               TYPE_NFIELDS (type) * sizeof (struct field));
10559
10560       /* Install the discriminant at index 0 in the union.  */
10561       TYPE_FIELD (union_type, 0) = *disr_field;
10562       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10563       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10564
10565       /* Install the union in the outer struct type.  */
10566       TYPE_FIELD_TYPE (type, 0) = union_type;
10567       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10568       TYPE_NFIELDS (type) = 1;
10569
10570       /* Set the size and offset of the union type.  */
10571       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10572
10573       /* We need a way to find the correct discriminant given a
10574          variant name.  For convenience we build a map here.  */
10575       struct type *enum_type = FIELD_TYPE (*disr_field);
10576       std::unordered_map<std::string, ULONGEST> discriminant_map;
10577       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10578         {
10579           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10580             {
10581               const char *name
10582                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10583               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10584             }
10585         }
10586
10587       int n_fields = TYPE_NFIELDS (union_type);
10588       struct discriminant_info *disc
10589         = alloc_discriminant_info (union_type, 0, -1);
10590       /* Skip the discriminant here.  */
10591       for (int i = 1; i < n_fields; ++i)
10592         {
10593           /* Find the final word in the name of this variant's type.
10594              That name can be used to look up the correct
10595              discriminant.  */
10596           const char *variant_name
10597             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10598                                                                   i)));
10599
10600           auto iter = discriminant_map.find (variant_name);
10601           if (iter != discriminant_map.end ())
10602             disc->discriminants[i] = iter->second;
10603
10604           /* Remove the discriminant field.  */
10605           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10606           --TYPE_NFIELDS (sub_type);
10607           ++TYPE_FIELDS (sub_type);
10608           TYPE_FIELD_NAME (union_type, i) = variant_name;
10609           TYPE_NAME (sub_type)
10610             = rust_fully_qualify (&objfile->objfile_obstack,
10611                                   TYPE_NAME (type), variant_name);
10612         }
10613     }
10614 }
10615
10616 /* Rewrite some Rust unions to be structures with variants parts.  */
10617
10618 static void
10619 rust_union_quirks (struct dwarf2_cu *cu)
10620 {
10621   gdb_assert (cu->language == language_rust);
10622   for (struct type *type : cu->rust_unions)
10623     quirk_rust_enum (type, cu->per_cu->dwarf2_per_objfile->objfile);
10624 }
10625
10626 /* Return the symtab for PER_CU.  This works properly regardless of
10627    whether we're using the index or psymtabs.  */
10628
10629 static struct compunit_symtab *
10630 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10631 {
10632   return (per_cu->dwarf2_per_objfile->using_index
10633           ? per_cu->v.quick->compunit_symtab
10634           : per_cu->v.psymtab->compunit_symtab);
10635 }
10636
10637 /* A helper function for computing the list of all symbol tables
10638    included by PER_CU.  */
10639
10640 static void
10641 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10642                                 htab_t all_children, htab_t all_type_symtabs,
10643                                 struct dwarf2_per_cu_data *per_cu,
10644                                 struct compunit_symtab *immediate_parent)
10645 {
10646   void **slot;
10647   int ix;
10648   struct compunit_symtab *cust;
10649   struct dwarf2_per_cu_data *iter;
10650
10651   slot = htab_find_slot (all_children, per_cu, INSERT);
10652   if (*slot != NULL)
10653     {
10654       /* This inclusion and its children have been processed.  */
10655       return;
10656     }
10657
10658   *slot = per_cu;
10659   /* Only add a CU if it has a symbol table.  */
10660   cust = get_compunit_symtab (per_cu);
10661   if (cust != NULL)
10662     {
10663       /* If this is a type unit only add its symbol table if we haven't
10664          seen it yet (type unit per_cu's can share symtabs).  */
10665       if (per_cu->is_debug_types)
10666         {
10667           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10668           if (*slot == NULL)
10669             {
10670               *slot = cust;
10671               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10672               if (cust->user == NULL)
10673                 cust->user = immediate_parent;
10674             }
10675         }
10676       else
10677         {
10678           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10679           if (cust->user == NULL)
10680             cust->user = immediate_parent;
10681         }
10682     }
10683
10684   for (ix = 0;
10685        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10686        ++ix)
10687     {
10688       recursively_compute_inclusions (result, all_children,
10689                                       all_type_symtabs, iter, cust);
10690     }
10691 }
10692
10693 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10694    PER_CU.  */
10695
10696 static void
10697 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10698 {
10699   gdb_assert (! per_cu->is_debug_types);
10700
10701   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10702     {
10703       int ix, len;
10704       struct dwarf2_per_cu_data *per_cu_iter;
10705       struct compunit_symtab *compunit_symtab_iter;
10706       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10707       htab_t all_children, all_type_symtabs;
10708       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10709
10710       /* If we don't have a symtab, we can just skip this case.  */
10711       if (cust == NULL)
10712         return;
10713
10714       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10715                                         NULL, xcalloc, xfree);
10716       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10717                                             NULL, xcalloc, xfree);
10718
10719       for (ix = 0;
10720            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10721                         ix, per_cu_iter);
10722            ++ix)
10723         {
10724           recursively_compute_inclusions (&result_symtabs, all_children,
10725                                           all_type_symtabs, per_cu_iter,
10726                                           cust);
10727         }
10728
10729       /* Now we have a transitive closure of all the included symtabs.  */
10730       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10731       cust->includes
10732         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10733                      struct compunit_symtab *, len + 1);
10734       for (ix = 0;
10735            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10736                         compunit_symtab_iter);
10737            ++ix)
10738         cust->includes[ix] = compunit_symtab_iter;
10739       cust->includes[len] = NULL;
10740
10741       VEC_free (compunit_symtab_ptr, result_symtabs);
10742       htab_delete (all_children);
10743       htab_delete (all_type_symtabs);
10744     }
10745 }
10746
10747 /* Compute the 'includes' field for the symtabs of all the CUs we just
10748    read.  */
10749
10750 static void
10751 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10752 {
10753   int ix;
10754   struct dwarf2_per_cu_data *iter;
10755
10756   for (ix = 0;
10757        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10758                     ix, iter);
10759        ++ix)
10760     {
10761       if (! iter->is_debug_types)
10762         compute_compunit_symtab_includes (iter);
10763     }
10764
10765   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10766 }
10767
10768 /* Generate full symbol information for PER_CU, whose DIEs have
10769    already been loaded into memory.  */
10770
10771 static void
10772 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10773                         enum language pretend_language)
10774 {
10775   struct dwarf2_cu *cu = per_cu->cu;
10776   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10777   struct objfile *objfile = dwarf2_per_objfile->objfile;
10778   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10779   CORE_ADDR lowpc, highpc;
10780   struct compunit_symtab *cust;
10781   CORE_ADDR baseaddr;
10782   struct block *static_block;
10783   CORE_ADDR addr;
10784
10785   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10786
10787   buildsym_init ();
10788   scoped_free_pendings free_pending;
10789
10790   /* Clear the list here in case something was left over.  */
10791   cu->method_list.clear ();
10792
10793   cu->list_in_scope = &file_symbols;
10794
10795   cu->language = pretend_language;
10796   cu->language_defn = language_def (cu->language);
10797
10798   /* Do line number decoding in read_file_scope () */
10799   process_die (cu->dies, cu);
10800
10801   /* For now fudge the Go package.  */
10802   if (cu->language == language_go)
10803     fixup_go_packaging (cu);
10804
10805   /* Now that we have processed all the DIEs in the CU, all the types 
10806      should be complete, and it should now be safe to compute all of the
10807      physnames.  */
10808   compute_delayed_physnames (cu);
10809
10810   if (cu->language == language_rust)
10811     rust_union_quirks (cu);
10812
10813   /* Some compilers don't define a DW_AT_high_pc attribute for the
10814      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10815      it, by scanning the DIE's below the compilation unit.  */
10816   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10817
10818   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10819   static_block = end_symtab_get_static_block (addr, 0, 1);
10820
10821   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10822      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10823      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10824      addrmap to help ensure it has an accurate map of pc values belonging to
10825      this comp unit.  */
10826   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10827
10828   cust = end_symtab_from_static_block (static_block,
10829                                        SECT_OFF_TEXT (objfile), 0);
10830
10831   if (cust != NULL)
10832     {
10833       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10834
10835       /* Set symtab language to language from DW_AT_language.  If the
10836          compilation is from a C file generated by language preprocessors, do
10837          not set the language if it was already deduced by start_subfile.  */
10838       if (!(cu->language == language_c
10839             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10840         COMPUNIT_FILETABS (cust)->language = cu->language;
10841
10842       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10843          produce DW_AT_location with location lists but it can be possibly
10844          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10845          there were bugs in prologue debug info, fixed later in GCC-4.5
10846          by "unwind info for epilogues" patch (which is not directly related).
10847
10848          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10849          needed, it would be wrong due to missing DW_AT_producer there.
10850
10851          Still one can confuse GDB by using non-standard GCC compilation
10852          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10853          */ 
10854       if (cu->has_loclist && gcc_4_minor >= 5)
10855         cust->locations_valid = 1;
10856
10857       if (gcc_4_minor >= 5)
10858         cust->epilogue_unwind_valid = 1;
10859
10860       cust->call_site_htab = cu->call_site_htab;
10861     }
10862
10863   if (dwarf2_per_objfile->using_index)
10864     per_cu->v.quick->compunit_symtab = cust;
10865   else
10866     {
10867       struct partial_symtab *pst = per_cu->v.psymtab;
10868       pst->compunit_symtab = cust;
10869       pst->readin = 1;
10870     }
10871
10872   /* Push it for inclusion processing later.  */
10873   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10874 }
10875
10876 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10877    already been loaded into memory.  */
10878
10879 static void
10880 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10881                         enum language pretend_language)
10882 {
10883   struct dwarf2_cu *cu = per_cu->cu;
10884   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10885   struct objfile *objfile = dwarf2_per_objfile->objfile;
10886   struct compunit_symtab *cust;
10887   struct signatured_type *sig_type;
10888
10889   gdb_assert (per_cu->is_debug_types);
10890   sig_type = (struct signatured_type *) per_cu;
10891
10892   buildsym_init ();
10893   scoped_free_pendings free_pending;
10894
10895   /* Clear the list here in case something was left over.  */
10896   cu->method_list.clear ();
10897
10898   cu->list_in_scope = &file_symbols;
10899
10900   cu->language = pretend_language;
10901   cu->language_defn = language_def (cu->language);
10902
10903   /* The symbol tables are set up in read_type_unit_scope.  */
10904   process_die (cu->dies, cu);
10905
10906   /* For now fudge the Go package.  */
10907   if (cu->language == language_go)
10908     fixup_go_packaging (cu);
10909
10910   /* Now that we have processed all the DIEs in the CU, all the types 
10911      should be complete, and it should now be safe to compute all of the
10912      physnames.  */
10913   compute_delayed_physnames (cu);
10914
10915   if (cu->language == language_rust)
10916     rust_union_quirks (cu);
10917
10918   /* TUs share symbol tables.
10919      If this is the first TU to use this symtab, complete the construction
10920      of it with end_expandable_symtab.  Otherwise, complete the addition of
10921      this TU's symbols to the existing symtab.  */
10922   if (sig_type->type_unit_group->compunit_symtab == NULL)
10923     {
10924       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10925       sig_type->type_unit_group->compunit_symtab = cust;
10926
10927       if (cust != NULL)
10928         {
10929           /* Set symtab language to language from DW_AT_language.  If the
10930              compilation is from a C file generated by language preprocessors,
10931              do not set the language if it was already deduced by
10932              start_subfile.  */
10933           if (!(cu->language == language_c
10934                 && COMPUNIT_FILETABS (cust)->language != language_c))
10935             COMPUNIT_FILETABS (cust)->language = cu->language;
10936         }
10937     }
10938   else
10939     {
10940       augment_type_symtab ();
10941       cust = sig_type->type_unit_group->compunit_symtab;
10942     }
10943
10944   if (dwarf2_per_objfile->using_index)
10945     per_cu->v.quick->compunit_symtab = cust;
10946   else
10947     {
10948       struct partial_symtab *pst = per_cu->v.psymtab;
10949       pst->compunit_symtab = cust;
10950       pst->readin = 1;
10951     }
10952 }
10953
10954 /* Process an imported unit DIE.  */
10955
10956 static void
10957 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10958 {
10959   struct attribute *attr;
10960
10961   /* For now we don't handle imported units in type units.  */
10962   if (cu->per_cu->is_debug_types)
10963     {
10964       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10965                " supported in type units [in module %s]"),
10966              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10967     }
10968
10969   attr = dwarf2_attr (die, DW_AT_import, cu);
10970   if (attr != NULL)
10971     {
10972       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10973       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10974       dwarf2_per_cu_data *per_cu
10975         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10976                                             cu->per_cu->dwarf2_per_objfile);
10977
10978       /* If necessary, add it to the queue and load its DIEs.  */
10979       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10980         load_full_comp_unit (per_cu, cu->language);
10981
10982       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10983                      per_cu);
10984     }
10985 }
10986
10987 /* RAII object that represents a process_die scope: i.e.,
10988    starts/finishes processing a DIE.  */
10989 class process_die_scope
10990 {
10991 public:
10992   process_die_scope (die_info *die, dwarf2_cu *cu)
10993     : m_die (die), m_cu (cu)
10994   {
10995     /* We should only be processing DIEs not already in process.  */
10996     gdb_assert (!m_die->in_process);
10997     m_die->in_process = true;
10998   }
10999
11000   ~process_die_scope ()
11001   {
11002     m_die->in_process = false;
11003
11004     /* If we're done processing the DIE for the CU that owns the line
11005        header, we don't need the line header anymore.  */
11006     if (m_cu->line_header_die_owner == m_die)
11007       {
11008         delete m_cu->line_header;
11009         m_cu->line_header = NULL;
11010         m_cu->line_header_die_owner = NULL;
11011       }
11012   }
11013
11014 private:
11015   die_info *m_die;
11016   dwarf2_cu *m_cu;
11017 };
11018
11019 /* Process a die and its children.  */
11020
11021 static void
11022 process_die (struct die_info *die, struct dwarf2_cu *cu)
11023 {
11024   process_die_scope scope (die, cu);
11025
11026   switch (die->tag)
11027     {
11028     case DW_TAG_padding:
11029       break;
11030     case DW_TAG_compile_unit:
11031     case DW_TAG_partial_unit:
11032       read_file_scope (die, cu);
11033       break;
11034     case DW_TAG_type_unit:
11035       read_type_unit_scope (die, cu);
11036       break;
11037     case DW_TAG_subprogram:
11038     case DW_TAG_inlined_subroutine:
11039       read_func_scope (die, cu);
11040       break;
11041     case DW_TAG_lexical_block:
11042     case DW_TAG_try_block:
11043     case DW_TAG_catch_block:
11044       read_lexical_block_scope (die, cu);
11045       break;
11046     case DW_TAG_call_site:
11047     case DW_TAG_GNU_call_site:
11048       read_call_site_scope (die, cu);
11049       break;
11050     case DW_TAG_class_type:
11051     case DW_TAG_interface_type:
11052     case DW_TAG_structure_type:
11053     case DW_TAG_union_type:
11054       process_structure_scope (die, cu);
11055       break;
11056     case DW_TAG_enumeration_type:
11057       process_enumeration_scope (die, cu);
11058       break;
11059
11060     /* These dies have a type, but processing them does not create
11061        a symbol or recurse to process the children.  Therefore we can
11062        read them on-demand through read_type_die.  */
11063     case DW_TAG_subroutine_type:
11064     case DW_TAG_set_type:
11065     case DW_TAG_array_type:
11066     case DW_TAG_pointer_type:
11067     case DW_TAG_ptr_to_member_type:
11068     case DW_TAG_reference_type:
11069     case DW_TAG_rvalue_reference_type:
11070     case DW_TAG_string_type:
11071       break;
11072
11073     case DW_TAG_base_type:
11074     case DW_TAG_subrange_type:
11075     case DW_TAG_typedef:
11076       /* Add a typedef symbol for the type definition, if it has a
11077          DW_AT_name.  */
11078       new_symbol (die, read_type_die (die, cu), cu);
11079       break;
11080     case DW_TAG_common_block:
11081       read_common_block (die, cu);
11082       break;
11083     case DW_TAG_common_inclusion:
11084       break;
11085     case DW_TAG_namespace:
11086       cu->processing_has_namespace_info = 1;
11087       read_namespace (die, cu);
11088       break;
11089     case DW_TAG_module:
11090       cu->processing_has_namespace_info = 1;
11091       read_module (die, cu);
11092       break;
11093     case DW_TAG_imported_declaration:
11094       cu->processing_has_namespace_info = 1;
11095       if (read_namespace_alias (die, cu))
11096         break;
11097       /* The declaration is not a global namespace alias: fall through.  */
11098     case DW_TAG_imported_module:
11099       cu->processing_has_namespace_info = 1;
11100       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
11101                                  || cu->language != language_fortran))
11102         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
11103                    dwarf_tag_name (die->tag));
11104       read_import_statement (die, cu);
11105       break;
11106
11107     case DW_TAG_imported_unit:
11108       process_imported_unit_die (die, cu);
11109       break;
11110
11111     case DW_TAG_variable:
11112       read_variable (die, cu);
11113       break;
11114
11115     default:
11116       new_symbol (die, NULL, cu);
11117       break;
11118     }
11119 }
11120 \f
11121 /* DWARF name computation.  */
11122
11123 /* A helper function for dwarf2_compute_name which determines whether DIE
11124    needs to have the name of the scope prepended to the name listed in the
11125    die.  */
11126
11127 static int
11128 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
11129 {
11130   struct attribute *attr;
11131
11132   switch (die->tag)
11133     {
11134     case DW_TAG_namespace:
11135     case DW_TAG_typedef:
11136     case DW_TAG_class_type:
11137     case DW_TAG_interface_type:
11138     case DW_TAG_structure_type:
11139     case DW_TAG_union_type:
11140     case DW_TAG_enumeration_type:
11141     case DW_TAG_enumerator:
11142     case DW_TAG_subprogram:
11143     case DW_TAG_inlined_subroutine:
11144     case DW_TAG_member:
11145     case DW_TAG_imported_declaration:
11146       return 1;
11147
11148     case DW_TAG_variable:
11149     case DW_TAG_constant:
11150       /* We only need to prefix "globally" visible variables.  These include
11151          any variable marked with DW_AT_external or any variable that
11152          lives in a namespace.  [Variables in anonymous namespaces
11153          require prefixing, but they are not DW_AT_external.]  */
11154
11155       if (dwarf2_attr (die, DW_AT_specification, cu))
11156         {
11157           struct dwarf2_cu *spec_cu = cu;
11158
11159           return die_needs_namespace (die_specification (die, &spec_cu),
11160                                       spec_cu);
11161         }
11162
11163       attr = dwarf2_attr (die, DW_AT_external, cu);
11164       if (attr == NULL && die->parent->tag != DW_TAG_namespace
11165           && die->parent->tag != DW_TAG_module)
11166         return 0;
11167       /* A variable in a lexical block of some kind does not need a
11168          namespace, even though in C++ such variables may be external
11169          and have a mangled name.  */
11170       if (die->parent->tag ==  DW_TAG_lexical_block
11171           || die->parent->tag ==  DW_TAG_try_block
11172           || die->parent->tag ==  DW_TAG_catch_block
11173           || die->parent->tag == DW_TAG_subprogram)
11174         return 0;
11175       return 1;
11176
11177     default:
11178       return 0;
11179     }
11180 }
11181
11182 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
11183    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
11184    defined for the given DIE.  */
11185
11186 static struct attribute *
11187 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
11188 {
11189   struct attribute *attr;
11190
11191   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
11192   if (attr == NULL)
11193     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
11194
11195   return attr;
11196 }
11197
11198 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
11199    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
11200    defined for the given DIE.  */
11201
11202 static const char *
11203 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
11204 {
11205   const char *linkage_name;
11206
11207   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
11208   if (linkage_name == NULL)
11209     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
11210
11211   return linkage_name;
11212 }
11213
11214 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
11215    compute the physname for the object, which include a method's:
11216    - formal parameters (C++),
11217    - receiver type (Go),
11218
11219    The term "physname" is a bit confusing.
11220    For C++, for example, it is the demangled name.
11221    For Go, for example, it's the mangled name.
11222
11223    For Ada, return the DIE's linkage name rather than the fully qualified
11224    name.  PHYSNAME is ignored..
11225
11226    The result is allocated on the objfile_obstack and canonicalized.  */
11227
11228 static const char *
11229 dwarf2_compute_name (const char *name,
11230                      struct die_info *die, struct dwarf2_cu *cu,
11231                      int physname)
11232 {
11233   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11234
11235   if (name == NULL)
11236     name = dwarf2_name (die, cu);
11237
11238   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
11239      but otherwise compute it by typename_concat inside GDB.
11240      FIXME: Actually this is not really true, or at least not always true.
11241      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
11242      Fortran names because there is no mangling standard.  So new_symbol
11243      will set the demangled name to the result of dwarf2_full_name, and it is
11244      the demangled name that GDB uses if it exists.  */
11245   if (cu->language == language_ada
11246       || (cu->language == language_fortran && physname))
11247     {
11248       /* For Ada unit, we prefer the linkage name over the name, as
11249          the former contains the exported name, which the user expects
11250          to be able to reference.  Ideally, we want the user to be able
11251          to reference this entity using either natural or linkage name,
11252          but we haven't started looking at this enhancement yet.  */
11253       const char *linkage_name = dw2_linkage_name (die, cu);
11254
11255       if (linkage_name != NULL)
11256         return linkage_name;
11257     }
11258
11259   /* These are the only languages we know how to qualify names in.  */
11260   if (name != NULL
11261       && (cu->language == language_cplus
11262           || cu->language == language_fortran || cu->language == language_d
11263           || cu->language == language_rust))
11264     {
11265       if (die_needs_namespace (die, cu))
11266         {
11267           const char *prefix;
11268           const char *canonical_name = NULL;
11269
11270           string_file buf;
11271
11272           prefix = determine_prefix (die, cu);
11273           if (*prefix != '\0')
11274             {
11275               char *prefixed_name = typename_concat (NULL, prefix, name,
11276                                                      physname, cu);
11277
11278               buf.puts (prefixed_name);
11279               xfree (prefixed_name);
11280             }
11281           else
11282             buf.puts (name);
11283
11284           /* Template parameters may be specified in the DIE's DW_AT_name, or
11285              as children with DW_TAG_template_type_param or
11286              DW_TAG_value_type_param.  If the latter, add them to the name
11287              here.  If the name already has template parameters, then
11288              skip this step; some versions of GCC emit both, and
11289              it is more efficient to use the pre-computed name.
11290
11291              Something to keep in mind about this process: it is very
11292              unlikely, or in some cases downright impossible, to produce
11293              something that will match the mangled name of a function.
11294              If the definition of the function has the same debug info,
11295              we should be able to match up with it anyway.  But fallbacks
11296              using the minimal symbol, for instance to find a method
11297              implemented in a stripped copy of libstdc++, will not work.
11298              If we do not have debug info for the definition, we will have to
11299              match them up some other way.
11300
11301              When we do name matching there is a related problem with function
11302              templates; two instantiated function templates are allowed to
11303              differ only by their return types, which we do not add here.  */
11304
11305           if (cu->language == language_cplus && strchr (name, '<') == NULL)
11306             {
11307               struct attribute *attr;
11308               struct die_info *child;
11309               int first = 1;
11310
11311               die->building_fullname = 1;
11312
11313               for (child = die->child; child != NULL; child = child->sibling)
11314                 {
11315                   struct type *type;
11316                   LONGEST value;
11317                   const gdb_byte *bytes;
11318                   struct dwarf2_locexpr_baton *baton;
11319                   struct value *v;
11320
11321                   if (child->tag != DW_TAG_template_type_param
11322                       && child->tag != DW_TAG_template_value_param)
11323                     continue;
11324
11325                   if (first)
11326                     {
11327                       buf.puts ("<");
11328                       first = 0;
11329                     }
11330                   else
11331                     buf.puts (", ");
11332
11333                   attr = dwarf2_attr (child, DW_AT_type, cu);
11334                   if (attr == NULL)
11335                     {
11336                       complaint (&symfile_complaints,
11337                                  _("template parameter missing DW_AT_type"));
11338                       buf.puts ("UNKNOWN_TYPE");
11339                       continue;
11340                     }
11341                   type = die_type (child, cu);
11342
11343                   if (child->tag == DW_TAG_template_type_param)
11344                     {
11345                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11346                       continue;
11347                     }
11348
11349                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11350                   if (attr == NULL)
11351                     {
11352                       complaint (&symfile_complaints,
11353                                  _("template parameter missing "
11354                                    "DW_AT_const_value"));
11355                       buf.puts ("UNKNOWN_VALUE");
11356                       continue;
11357                     }
11358
11359                   dwarf2_const_value_attr (attr, type, name,
11360                                            &cu->comp_unit_obstack, cu,
11361                                            &value, &bytes, &baton);
11362
11363                   if (TYPE_NOSIGN (type))
11364                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11365                        changed, this can use value_print instead.  */
11366                     c_printchar (value, type, &buf);
11367                   else
11368                     {
11369                       struct value_print_options opts;
11370
11371                       if (baton != NULL)
11372                         v = dwarf2_evaluate_loc_desc (type, NULL,
11373                                                       baton->data,
11374                                                       baton->size,
11375                                                       baton->per_cu);
11376                       else if (bytes != NULL)
11377                         {
11378                           v = allocate_value (type);
11379                           memcpy (value_contents_writeable (v), bytes,
11380                                   TYPE_LENGTH (type));
11381                         }
11382                       else
11383                         v = value_from_longest (type, value);
11384
11385                       /* Specify decimal so that we do not depend on
11386                          the radix.  */
11387                       get_formatted_print_options (&opts, 'd');
11388                       opts.raw = 1;
11389                       value_print (v, &buf, &opts);
11390                       release_value (v);
11391                       value_free (v);
11392                     }
11393                 }
11394
11395               die->building_fullname = 0;
11396
11397               if (!first)
11398                 {
11399                   /* Close the argument list, with a space if necessary
11400                      (nested templates).  */
11401                   if (!buf.empty () && buf.string ().back () == '>')
11402                     buf.puts (" >");
11403                   else
11404                     buf.puts (">");
11405                 }
11406             }
11407
11408           /* For C++ methods, append formal parameter type
11409              information, if PHYSNAME.  */
11410
11411           if (physname && die->tag == DW_TAG_subprogram
11412               && cu->language == language_cplus)
11413             {
11414               struct type *type = read_type_die (die, cu);
11415
11416               c_type_print_args (type, &buf, 1, cu->language,
11417                                  &type_print_raw_options);
11418
11419               if (cu->language == language_cplus)
11420                 {
11421                   /* Assume that an artificial first parameter is
11422                      "this", but do not crash if it is not.  RealView
11423                      marks unnamed (and thus unused) parameters as
11424                      artificial; there is no way to differentiate
11425                      the two cases.  */
11426                   if (TYPE_NFIELDS (type) > 0
11427                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11428                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11429                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11430                                                                         0))))
11431                     buf.puts (" const");
11432                 }
11433             }
11434
11435           const std::string &intermediate_name = buf.string ();
11436
11437           if (cu->language == language_cplus)
11438             canonical_name
11439               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11440                                           &objfile->per_bfd->storage_obstack);
11441
11442           /* If we only computed INTERMEDIATE_NAME, or if
11443              INTERMEDIATE_NAME is already canonical, then we need to
11444              copy it to the appropriate obstack.  */
11445           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11446             name = ((const char *)
11447                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11448                                    intermediate_name.c_str (),
11449                                    intermediate_name.length ()));
11450           else
11451             name = canonical_name;
11452         }
11453     }
11454
11455   return name;
11456 }
11457
11458 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11459    If scope qualifiers are appropriate they will be added.  The result
11460    will be allocated on the storage_obstack, or NULL if the DIE does
11461    not have a name.  NAME may either be from a previous call to
11462    dwarf2_name or NULL.
11463
11464    The output string will be canonicalized (if C++).  */
11465
11466 static const char *
11467 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11468 {
11469   return dwarf2_compute_name (name, die, cu, 0);
11470 }
11471
11472 /* Construct a physname for the given DIE in CU.  NAME may either be
11473    from a previous call to dwarf2_name or NULL.  The result will be
11474    allocated on the objfile_objstack or NULL if the DIE does not have a
11475    name.
11476
11477    The output string will be canonicalized (if C++).  */
11478
11479 static const char *
11480 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11481 {
11482   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11483   const char *retval, *mangled = NULL, *canon = NULL;
11484   int need_copy = 1;
11485
11486   /* In this case dwarf2_compute_name is just a shortcut not building anything
11487      on its own.  */
11488   if (!die_needs_namespace (die, cu))
11489     return dwarf2_compute_name (name, die, cu, 1);
11490
11491   mangled = dw2_linkage_name (die, cu);
11492
11493   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11494      See https://github.com/rust-lang/rust/issues/32925.  */
11495   if (cu->language == language_rust && mangled != NULL
11496       && strchr (mangled, '{') != NULL)
11497     mangled = NULL;
11498
11499   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11500      has computed.  */
11501   gdb::unique_xmalloc_ptr<char> demangled;
11502   if (mangled != NULL)
11503     {
11504
11505       if (cu->language == language_go)
11506         {
11507           /* This is a lie, but we already lie to the caller new_symbol.
11508              new_symbol assumes we return the mangled name.
11509              This just undoes that lie until things are cleaned up.  */
11510         }
11511       else
11512         {
11513           /* Use DMGL_RET_DROP for C++ template functions to suppress
11514              their return type.  It is easier for GDB users to search
11515              for such functions as `name(params)' than `long name(params)'.
11516              In such case the minimal symbol names do not match the full
11517              symbol names but for template functions there is never a need
11518              to look up their definition from their declaration so
11519              the only disadvantage remains the minimal symbol variant
11520              `long name(params)' does not have the proper inferior type.  */
11521           demangled.reset (gdb_demangle (mangled,
11522                                          (DMGL_PARAMS | DMGL_ANSI
11523                                           | DMGL_RET_DROP)));
11524         }
11525       if (demangled)
11526         canon = demangled.get ();
11527       else
11528         {
11529           canon = mangled;
11530           need_copy = 0;
11531         }
11532     }
11533
11534   if (canon == NULL || check_physname)
11535     {
11536       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11537
11538       if (canon != NULL && strcmp (physname, canon) != 0)
11539         {
11540           /* It may not mean a bug in GDB.  The compiler could also
11541              compute DW_AT_linkage_name incorrectly.  But in such case
11542              GDB would need to be bug-to-bug compatible.  */
11543
11544           complaint (&symfile_complaints,
11545                      _("Computed physname <%s> does not match demangled <%s> "
11546                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11547                      physname, canon, mangled, sect_offset_str (die->sect_off),
11548                      objfile_name (objfile));
11549
11550           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11551              is available here - over computed PHYSNAME.  It is safer
11552              against both buggy GDB and buggy compilers.  */
11553
11554           retval = canon;
11555         }
11556       else
11557         {
11558           retval = physname;
11559           need_copy = 0;
11560         }
11561     }
11562   else
11563     retval = canon;
11564
11565   if (need_copy)
11566     retval = ((const char *)
11567               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11568                              retval, strlen (retval)));
11569
11570   return retval;
11571 }
11572
11573 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11574    a new symbol for it.
11575
11576    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11577
11578 static int
11579 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11580 {
11581   struct attribute *attr;
11582
11583   /* If the die does not have a name, this is not a namespace
11584      alias.  */
11585   attr = dwarf2_attr (die, DW_AT_name, cu);
11586   if (attr != NULL)
11587     {
11588       int num;
11589       struct die_info *d = die;
11590       struct dwarf2_cu *imported_cu = cu;
11591
11592       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11593          keep inspecting DIEs until we hit the underlying import.  */
11594 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11595       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11596         {
11597           attr = dwarf2_attr (d, DW_AT_import, cu);
11598           if (attr == NULL)
11599             break;
11600
11601           d = follow_die_ref (d, attr, &imported_cu);
11602           if (d->tag != DW_TAG_imported_declaration)
11603             break;
11604         }
11605
11606       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11607         {
11608           complaint (&symfile_complaints,
11609                      _("DIE at %s has too many recursively imported "
11610                        "declarations"), sect_offset_str (d->sect_off));
11611           return 0;
11612         }
11613
11614       if (attr != NULL)
11615         {
11616           struct type *type;
11617           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11618
11619           type = get_die_type_at_offset (sect_off, cu->per_cu);
11620           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11621             {
11622               /* This declaration is a global namespace alias.  Add
11623                  a symbol for it whose type is the aliased namespace.  */
11624               new_symbol (die, type, cu);
11625               return 1;
11626             }
11627         }
11628     }
11629
11630   return 0;
11631 }
11632
11633 /* Return the using directives repository (global or local?) to use in the
11634    current context for LANGUAGE.
11635
11636    For Ada, imported declarations can materialize renamings, which *may* be
11637    global.  However it is impossible (for now?) in DWARF to distinguish
11638    "external" imported declarations and "static" ones.  As all imported
11639    declarations seem to be static in all other languages, make them all CU-wide
11640    global only in Ada.  */
11641
11642 static struct using_direct **
11643 using_directives (enum language language)
11644 {
11645   if (language == language_ada && context_stack_depth == 0)
11646     return &global_using_directives;
11647   else
11648     return &local_using_directives;
11649 }
11650
11651 /* Read the import statement specified by the given die and record it.  */
11652
11653 static void
11654 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11655 {
11656   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11657   struct attribute *import_attr;
11658   struct die_info *imported_die, *child_die;
11659   struct dwarf2_cu *imported_cu;
11660   const char *imported_name;
11661   const char *imported_name_prefix;
11662   const char *canonical_name;
11663   const char *import_alias;
11664   const char *imported_declaration = NULL;
11665   const char *import_prefix;
11666   std::vector<const char *> excludes;
11667
11668   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11669   if (import_attr == NULL)
11670     {
11671       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11672                  dwarf_tag_name (die->tag));
11673       return;
11674     }
11675
11676   imported_cu = cu;
11677   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11678   imported_name = dwarf2_name (imported_die, imported_cu);
11679   if (imported_name == NULL)
11680     {
11681       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11682
11683         The import in the following code:
11684         namespace A
11685           {
11686             typedef int B;
11687           }
11688
11689         int main ()
11690           {
11691             using A::B;
11692             B b;
11693             return b;
11694           }
11695
11696         ...
11697          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11698             <52>   DW_AT_decl_file   : 1
11699             <53>   DW_AT_decl_line   : 6
11700             <54>   DW_AT_import      : <0x75>
11701          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11702             <59>   DW_AT_name        : B
11703             <5b>   DW_AT_decl_file   : 1
11704             <5c>   DW_AT_decl_line   : 2
11705             <5d>   DW_AT_type        : <0x6e>
11706         ...
11707          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11708             <76>   DW_AT_byte_size   : 4
11709             <77>   DW_AT_encoding    : 5        (signed)
11710
11711         imports the wrong die ( 0x75 instead of 0x58 ).
11712         This case will be ignored until the gcc bug is fixed.  */
11713       return;
11714     }
11715
11716   /* Figure out the local name after import.  */
11717   import_alias = dwarf2_name (die, cu);
11718
11719   /* Figure out where the statement is being imported to.  */
11720   import_prefix = determine_prefix (die, cu);
11721
11722   /* Figure out what the scope of the imported die is and prepend it
11723      to the name of the imported die.  */
11724   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11725
11726   if (imported_die->tag != DW_TAG_namespace
11727       && imported_die->tag != DW_TAG_module)
11728     {
11729       imported_declaration = imported_name;
11730       canonical_name = imported_name_prefix;
11731     }
11732   else if (strlen (imported_name_prefix) > 0)
11733     canonical_name = obconcat (&objfile->objfile_obstack,
11734                                imported_name_prefix,
11735                                (cu->language == language_d ? "." : "::"),
11736                                imported_name, (char *) NULL);
11737   else
11738     canonical_name = imported_name;
11739
11740   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11741     for (child_die = die->child; child_die && child_die->tag;
11742          child_die = sibling_die (child_die))
11743       {
11744         /* DWARF-4: A Fortran use statement with a “rename list” may be
11745            represented by an imported module entry with an import attribute
11746            referring to the module and owned entries corresponding to those
11747            entities that are renamed as part of being imported.  */
11748
11749         if (child_die->tag != DW_TAG_imported_declaration)
11750           {
11751             complaint (&symfile_complaints,
11752                        _("child DW_TAG_imported_declaration expected "
11753                          "- DIE at %s [in module %s]"),
11754                        sect_offset_str (child_die->sect_off),
11755                        objfile_name (objfile));
11756             continue;
11757           }
11758
11759         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11760         if (import_attr == NULL)
11761           {
11762             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11763                        dwarf_tag_name (child_die->tag));
11764             continue;
11765           }
11766
11767         imported_cu = cu;
11768         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11769                                               &imported_cu);
11770         imported_name = dwarf2_name (imported_die, imported_cu);
11771         if (imported_name == NULL)
11772           {
11773             complaint (&symfile_complaints,
11774                        _("child DW_TAG_imported_declaration has unknown "
11775                          "imported name - DIE at %s [in module %s]"),
11776                        sect_offset_str (child_die->sect_off),
11777                        objfile_name (objfile));
11778             continue;
11779           }
11780
11781         excludes.push_back (imported_name);
11782
11783         process_die (child_die, cu);
11784       }
11785
11786   add_using_directive (using_directives (cu->language),
11787                        import_prefix,
11788                        canonical_name,
11789                        import_alias,
11790                        imported_declaration,
11791                        excludes,
11792                        0,
11793                        &objfile->objfile_obstack);
11794 }
11795
11796 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11797    types, but gives them a size of zero.  Starting with version 14,
11798    ICC is compatible with GCC.  */
11799
11800 static int
11801 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11802 {
11803   if (!cu->checked_producer)
11804     check_producer (cu);
11805
11806   return cu->producer_is_icc_lt_14;
11807 }
11808
11809 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11810    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11811    this, it was first present in GCC release 4.3.0.  */
11812
11813 static int
11814 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11815 {
11816   if (!cu->checked_producer)
11817     check_producer (cu);
11818
11819   return cu->producer_is_gcc_lt_4_3;
11820 }
11821
11822 static file_and_directory
11823 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11824 {
11825   file_and_directory res;
11826
11827   /* Find the filename.  Do not use dwarf2_name here, since the filename
11828      is not a source language identifier.  */
11829   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11830   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11831
11832   if (res.comp_dir == NULL
11833       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11834       && IS_ABSOLUTE_PATH (res.name))
11835     {
11836       res.comp_dir_storage = ldirname (res.name);
11837       if (!res.comp_dir_storage.empty ())
11838         res.comp_dir = res.comp_dir_storage.c_str ();
11839     }
11840   if (res.comp_dir != NULL)
11841     {
11842       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11843          directory, get rid of it.  */
11844       const char *cp = strchr (res.comp_dir, ':');
11845
11846       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11847         res.comp_dir = cp + 1;
11848     }
11849
11850   if (res.name == NULL)
11851     res.name = "<unknown>";
11852
11853   return res;
11854 }
11855
11856 /* Handle DW_AT_stmt_list for a compilation unit.
11857    DIE is the DW_TAG_compile_unit die for CU.
11858    COMP_DIR is the compilation directory.  LOWPC is passed to
11859    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11860
11861 static void
11862 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11863                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11864 {
11865   struct dwarf2_per_objfile *dwarf2_per_objfile
11866     = cu->per_cu->dwarf2_per_objfile;
11867   struct objfile *objfile = dwarf2_per_objfile->objfile;
11868   struct attribute *attr;
11869   struct line_header line_header_local;
11870   hashval_t line_header_local_hash;
11871   void **slot;
11872   int decode_mapping;
11873
11874   gdb_assert (! cu->per_cu->is_debug_types);
11875
11876   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11877   if (attr == NULL)
11878     return;
11879
11880   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11881
11882   /* The line header hash table is only created if needed (it exists to
11883      prevent redundant reading of the line table for partial_units).
11884      If we're given a partial_unit, we'll need it.  If we're given a
11885      compile_unit, then use the line header hash table if it's already
11886      created, but don't create one just yet.  */
11887
11888   if (dwarf2_per_objfile->line_header_hash == NULL
11889       && die->tag == DW_TAG_partial_unit)
11890     {
11891       dwarf2_per_objfile->line_header_hash
11892         = htab_create_alloc_ex (127, line_header_hash_voidp,
11893                                 line_header_eq_voidp,
11894                                 free_line_header_voidp,
11895                                 &objfile->objfile_obstack,
11896                                 hashtab_obstack_allocate,
11897                                 dummy_obstack_deallocate);
11898     }
11899
11900   line_header_local.sect_off = line_offset;
11901   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11902   line_header_local_hash = line_header_hash (&line_header_local);
11903   if (dwarf2_per_objfile->line_header_hash != NULL)
11904     {
11905       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11906                                        &line_header_local,
11907                                        line_header_local_hash, NO_INSERT);
11908
11909       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11910          is not present in *SLOT (since if there is something in *SLOT then
11911          it will be for a partial_unit).  */
11912       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11913         {
11914           gdb_assert (*slot != NULL);
11915           cu->line_header = (struct line_header *) *slot;
11916           return;
11917         }
11918     }
11919
11920   /* dwarf_decode_line_header does not yet provide sufficient information.
11921      We always have to call also dwarf_decode_lines for it.  */
11922   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11923   if (lh == NULL)
11924     return;
11925
11926   cu->line_header = lh.release ();
11927   cu->line_header_die_owner = die;
11928
11929   if (dwarf2_per_objfile->line_header_hash == NULL)
11930     slot = NULL;
11931   else
11932     {
11933       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11934                                        &line_header_local,
11935                                        line_header_local_hash, INSERT);
11936       gdb_assert (slot != NULL);
11937     }
11938   if (slot != NULL && *slot == NULL)
11939     {
11940       /* This newly decoded line number information unit will be owned
11941          by line_header_hash hash table.  */
11942       *slot = cu->line_header;
11943       cu->line_header_die_owner = NULL;
11944     }
11945   else
11946     {
11947       /* We cannot free any current entry in (*slot) as that struct line_header
11948          may be already used by multiple CUs.  Create only temporary decoded
11949          line_header for this CU - it may happen at most once for each line
11950          number information unit.  And if we're not using line_header_hash
11951          then this is what we want as well.  */
11952       gdb_assert (die->tag != DW_TAG_partial_unit);
11953     }
11954   decode_mapping = (die->tag != DW_TAG_partial_unit);
11955   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11956                       decode_mapping);
11957
11958 }
11959
11960 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11961
11962 static void
11963 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11964 {
11965   struct dwarf2_per_objfile *dwarf2_per_objfile
11966     = cu->per_cu->dwarf2_per_objfile;
11967   struct objfile *objfile = dwarf2_per_objfile->objfile;
11968   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11969   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11970   CORE_ADDR highpc = ((CORE_ADDR) 0);
11971   struct attribute *attr;
11972   struct die_info *child_die;
11973   CORE_ADDR baseaddr;
11974
11975   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11976
11977   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11978
11979   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11980      from finish_block.  */
11981   if (lowpc == ((CORE_ADDR) -1))
11982     lowpc = highpc;
11983   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11984
11985   file_and_directory fnd = find_file_and_directory (die, cu);
11986
11987   prepare_one_comp_unit (cu, die, cu->language);
11988
11989   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11990      standardised yet.  As a workaround for the language detection we fall
11991      back to the DW_AT_producer string.  */
11992   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11993     cu->language = language_opencl;
11994
11995   /* Similar hack for Go.  */
11996   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11997     set_cu_language (DW_LANG_Go, cu);
11998
11999   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
12000
12001   /* Decode line number information if present.  We do this before
12002      processing child DIEs, so that the line header table is available
12003      for DW_AT_decl_file.  */
12004   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
12005
12006   /* Process all dies in compilation unit.  */
12007   if (die->child != NULL)
12008     {
12009       child_die = die->child;
12010       while (child_die && child_die->tag)
12011         {
12012           process_die (child_die, cu);
12013           child_die = sibling_die (child_die);
12014         }
12015     }
12016
12017   /* Decode macro information, if present.  Dwarf 2 macro information
12018      refers to information in the line number info statement program
12019      header, so we can only read it if we've read the header
12020      successfully.  */
12021   attr = dwarf2_attr (die, DW_AT_macros, cu);
12022   if (attr == NULL)
12023     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
12024   if (attr && cu->line_header)
12025     {
12026       if (dwarf2_attr (die, DW_AT_macro_info, cu))
12027         complaint (&symfile_complaints,
12028                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
12029
12030       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
12031     }
12032   else
12033     {
12034       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
12035       if (attr && cu->line_header)
12036         {
12037           unsigned int macro_offset = DW_UNSND (attr);
12038
12039           dwarf_decode_macros (cu, macro_offset, 0);
12040         }
12041     }
12042 }
12043
12044 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
12045    Create the set of symtabs used by this TU, or if this TU is sharing
12046    symtabs with another TU and the symtabs have already been created
12047    then restore those symtabs in the line header.
12048    We don't need the pc/line-number mapping for type units.  */
12049
12050 static void
12051 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
12052 {
12053   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
12054   struct type_unit_group *tu_group;
12055   int first_time;
12056   struct attribute *attr;
12057   unsigned int i;
12058   struct signatured_type *sig_type;
12059
12060   gdb_assert (per_cu->is_debug_types);
12061   sig_type = (struct signatured_type *) per_cu;
12062
12063   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
12064
12065   /* If we're using .gdb_index (includes -readnow) then
12066      per_cu->type_unit_group may not have been set up yet.  */
12067   if (sig_type->type_unit_group == NULL)
12068     sig_type->type_unit_group = get_type_unit_group (cu, attr);
12069   tu_group = sig_type->type_unit_group;
12070
12071   /* If we've already processed this stmt_list there's no real need to
12072      do it again, we could fake it and just recreate the part we need
12073      (file name,index -> symtab mapping).  If data shows this optimization
12074      is useful we can do it then.  */
12075   first_time = tu_group->compunit_symtab == NULL;
12076
12077   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
12078      debug info.  */
12079   line_header_up lh;
12080   if (attr != NULL)
12081     {
12082       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
12083       lh = dwarf_decode_line_header (line_offset, cu);
12084     }
12085   if (lh == NULL)
12086     {
12087       if (first_time)
12088         dwarf2_start_symtab (cu, "", NULL, 0);
12089       else
12090         {
12091           gdb_assert (tu_group->symtabs == NULL);
12092           restart_symtab (tu_group->compunit_symtab, "", 0);
12093         }
12094       return;
12095     }
12096
12097   cu->line_header = lh.release ();
12098   cu->line_header_die_owner = die;
12099
12100   if (first_time)
12101     {
12102       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
12103
12104       /* Note: We don't assign tu_group->compunit_symtab yet because we're
12105          still initializing it, and our caller (a few levels up)
12106          process_full_type_unit still needs to know if this is the first
12107          time.  */
12108
12109       tu_group->num_symtabs = cu->line_header->file_names.size ();
12110       tu_group->symtabs = XNEWVEC (struct symtab *,
12111                                    cu->line_header->file_names.size ());
12112
12113       for (i = 0; i < cu->line_header->file_names.size (); ++i)
12114         {
12115           file_entry &fe = cu->line_header->file_names[i];
12116
12117           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
12118
12119           if (current_subfile->symtab == NULL)
12120             {
12121               /* NOTE: start_subfile will recognize when it's been
12122                  passed a file it has already seen.  So we can't
12123                  assume there's a simple mapping from
12124                  cu->line_header->file_names to subfiles, plus
12125                  cu->line_header->file_names may contain dups.  */
12126               current_subfile->symtab
12127                 = allocate_symtab (cust, current_subfile->name);
12128             }
12129
12130           fe.symtab = current_subfile->symtab;
12131           tu_group->symtabs[i] = fe.symtab;
12132         }
12133     }
12134   else
12135     {
12136       restart_symtab (tu_group->compunit_symtab, "", 0);
12137
12138       for (i = 0; i < cu->line_header->file_names.size (); ++i)
12139         {
12140           file_entry &fe = cu->line_header->file_names[i];
12141
12142           fe.symtab = tu_group->symtabs[i];
12143         }
12144     }
12145
12146   /* The main symtab is allocated last.  Type units don't have DW_AT_name
12147      so they don't have a "real" (so to speak) symtab anyway.
12148      There is later code that will assign the main symtab to all symbols
12149      that don't have one.  We need to handle the case of a symbol with a
12150      missing symtab (DW_AT_decl_file) anyway.  */
12151 }
12152
12153 /* Process DW_TAG_type_unit.
12154    For TUs we want to skip the first top level sibling if it's not the
12155    actual type being defined by this TU.  In this case the first top
12156    level sibling is there to provide context only.  */
12157
12158 static void
12159 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
12160 {
12161   struct die_info *child_die;
12162
12163   prepare_one_comp_unit (cu, die, language_minimal);
12164
12165   /* Initialize (or reinitialize) the machinery for building symtabs.
12166      We do this before processing child DIEs, so that the line header table
12167      is available for DW_AT_decl_file.  */
12168   setup_type_unit_groups (die, cu);
12169
12170   if (die->child != NULL)
12171     {
12172       child_die = die->child;
12173       while (child_die && child_die->tag)
12174         {
12175           process_die (child_die, cu);
12176           child_die = sibling_die (child_die);
12177         }
12178     }
12179 }
12180 \f
12181 /* DWO/DWP files.
12182
12183    http://gcc.gnu.org/wiki/DebugFission
12184    http://gcc.gnu.org/wiki/DebugFissionDWP
12185
12186    To simplify handling of both DWO files ("object" files with the DWARF info)
12187    and DWP files (a file with the DWOs packaged up into one file), we treat
12188    DWP files as having a collection of virtual DWO files.  */
12189
12190 static hashval_t
12191 hash_dwo_file (const void *item)
12192 {
12193   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
12194   hashval_t hash;
12195
12196   hash = htab_hash_string (dwo_file->dwo_name);
12197   if (dwo_file->comp_dir != NULL)
12198     hash += htab_hash_string (dwo_file->comp_dir);
12199   return hash;
12200 }
12201
12202 static int
12203 eq_dwo_file (const void *item_lhs, const void *item_rhs)
12204 {
12205   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
12206   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
12207
12208   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
12209     return 0;
12210   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
12211     return lhs->comp_dir == rhs->comp_dir;
12212   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
12213 }
12214
12215 /* Allocate a hash table for DWO files.  */
12216
12217 static htab_t
12218 allocate_dwo_file_hash_table (struct objfile *objfile)
12219 {
12220   return htab_create_alloc_ex (41,
12221                                hash_dwo_file,
12222                                eq_dwo_file,
12223                                NULL,
12224                                &objfile->objfile_obstack,
12225                                hashtab_obstack_allocate,
12226                                dummy_obstack_deallocate);
12227 }
12228
12229 /* Lookup DWO file DWO_NAME.  */
12230
12231 static void **
12232 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
12233                       const char *dwo_name,
12234                       const char *comp_dir)
12235 {
12236   struct dwo_file find_entry;
12237   void **slot;
12238
12239   if (dwarf2_per_objfile->dwo_files == NULL)
12240     dwarf2_per_objfile->dwo_files
12241       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
12242
12243   memset (&find_entry, 0, sizeof (find_entry));
12244   find_entry.dwo_name = dwo_name;
12245   find_entry.comp_dir = comp_dir;
12246   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
12247
12248   return slot;
12249 }
12250
12251 static hashval_t
12252 hash_dwo_unit (const void *item)
12253 {
12254   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12255
12256   /* This drops the top 32 bits of the id, but is ok for a hash.  */
12257   return dwo_unit->signature;
12258 }
12259
12260 static int
12261 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
12262 {
12263   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
12264   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
12265
12266   /* The signature is assumed to be unique within the DWO file.
12267      So while object file CU dwo_id's always have the value zero,
12268      that's OK, assuming each object file DWO file has only one CU,
12269      and that's the rule for now.  */
12270   return lhs->signature == rhs->signature;
12271 }
12272
12273 /* Allocate a hash table for DWO CUs,TUs.
12274    There is one of these tables for each of CUs,TUs for each DWO file.  */
12275
12276 static htab_t
12277 allocate_dwo_unit_table (struct objfile *objfile)
12278 {
12279   /* Start out with a pretty small number.
12280      Generally DWO files contain only one CU and maybe some TUs.  */
12281   return htab_create_alloc_ex (3,
12282                                hash_dwo_unit,
12283                                eq_dwo_unit,
12284                                NULL,
12285                                &objfile->objfile_obstack,
12286                                hashtab_obstack_allocate,
12287                                dummy_obstack_deallocate);
12288 }
12289
12290 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
12291
12292 struct create_dwo_cu_data
12293 {
12294   struct dwo_file *dwo_file;
12295   struct dwo_unit dwo_unit;
12296 };
12297
12298 /* die_reader_func for create_dwo_cu.  */
12299
12300 static void
12301 create_dwo_cu_reader (const struct die_reader_specs *reader,
12302                       const gdb_byte *info_ptr,
12303                       struct die_info *comp_unit_die,
12304                       int has_children,
12305                       void *datap)
12306 {
12307   struct dwarf2_cu *cu = reader->cu;
12308   sect_offset sect_off = cu->per_cu->sect_off;
12309   struct dwarf2_section_info *section = cu->per_cu->section;
12310   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
12311   struct dwo_file *dwo_file = data->dwo_file;
12312   struct dwo_unit *dwo_unit = &data->dwo_unit;
12313   struct attribute *attr;
12314
12315   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
12316   if (attr == NULL)
12317     {
12318       complaint (&symfile_complaints,
12319                  _("Dwarf Error: debug entry at offset %s is missing"
12320                    " its dwo_id [in module %s]"),
12321                  sect_offset_str (sect_off), dwo_file->dwo_name);
12322       return;
12323     }
12324
12325   dwo_unit->dwo_file = dwo_file;
12326   dwo_unit->signature = DW_UNSND (attr);
12327   dwo_unit->section = section;
12328   dwo_unit->sect_off = sect_off;
12329   dwo_unit->length = cu->per_cu->length;
12330
12331   if (dwarf_read_debug)
12332     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
12333                         sect_offset_str (sect_off),
12334                         hex_string (dwo_unit->signature));
12335 }
12336
12337 /* Create the dwo_units for the CUs in a DWO_FILE.
12338    Note: This function processes DWO files only, not DWP files.  */
12339
12340 static void
12341 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12342                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12343                        htab_t &cus_htab)
12344 {
12345   struct objfile *objfile = dwarf2_per_objfile->objfile;
12346   const gdb_byte *info_ptr, *end_ptr;
12347
12348   dwarf2_read_section (objfile, &section);
12349   info_ptr = section.buffer;
12350
12351   if (info_ptr == NULL)
12352     return;
12353
12354   if (dwarf_read_debug)
12355     {
12356       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12357                           get_section_name (&section),
12358                           get_section_file_name (&section));
12359     }
12360
12361   end_ptr = info_ptr + section.size;
12362   while (info_ptr < end_ptr)
12363     {
12364       struct dwarf2_per_cu_data per_cu;
12365       struct create_dwo_cu_data create_dwo_cu_data;
12366       struct dwo_unit *dwo_unit;
12367       void **slot;
12368       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12369
12370       memset (&create_dwo_cu_data.dwo_unit, 0,
12371               sizeof (create_dwo_cu_data.dwo_unit));
12372       memset (&per_cu, 0, sizeof (per_cu));
12373       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12374       per_cu.is_debug_types = 0;
12375       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12376       per_cu.section = &section;
12377       create_dwo_cu_data.dwo_file = &dwo_file;
12378
12379       init_cutu_and_read_dies_no_follow (
12380           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12381       info_ptr += per_cu.length;
12382
12383       // If the unit could not be parsed, skip it.
12384       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12385         continue;
12386
12387       if (cus_htab == NULL)
12388         cus_htab = allocate_dwo_unit_table (objfile);
12389
12390       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12391       *dwo_unit = create_dwo_cu_data.dwo_unit;
12392       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12393       gdb_assert (slot != NULL);
12394       if (*slot != NULL)
12395         {
12396           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12397           sect_offset dup_sect_off = dup_cu->sect_off;
12398
12399           complaint (&symfile_complaints,
12400                      _("debug cu entry at offset %s is duplicate to"
12401                        " the entry at offset %s, signature %s"),
12402                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
12403                      hex_string (dwo_unit->signature));
12404         }
12405       *slot = (void *)dwo_unit;
12406     }
12407 }
12408
12409 /* DWP file .debug_{cu,tu}_index section format:
12410    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12411
12412    DWP Version 1:
12413
12414    Both index sections have the same format, and serve to map a 64-bit
12415    signature to a set of section numbers.  Each section begins with a header,
12416    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12417    indexes, and a pool of 32-bit section numbers.  The index sections will be
12418    aligned at 8-byte boundaries in the file.
12419
12420    The index section header consists of:
12421
12422     V, 32 bit version number
12423     -, 32 bits unused
12424     N, 32 bit number of compilation units or type units in the index
12425     M, 32 bit number of slots in the hash table
12426
12427    Numbers are recorded using the byte order of the application binary.
12428
12429    The hash table begins at offset 16 in the section, and consists of an array
12430    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12431    order of the application binary).  Unused slots in the hash table are 0.
12432    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12433
12434    The parallel table begins immediately after the hash table
12435    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12436    array of 32-bit indexes (using the byte order of the application binary),
12437    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12438    table contains a 32-bit index into the pool of section numbers.  For unused
12439    hash table slots, the corresponding entry in the parallel table will be 0.
12440
12441    The pool of section numbers begins immediately following the hash table
12442    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12443    section numbers consists of an array of 32-bit words (using the byte order
12444    of the application binary).  Each item in the array is indexed starting
12445    from 0.  The hash table entry provides the index of the first section
12446    number in the set.  Additional section numbers in the set follow, and the
12447    set is terminated by a 0 entry (section number 0 is not used in ELF).
12448
12449    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12450    section must be the first entry in the set, and the .debug_abbrev.dwo must
12451    be the second entry. Other members of the set may follow in any order.
12452
12453    ---
12454
12455    DWP Version 2:
12456
12457    DWP Version 2 combines all the .debug_info, etc. sections into one,
12458    and the entries in the index tables are now offsets into these sections.
12459    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12460    section.
12461
12462    Index Section Contents:
12463     Header
12464     Hash Table of Signatures   dwp_hash_table.hash_table
12465     Parallel Table of Indices  dwp_hash_table.unit_table
12466     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12467     Table of Section Sizes     dwp_hash_table.v2.sizes
12468
12469    The index section header consists of:
12470
12471     V, 32 bit version number
12472     L, 32 bit number of columns in the table of section offsets
12473     N, 32 bit number of compilation units or type units in the index
12474     M, 32 bit number of slots in the hash table
12475
12476    Numbers are recorded using the byte order of the application binary.
12477
12478    The hash table has the same format as version 1.
12479    The parallel table of indices has the same format as version 1,
12480    except that the entries are origin-1 indices into the table of sections
12481    offsets and the table of section sizes.
12482
12483    The table of offsets begins immediately following the parallel table
12484    (at offset 16 + 12 * M from the beginning of the section).  The table is
12485    a two-dimensional array of 32-bit words (using the byte order of the
12486    application binary), with L columns and N+1 rows, in row-major order.
12487    Each row in the array is indexed starting from 0.  The first row provides
12488    a key to the remaining rows: each column in this row provides an identifier
12489    for a debug section, and the offsets in the same column of subsequent rows
12490    refer to that section.  The section identifiers are:
12491
12492     DW_SECT_INFO         1  .debug_info.dwo
12493     DW_SECT_TYPES        2  .debug_types.dwo
12494     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12495     DW_SECT_LINE         4  .debug_line.dwo
12496     DW_SECT_LOC          5  .debug_loc.dwo
12497     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12498     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12499     DW_SECT_MACRO        8  .debug_macro.dwo
12500
12501    The offsets provided by the CU and TU index sections are the base offsets
12502    for the contributions made by each CU or TU to the corresponding section
12503    in the package file.  Each CU and TU header contains an abbrev_offset
12504    field, used to find the abbreviations table for that CU or TU within the
12505    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12506    be interpreted as relative to the base offset given in the index section.
12507    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12508    should be interpreted as relative to the base offset for .debug_line.dwo,
12509    and offsets into other debug sections obtained from DWARF attributes should
12510    also be interpreted as relative to the corresponding base offset.
12511
12512    The table of sizes begins immediately following the table of offsets.
12513    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12514    with L columns and N rows, in row-major order.  Each row in the array is
12515    indexed starting from 1 (row 0 is shared by the two tables).
12516
12517    ---
12518
12519    Hash table lookup is handled the same in version 1 and 2:
12520
12521    We assume that N and M will not exceed 2^32 - 1.
12522    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12523
12524    Given a 64-bit compilation unit signature or a type signature S, an entry
12525    in the hash table is located as follows:
12526
12527    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12528       the low-order k bits all set to 1.
12529
12530    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12531
12532    3) If the hash table entry at index H matches the signature, use that
12533       entry.  If the hash table entry at index H is unused (all zeroes),
12534       terminate the search: the signature is not present in the table.
12535
12536    4) Let H = (H + H') modulo M. Repeat at Step 3.
12537
12538    Because M > N and H' and M are relatively prime, the search is guaranteed
12539    to stop at an unused slot or find the match.  */
12540
12541 /* Create a hash table to map DWO IDs to their CU/TU entry in
12542    .debug_{info,types}.dwo in DWP_FILE.
12543    Returns NULL if there isn't one.
12544    Note: This function processes DWP files only, not DWO files.  */
12545
12546 static struct dwp_hash_table *
12547 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12548                        struct dwp_file *dwp_file, int is_debug_types)
12549 {
12550   struct objfile *objfile = dwarf2_per_objfile->objfile;
12551   bfd *dbfd = dwp_file->dbfd;
12552   const gdb_byte *index_ptr, *index_end;
12553   struct dwarf2_section_info *index;
12554   uint32_t version, nr_columns, nr_units, nr_slots;
12555   struct dwp_hash_table *htab;
12556
12557   if (is_debug_types)
12558     index = &dwp_file->sections.tu_index;
12559   else
12560     index = &dwp_file->sections.cu_index;
12561
12562   if (dwarf2_section_empty_p (index))
12563     return NULL;
12564   dwarf2_read_section (objfile, index);
12565
12566   index_ptr = index->buffer;
12567   index_end = index_ptr + index->size;
12568
12569   version = read_4_bytes (dbfd, index_ptr);
12570   index_ptr += 4;
12571   if (version == 2)
12572     nr_columns = read_4_bytes (dbfd, index_ptr);
12573   else
12574     nr_columns = 0;
12575   index_ptr += 4;
12576   nr_units = read_4_bytes (dbfd, index_ptr);
12577   index_ptr += 4;
12578   nr_slots = read_4_bytes (dbfd, index_ptr);
12579   index_ptr += 4;
12580
12581   if (version != 1 && version != 2)
12582     {
12583       error (_("Dwarf Error: unsupported DWP file version (%s)"
12584                " [in module %s]"),
12585              pulongest (version), dwp_file->name);
12586     }
12587   if (nr_slots != (nr_slots & -nr_slots))
12588     {
12589       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12590                " is not power of 2 [in module %s]"),
12591              pulongest (nr_slots), dwp_file->name);
12592     }
12593
12594   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12595   htab->version = version;
12596   htab->nr_columns = nr_columns;
12597   htab->nr_units = nr_units;
12598   htab->nr_slots = nr_slots;
12599   htab->hash_table = index_ptr;
12600   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12601
12602   /* Exit early if the table is empty.  */
12603   if (nr_slots == 0 || nr_units == 0
12604       || (version == 2 && nr_columns == 0))
12605     {
12606       /* All must be zero.  */
12607       if (nr_slots != 0 || nr_units != 0
12608           || (version == 2 && nr_columns != 0))
12609         {
12610           complaint (&symfile_complaints,
12611                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12612                        " all zero [in modules %s]"),
12613                      dwp_file->name);
12614         }
12615       return htab;
12616     }
12617
12618   if (version == 1)
12619     {
12620       htab->section_pool.v1.indices =
12621         htab->unit_table + sizeof (uint32_t) * nr_slots;
12622       /* It's harder to decide whether the section is too small in v1.
12623          V1 is deprecated anyway so we punt.  */
12624     }
12625   else
12626     {
12627       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12628       int *ids = htab->section_pool.v2.section_ids;
12629       /* Reverse map for error checking.  */
12630       int ids_seen[DW_SECT_MAX + 1];
12631       int i;
12632
12633       if (nr_columns < 2)
12634         {
12635           error (_("Dwarf Error: bad DWP hash table, too few columns"
12636                    " in section table [in module %s]"),
12637                  dwp_file->name);
12638         }
12639       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12640         {
12641           error (_("Dwarf Error: bad DWP hash table, too many columns"
12642                    " in section table [in module %s]"),
12643                  dwp_file->name);
12644         }
12645       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12646       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12647       for (i = 0; i < nr_columns; ++i)
12648         {
12649           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12650
12651           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12652             {
12653               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12654                        " in section table [in module %s]"),
12655                      id, dwp_file->name);
12656             }
12657           if (ids_seen[id] != -1)
12658             {
12659               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12660                        " id %d in section table [in module %s]"),
12661                      id, dwp_file->name);
12662             }
12663           ids_seen[id] = i;
12664           ids[i] = id;
12665         }
12666       /* Must have exactly one info or types section.  */
12667       if (((ids_seen[DW_SECT_INFO] != -1)
12668            + (ids_seen[DW_SECT_TYPES] != -1))
12669           != 1)
12670         {
12671           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12672                    " DWO info/types section [in module %s]"),
12673                  dwp_file->name);
12674         }
12675       /* Must have an abbrev section.  */
12676       if (ids_seen[DW_SECT_ABBREV] == -1)
12677         {
12678           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12679                    " section [in module %s]"),
12680                  dwp_file->name);
12681         }
12682       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12683       htab->section_pool.v2.sizes =
12684         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12685                                          * nr_units * nr_columns);
12686       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12687                                           * nr_units * nr_columns))
12688           > index_end)
12689         {
12690           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12691                    " [in module %s]"),
12692                  dwp_file->name);
12693         }
12694     }
12695
12696   return htab;
12697 }
12698
12699 /* Update SECTIONS with the data from SECTP.
12700
12701    This function is like the other "locate" section routines that are
12702    passed to bfd_map_over_sections, but in this context the sections to
12703    read comes from the DWP V1 hash table, not the full ELF section table.
12704
12705    The result is non-zero for success, or zero if an error was found.  */
12706
12707 static int
12708 locate_v1_virtual_dwo_sections (asection *sectp,
12709                                 struct virtual_v1_dwo_sections *sections)
12710 {
12711   const struct dwop_section_names *names = &dwop_section_names;
12712
12713   if (section_is_p (sectp->name, &names->abbrev_dwo))
12714     {
12715       /* There can be only one.  */
12716       if (sections->abbrev.s.section != NULL)
12717         return 0;
12718       sections->abbrev.s.section = sectp;
12719       sections->abbrev.size = bfd_get_section_size (sectp);
12720     }
12721   else if (section_is_p (sectp->name, &names->info_dwo)
12722            || section_is_p (sectp->name, &names->types_dwo))
12723     {
12724       /* There can be only one.  */
12725       if (sections->info_or_types.s.section != NULL)
12726         return 0;
12727       sections->info_or_types.s.section = sectp;
12728       sections->info_or_types.size = bfd_get_section_size (sectp);
12729     }
12730   else if (section_is_p (sectp->name, &names->line_dwo))
12731     {
12732       /* There can be only one.  */
12733       if (sections->line.s.section != NULL)
12734         return 0;
12735       sections->line.s.section = sectp;
12736       sections->line.size = bfd_get_section_size (sectp);
12737     }
12738   else if (section_is_p (sectp->name, &names->loc_dwo))
12739     {
12740       /* There can be only one.  */
12741       if (sections->loc.s.section != NULL)
12742         return 0;
12743       sections->loc.s.section = sectp;
12744       sections->loc.size = bfd_get_section_size (sectp);
12745     }
12746   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12747     {
12748       /* There can be only one.  */
12749       if (sections->macinfo.s.section != NULL)
12750         return 0;
12751       sections->macinfo.s.section = sectp;
12752       sections->macinfo.size = bfd_get_section_size (sectp);
12753     }
12754   else if (section_is_p (sectp->name, &names->macro_dwo))
12755     {
12756       /* There can be only one.  */
12757       if (sections->macro.s.section != NULL)
12758         return 0;
12759       sections->macro.s.section = sectp;
12760       sections->macro.size = bfd_get_section_size (sectp);
12761     }
12762   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12763     {
12764       /* There can be only one.  */
12765       if (sections->str_offsets.s.section != NULL)
12766         return 0;
12767       sections->str_offsets.s.section = sectp;
12768       sections->str_offsets.size = bfd_get_section_size (sectp);
12769     }
12770   else
12771     {
12772       /* No other kind of section is valid.  */
12773       return 0;
12774     }
12775
12776   return 1;
12777 }
12778
12779 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12780    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12781    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12782    This is for DWP version 1 files.  */
12783
12784 static struct dwo_unit *
12785 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12786                            struct dwp_file *dwp_file,
12787                            uint32_t unit_index,
12788                            const char *comp_dir,
12789                            ULONGEST signature, int is_debug_types)
12790 {
12791   struct objfile *objfile = dwarf2_per_objfile->objfile;
12792   const struct dwp_hash_table *dwp_htab =
12793     is_debug_types ? dwp_file->tus : dwp_file->cus;
12794   bfd *dbfd = dwp_file->dbfd;
12795   const char *kind = is_debug_types ? "TU" : "CU";
12796   struct dwo_file *dwo_file;
12797   struct dwo_unit *dwo_unit;
12798   struct virtual_v1_dwo_sections sections;
12799   void **dwo_file_slot;
12800   int i;
12801
12802   gdb_assert (dwp_file->version == 1);
12803
12804   if (dwarf_read_debug)
12805     {
12806       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12807                           kind,
12808                           pulongest (unit_index), hex_string (signature),
12809                           dwp_file->name);
12810     }
12811
12812   /* Fetch the sections of this DWO unit.
12813      Put a limit on the number of sections we look for so that bad data
12814      doesn't cause us to loop forever.  */
12815
12816 #define MAX_NR_V1_DWO_SECTIONS \
12817   (1 /* .debug_info or .debug_types */ \
12818    + 1 /* .debug_abbrev */ \
12819    + 1 /* .debug_line */ \
12820    + 1 /* .debug_loc */ \
12821    + 1 /* .debug_str_offsets */ \
12822    + 1 /* .debug_macro or .debug_macinfo */ \
12823    + 1 /* trailing zero */)
12824
12825   memset (&sections, 0, sizeof (sections));
12826
12827   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12828     {
12829       asection *sectp;
12830       uint32_t section_nr =
12831         read_4_bytes (dbfd,
12832                       dwp_htab->section_pool.v1.indices
12833                       + (unit_index + i) * sizeof (uint32_t));
12834
12835       if (section_nr == 0)
12836         break;
12837       if (section_nr >= dwp_file->num_sections)
12838         {
12839           error (_("Dwarf Error: bad DWP hash table, section number too large"
12840                    " [in module %s]"),
12841                  dwp_file->name);
12842         }
12843
12844       sectp = dwp_file->elf_sections[section_nr];
12845       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12846         {
12847           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12848                    " [in module %s]"),
12849                  dwp_file->name);
12850         }
12851     }
12852
12853   if (i < 2
12854       || dwarf2_section_empty_p (&sections.info_or_types)
12855       || dwarf2_section_empty_p (&sections.abbrev))
12856     {
12857       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12858                " [in module %s]"),
12859              dwp_file->name);
12860     }
12861   if (i == MAX_NR_V1_DWO_SECTIONS)
12862     {
12863       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12864                " [in module %s]"),
12865              dwp_file->name);
12866     }
12867
12868   /* It's easier for the rest of the code if we fake a struct dwo_file and
12869      have dwo_unit "live" in that.  At least for now.
12870
12871      The DWP file can be made up of a random collection of CUs and TUs.
12872      However, for each CU + set of TUs that came from the same original DWO
12873      file, we can combine them back into a virtual DWO file to save space
12874      (fewer struct dwo_file objects to allocate).  Remember that for really
12875      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12876
12877   std::string virtual_dwo_name =
12878     string_printf ("virtual-dwo/%d-%d-%d-%d",
12879                    get_section_id (&sections.abbrev),
12880                    get_section_id (&sections.line),
12881                    get_section_id (&sections.loc),
12882                    get_section_id (&sections.str_offsets));
12883   /* Can we use an existing virtual DWO file?  */
12884   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12885                                         virtual_dwo_name.c_str (),
12886                                         comp_dir);
12887   /* Create one if necessary.  */
12888   if (*dwo_file_slot == NULL)
12889     {
12890       if (dwarf_read_debug)
12891         {
12892           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12893                               virtual_dwo_name.c_str ());
12894         }
12895       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12896       dwo_file->dwo_name
12897         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12898                                         virtual_dwo_name.c_str (),
12899                                         virtual_dwo_name.size ());
12900       dwo_file->comp_dir = comp_dir;
12901       dwo_file->sections.abbrev = sections.abbrev;
12902       dwo_file->sections.line = sections.line;
12903       dwo_file->sections.loc = sections.loc;
12904       dwo_file->sections.macinfo = sections.macinfo;
12905       dwo_file->sections.macro = sections.macro;
12906       dwo_file->sections.str_offsets = sections.str_offsets;
12907       /* The "str" section is global to the entire DWP file.  */
12908       dwo_file->sections.str = dwp_file->sections.str;
12909       /* The info or types section is assigned below to dwo_unit,
12910          there's no need to record it in dwo_file.
12911          Also, we can't simply record type sections in dwo_file because
12912          we record a pointer into the vector in dwo_unit.  As we collect more
12913          types we'll grow the vector and eventually have to reallocate space
12914          for it, invalidating all copies of pointers into the previous
12915          contents.  */
12916       *dwo_file_slot = dwo_file;
12917     }
12918   else
12919     {
12920       if (dwarf_read_debug)
12921         {
12922           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12923                               virtual_dwo_name.c_str ());
12924         }
12925       dwo_file = (struct dwo_file *) *dwo_file_slot;
12926     }
12927
12928   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12929   dwo_unit->dwo_file = dwo_file;
12930   dwo_unit->signature = signature;
12931   dwo_unit->section =
12932     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12933   *dwo_unit->section = sections.info_or_types;
12934   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12935
12936   return dwo_unit;
12937 }
12938
12939 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12940    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12941    piece within that section used by a TU/CU, return a virtual section
12942    of just that piece.  */
12943
12944 static struct dwarf2_section_info
12945 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12946                        struct dwarf2_section_info *section,
12947                        bfd_size_type offset, bfd_size_type size)
12948 {
12949   struct dwarf2_section_info result;
12950   asection *sectp;
12951
12952   gdb_assert (section != NULL);
12953   gdb_assert (!section->is_virtual);
12954
12955   memset (&result, 0, sizeof (result));
12956   result.s.containing_section = section;
12957   result.is_virtual = 1;
12958
12959   if (size == 0)
12960     return result;
12961
12962   sectp = get_section_bfd_section (section);
12963
12964   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12965      bounds of the real section.  This is a pretty-rare event, so just
12966      flag an error (easier) instead of a warning and trying to cope.  */
12967   if (sectp == NULL
12968       || offset + size > bfd_get_section_size (sectp))
12969     {
12970       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12971                " in section %s [in module %s]"),
12972              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12973              objfile_name (dwarf2_per_objfile->objfile));
12974     }
12975
12976   result.virtual_offset = offset;
12977   result.size = size;
12978   return result;
12979 }
12980
12981 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12982    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12983    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12984    This is for DWP version 2 files.  */
12985
12986 static struct dwo_unit *
12987 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12988                            struct dwp_file *dwp_file,
12989                            uint32_t unit_index,
12990                            const char *comp_dir,
12991                            ULONGEST signature, int is_debug_types)
12992 {
12993   struct objfile *objfile = dwarf2_per_objfile->objfile;
12994   const struct dwp_hash_table *dwp_htab =
12995     is_debug_types ? dwp_file->tus : dwp_file->cus;
12996   bfd *dbfd = dwp_file->dbfd;
12997   const char *kind = is_debug_types ? "TU" : "CU";
12998   struct dwo_file *dwo_file;
12999   struct dwo_unit *dwo_unit;
13000   struct virtual_v2_dwo_sections sections;
13001   void **dwo_file_slot;
13002   int i;
13003
13004   gdb_assert (dwp_file->version == 2);
13005
13006   if (dwarf_read_debug)
13007     {
13008       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
13009                           kind,
13010                           pulongest (unit_index), hex_string (signature),
13011                           dwp_file->name);
13012     }
13013
13014   /* Fetch the section offsets of this DWO unit.  */
13015
13016   memset (&sections, 0, sizeof (sections));
13017
13018   for (i = 0; i < dwp_htab->nr_columns; ++i)
13019     {
13020       uint32_t offset = read_4_bytes (dbfd,
13021                                       dwp_htab->section_pool.v2.offsets
13022                                       + (((unit_index - 1) * dwp_htab->nr_columns
13023                                           + i)
13024                                          * sizeof (uint32_t)));
13025       uint32_t size = read_4_bytes (dbfd,
13026                                     dwp_htab->section_pool.v2.sizes
13027                                     + (((unit_index - 1) * dwp_htab->nr_columns
13028                                         + i)
13029                                        * sizeof (uint32_t)));
13030
13031       switch (dwp_htab->section_pool.v2.section_ids[i])
13032         {
13033         case DW_SECT_INFO:
13034         case DW_SECT_TYPES:
13035           sections.info_or_types_offset = offset;
13036           sections.info_or_types_size = size;
13037           break;
13038         case DW_SECT_ABBREV:
13039           sections.abbrev_offset = offset;
13040           sections.abbrev_size = size;
13041           break;
13042         case DW_SECT_LINE:
13043           sections.line_offset = offset;
13044           sections.line_size = size;
13045           break;
13046         case DW_SECT_LOC:
13047           sections.loc_offset = offset;
13048           sections.loc_size = size;
13049           break;
13050         case DW_SECT_STR_OFFSETS:
13051           sections.str_offsets_offset = offset;
13052           sections.str_offsets_size = size;
13053           break;
13054         case DW_SECT_MACINFO:
13055           sections.macinfo_offset = offset;
13056           sections.macinfo_size = size;
13057           break;
13058         case DW_SECT_MACRO:
13059           sections.macro_offset = offset;
13060           sections.macro_size = size;
13061           break;
13062         }
13063     }
13064
13065   /* It's easier for the rest of the code if we fake a struct dwo_file and
13066      have dwo_unit "live" in that.  At least for now.
13067
13068      The DWP file can be made up of a random collection of CUs and TUs.
13069      However, for each CU + set of TUs that came from the same original DWO
13070      file, we can combine them back into a virtual DWO file to save space
13071      (fewer struct dwo_file objects to allocate).  Remember that for really
13072      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
13073
13074   std::string virtual_dwo_name =
13075     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
13076                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
13077                    (long) (sections.line_size ? sections.line_offset : 0),
13078                    (long) (sections.loc_size ? sections.loc_offset : 0),
13079                    (long) (sections.str_offsets_size
13080                            ? sections.str_offsets_offset : 0));
13081   /* Can we use an existing virtual DWO file?  */
13082   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13083                                         virtual_dwo_name.c_str (),
13084                                         comp_dir);
13085   /* Create one if necessary.  */
13086   if (*dwo_file_slot == NULL)
13087     {
13088       if (dwarf_read_debug)
13089         {
13090           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
13091                               virtual_dwo_name.c_str ());
13092         }
13093       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13094       dwo_file->dwo_name
13095         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
13096                                         virtual_dwo_name.c_str (),
13097                                         virtual_dwo_name.size ());
13098       dwo_file->comp_dir = comp_dir;
13099       dwo_file->sections.abbrev =
13100         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
13101                                sections.abbrev_offset, sections.abbrev_size);
13102       dwo_file->sections.line =
13103         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
13104                                sections.line_offset, sections.line_size);
13105       dwo_file->sections.loc =
13106         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
13107                                sections.loc_offset, sections.loc_size);
13108       dwo_file->sections.macinfo =
13109         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
13110                                sections.macinfo_offset, sections.macinfo_size);
13111       dwo_file->sections.macro =
13112         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
13113                                sections.macro_offset, sections.macro_size);
13114       dwo_file->sections.str_offsets =
13115         create_dwp_v2_section (dwarf2_per_objfile,
13116                                &dwp_file->sections.str_offsets,
13117                                sections.str_offsets_offset,
13118                                sections.str_offsets_size);
13119       /* The "str" section is global to the entire DWP file.  */
13120       dwo_file->sections.str = dwp_file->sections.str;
13121       /* The info or types section is assigned below to dwo_unit,
13122          there's no need to record it in dwo_file.
13123          Also, we can't simply record type sections in dwo_file because
13124          we record a pointer into the vector in dwo_unit.  As we collect more
13125          types we'll grow the vector and eventually have to reallocate space
13126          for it, invalidating all copies of pointers into the previous
13127          contents.  */
13128       *dwo_file_slot = dwo_file;
13129     }
13130   else
13131     {
13132       if (dwarf_read_debug)
13133         {
13134           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
13135                               virtual_dwo_name.c_str ());
13136         }
13137       dwo_file = (struct dwo_file *) *dwo_file_slot;
13138     }
13139
13140   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
13141   dwo_unit->dwo_file = dwo_file;
13142   dwo_unit->signature = signature;
13143   dwo_unit->section =
13144     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
13145   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
13146                                               is_debug_types
13147                                               ? &dwp_file->sections.types
13148                                               : &dwp_file->sections.info,
13149                                               sections.info_or_types_offset,
13150                                               sections.info_or_types_size);
13151   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
13152
13153   return dwo_unit;
13154 }
13155
13156 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
13157    Returns NULL if the signature isn't found.  */
13158
13159 static struct dwo_unit *
13160 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
13161                         struct dwp_file *dwp_file, const char *comp_dir,
13162                         ULONGEST signature, int is_debug_types)
13163 {
13164   const struct dwp_hash_table *dwp_htab =
13165     is_debug_types ? dwp_file->tus : dwp_file->cus;
13166   bfd *dbfd = dwp_file->dbfd;
13167   uint32_t mask = dwp_htab->nr_slots - 1;
13168   uint32_t hash = signature & mask;
13169   uint32_t hash2 = ((signature >> 32) & mask) | 1;
13170   unsigned int i;
13171   void **slot;
13172   struct dwo_unit find_dwo_cu;
13173
13174   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
13175   find_dwo_cu.signature = signature;
13176   slot = htab_find_slot (is_debug_types
13177                          ? dwp_file->loaded_tus
13178                          : dwp_file->loaded_cus,
13179                          &find_dwo_cu, INSERT);
13180
13181   if (*slot != NULL)
13182     return (struct dwo_unit *) *slot;
13183
13184   /* Use a for loop so that we don't loop forever on bad debug info.  */
13185   for (i = 0; i < dwp_htab->nr_slots; ++i)
13186     {
13187       ULONGEST signature_in_table;
13188
13189       signature_in_table =
13190         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
13191       if (signature_in_table == signature)
13192         {
13193           uint32_t unit_index =
13194             read_4_bytes (dbfd,
13195                           dwp_htab->unit_table + hash * sizeof (uint32_t));
13196
13197           if (dwp_file->version == 1)
13198             {
13199               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
13200                                                  dwp_file, unit_index,
13201                                                  comp_dir, signature,
13202                                                  is_debug_types);
13203             }
13204           else
13205             {
13206               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
13207                                                  dwp_file, unit_index,
13208                                                  comp_dir, signature,
13209                                                  is_debug_types);
13210             }
13211           return (struct dwo_unit *) *slot;
13212         }
13213       if (signature_in_table == 0)
13214         return NULL;
13215       hash = (hash + hash2) & mask;
13216     }
13217
13218   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
13219            " [in module %s]"),
13220          dwp_file->name);
13221 }
13222
13223 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
13224    Open the file specified by FILE_NAME and hand it off to BFD for
13225    preliminary analysis.  Return a newly initialized bfd *, which
13226    includes a canonicalized copy of FILE_NAME.
13227    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
13228    SEARCH_CWD is true if the current directory is to be searched.
13229    It will be searched before debug-file-directory.
13230    If successful, the file is added to the bfd include table of the
13231    objfile's bfd (see gdb_bfd_record_inclusion).
13232    If unable to find/open the file, return NULL.
13233    NOTE: This function is derived from symfile_bfd_open.  */
13234
13235 static gdb_bfd_ref_ptr
13236 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13237                     const char *file_name, int is_dwp, int search_cwd)
13238 {
13239   int desc;
13240   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
13241      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
13242      to debug_file_directory.  */
13243   const char *search_path;
13244   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
13245
13246   gdb::unique_xmalloc_ptr<char> search_path_holder;
13247   if (search_cwd)
13248     {
13249       if (*debug_file_directory != '\0')
13250         {
13251           search_path_holder.reset (concat (".", dirname_separator_string,
13252                                             debug_file_directory,
13253                                             (char *) NULL));
13254           search_path = search_path_holder.get ();
13255         }
13256       else
13257         search_path = ".";
13258     }
13259   else
13260     search_path = debug_file_directory;
13261
13262   openp_flags flags = OPF_RETURN_REALPATH;
13263   if (is_dwp)
13264     flags |= OPF_SEARCH_IN_PATH;
13265
13266   gdb::unique_xmalloc_ptr<char> absolute_name;
13267   desc = openp (search_path, flags, file_name,
13268                 O_RDONLY | O_BINARY, &absolute_name);
13269   if (desc < 0)
13270     return NULL;
13271
13272   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
13273                                          gnutarget, desc));
13274   if (sym_bfd == NULL)
13275     return NULL;
13276   bfd_set_cacheable (sym_bfd.get (), 1);
13277
13278   if (!bfd_check_format (sym_bfd.get (), bfd_object))
13279     return NULL;
13280
13281   /* Success.  Record the bfd as having been included by the objfile's bfd.
13282      This is important because things like demangled_names_hash lives in the
13283      objfile's per_bfd space and may have references to things like symbol
13284      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
13285   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
13286
13287   return sym_bfd;
13288 }
13289
13290 /* Try to open DWO file FILE_NAME.
13291    COMP_DIR is the DW_AT_comp_dir attribute.
13292    The result is the bfd handle of the file.
13293    If there is a problem finding or opening the file, return NULL.
13294    Upon success, the canonicalized path of the file is stored in the bfd,
13295    same as symfile_bfd_open.  */
13296
13297 static gdb_bfd_ref_ptr
13298 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13299                const char *file_name, const char *comp_dir)
13300 {
13301   if (IS_ABSOLUTE_PATH (file_name))
13302     return try_open_dwop_file (dwarf2_per_objfile, file_name,
13303                                0 /*is_dwp*/, 0 /*search_cwd*/);
13304
13305   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
13306
13307   if (comp_dir != NULL)
13308     {
13309       char *path_to_try = concat (comp_dir, SLASH_STRING,
13310                                   file_name, (char *) NULL);
13311
13312       /* NOTE: If comp_dir is a relative path, this will also try the
13313          search path, which seems useful.  */
13314       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
13315                                                 path_to_try,
13316                                                 0 /*is_dwp*/,
13317                                                 1 /*search_cwd*/));
13318       xfree (path_to_try);
13319       if (abfd != NULL)
13320         return abfd;
13321     }
13322
13323   /* That didn't work, try debug-file-directory, which, despite its name,
13324      is a list of paths.  */
13325
13326   if (*debug_file_directory == '\0')
13327     return NULL;
13328
13329   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13330                              0 /*is_dwp*/, 1 /*search_cwd*/);
13331 }
13332
13333 /* This function is mapped across the sections and remembers the offset and
13334    size of each of the DWO debugging sections we are interested in.  */
13335
13336 static void
13337 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13338 {
13339   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13340   const struct dwop_section_names *names = &dwop_section_names;
13341
13342   if (section_is_p (sectp->name, &names->abbrev_dwo))
13343     {
13344       dwo_sections->abbrev.s.section = sectp;
13345       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13346     }
13347   else if (section_is_p (sectp->name, &names->info_dwo))
13348     {
13349       dwo_sections->info.s.section = sectp;
13350       dwo_sections->info.size = bfd_get_section_size (sectp);
13351     }
13352   else if (section_is_p (sectp->name, &names->line_dwo))
13353     {
13354       dwo_sections->line.s.section = sectp;
13355       dwo_sections->line.size = bfd_get_section_size (sectp);
13356     }
13357   else if (section_is_p (sectp->name, &names->loc_dwo))
13358     {
13359       dwo_sections->loc.s.section = sectp;
13360       dwo_sections->loc.size = bfd_get_section_size (sectp);
13361     }
13362   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13363     {
13364       dwo_sections->macinfo.s.section = sectp;
13365       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13366     }
13367   else if (section_is_p (sectp->name, &names->macro_dwo))
13368     {
13369       dwo_sections->macro.s.section = sectp;
13370       dwo_sections->macro.size = bfd_get_section_size (sectp);
13371     }
13372   else if (section_is_p (sectp->name, &names->str_dwo))
13373     {
13374       dwo_sections->str.s.section = sectp;
13375       dwo_sections->str.size = bfd_get_section_size (sectp);
13376     }
13377   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13378     {
13379       dwo_sections->str_offsets.s.section = sectp;
13380       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13381     }
13382   else if (section_is_p (sectp->name, &names->types_dwo))
13383     {
13384       struct dwarf2_section_info type_section;
13385
13386       memset (&type_section, 0, sizeof (type_section));
13387       type_section.s.section = sectp;
13388       type_section.size = bfd_get_section_size (sectp);
13389       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13390                      &type_section);
13391     }
13392 }
13393
13394 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13395    by PER_CU.  This is for the non-DWP case.
13396    The result is NULL if DWO_NAME can't be found.  */
13397
13398 static struct dwo_file *
13399 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13400                         const char *dwo_name, const char *comp_dir)
13401 {
13402   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13403   struct objfile *objfile = dwarf2_per_objfile->objfile;
13404   struct dwo_file *dwo_file;
13405   struct cleanup *cleanups;
13406
13407   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13408   if (dbfd == NULL)
13409     {
13410       if (dwarf_read_debug)
13411         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13412       return NULL;
13413     }
13414   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13415   dwo_file->dwo_name = dwo_name;
13416   dwo_file->comp_dir = comp_dir;
13417   dwo_file->dbfd = dbfd.release ();
13418
13419   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13420   cleanup_data->dwo_file = dwo_file;
13421   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13422
13423   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13424
13425   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13426                          &dwo_file->sections);
13427
13428   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13429                          dwo_file->cus);
13430
13431   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13432                                  dwo_file->sections.types, dwo_file->tus);
13433
13434   discard_cleanups (cleanups);
13435
13436   if (dwarf_read_debug)
13437     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13438
13439   return dwo_file;
13440 }
13441
13442 /* This function is mapped across the sections and remembers the offset and
13443    size of each of the DWP debugging sections common to version 1 and 2 that
13444    we are interested in.  */
13445
13446 static void
13447 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13448                                    void *dwp_file_ptr)
13449 {
13450   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13451   const struct dwop_section_names *names = &dwop_section_names;
13452   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13453
13454   /* Record the ELF section number for later lookup: this is what the
13455      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13456   gdb_assert (elf_section_nr < dwp_file->num_sections);
13457   dwp_file->elf_sections[elf_section_nr] = sectp;
13458
13459   /* Look for specific sections that we need.  */
13460   if (section_is_p (sectp->name, &names->str_dwo))
13461     {
13462       dwp_file->sections.str.s.section = sectp;
13463       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13464     }
13465   else if (section_is_p (sectp->name, &names->cu_index))
13466     {
13467       dwp_file->sections.cu_index.s.section = sectp;
13468       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13469     }
13470   else if (section_is_p (sectp->name, &names->tu_index))
13471     {
13472       dwp_file->sections.tu_index.s.section = sectp;
13473       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13474     }
13475 }
13476
13477 /* This function is mapped across the sections and remembers the offset and
13478    size of each of the DWP version 2 debugging sections that we are interested
13479    in.  This is split into a separate function because we don't know if we
13480    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13481
13482 static void
13483 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13484 {
13485   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13486   const struct dwop_section_names *names = &dwop_section_names;
13487   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13488
13489   /* Record the ELF section number for later lookup: this is what the
13490      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13491   gdb_assert (elf_section_nr < dwp_file->num_sections);
13492   dwp_file->elf_sections[elf_section_nr] = sectp;
13493
13494   /* Look for specific sections that we need.  */
13495   if (section_is_p (sectp->name, &names->abbrev_dwo))
13496     {
13497       dwp_file->sections.abbrev.s.section = sectp;
13498       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13499     }
13500   else if (section_is_p (sectp->name, &names->info_dwo))
13501     {
13502       dwp_file->sections.info.s.section = sectp;
13503       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13504     }
13505   else if (section_is_p (sectp->name, &names->line_dwo))
13506     {
13507       dwp_file->sections.line.s.section = sectp;
13508       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13509     }
13510   else if (section_is_p (sectp->name, &names->loc_dwo))
13511     {
13512       dwp_file->sections.loc.s.section = sectp;
13513       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13514     }
13515   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13516     {
13517       dwp_file->sections.macinfo.s.section = sectp;
13518       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13519     }
13520   else if (section_is_p (sectp->name, &names->macro_dwo))
13521     {
13522       dwp_file->sections.macro.s.section = sectp;
13523       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13524     }
13525   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13526     {
13527       dwp_file->sections.str_offsets.s.section = sectp;
13528       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13529     }
13530   else if (section_is_p (sectp->name, &names->types_dwo))
13531     {
13532       dwp_file->sections.types.s.section = sectp;
13533       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13534     }
13535 }
13536
13537 /* Hash function for dwp_file loaded CUs/TUs.  */
13538
13539 static hashval_t
13540 hash_dwp_loaded_cutus (const void *item)
13541 {
13542   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13543
13544   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13545   return dwo_unit->signature;
13546 }
13547
13548 /* Equality function for dwp_file loaded CUs/TUs.  */
13549
13550 static int
13551 eq_dwp_loaded_cutus (const void *a, const void *b)
13552 {
13553   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13554   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13555
13556   return dua->signature == dub->signature;
13557 }
13558
13559 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13560
13561 static htab_t
13562 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13563 {
13564   return htab_create_alloc_ex (3,
13565                                hash_dwp_loaded_cutus,
13566                                eq_dwp_loaded_cutus,
13567                                NULL,
13568                                &objfile->objfile_obstack,
13569                                hashtab_obstack_allocate,
13570                                dummy_obstack_deallocate);
13571 }
13572
13573 /* Try to open DWP file FILE_NAME.
13574    The result is the bfd handle of the file.
13575    If there is a problem finding or opening the file, return NULL.
13576    Upon success, the canonicalized path of the file is stored in the bfd,
13577    same as symfile_bfd_open.  */
13578
13579 static gdb_bfd_ref_ptr
13580 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13581                const char *file_name)
13582 {
13583   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13584                                             1 /*is_dwp*/,
13585                                             1 /*search_cwd*/));
13586   if (abfd != NULL)
13587     return abfd;
13588
13589   /* Work around upstream bug 15652.
13590      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13591      [Whether that's a "bug" is debatable, but it is getting in our way.]
13592      We have no real idea where the dwp file is, because gdb's realpath-ing
13593      of the executable's path may have discarded the needed info.
13594      [IWBN if the dwp file name was recorded in the executable, akin to
13595      .gnu_debuglink, but that doesn't exist yet.]
13596      Strip the directory from FILE_NAME and search again.  */
13597   if (*debug_file_directory != '\0')
13598     {
13599       /* Don't implicitly search the current directory here.
13600          If the user wants to search "." to handle this case,
13601          it must be added to debug-file-directory.  */
13602       return try_open_dwop_file (dwarf2_per_objfile,
13603                                  lbasename (file_name), 1 /*is_dwp*/,
13604                                  0 /*search_cwd*/);
13605     }
13606
13607   return NULL;
13608 }
13609
13610 /* Initialize the use of the DWP file for the current objfile.
13611    By convention the name of the DWP file is ${objfile}.dwp.
13612    The result is NULL if it can't be found.  */
13613
13614 static struct dwp_file *
13615 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13616 {
13617   struct objfile *objfile = dwarf2_per_objfile->objfile;
13618   struct dwp_file *dwp_file;
13619
13620   /* Try to find first .dwp for the binary file before any symbolic links
13621      resolving.  */
13622
13623   /* If the objfile is a debug file, find the name of the real binary
13624      file and get the name of dwp file from there.  */
13625   std::string dwp_name;
13626   if (objfile->separate_debug_objfile_backlink != NULL)
13627     {
13628       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13629       const char *backlink_basename = lbasename (backlink->original_name);
13630
13631       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13632     }
13633   else
13634     dwp_name = objfile->original_name;
13635
13636   dwp_name += ".dwp";
13637
13638   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13639   if (dbfd == NULL
13640       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13641     {
13642       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13643       dwp_name = objfile_name (objfile);
13644       dwp_name += ".dwp";
13645       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13646     }
13647
13648   if (dbfd == NULL)
13649     {
13650       if (dwarf_read_debug)
13651         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13652       return NULL;
13653     }
13654   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13655   dwp_file->name = bfd_get_filename (dbfd.get ());
13656   dwp_file->dbfd = dbfd.release ();
13657
13658   /* +1: section 0 is unused */
13659   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13660   dwp_file->elf_sections =
13661     OBSTACK_CALLOC (&objfile->objfile_obstack,
13662                     dwp_file->num_sections, asection *);
13663
13664   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13665                          dwp_file);
13666
13667   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13668
13669   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13670
13671   /* The DWP file version is stored in the hash table.  Oh well.  */
13672   if (dwp_file->cus && dwp_file->tus
13673       && dwp_file->cus->version != dwp_file->tus->version)
13674     {
13675       /* Technically speaking, we should try to limp along, but this is
13676          pretty bizarre.  We use pulongest here because that's the established
13677          portability solution (e.g, we cannot use %u for uint32_t).  */
13678       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13679                " TU version %s [in DWP file %s]"),
13680              pulongest (dwp_file->cus->version),
13681              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13682     }
13683
13684   if (dwp_file->cus)
13685     dwp_file->version = dwp_file->cus->version;
13686   else if (dwp_file->tus)
13687     dwp_file->version = dwp_file->tus->version;
13688   else
13689     dwp_file->version = 2;
13690
13691   if (dwp_file->version == 2)
13692     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13693                            dwp_file);
13694
13695   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13696   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13697
13698   if (dwarf_read_debug)
13699     {
13700       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13701       fprintf_unfiltered (gdb_stdlog,
13702                           "    %s CUs, %s TUs\n",
13703                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13704                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13705     }
13706
13707   return dwp_file;
13708 }
13709
13710 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13711
13712 static struct dwp_file *
13713 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13714 {
13715   if (! dwarf2_per_objfile->dwp_checked)
13716     {
13717       dwarf2_per_objfile->dwp_file
13718         = open_and_init_dwp_file (dwarf2_per_objfile);
13719       dwarf2_per_objfile->dwp_checked = 1;
13720     }
13721   return dwarf2_per_objfile->dwp_file;
13722 }
13723
13724 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13725    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13726    or in the DWP file for the objfile, referenced by THIS_UNIT.
13727    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13728    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13729
13730    This is called, for example, when wanting to read a variable with a
13731    complex location.  Therefore we don't want to do file i/o for every call.
13732    Therefore we don't want to look for a DWO file on every call.
13733    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13734    then we check if we've already seen DWO_NAME, and only THEN do we check
13735    for a DWO file.
13736
13737    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13738    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13739
13740 static struct dwo_unit *
13741 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13742                  const char *dwo_name, const char *comp_dir,
13743                  ULONGEST signature, int is_debug_types)
13744 {
13745   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13746   struct objfile *objfile = dwarf2_per_objfile->objfile;
13747   const char *kind = is_debug_types ? "TU" : "CU";
13748   void **dwo_file_slot;
13749   struct dwo_file *dwo_file;
13750   struct dwp_file *dwp_file;
13751
13752   /* First see if there's a DWP file.
13753      If we have a DWP file but didn't find the DWO inside it, don't
13754      look for the original DWO file.  It makes gdb behave differently
13755      depending on whether one is debugging in the build tree.  */
13756
13757   dwp_file = get_dwp_file (dwarf2_per_objfile);
13758   if (dwp_file != NULL)
13759     {
13760       const struct dwp_hash_table *dwp_htab =
13761         is_debug_types ? dwp_file->tus : dwp_file->cus;
13762
13763       if (dwp_htab != NULL)
13764         {
13765           struct dwo_unit *dwo_cutu =
13766             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13767                                     signature, is_debug_types);
13768
13769           if (dwo_cutu != NULL)
13770             {
13771               if (dwarf_read_debug)
13772                 {
13773                   fprintf_unfiltered (gdb_stdlog,
13774                                       "Virtual DWO %s %s found: @%s\n",
13775                                       kind, hex_string (signature),
13776                                       host_address_to_string (dwo_cutu));
13777                 }
13778               return dwo_cutu;
13779             }
13780         }
13781     }
13782   else
13783     {
13784       /* No DWP file, look for the DWO file.  */
13785
13786       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13787                                             dwo_name, comp_dir);
13788       if (*dwo_file_slot == NULL)
13789         {
13790           /* Read in the file and build a table of the CUs/TUs it contains.  */
13791           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13792         }
13793       /* NOTE: This will be NULL if unable to open the file.  */
13794       dwo_file = (struct dwo_file *) *dwo_file_slot;
13795
13796       if (dwo_file != NULL)
13797         {
13798           struct dwo_unit *dwo_cutu = NULL;
13799
13800           if (is_debug_types && dwo_file->tus)
13801             {
13802               struct dwo_unit find_dwo_cutu;
13803
13804               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13805               find_dwo_cutu.signature = signature;
13806               dwo_cutu
13807                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13808             }
13809           else if (!is_debug_types && dwo_file->cus)
13810             {
13811               struct dwo_unit find_dwo_cutu;
13812
13813               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13814               find_dwo_cutu.signature = signature;
13815               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13816                                                        &find_dwo_cutu);
13817             }
13818
13819           if (dwo_cutu != NULL)
13820             {
13821               if (dwarf_read_debug)
13822                 {
13823                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13824                                       kind, dwo_name, hex_string (signature),
13825                                       host_address_to_string (dwo_cutu));
13826                 }
13827               return dwo_cutu;
13828             }
13829         }
13830     }
13831
13832   /* We didn't find it.  This could mean a dwo_id mismatch, or
13833      someone deleted the DWO/DWP file, or the search path isn't set up
13834      correctly to find the file.  */
13835
13836   if (dwarf_read_debug)
13837     {
13838       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13839                           kind, dwo_name, hex_string (signature));
13840     }
13841
13842   /* This is a warning and not a complaint because it can be caused by
13843      pilot error (e.g., user accidentally deleting the DWO).  */
13844   {
13845     /* Print the name of the DWP file if we looked there, helps the user
13846        better diagnose the problem.  */
13847     std::string dwp_text;
13848
13849     if (dwp_file != NULL)
13850       dwp_text = string_printf (" [in DWP file %s]",
13851                                 lbasename (dwp_file->name));
13852
13853     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13854                " [in module %s]"),
13855              kind, dwo_name, hex_string (signature),
13856              dwp_text.c_str (),
13857              this_unit->is_debug_types ? "TU" : "CU",
13858              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13859   }
13860   return NULL;
13861 }
13862
13863 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13864    See lookup_dwo_cutu_unit for details.  */
13865
13866 static struct dwo_unit *
13867 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13868                       const char *dwo_name, const char *comp_dir,
13869                       ULONGEST signature)
13870 {
13871   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13872 }
13873
13874 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13875    See lookup_dwo_cutu_unit for details.  */
13876
13877 static struct dwo_unit *
13878 lookup_dwo_type_unit (struct signatured_type *this_tu,
13879                       const char *dwo_name, const char *comp_dir)
13880 {
13881   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13882 }
13883
13884 /* Traversal function for queue_and_load_all_dwo_tus.  */
13885
13886 static int
13887 queue_and_load_dwo_tu (void **slot, void *info)
13888 {
13889   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13890   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13891   ULONGEST signature = dwo_unit->signature;
13892   struct signatured_type *sig_type =
13893     lookup_dwo_signatured_type (per_cu->cu, signature);
13894
13895   if (sig_type != NULL)
13896     {
13897       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13898
13899       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13900          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13901          while processing PER_CU.  */
13902       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13903         load_full_type_unit (sig_cu);
13904       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13905     }
13906
13907   return 1;
13908 }
13909
13910 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13911    The DWO may have the only definition of the type, though it may not be
13912    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13913    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13914
13915 static void
13916 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13917 {
13918   struct dwo_unit *dwo_unit;
13919   struct dwo_file *dwo_file;
13920
13921   gdb_assert (!per_cu->is_debug_types);
13922   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13923   gdb_assert (per_cu->cu != NULL);
13924
13925   dwo_unit = per_cu->cu->dwo_unit;
13926   gdb_assert (dwo_unit != NULL);
13927
13928   dwo_file = dwo_unit->dwo_file;
13929   if (dwo_file->tus != NULL)
13930     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13931 }
13932
13933 /* Free all resources associated with DWO_FILE.
13934    Close the DWO file and munmap the sections.
13935    All memory should be on the objfile obstack.  */
13936
13937 static void
13938 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13939 {
13940
13941   /* Note: dbfd is NULL for virtual DWO files.  */
13942   gdb_bfd_unref (dwo_file->dbfd);
13943
13944   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13945 }
13946
13947 /* Wrapper for free_dwo_file for use in cleanups.  */
13948
13949 static void
13950 free_dwo_file_cleanup (void *arg)
13951 {
13952   struct free_dwo_file_cleanup_data *data
13953     = (struct free_dwo_file_cleanup_data *) arg;
13954   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13955
13956   free_dwo_file (data->dwo_file, objfile);
13957
13958   xfree (data);
13959 }
13960
13961 /* Traversal function for free_dwo_files.  */
13962
13963 static int
13964 free_dwo_file_from_slot (void **slot, void *info)
13965 {
13966   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13967   struct objfile *objfile = (struct objfile *) info;
13968
13969   free_dwo_file (dwo_file, objfile);
13970
13971   return 1;
13972 }
13973
13974 /* Free all resources associated with DWO_FILES.  */
13975
13976 static void
13977 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13978 {
13979   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13980 }
13981 \f
13982 /* Read in various DIEs.  */
13983
13984 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13985    Inherit only the children of the DW_AT_abstract_origin DIE not being
13986    already referenced by DW_AT_abstract_origin from the children of the
13987    current DIE.  */
13988
13989 static void
13990 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13991 {
13992   struct die_info *child_die;
13993   sect_offset *offsetp;
13994   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13995   struct die_info *origin_die;
13996   /* Iterator of the ORIGIN_DIE children.  */
13997   struct die_info *origin_child_die;
13998   struct attribute *attr;
13999   struct dwarf2_cu *origin_cu;
14000   struct pending **origin_previous_list_in_scope;
14001
14002   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14003   if (!attr)
14004     return;
14005
14006   /* Note that following die references may follow to a die in a
14007      different cu.  */
14008
14009   origin_cu = cu;
14010   origin_die = follow_die_ref (die, attr, &origin_cu);
14011
14012   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
14013      symbols in.  */
14014   origin_previous_list_in_scope = origin_cu->list_in_scope;
14015   origin_cu->list_in_scope = cu->list_in_scope;
14016
14017   if (die->tag != origin_die->tag
14018       && !(die->tag == DW_TAG_inlined_subroutine
14019            && origin_die->tag == DW_TAG_subprogram))
14020     complaint (&symfile_complaints,
14021                _("DIE %s and its abstract origin %s have different tags"),
14022                sect_offset_str (die->sect_off),
14023                sect_offset_str (origin_die->sect_off));
14024
14025   std::vector<sect_offset> offsets;
14026
14027   for (child_die = die->child;
14028        child_die && child_die->tag;
14029        child_die = sibling_die (child_die))
14030     {
14031       struct die_info *child_origin_die;
14032       struct dwarf2_cu *child_origin_cu;
14033
14034       /* We are trying to process concrete instance entries:
14035          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
14036          it's not relevant to our analysis here. i.e. detecting DIEs that are
14037          present in the abstract instance but not referenced in the concrete
14038          one.  */
14039       if (child_die->tag == DW_TAG_call_site
14040           || child_die->tag == DW_TAG_GNU_call_site)
14041         continue;
14042
14043       /* For each CHILD_DIE, find the corresponding child of
14044          ORIGIN_DIE.  If there is more than one layer of
14045          DW_AT_abstract_origin, follow them all; there shouldn't be,
14046          but GCC versions at least through 4.4 generate this (GCC PR
14047          40573).  */
14048       child_origin_die = child_die;
14049       child_origin_cu = cu;
14050       while (1)
14051         {
14052           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
14053                               child_origin_cu);
14054           if (attr == NULL)
14055             break;
14056           child_origin_die = follow_die_ref (child_origin_die, attr,
14057                                              &child_origin_cu);
14058         }
14059
14060       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
14061          counterpart may exist.  */
14062       if (child_origin_die != child_die)
14063         {
14064           if (child_die->tag != child_origin_die->tag
14065               && !(child_die->tag == DW_TAG_inlined_subroutine
14066                    && child_origin_die->tag == DW_TAG_subprogram))
14067             complaint (&symfile_complaints,
14068                        _("Child DIE %s and its abstract origin %s have "
14069                          "different tags"),
14070                        sect_offset_str (child_die->sect_off),
14071                        sect_offset_str (child_origin_die->sect_off));
14072           if (child_origin_die->parent != origin_die)
14073             complaint (&symfile_complaints,
14074                        _("Child DIE %s and its abstract origin %s have "
14075                          "different parents"),
14076                        sect_offset_str (child_die->sect_off),
14077                        sect_offset_str (child_origin_die->sect_off));
14078           else
14079             offsets.push_back (child_origin_die->sect_off);
14080         }
14081     }
14082   std::sort (offsets.begin (), offsets.end ());
14083   sect_offset *offsets_end = offsets.data () + offsets.size ();
14084   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
14085     if (offsetp[-1] == *offsetp)
14086       complaint (&symfile_complaints,
14087                  _("Multiple children of DIE %s refer "
14088                    "to DIE %s as their abstract origin"),
14089                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
14090
14091   offsetp = offsets.data ();
14092   origin_child_die = origin_die->child;
14093   while (origin_child_die && origin_child_die->tag)
14094     {
14095       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
14096       while (offsetp < offsets_end
14097              && *offsetp < origin_child_die->sect_off)
14098         offsetp++;
14099       if (offsetp >= offsets_end
14100           || *offsetp > origin_child_die->sect_off)
14101         {
14102           /* Found that ORIGIN_CHILD_DIE is really not referenced.
14103              Check whether we're already processing ORIGIN_CHILD_DIE.
14104              This can happen with mutually referenced abstract_origins.
14105              PR 16581.  */
14106           if (!origin_child_die->in_process)
14107             process_die (origin_child_die, origin_cu);
14108         }
14109       origin_child_die = sibling_die (origin_child_die);
14110     }
14111   origin_cu->list_in_scope = origin_previous_list_in_scope;
14112 }
14113
14114 static void
14115 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
14116 {
14117   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14118   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14119   struct context_stack *newobj;
14120   CORE_ADDR lowpc;
14121   CORE_ADDR highpc;
14122   struct die_info *child_die;
14123   struct attribute *attr, *call_line, *call_file;
14124   const char *name;
14125   CORE_ADDR baseaddr;
14126   struct block *block;
14127   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
14128   std::vector<struct symbol *> template_args;
14129   struct template_symbol *templ_func = NULL;
14130
14131   if (inlined_func)
14132     {
14133       /* If we do not have call site information, we can't show the
14134          caller of this inlined function.  That's too confusing, so
14135          only use the scope for local variables.  */
14136       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
14137       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
14138       if (call_line == NULL || call_file == NULL)
14139         {
14140           read_lexical_block_scope (die, cu);
14141           return;
14142         }
14143     }
14144
14145   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14146
14147   name = dwarf2_name (die, cu);
14148
14149   /* Ignore functions with missing or empty names.  These are actually
14150      illegal according to the DWARF standard.  */
14151   if (name == NULL)
14152     {
14153       complaint (&symfile_complaints,
14154                  _("missing name for subprogram DIE at %s"),
14155                  sect_offset_str (die->sect_off));
14156       return;
14157     }
14158
14159   /* Ignore functions with missing or invalid low and high pc attributes.  */
14160   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
14161       <= PC_BOUNDS_INVALID)
14162     {
14163       attr = dwarf2_attr (die, DW_AT_external, cu);
14164       if (!attr || !DW_UNSND (attr))
14165         complaint (&symfile_complaints,
14166                    _("cannot get low and high bounds "
14167                      "for subprogram DIE at %s"),
14168                    sect_offset_str (die->sect_off));
14169       return;
14170     }
14171
14172   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14173   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14174
14175   /* If we have any template arguments, then we must allocate a
14176      different sort of symbol.  */
14177   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
14178     {
14179       if (child_die->tag == DW_TAG_template_type_param
14180           || child_die->tag == DW_TAG_template_value_param)
14181         {
14182           templ_func = allocate_template_symbol (objfile);
14183           templ_func->subclass = SYMBOL_TEMPLATE;
14184           break;
14185         }
14186     }
14187
14188   newobj = push_context (0, lowpc);
14189   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
14190                              (struct symbol *) templ_func);
14191
14192   /* If there is a location expression for DW_AT_frame_base, record
14193      it.  */
14194   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
14195   if (attr)
14196     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
14197
14198   /* If there is a location for the static link, record it.  */
14199   newobj->static_link = NULL;
14200   attr = dwarf2_attr (die, DW_AT_static_link, cu);
14201   if (attr)
14202     {
14203       newobj->static_link
14204         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
14205       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
14206     }
14207
14208   cu->list_in_scope = &local_symbols;
14209
14210   if (die->child != NULL)
14211     {
14212       child_die = die->child;
14213       while (child_die && child_die->tag)
14214         {
14215           if (child_die->tag == DW_TAG_template_type_param
14216               || child_die->tag == DW_TAG_template_value_param)
14217             {
14218               struct symbol *arg = new_symbol (child_die, NULL, cu);
14219
14220               if (arg != NULL)
14221                 template_args.push_back (arg);
14222             }
14223           else
14224             process_die (child_die, cu);
14225           child_die = sibling_die (child_die);
14226         }
14227     }
14228
14229   inherit_abstract_dies (die, cu);
14230
14231   /* If we have a DW_AT_specification, we might need to import using
14232      directives from the context of the specification DIE.  See the
14233      comment in determine_prefix.  */
14234   if (cu->language == language_cplus
14235       && dwarf2_attr (die, DW_AT_specification, cu))
14236     {
14237       struct dwarf2_cu *spec_cu = cu;
14238       struct die_info *spec_die = die_specification (die, &spec_cu);
14239
14240       while (spec_die)
14241         {
14242           child_die = spec_die->child;
14243           while (child_die && child_die->tag)
14244             {
14245               if (child_die->tag == DW_TAG_imported_module)
14246                 process_die (child_die, spec_cu);
14247               child_die = sibling_die (child_die);
14248             }
14249
14250           /* In some cases, GCC generates specification DIEs that
14251              themselves contain DW_AT_specification attributes.  */
14252           spec_die = die_specification (spec_die, &spec_cu);
14253         }
14254     }
14255
14256   newobj = pop_context ();
14257   /* Make a block for the local symbols within.  */
14258   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
14259                         newobj->static_link, lowpc, highpc);
14260
14261   /* For C++, set the block's scope.  */
14262   if ((cu->language == language_cplus
14263        || cu->language == language_fortran
14264        || cu->language == language_d
14265        || cu->language == language_rust)
14266       && cu->processing_has_namespace_info)
14267     block_set_scope (block, determine_prefix (die, cu),
14268                      &objfile->objfile_obstack);
14269
14270   /* If we have address ranges, record them.  */
14271   dwarf2_record_block_ranges (die, block, baseaddr, cu);
14272
14273   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
14274
14275   /* Attach template arguments to function.  */
14276   if (!template_args.empty ())
14277     {
14278       gdb_assert (templ_func != NULL);
14279
14280       templ_func->n_template_arguments = template_args.size ();
14281       templ_func->template_arguments
14282         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
14283                      templ_func->n_template_arguments);
14284       memcpy (templ_func->template_arguments,
14285               template_args.data (),
14286               (templ_func->n_template_arguments * sizeof (struct symbol *)));
14287     }
14288
14289   /* In C++, we can have functions nested inside functions (e.g., when
14290      a function declares a class that has methods).  This means that
14291      when we finish processing a function scope, we may need to go
14292      back to building a containing block's symbol lists.  */
14293   local_symbols = newobj->locals;
14294   local_using_directives = newobj->local_using_directives;
14295
14296   /* If we've finished processing a top-level function, subsequent
14297      symbols go in the file symbol list.  */
14298   if (outermost_context_p ())
14299     cu->list_in_scope = &file_symbols;
14300 }
14301
14302 /* Process all the DIES contained within a lexical block scope.  Start
14303    a new scope, process the dies, and then close the scope.  */
14304
14305 static void
14306 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
14307 {
14308   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14309   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14310   struct context_stack *newobj;
14311   CORE_ADDR lowpc, highpc;
14312   struct die_info *child_die;
14313   CORE_ADDR baseaddr;
14314
14315   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14316
14317   /* Ignore blocks with missing or invalid low and high pc attributes.  */
14318   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
14319      as multiple lexical blocks?  Handling children in a sane way would
14320      be nasty.  Might be easier to properly extend generic blocks to
14321      describe ranges.  */
14322   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14323     {
14324     case PC_BOUNDS_NOT_PRESENT:
14325       /* DW_TAG_lexical_block has no attributes, process its children as if
14326          there was no wrapping by that DW_TAG_lexical_block.
14327          GCC does no longer produces such DWARF since GCC r224161.  */
14328       for (child_die = die->child;
14329            child_die != NULL && child_die->tag;
14330            child_die = sibling_die (child_die))
14331         process_die (child_die, cu);
14332       return;
14333     case PC_BOUNDS_INVALID:
14334       return;
14335     }
14336   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14337   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14338
14339   push_context (0, lowpc);
14340   if (die->child != NULL)
14341     {
14342       child_die = die->child;
14343       while (child_die && child_die->tag)
14344         {
14345           process_die (child_die, cu);
14346           child_die = sibling_die (child_die);
14347         }
14348     }
14349   inherit_abstract_dies (die, cu);
14350   newobj = pop_context ();
14351
14352   if (local_symbols != NULL || local_using_directives != NULL)
14353     {
14354       struct block *block
14355         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14356                         newobj->start_addr, highpc);
14357
14358       /* Note that recording ranges after traversing children, as we
14359          do here, means that recording a parent's ranges entails
14360          walking across all its children's ranges as they appear in
14361          the address map, which is quadratic behavior.
14362
14363          It would be nicer to record the parent's ranges before
14364          traversing its children, simply overriding whatever you find
14365          there.  But since we don't even decide whether to create a
14366          block until after we've traversed its children, that's hard
14367          to do.  */
14368       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14369     }
14370   local_symbols = newobj->locals;
14371   local_using_directives = newobj->local_using_directives;
14372 }
14373
14374 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14375
14376 static void
14377 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14378 {
14379   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14380   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14381   CORE_ADDR pc, baseaddr;
14382   struct attribute *attr;
14383   struct call_site *call_site, call_site_local;
14384   void **slot;
14385   int nparams;
14386   struct die_info *child_die;
14387
14388   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14389
14390   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14391   if (attr == NULL)
14392     {
14393       /* This was a pre-DWARF-5 GNU extension alias
14394          for DW_AT_call_return_pc.  */
14395       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14396     }
14397   if (!attr)
14398     {
14399       complaint (&symfile_complaints,
14400                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14401                    "DIE %s [in module %s]"),
14402                  sect_offset_str (die->sect_off), objfile_name (objfile));
14403       return;
14404     }
14405   pc = attr_value_as_address (attr) + baseaddr;
14406   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14407
14408   if (cu->call_site_htab == NULL)
14409     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14410                                                NULL, &objfile->objfile_obstack,
14411                                                hashtab_obstack_allocate, NULL);
14412   call_site_local.pc = pc;
14413   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14414   if (*slot != NULL)
14415     {
14416       complaint (&symfile_complaints,
14417                  _("Duplicate PC %s for DW_TAG_call_site "
14418                    "DIE %s [in module %s]"),
14419                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
14420                  objfile_name (objfile));
14421       return;
14422     }
14423
14424   /* Count parameters at the caller.  */
14425
14426   nparams = 0;
14427   for (child_die = die->child; child_die && child_die->tag;
14428        child_die = sibling_die (child_die))
14429     {
14430       if (child_die->tag != DW_TAG_call_site_parameter
14431           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14432         {
14433           complaint (&symfile_complaints,
14434                      _("Tag %d is not DW_TAG_call_site_parameter in "
14435                        "DW_TAG_call_site child DIE %s [in module %s]"),
14436                      child_die->tag, sect_offset_str (child_die->sect_off),
14437                      objfile_name (objfile));
14438           continue;
14439         }
14440
14441       nparams++;
14442     }
14443
14444   call_site
14445     = ((struct call_site *)
14446        obstack_alloc (&objfile->objfile_obstack,
14447                       sizeof (*call_site)
14448                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14449   *slot = call_site;
14450   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14451   call_site->pc = pc;
14452
14453   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14454       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14455     {
14456       struct die_info *func_die;
14457
14458       /* Skip also over DW_TAG_inlined_subroutine.  */
14459       for (func_die = die->parent;
14460            func_die && func_die->tag != DW_TAG_subprogram
14461            && func_die->tag != DW_TAG_subroutine_type;
14462            func_die = func_die->parent);
14463
14464       /* DW_AT_call_all_calls is a superset
14465          of DW_AT_call_all_tail_calls.  */
14466       if (func_die
14467           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14468           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14469           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14470           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14471         {
14472           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14473              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14474              both the initial caller containing the real return address PC and
14475              the final callee containing the current PC of a chain of tail
14476              calls do not need to have the tail call list complete.  But any
14477              function candidate for a virtual tail call frame searched via
14478              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14479              determined unambiguously.  */
14480         }
14481       else
14482         {
14483           struct type *func_type = NULL;
14484
14485           if (func_die)
14486             func_type = get_die_type (func_die, cu);
14487           if (func_type != NULL)
14488             {
14489               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14490
14491               /* Enlist this call site to the function.  */
14492               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14493               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14494             }
14495           else
14496             complaint (&symfile_complaints,
14497                        _("Cannot find function owning DW_TAG_call_site "
14498                          "DIE %s [in module %s]"),
14499                        sect_offset_str (die->sect_off), objfile_name (objfile));
14500         }
14501     }
14502
14503   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14504   if (attr == NULL)
14505     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14506   if (attr == NULL)
14507     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14508   if (attr == NULL)
14509     {
14510       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14511       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14512     }
14513   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14514   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14515     /* Keep NULL DWARF_BLOCK.  */;
14516   else if (attr_form_is_block (attr))
14517     {
14518       struct dwarf2_locexpr_baton *dlbaton;
14519
14520       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14521       dlbaton->data = DW_BLOCK (attr)->data;
14522       dlbaton->size = DW_BLOCK (attr)->size;
14523       dlbaton->per_cu = cu->per_cu;
14524
14525       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14526     }
14527   else if (attr_form_is_ref (attr))
14528     {
14529       struct dwarf2_cu *target_cu = cu;
14530       struct die_info *target_die;
14531
14532       target_die = follow_die_ref (die, attr, &target_cu);
14533       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14534       if (die_is_declaration (target_die, target_cu))
14535         {
14536           const char *target_physname;
14537
14538           /* Prefer the mangled name; otherwise compute the demangled one.  */
14539           target_physname = dw2_linkage_name (target_die, target_cu);
14540           if (target_physname == NULL)
14541             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14542           if (target_physname == NULL)
14543             complaint (&symfile_complaints,
14544                        _("DW_AT_call_target target DIE has invalid "
14545                          "physname, for referencing DIE %s [in module %s]"),
14546                        sect_offset_str (die->sect_off), objfile_name (objfile));
14547           else
14548             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14549         }
14550       else
14551         {
14552           CORE_ADDR lowpc;
14553
14554           /* DW_AT_entry_pc should be preferred.  */
14555           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14556               <= PC_BOUNDS_INVALID)
14557             complaint (&symfile_complaints,
14558                        _("DW_AT_call_target target DIE has invalid "
14559                          "low pc, for referencing DIE %s [in module %s]"),
14560                        sect_offset_str (die->sect_off), objfile_name (objfile));
14561           else
14562             {
14563               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14564               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14565             }
14566         }
14567     }
14568   else
14569     complaint (&symfile_complaints,
14570                _("DW_TAG_call_site DW_AT_call_target is neither "
14571                  "block nor reference, for DIE %s [in module %s]"),
14572                sect_offset_str (die->sect_off), objfile_name (objfile));
14573
14574   call_site->per_cu = cu->per_cu;
14575
14576   for (child_die = die->child;
14577        child_die && child_die->tag;
14578        child_die = sibling_die (child_die))
14579     {
14580       struct call_site_parameter *parameter;
14581       struct attribute *loc, *origin;
14582
14583       if (child_die->tag != DW_TAG_call_site_parameter
14584           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14585         {
14586           /* Already printed the complaint above.  */
14587           continue;
14588         }
14589
14590       gdb_assert (call_site->parameter_count < nparams);
14591       parameter = &call_site->parameter[call_site->parameter_count];
14592
14593       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14594          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14595          register is contained in DW_AT_call_value.  */
14596
14597       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14598       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14599       if (origin == NULL)
14600         {
14601           /* This was a pre-DWARF-5 GNU extension alias
14602              for DW_AT_call_parameter.  */
14603           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14604         }
14605       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14606         {
14607           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14608
14609           sect_offset sect_off
14610             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14611           if (!offset_in_cu_p (&cu->header, sect_off))
14612             {
14613               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14614                  binding can be done only inside one CU.  Such referenced DIE
14615                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14616               complaint (&symfile_complaints,
14617                          _("DW_AT_call_parameter offset is not in CU for "
14618                            "DW_TAG_call_site child DIE %s [in module %s]"),
14619                          sect_offset_str (child_die->sect_off),
14620                          objfile_name (objfile));
14621               continue;
14622             }
14623           parameter->u.param_cu_off
14624             = (cu_offset) (sect_off - cu->header.sect_off);
14625         }
14626       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14627         {
14628           complaint (&symfile_complaints,
14629                      _("No DW_FORM_block* DW_AT_location for "
14630                        "DW_TAG_call_site child DIE %s [in module %s]"),
14631                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14632           continue;
14633         }
14634       else
14635         {
14636           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14637             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14638           if (parameter->u.dwarf_reg != -1)
14639             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14640           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14641                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14642                                              &parameter->u.fb_offset))
14643             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14644           else
14645             {
14646               complaint (&symfile_complaints,
14647                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14648                            "for DW_FORM_block* DW_AT_location is supported for "
14649                            "DW_TAG_call_site child DIE %s "
14650                            "[in module %s]"),
14651                          sect_offset_str (child_die->sect_off),
14652                          objfile_name (objfile));
14653               continue;
14654             }
14655         }
14656
14657       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14658       if (attr == NULL)
14659         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14660       if (!attr_form_is_block (attr))
14661         {
14662           complaint (&symfile_complaints,
14663                      _("No DW_FORM_block* DW_AT_call_value for "
14664                        "DW_TAG_call_site child DIE %s [in module %s]"),
14665                      sect_offset_str (child_die->sect_off),
14666                      objfile_name (objfile));
14667           continue;
14668         }
14669       parameter->value = DW_BLOCK (attr)->data;
14670       parameter->value_size = DW_BLOCK (attr)->size;
14671
14672       /* Parameters are not pre-cleared by memset above.  */
14673       parameter->data_value = NULL;
14674       parameter->data_value_size = 0;
14675       call_site->parameter_count++;
14676
14677       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14678       if (attr == NULL)
14679         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14680       if (attr)
14681         {
14682           if (!attr_form_is_block (attr))
14683             complaint (&symfile_complaints,
14684                        _("No DW_FORM_block* DW_AT_call_data_value for "
14685                          "DW_TAG_call_site child DIE %s [in module %s]"),
14686                        sect_offset_str (child_die->sect_off),
14687                        objfile_name (objfile));
14688           else
14689             {
14690               parameter->data_value = DW_BLOCK (attr)->data;
14691               parameter->data_value_size = DW_BLOCK (attr)->size;
14692             }
14693         }
14694     }
14695 }
14696
14697 /* Helper function for read_variable.  If DIE represents a virtual
14698    table, then return the type of the concrete object that is
14699    associated with the virtual table.  Otherwise, return NULL.  */
14700
14701 static struct type *
14702 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14703 {
14704   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14705   if (attr == NULL)
14706     return NULL;
14707
14708   /* Find the type DIE.  */
14709   struct die_info *type_die = NULL;
14710   struct dwarf2_cu *type_cu = cu;
14711
14712   if (attr_form_is_ref (attr))
14713     type_die = follow_die_ref (die, attr, &type_cu);
14714   if (type_die == NULL)
14715     return NULL;
14716
14717   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14718     return NULL;
14719   return die_containing_type (type_die, type_cu);
14720 }
14721
14722 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14723
14724 static void
14725 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14726 {
14727   struct rust_vtable_symbol *storage = NULL;
14728
14729   if (cu->language == language_rust)
14730     {
14731       struct type *containing_type = rust_containing_type (die, cu);
14732
14733       if (containing_type != NULL)
14734         {
14735           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14736
14737           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14738                                     struct rust_vtable_symbol);
14739           initialize_objfile_symbol (storage);
14740           storage->concrete_type = containing_type;
14741           storage->subclass = SYMBOL_RUST_VTABLE;
14742         }
14743     }
14744
14745   new_symbol (die, NULL, cu, storage);
14746 }
14747
14748 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14749    reading .debug_rnglists.
14750    Callback's type should be:
14751     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14752    Return true if the attributes are present and valid, otherwise,
14753    return false.  */
14754
14755 template <typename Callback>
14756 static bool
14757 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14758                          Callback &&callback)
14759 {
14760   struct dwarf2_per_objfile *dwarf2_per_objfile
14761     = cu->per_cu->dwarf2_per_objfile;
14762   struct objfile *objfile = dwarf2_per_objfile->objfile;
14763   bfd *obfd = objfile->obfd;
14764   /* Base address selection entry.  */
14765   CORE_ADDR base;
14766   int found_base;
14767   const gdb_byte *buffer;
14768   CORE_ADDR baseaddr;
14769   bool overflow = false;
14770
14771   found_base = cu->base_known;
14772   base = cu->base_address;
14773
14774   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14775   if (offset >= dwarf2_per_objfile->rnglists.size)
14776     {
14777       complaint (&symfile_complaints,
14778                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14779                  offset);
14780       return false;
14781     }
14782   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14783
14784   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14785
14786   while (1)
14787     {
14788       /* Initialize it due to a false compiler warning.  */
14789       CORE_ADDR range_beginning = 0, range_end = 0;
14790       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14791                                  + dwarf2_per_objfile->rnglists.size);
14792       unsigned int bytes_read;
14793
14794       if (buffer == buf_end)
14795         {
14796           overflow = true;
14797           break;
14798         }
14799       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14800       switch (rlet)
14801         {
14802         case DW_RLE_end_of_list:
14803           break;
14804         case DW_RLE_base_address:
14805           if (buffer + cu->header.addr_size > buf_end)
14806             {
14807               overflow = true;
14808               break;
14809             }
14810           base = read_address (obfd, buffer, cu, &bytes_read);
14811           found_base = 1;
14812           buffer += bytes_read;
14813           break;
14814         case DW_RLE_start_length:
14815           if (buffer + cu->header.addr_size > buf_end)
14816             {
14817               overflow = true;
14818               break;
14819             }
14820           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14821           buffer += bytes_read;
14822           range_end = (range_beginning
14823                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14824           buffer += bytes_read;
14825           if (buffer > buf_end)
14826             {
14827               overflow = true;
14828               break;
14829             }
14830           break;
14831         case DW_RLE_offset_pair:
14832           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14833           buffer += bytes_read;
14834           if (buffer > buf_end)
14835             {
14836               overflow = true;
14837               break;
14838             }
14839           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14840           buffer += bytes_read;
14841           if (buffer > buf_end)
14842             {
14843               overflow = true;
14844               break;
14845             }
14846           break;
14847         case DW_RLE_start_end:
14848           if (buffer + 2 * cu->header.addr_size > buf_end)
14849             {
14850               overflow = true;
14851               break;
14852             }
14853           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14854           buffer += bytes_read;
14855           range_end = read_address (obfd, buffer, cu, &bytes_read);
14856           buffer += bytes_read;
14857           break;
14858         default:
14859           complaint (&symfile_complaints,
14860                      _("Invalid .debug_rnglists data (no base address)"));
14861           return false;
14862         }
14863       if (rlet == DW_RLE_end_of_list || overflow)
14864         break;
14865       if (rlet == DW_RLE_base_address)
14866         continue;
14867
14868       if (!found_base)
14869         {
14870           /* We have no valid base address for the ranges
14871              data.  */
14872           complaint (&symfile_complaints,
14873                      _("Invalid .debug_rnglists data (no base address)"));
14874           return false;
14875         }
14876
14877       if (range_beginning > range_end)
14878         {
14879           /* Inverted range entries are invalid.  */
14880           complaint (&symfile_complaints,
14881                      _("Invalid .debug_rnglists data (inverted range)"));
14882           return false;
14883         }
14884
14885       /* Empty range entries have no effect.  */
14886       if (range_beginning == range_end)
14887         continue;
14888
14889       range_beginning += base;
14890       range_end += base;
14891
14892       /* A not-uncommon case of bad debug info.
14893          Don't pollute the addrmap with bad data.  */
14894       if (range_beginning + baseaddr == 0
14895           && !dwarf2_per_objfile->has_section_at_zero)
14896         {
14897           complaint (&symfile_complaints,
14898                      _(".debug_rnglists entry has start address of zero"
14899                        " [in module %s]"), objfile_name (objfile));
14900           continue;
14901         }
14902
14903       callback (range_beginning, range_end);
14904     }
14905
14906   if (overflow)
14907     {
14908       complaint (&symfile_complaints,
14909                  _("Offset %d is not terminated "
14910                    "for DW_AT_ranges attribute"),
14911                  offset);
14912       return false;
14913     }
14914
14915   return true;
14916 }
14917
14918 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14919    Callback's type should be:
14920     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14921    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14922
14923 template <typename Callback>
14924 static int
14925 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14926                        Callback &&callback)
14927 {
14928   struct dwarf2_per_objfile *dwarf2_per_objfile
14929       = cu->per_cu->dwarf2_per_objfile;
14930   struct objfile *objfile = dwarf2_per_objfile->objfile;
14931   struct comp_unit_head *cu_header = &cu->header;
14932   bfd *obfd = objfile->obfd;
14933   unsigned int addr_size = cu_header->addr_size;
14934   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14935   /* Base address selection entry.  */
14936   CORE_ADDR base;
14937   int found_base;
14938   unsigned int dummy;
14939   const gdb_byte *buffer;
14940   CORE_ADDR baseaddr;
14941
14942   if (cu_header->version >= 5)
14943     return dwarf2_rnglists_process (offset, cu, callback);
14944
14945   found_base = cu->base_known;
14946   base = cu->base_address;
14947
14948   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14949   if (offset >= dwarf2_per_objfile->ranges.size)
14950     {
14951       complaint (&symfile_complaints,
14952                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14953                  offset);
14954       return 0;
14955     }
14956   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14957
14958   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14959
14960   while (1)
14961     {
14962       CORE_ADDR range_beginning, range_end;
14963
14964       range_beginning = read_address (obfd, buffer, cu, &dummy);
14965       buffer += addr_size;
14966       range_end = read_address (obfd, buffer, cu, &dummy);
14967       buffer += addr_size;
14968       offset += 2 * addr_size;
14969
14970       /* An end of list marker is a pair of zero addresses.  */
14971       if (range_beginning == 0 && range_end == 0)
14972         /* Found the end of list entry.  */
14973         break;
14974
14975       /* Each base address selection entry is a pair of 2 values.
14976          The first is the largest possible address, the second is
14977          the base address.  Check for a base address here.  */
14978       if ((range_beginning & mask) == mask)
14979         {
14980           /* If we found the largest possible address, then we already
14981              have the base address in range_end.  */
14982           base = range_end;
14983           found_base = 1;
14984           continue;
14985         }
14986
14987       if (!found_base)
14988         {
14989           /* We have no valid base address for the ranges
14990              data.  */
14991           complaint (&symfile_complaints,
14992                      _("Invalid .debug_ranges data (no base address)"));
14993           return 0;
14994         }
14995
14996       if (range_beginning > range_end)
14997         {
14998           /* Inverted range entries are invalid.  */
14999           complaint (&symfile_complaints,
15000                      _("Invalid .debug_ranges data (inverted range)"));
15001           return 0;
15002         }
15003
15004       /* Empty range entries have no effect.  */
15005       if (range_beginning == range_end)
15006         continue;
15007
15008       range_beginning += base;
15009       range_end += base;
15010
15011       /* A not-uncommon case of bad debug info.
15012          Don't pollute the addrmap with bad data.  */
15013       if (range_beginning + baseaddr == 0
15014           && !dwarf2_per_objfile->has_section_at_zero)
15015         {
15016           complaint (&symfile_complaints,
15017                      _(".debug_ranges entry has start address of zero"
15018                        " [in module %s]"), objfile_name (objfile));
15019           continue;
15020         }
15021
15022       callback (range_beginning, range_end);
15023     }
15024
15025   return 1;
15026 }
15027
15028 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
15029    Return 1 if the attributes are present and valid, otherwise, return 0.
15030    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
15031
15032 static int
15033 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
15034                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
15035                     struct partial_symtab *ranges_pst)
15036 {
15037   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15038   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15039   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
15040                                        SECT_OFF_TEXT (objfile));
15041   int low_set = 0;
15042   CORE_ADDR low = 0;
15043   CORE_ADDR high = 0;
15044   int retval;
15045
15046   retval = dwarf2_ranges_process (offset, cu,
15047     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
15048     {
15049       if (ranges_pst != NULL)
15050         {
15051           CORE_ADDR lowpc;
15052           CORE_ADDR highpc;
15053
15054           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
15055                                               range_beginning + baseaddr);
15056           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
15057                                                range_end + baseaddr);
15058           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
15059                              ranges_pst);
15060         }
15061
15062       /* FIXME: This is recording everything as a low-high
15063          segment of consecutive addresses.  We should have a
15064          data structure for discontiguous block ranges
15065          instead.  */
15066       if (! low_set)
15067         {
15068           low = range_beginning;
15069           high = range_end;
15070           low_set = 1;
15071         }
15072       else
15073         {
15074           if (range_beginning < low)
15075             low = range_beginning;
15076           if (range_end > high)
15077             high = range_end;
15078         }
15079     });
15080   if (!retval)
15081     return 0;
15082
15083   if (! low_set)
15084     /* If the first entry is an end-of-list marker, the range
15085        describes an empty scope, i.e. no instructions.  */
15086     return 0;
15087
15088   if (low_return)
15089     *low_return = low;
15090   if (high_return)
15091     *high_return = high;
15092   return 1;
15093 }
15094
15095 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
15096    definition for the return value.  *LOWPC and *HIGHPC are set iff
15097    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
15098
15099 static enum pc_bounds_kind
15100 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
15101                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
15102                       struct partial_symtab *pst)
15103 {
15104   struct dwarf2_per_objfile *dwarf2_per_objfile
15105     = cu->per_cu->dwarf2_per_objfile;
15106   struct attribute *attr;
15107   struct attribute *attr_high;
15108   CORE_ADDR low = 0;
15109   CORE_ADDR high = 0;
15110   enum pc_bounds_kind ret;
15111
15112   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
15113   if (attr_high)
15114     {
15115       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15116       if (attr)
15117         {
15118           low = attr_value_as_address (attr);
15119           high = attr_value_as_address (attr_high);
15120           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
15121             high += low;
15122         }
15123       else
15124         /* Found high w/o low attribute.  */
15125         return PC_BOUNDS_INVALID;
15126
15127       /* Found consecutive range of addresses.  */
15128       ret = PC_BOUNDS_HIGH_LOW;
15129     }
15130   else
15131     {
15132       attr = dwarf2_attr (die, DW_AT_ranges, cu);
15133       if (attr != NULL)
15134         {
15135           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
15136              We take advantage of the fact that DW_AT_ranges does not appear
15137              in DW_TAG_compile_unit of DWO files.  */
15138           int need_ranges_base = die->tag != DW_TAG_compile_unit;
15139           unsigned int ranges_offset = (DW_UNSND (attr)
15140                                         + (need_ranges_base
15141                                            ? cu->ranges_base
15142                                            : 0));
15143
15144           /* Value of the DW_AT_ranges attribute is the offset in the
15145              .debug_ranges section.  */
15146           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
15147             return PC_BOUNDS_INVALID;
15148           /* Found discontinuous range of addresses.  */
15149           ret = PC_BOUNDS_RANGES;
15150         }
15151       else
15152         return PC_BOUNDS_NOT_PRESENT;
15153     }
15154
15155   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
15156   if (high <= low)
15157     return PC_BOUNDS_INVALID;
15158
15159   /* When using the GNU linker, .gnu.linkonce. sections are used to
15160      eliminate duplicate copies of functions and vtables and such.
15161      The linker will arbitrarily choose one and discard the others.
15162      The AT_*_pc values for such functions refer to local labels in
15163      these sections.  If the section from that file was discarded, the
15164      labels are not in the output, so the relocs get a value of 0.
15165      If this is a discarded function, mark the pc bounds as invalid,
15166      so that GDB will ignore it.  */
15167   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
15168     return PC_BOUNDS_INVALID;
15169
15170   *lowpc = low;
15171   if (highpc)
15172     *highpc = high;
15173   return ret;
15174 }
15175
15176 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
15177    its low and high PC addresses.  Do nothing if these addresses could not
15178    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
15179    and HIGHPC to the high address if greater than HIGHPC.  */
15180
15181 static void
15182 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
15183                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
15184                                  struct dwarf2_cu *cu)
15185 {
15186   CORE_ADDR low, high;
15187   struct die_info *child = die->child;
15188
15189   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
15190     {
15191       *lowpc = std::min (*lowpc, low);
15192       *highpc = std::max (*highpc, high);
15193     }
15194
15195   /* If the language does not allow nested subprograms (either inside
15196      subprograms or lexical blocks), we're done.  */
15197   if (cu->language != language_ada)
15198     return;
15199
15200   /* Check all the children of the given DIE.  If it contains nested
15201      subprograms, then check their pc bounds.  Likewise, we need to
15202      check lexical blocks as well, as they may also contain subprogram
15203      definitions.  */
15204   while (child && child->tag)
15205     {
15206       if (child->tag == DW_TAG_subprogram
15207           || child->tag == DW_TAG_lexical_block)
15208         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
15209       child = sibling_die (child);
15210     }
15211 }
15212
15213 /* Get the low and high pc's represented by the scope DIE, and store
15214    them in *LOWPC and *HIGHPC.  If the correct values can't be
15215    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
15216
15217 static void
15218 get_scope_pc_bounds (struct die_info *die,
15219                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
15220                      struct dwarf2_cu *cu)
15221 {
15222   CORE_ADDR best_low = (CORE_ADDR) -1;
15223   CORE_ADDR best_high = (CORE_ADDR) 0;
15224   CORE_ADDR current_low, current_high;
15225
15226   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
15227       >= PC_BOUNDS_RANGES)
15228     {
15229       best_low = current_low;
15230       best_high = current_high;
15231     }
15232   else
15233     {
15234       struct die_info *child = die->child;
15235
15236       while (child && child->tag)
15237         {
15238           switch (child->tag) {
15239           case DW_TAG_subprogram:
15240             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
15241             break;
15242           case DW_TAG_namespace:
15243           case DW_TAG_module:
15244             /* FIXME: carlton/2004-01-16: Should we do this for
15245                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
15246                that current GCC's always emit the DIEs corresponding
15247                to definitions of methods of classes as children of a
15248                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
15249                the DIEs giving the declarations, which could be
15250                anywhere).  But I don't see any reason why the
15251                standards says that they have to be there.  */
15252             get_scope_pc_bounds (child, &current_low, &current_high, cu);
15253
15254             if (current_low != ((CORE_ADDR) -1))
15255               {
15256                 best_low = std::min (best_low, current_low);
15257                 best_high = std::max (best_high, current_high);
15258               }
15259             break;
15260           default:
15261             /* Ignore.  */
15262             break;
15263           }
15264
15265           child = sibling_die (child);
15266         }
15267     }
15268
15269   *lowpc = best_low;
15270   *highpc = best_high;
15271 }
15272
15273 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
15274    in DIE.  */
15275
15276 static void
15277 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
15278                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
15279 {
15280   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15281   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15282   struct attribute *attr;
15283   struct attribute *attr_high;
15284
15285   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
15286   if (attr_high)
15287     {
15288       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15289       if (attr)
15290         {
15291           CORE_ADDR low = attr_value_as_address (attr);
15292           CORE_ADDR high = attr_value_as_address (attr_high);
15293
15294           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
15295             high += low;
15296
15297           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
15298           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
15299           record_block_range (block, low, high - 1);
15300         }
15301     }
15302
15303   attr = dwarf2_attr (die, DW_AT_ranges, cu);
15304   if (attr)
15305     {
15306       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
15307          We take advantage of the fact that DW_AT_ranges does not appear
15308          in DW_TAG_compile_unit of DWO files.  */
15309       int need_ranges_base = die->tag != DW_TAG_compile_unit;
15310
15311       /* The value of the DW_AT_ranges attribute is the offset of the
15312          address range list in the .debug_ranges section.  */
15313       unsigned long offset = (DW_UNSND (attr)
15314                               + (need_ranges_base ? cu->ranges_base : 0));
15315       const gdb_byte *buffer;
15316
15317       /* For some target architectures, but not others, the
15318          read_address function sign-extends the addresses it returns.
15319          To recognize base address selection entries, we need a
15320          mask.  */
15321       unsigned int addr_size = cu->header.addr_size;
15322       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15323
15324       /* The base address, to which the next pair is relative.  Note
15325          that this 'base' is a DWARF concept: most entries in a range
15326          list are relative, to reduce the number of relocs against the
15327          debugging information.  This is separate from this function's
15328          'baseaddr' argument, which GDB uses to relocate debugging
15329          information from a shared library based on the address at
15330          which the library was loaded.  */
15331       CORE_ADDR base = cu->base_address;
15332       int base_known = cu->base_known;
15333
15334       dwarf2_ranges_process (offset, cu,
15335         [&] (CORE_ADDR start, CORE_ADDR end)
15336         {
15337           start += baseaddr;
15338           end += baseaddr;
15339           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15340           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15341           record_block_range (block, start, end - 1);
15342         });
15343     }
15344 }
15345
15346 /* Check whether the producer field indicates either of GCC < 4.6, or the
15347    Intel C/C++ compiler, and cache the result in CU.  */
15348
15349 static void
15350 check_producer (struct dwarf2_cu *cu)
15351 {
15352   int major, minor;
15353
15354   if (cu->producer == NULL)
15355     {
15356       /* For unknown compilers expect their behavior is DWARF version
15357          compliant.
15358
15359          GCC started to support .debug_types sections by -gdwarf-4 since
15360          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15361          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15362          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15363          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15364     }
15365   else if (producer_is_gcc (cu->producer, &major, &minor))
15366     {
15367       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15368       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15369     }
15370   else if (producer_is_icc (cu->producer, &major, &minor))
15371     cu->producer_is_icc_lt_14 = major < 14;
15372   else
15373     {
15374       /* For other non-GCC compilers, expect their behavior is DWARF version
15375          compliant.  */
15376     }
15377
15378   cu->checked_producer = 1;
15379 }
15380
15381 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15382    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15383    during 4.6.0 experimental.  */
15384
15385 static int
15386 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15387 {
15388   if (!cu->checked_producer)
15389     check_producer (cu);
15390
15391   return cu->producer_is_gxx_lt_4_6;
15392 }
15393
15394 /* Return the default accessibility type if it is not overriden by
15395    DW_AT_accessibility.  */
15396
15397 static enum dwarf_access_attribute
15398 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15399 {
15400   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15401     {
15402       /* The default DWARF 2 accessibility for members is public, the default
15403          accessibility for inheritance is private.  */
15404
15405       if (die->tag != DW_TAG_inheritance)
15406         return DW_ACCESS_public;
15407       else
15408         return DW_ACCESS_private;
15409     }
15410   else
15411     {
15412       /* DWARF 3+ defines the default accessibility a different way.  The same
15413          rules apply now for DW_TAG_inheritance as for the members and it only
15414          depends on the container kind.  */
15415
15416       if (die->parent->tag == DW_TAG_class_type)
15417         return DW_ACCESS_private;
15418       else
15419         return DW_ACCESS_public;
15420     }
15421 }
15422
15423 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15424    offset.  If the attribute was not found return 0, otherwise return
15425    1.  If it was found but could not properly be handled, set *OFFSET
15426    to 0.  */
15427
15428 static int
15429 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15430                              LONGEST *offset)
15431 {
15432   struct attribute *attr;
15433
15434   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15435   if (attr != NULL)
15436     {
15437       *offset = 0;
15438
15439       /* Note that we do not check for a section offset first here.
15440          This is because DW_AT_data_member_location is new in DWARF 4,
15441          so if we see it, we can assume that a constant form is really
15442          a constant and not a section offset.  */
15443       if (attr_form_is_constant (attr))
15444         *offset = dwarf2_get_attr_constant_value (attr, 0);
15445       else if (attr_form_is_section_offset (attr))
15446         dwarf2_complex_location_expr_complaint ();
15447       else if (attr_form_is_block (attr))
15448         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15449       else
15450         dwarf2_complex_location_expr_complaint ();
15451
15452       return 1;
15453     }
15454
15455   return 0;
15456 }
15457
15458 /* Add an aggregate field to the field list.  */
15459
15460 static void
15461 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15462                   struct dwarf2_cu *cu)
15463 {
15464   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15465   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15466   struct nextfield *new_field;
15467   struct attribute *attr;
15468   struct field *fp;
15469   const char *fieldname = "";
15470
15471   /* Allocate a new field list entry and link it in.  */
15472   new_field = XNEW (struct nextfield);
15473   make_cleanup (xfree, new_field);
15474   memset (new_field, 0, sizeof (struct nextfield));
15475
15476   if (die->tag == DW_TAG_inheritance)
15477     {
15478       new_field->next = fip->baseclasses;
15479       fip->baseclasses = new_field;
15480     }
15481   else
15482     {
15483       new_field->next = fip->fields;
15484       fip->fields = new_field;
15485     }
15486   fip->nfields++;
15487
15488   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15489   if (attr)
15490     new_field->accessibility = DW_UNSND (attr);
15491   else
15492     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15493   if (new_field->accessibility != DW_ACCESS_public)
15494     fip->non_public_fields = 1;
15495
15496   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15497   if (attr)
15498     new_field->virtuality = DW_UNSND (attr);
15499   else
15500     new_field->virtuality = DW_VIRTUALITY_none;
15501
15502   fp = &new_field->field;
15503
15504   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15505     {
15506       LONGEST offset;
15507
15508       /* Data member other than a C++ static data member.  */
15509
15510       /* Get type of field.  */
15511       fp->type = die_type (die, cu);
15512
15513       SET_FIELD_BITPOS (*fp, 0);
15514
15515       /* Get bit size of field (zero if none).  */
15516       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15517       if (attr)
15518         {
15519           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15520         }
15521       else
15522         {
15523           FIELD_BITSIZE (*fp) = 0;
15524         }
15525
15526       /* Get bit offset of field.  */
15527       if (handle_data_member_location (die, cu, &offset))
15528         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15529       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15530       if (attr)
15531         {
15532           if (gdbarch_bits_big_endian (gdbarch))
15533             {
15534               /* For big endian bits, the DW_AT_bit_offset gives the
15535                  additional bit offset from the MSB of the containing
15536                  anonymous object to the MSB of the field.  We don't
15537                  have to do anything special since we don't need to
15538                  know the size of the anonymous object.  */
15539               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15540             }
15541           else
15542             {
15543               /* For little endian bits, compute the bit offset to the
15544                  MSB of the anonymous object, subtract off the number of
15545                  bits from the MSB of the field to the MSB of the
15546                  object, and then subtract off the number of bits of
15547                  the field itself.  The result is the bit offset of
15548                  the LSB of the field.  */
15549               int anonymous_size;
15550               int bit_offset = DW_UNSND (attr);
15551
15552               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15553               if (attr)
15554                 {
15555                   /* The size of the anonymous object containing
15556                      the bit field is explicit, so use the
15557                      indicated size (in bytes).  */
15558                   anonymous_size = DW_UNSND (attr);
15559                 }
15560               else
15561                 {
15562                   /* The size of the anonymous object containing
15563                      the bit field must be inferred from the type
15564                      attribute of the data member containing the
15565                      bit field.  */
15566                   anonymous_size = TYPE_LENGTH (fp->type);
15567                 }
15568               SET_FIELD_BITPOS (*fp,
15569                                 (FIELD_BITPOS (*fp)
15570                                  + anonymous_size * bits_per_byte
15571                                  - bit_offset - FIELD_BITSIZE (*fp)));
15572             }
15573         }
15574       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15575       if (attr != NULL)
15576         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15577                                 + dwarf2_get_attr_constant_value (attr, 0)));
15578
15579       /* Get name of field.  */
15580       fieldname = dwarf2_name (die, cu);
15581       if (fieldname == NULL)
15582         fieldname = "";
15583
15584       /* The name is already allocated along with this objfile, so we don't
15585          need to duplicate it for the type.  */
15586       fp->name = fieldname;
15587
15588       /* Change accessibility for artificial fields (e.g. virtual table
15589          pointer or virtual base class pointer) to private.  */
15590       if (dwarf2_attr (die, DW_AT_artificial, cu))
15591         {
15592           FIELD_ARTIFICIAL (*fp) = 1;
15593           new_field->accessibility = DW_ACCESS_private;
15594           fip->non_public_fields = 1;
15595         }
15596     }
15597   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15598     {
15599       /* C++ static member.  */
15600
15601       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15602          is a declaration, but all versions of G++ as of this writing
15603          (so through at least 3.2.1) incorrectly generate
15604          DW_TAG_variable tags.  */
15605
15606       const char *physname;
15607
15608       /* Get name of field.  */
15609       fieldname = dwarf2_name (die, cu);
15610       if (fieldname == NULL)
15611         return;
15612
15613       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15614       if (attr
15615           /* Only create a symbol if this is an external value.
15616              new_symbol checks this and puts the value in the global symbol
15617              table, which we want.  If it is not external, new_symbol
15618              will try to put the value in cu->list_in_scope which is wrong.  */
15619           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15620         {
15621           /* A static const member, not much different than an enum as far as
15622              we're concerned, except that we can support more types.  */
15623           new_symbol (die, NULL, cu);
15624         }
15625
15626       /* Get physical name.  */
15627       physname = dwarf2_physname (fieldname, die, cu);
15628
15629       /* The name is already allocated along with this objfile, so we don't
15630          need to duplicate it for the type.  */
15631       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15632       FIELD_TYPE (*fp) = die_type (die, cu);
15633       FIELD_NAME (*fp) = fieldname;
15634     }
15635   else if (die->tag == DW_TAG_inheritance)
15636     {
15637       LONGEST offset;
15638
15639       /* C++ base class field.  */
15640       if (handle_data_member_location (die, cu, &offset))
15641         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15642       FIELD_BITSIZE (*fp) = 0;
15643       FIELD_TYPE (*fp) = die_type (die, cu);
15644       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15645       fip->nbaseclasses++;
15646     }
15647 }
15648
15649 /* Can the type given by DIE define another type?  */
15650
15651 static bool
15652 type_can_define_types (const struct die_info *die)
15653 {
15654   switch (die->tag)
15655     {
15656     case DW_TAG_typedef:
15657     case DW_TAG_class_type:
15658     case DW_TAG_structure_type:
15659     case DW_TAG_union_type:
15660     case DW_TAG_enumeration_type:
15661       return true;
15662
15663     default:
15664       return false;
15665     }
15666 }
15667
15668 /* Add a type definition defined in the scope of the FIP's class.  */
15669
15670 static void
15671 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15672                       struct dwarf2_cu *cu)
15673 {
15674   struct decl_field_list *new_field;
15675   struct decl_field *fp;
15676
15677   /* Allocate a new field list entry and link it in.  */
15678   new_field = XCNEW (struct decl_field_list);
15679   make_cleanup (xfree, new_field);
15680
15681   gdb_assert (type_can_define_types (die));
15682
15683   fp = &new_field->field;
15684
15685   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15686   fp->name = dwarf2_name (die, cu);
15687   fp->type = read_type_die (die, cu);
15688
15689   /* Save accessibility.  */
15690   enum dwarf_access_attribute accessibility;
15691   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15692   if (attr != NULL)
15693     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15694   else
15695     accessibility = dwarf2_default_access_attribute (die, cu);
15696   switch (accessibility)
15697     {
15698     case DW_ACCESS_public:
15699       /* The assumed value if neither private nor protected.  */
15700       break;
15701     case DW_ACCESS_private:
15702       fp->is_private = 1;
15703       break;
15704     case DW_ACCESS_protected:
15705       fp->is_protected = 1;
15706       break;
15707     default:
15708       complaint (&symfile_complaints,
15709                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15710     }
15711
15712   if (die->tag == DW_TAG_typedef)
15713     {
15714       new_field->next = fip->typedef_field_list;
15715       fip->typedef_field_list = new_field;
15716       fip->typedef_field_list_count++;
15717     }
15718   else
15719     {
15720       new_field->next = fip->nested_types_list;
15721       fip->nested_types_list = new_field;
15722       fip->nested_types_list_count++;
15723     }
15724 }
15725
15726 /* Create the vector of fields, and attach it to the type.  */
15727
15728 static void
15729 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15730                               struct dwarf2_cu *cu)
15731 {
15732   int nfields = fip->nfields;
15733
15734   /* Record the field count, allocate space for the array of fields,
15735      and create blank accessibility bitfields if necessary.  */
15736   TYPE_NFIELDS (type) = nfields;
15737   TYPE_FIELDS (type) = (struct field *)
15738     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15739   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15740
15741   if (fip->non_public_fields && cu->language != language_ada)
15742     {
15743       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15744
15745       TYPE_FIELD_PRIVATE_BITS (type) =
15746         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15747       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15748
15749       TYPE_FIELD_PROTECTED_BITS (type) =
15750         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15751       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15752
15753       TYPE_FIELD_IGNORE_BITS (type) =
15754         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15755       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15756     }
15757
15758   /* If the type has baseclasses, allocate and clear a bit vector for
15759      TYPE_FIELD_VIRTUAL_BITS.  */
15760   if (fip->nbaseclasses && cu->language != language_ada)
15761     {
15762       int num_bytes = B_BYTES (fip->nbaseclasses);
15763       unsigned char *pointer;
15764
15765       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15766       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15767       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15768       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15769       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15770     }
15771
15772   /* Copy the saved-up fields into the field vector.  Start from the head of
15773      the list, adding to the tail of the field array, so that they end up in
15774      the same order in the array in which they were added to the list.  */
15775   while (nfields-- > 0)
15776     {
15777       struct nextfield *fieldp;
15778
15779       if (fip->fields)
15780         {
15781           fieldp = fip->fields;
15782           fip->fields = fieldp->next;
15783         }
15784       else
15785         {
15786           fieldp = fip->baseclasses;
15787           fip->baseclasses = fieldp->next;
15788         }
15789
15790       TYPE_FIELD (type, nfields) = fieldp->field;
15791       switch (fieldp->accessibility)
15792         {
15793         case DW_ACCESS_private:
15794           if (cu->language != language_ada)
15795             SET_TYPE_FIELD_PRIVATE (type, nfields);
15796           break;
15797
15798         case DW_ACCESS_protected:
15799           if (cu->language != language_ada)
15800             SET_TYPE_FIELD_PROTECTED (type, nfields);
15801           break;
15802
15803         case DW_ACCESS_public:
15804           break;
15805
15806         default:
15807           /* Unknown accessibility.  Complain and treat it as public.  */
15808           {
15809             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15810                        fieldp->accessibility);
15811           }
15812           break;
15813         }
15814       if (nfields < fip->nbaseclasses)
15815         {
15816           switch (fieldp->virtuality)
15817             {
15818             case DW_VIRTUALITY_virtual:
15819             case DW_VIRTUALITY_pure_virtual:
15820               if (cu->language == language_ada)
15821                 error (_("unexpected virtuality in component of Ada type"));
15822               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15823               break;
15824             }
15825         }
15826     }
15827 }
15828
15829 /* Return true if this member function is a constructor, false
15830    otherwise.  */
15831
15832 static int
15833 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15834 {
15835   const char *fieldname;
15836   const char *type_name;
15837   int len;
15838
15839   if (die->parent == NULL)
15840     return 0;
15841
15842   if (die->parent->tag != DW_TAG_structure_type
15843       && die->parent->tag != DW_TAG_union_type
15844       && die->parent->tag != DW_TAG_class_type)
15845     return 0;
15846
15847   fieldname = dwarf2_name (die, cu);
15848   type_name = dwarf2_name (die->parent, cu);
15849   if (fieldname == NULL || type_name == NULL)
15850     return 0;
15851
15852   len = strlen (fieldname);
15853   return (strncmp (fieldname, type_name, len) == 0
15854           && (type_name[len] == '\0' || type_name[len] == '<'));
15855 }
15856
15857 /* Add a member function to the proper fieldlist.  */
15858
15859 static void
15860 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15861                       struct type *type, struct dwarf2_cu *cu)
15862 {
15863   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15864   struct attribute *attr;
15865   struct fnfieldlist *flp;
15866   int i;
15867   struct fn_field *fnp;
15868   const char *fieldname;
15869   struct nextfnfield *new_fnfield;
15870   struct type *this_type;
15871   enum dwarf_access_attribute accessibility;
15872
15873   if (cu->language == language_ada)
15874     error (_("unexpected member function in Ada type"));
15875
15876   /* Get name of member function.  */
15877   fieldname = dwarf2_name (die, cu);
15878   if (fieldname == NULL)
15879     return;
15880
15881   /* Look up member function name in fieldlist.  */
15882   for (i = 0; i < fip->nfnfields; i++)
15883     {
15884       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15885         break;
15886     }
15887
15888   /* Create new list element if necessary.  */
15889   if (i < fip->nfnfields)
15890     flp = &fip->fnfieldlists[i];
15891   else
15892     {
15893       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15894         {
15895           fip->fnfieldlists = (struct fnfieldlist *)
15896             xrealloc (fip->fnfieldlists,
15897                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15898                       * sizeof (struct fnfieldlist));
15899           if (fip->nfnfields == 0)
15900             make_cleanup (free_current_contents, &fip->fnfieldlists);
15901         }
15902       flp = &fip->fnfieldlists[fip->nfnfields];
15903       flp->name = fieldname;
15904       flp->length = 0;
15905       flp->head = NULL;
15906       i = fip->nfnfields++;
15907     }
15908
15909   /* Create a new member function field and chain it to the field list
15910      entry.  */
15911   new_fnfield = XNEW (struct nextfnfield);
15912   make_cleanup (xfree, new_fnfield);
15913   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15914   new_fnfield->next = flp->head;
15915   flp->head = new_fnfield;
15916   flp->length++;
15917
15918   /* Fill in the member function field info.  */
15919   fnp = &new_fnfield->fnfield;
15920
15921   /* Delay processing of the physname until later.  */
15922   if (cu->language == language_cplus)
15923     {
15924       add_to_method_list (type, i, flp->length - 1, fieldname,
15925                           die, cu);
15926     }
15927   else
15928     {
15929       const char *physname = dwarf2_physname (fieldname, die, cu);
15930       fnp->physname = physname ? physname : "";
15931     }
15932
15933   fnp->type = alloc_type (objfile);
15934   this_type = read_type_die (die, cu);
15935   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15936     {
15937       int nparams = TYPE_NFIELDS (this_type);
15938
15939       /* TYPE is the domain of this method, and THIS_TYPE is the type
15940            of the method itself (TYPE_CODE_METHOD).  */
15941       smash_to_method_type (fnp->type, type,
15942                             TYPE_TARGET_TYPE (this_type),
15943                             TYPE_FIELDS (this_type),
15944                             TYPE_NFIELDS (this_type),
15945                             TYPE_VARARGS (this_type));
15946
15947       /* Handle static member functions.
15948          Dwarf2 has no clean way to discern C++ static and non-static
15949          member functions.  G++ helps GDB by marking the first
15950          parameter for non-static member functions (which is the this
15951          pointer) as artificial.  We obtain this information from
15952          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15953       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15954         fnp->voffset = VOFFSET_STATIC;
15955     }
15956   else
15957     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15958                dwarf2_full_name (fieldname, die, cu));
15959
15960   /* Get fcontext from DW_AT_containing_type if present.  */
15961   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15962     fnp->fcontext = die_containing_type (die, cu);
15963
15964   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15965      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15966
15967   /* Get accessibility.  */
15968   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15969   if (attr)
15970     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15971   else
15972     accessibility = dwarf2_default_access_attribute (die, cu);
15973   switch (accessibility)
15974     {
15975     case DW_ACCESS_private:
15976       fnp->is_private = 1;
15977       break;
15978     case DW_ACCESS_protected:
15979       fnp->is_protected = 1;
15980       break;
15981     }
15982
15983   /* Check for artificial methods.  */
15984   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15985   if (attr && DW_UNSND (attr) != 0)
15986     fnp->is_artificial = 1;
15987
15988   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15989
15990   /* Get index in virtual function table if it is a virtual member
15991      function.  For older versions of GCC, this is an offset in the
15992      appropriate virtual table, as specified by DW_AT_containing_type.
15993      For everyone else, it is an expression to be evaluated relative
15994      to the object address.  */
15995
15996   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15997   if (attr)
15998     {
15999       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
16000         {
16001           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
16002             {
16003               /* Old-style GCC.  */
16004               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
16005             }
16006           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
16007                    || (DW_BLOCK (attr)->size > 1
16008                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
16009                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
16010             {
16011               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
16012               if ((fnp->voffset % cu->header.addr_size) != 0)
16013                 dwarf2_complex_location_expr_complaint ();
16014               else
16015                 fnp->voffset /= cu->header.addr_size;
16016               fnp->voffset += 2;
16017             }
16018           else
16019             dwarf2_complex_location_expr_complaint ();
16020
16021           if (!fnp->fcontext)
16022             {
16023               /* If there is no `this' field and no DW_AT_containing_type,
16024                  we cannot actually find a base class context for the
16025                  vtable!  */
16026               if (TYPE_NFIELDS (this_type) == 0
16027                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
16028                 {
16029                   complaint (&symfile_complaints,
16030                              _("cannot determine context for virtual member "
16031                                "function \"%s\" (offset %s)"),
16032                              fieldname, sect_offset_str (die->sect_off));
16033                 }
16034               else
16035                 {
16036                   fnp->fcontext
16037                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
16038                 }
16039             }
16040         }
16041       else if (attr_form_is_section_offset (attr))
16042         {
16043           dwarf2_complex_location_expr_complaint ();
16044         }
16045       else
16046         {
16047           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
16048                                                  fieldname);
16049         }
16050     }
16051   else
16052     {
16053       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
16054       if (attr && DW_UNSND (attr))
16055         {
16056           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
16057           complaint (&symfile_complaints,
16058                      _("Member function \"%s\" (offset %s) is virtual "
16059                        "but the vtable offset is not specified"),
16060                      fieldname, sect_offset_str (die->sect_off));
16061           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16062           TYPE_CPLUS_DYNAMIC (type) = 1;
16063         }
16064     }
16065 }
16066
16067 /* Create the vector of member function fields, and attach it to the type.  */
16068
16069 static void
16070 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
16071                                  struct dwarf2_cu *cu)
16072 {
16073   struct fnfieldlist *flp;
16074   int i;
16075
16076   if (cu->language == language_ada)
16077     error (_("unexpected member functions in Ada type"));
16078
16079   ALLOCATE_CPLUS_STRUCT_TYPE (type);
16080   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
16081     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
16082
16083   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
16084     {
16085       struct nextfnfield *nfp = flp->head;
16086       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
16087       int k;
16088
16089       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
16090       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
16091       fn_flp->fn_fields = (struct fn_field *)
16092         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
16093       for (k = flp->length; (k--, nfp); nfp = nfp->next)
16094         fn_flp->fn_fields[k] = nfp->fnfield;
16095     }
16096
16097   TYPE_NFN_FIELDS (type) = fip->nfnfields;
16098 }
16099
16100 /* Returns non-zero if NAME is the name of a vtable member in CU's
16101    language, zero otherwise.  */
16102 static int
16103 is_vtable_name (const char *name, struct dwarf2_cu *cu)
16104 {
16105   static const char vptr[] = "_vptr";
16106
16107   /* Look for the C++ form of the vtable.  */
16108   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
16109     return 1;
16110
16111   return 0;
16112 }
16113
16114 /* GCC outputs unnamed structures that are really pointers to member
16115    functions, with the ABI-specified layout.  If TYPE describes
16116    such a structure, smash it into a member function type.
16117
16118    GCC shouldn't do this; it should just output pointer to member DIEs.
16119    This is GCC PR debug/28767.  */
16120
16121 static void
16122 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
16123 {
16124   struct type *pfn_type, *self_type, *new_type;
16125
16126   /* Check for a structure with no name and two children.  */
16127   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
16128     return;
16129
16130   /* Check for __pfn and __delta members.  */
16131   if (TYPE_FIELD_NAME (type, 0) == NULL
16132       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
16133       || TYPE_FIELD_NAME (type, 1) == NULL
16134       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
16135     return;
16136
16137   /* Find the type of the method.  */
16138   pfn_type = TYPE_FIELD_TYPE (type, 0);
16139   if (pfn_type == NULL
16140       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
16141       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
16142     return;
16143
16144   /* Look for the "this" argument.  */
16145   pfn_type = TYPE_TARGET_TYPE (pfn_type);
16146   if (TYPE_NFIELDS (pfn_type) == 0
16147       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
16148       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
16149     return;
16150
16151   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
16152   new_type = alloc_type (objfile);
16153   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
16154                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
16155                         TYPE_VARARGS (pfn_type));
16156   smash_to_methodptr_type (type, new_type);
16157 }
16158
16159
16160 /* Called when we find the DIE that starts a structure or union scope
16161    (definition) to create a type for the structure or union.  Fill in
16162    the type's name and general properties; the members will not be
16163    processed until process_structure_scope.  A symbol table entry for
16164    the type will also not be done until process_structure_scope (assuming
16165    the type has a name).
16166
16167    NOTE: we need to call these functions regardless of whether or not the
16168    DIE has a DW_AT_name attribute, since it might be an anonymous
16169    structure or union.  This gets the type entered into our set of
16170    user defined types.  */
16171
16172 static struct type *
16173 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
16174 {
16175   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16176   struct type *type;
16177   struct attribute *attr;
16178   const char *name;
16179
16180   /* If the definition of this type lives in .debug_types, read that type.
16181      Don't follow DW_AT_specification though, that will take us back up
16182      the chain and we want to go down.  */
16183   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16184   if (attr)
16185     {
16186       type = get_DW_AT_signature_type (die, attr, cu);
16187
16188       /* The type's CU may not be the same as CU.
16189          Ensure TYPE is recorded with CU in die_type_hash.  */
16190       return set_die_type (die, type, cu);
16191     }
16192
16193   type = alloc_type (objfile);
16194   INIT_CPLUS_SPECIFIC (type);
16195
16196   name = dwarf2_name (die, cu);
16197   if (name != NULL)
16198     {
16199       if (cu->language == language_cplus
16200           || cu->language == language_d
16201           || cu->language == language_rust)
16202         {
16203           const char *full_name = dwarf2_full_name (name, die, cu);
16204
16205           /* dwarf2_full_name might have already finished building the DIE's
16206              type.  If so, there is no need to continue.  */
16207           if (get_die_type (die, cu) != NULL)
16208             return get_die_type (die, cu);
16209
16210           TYPE_TAG_NAME (type) = full_name;
16211           if (die->tag == DW_TAG_structure_type
16212               || die->tag == DW_TAG_class_type)
16213             TYPE_NAME (type) = TYPE_TAG_NAME (type);
16214         }
16215       else
16216         {
16217           /* The name is already allocated along with this objfile, so
16218              we don't need to duplicate it for the type.  */
16219           TYPE_TAG_NAME (type) = name;
16220           if (die->tag == DW_TAG_class_type)
16221             TYPE_NAME (type) = TYPE_TAG_NAME (type);
16222         }
16223     }
16224
16225   if (die->tag == DW_TAG_structure_type)
16226     {
16227       TYPE_CODE (type) = TYPE_CODE_STRUCT;
16228     }
16229   else if (die->tag == DW_TAG_union_type)
16230     {
16231       TYPE_CODE (type) = TYPE_CODE_UNION;
16232     }
16233   else
16234     {
16235       TYPE_CODE (type) = TYPE_CODE_STRUCT;
16236     }
16237
16238   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
16239     TYPE_DECLARED_CLASS (type) = 1;
16240
16241   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16242   if (attr)
16243     {
16244       if (attr_form_is_constant (attr))
16245         TYPE_LENGTH (type) = DW_UNSND (attr);
16246       else
16247         {
16248           /* For the moment, dynamic type sizes are not supported
16249              by GDB's struct type.  The actual size is determined
16250              on-demand when resolving the type of a given object,
16251              so set the type's length to zero for now.  Otherwise,
16252              we record an expression as the length, and that expression
16253              could lead to a very large value, which could eventually
16254              lead to us trying to allocate that much memory when creating
16255              a value of that type.  */
16256           TYPE_LENGTH (type) = 0;
16257         }
16258     }
16259   else
16260     {
16261       TYPE_LENGTH (type) = 0;
16262     }
16263
16264   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
16265     {
16266       /* ICC<14 does not output the required DW_AT_declaration on
16267          incomplete types, but gives them a size of zero.  */
16268       TYPE_STUB (type) = 1;
16269     }
16270   else
16271     TYPE_STUB_SUPPORTED (type) = 1;
16272
16273   if (die_is_declaration (die, cu))
16274     TYPE_STUB (type) = 1;
16275   else if (attr == NULL && die->child == NULL
16276            && producer_is_realview (cu->producer))
16277     /* RealView does not output the required DW_AT_declaration
16278        on incomplete types.  */
16279     TYPE_STUB (type) = 1;
16280
16281   /* We need to add the type field to the die immediately so we don't
16282      infinitely recurse when dealing with pointers to the structure
16283      type within the structure itself.  */
16284   set_die_type (die, type, cu);
16285
16286   /* set_die_type should be already done.  */
16287   set_descriptive_type (type, die, cu);
16288
16289   return type;
16290 }
16291
16292 /* Finish creating a structure or union type, including filling in
16293    its members and creating a symbol for it.  */
16294
16295 static void
16296 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
16297 {
16298   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16299   struct die_info *child_die;
16300   struct type *type;
16301
16302   type = get_die_type (die, cu);
16303   if (type == NULL)
16304     type = read_structure_type (die, cu);
16305
16306   if (die->child != NULL && ! die_is_declaration (die, cu))
16307     {
16308       struct field_info fi;
16309       std::vector<struct symbol *> template_args;
16310       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
16311
16312       memset (&fi, 0, sizeof (struct field_info));
16313
16314       child_die = die->child;
16315
16316       while (child_die && child_die->tag)
16317         {
16318           if (child_die->tag == DW_TAG_member
16319               || child_die->tag == DW_TAG_variable)
16320             {
16321               /* NOTE: carlton/2002-11-05: A C++ static data member
16322                  should be a DW_TAG_member that is a declaration, but
16323                  all versions of G++ as of this writing (so through at
16324                  least 3.2.1) incorrectly generate DW_TAG_variable
16325                  tags for them instead.  */
16326               dwarf2_add_field (&fi, child_die, cu);
16327             }
16328           else if (child_die->tag == DW_TAG_subprogram)
16329             {
16330               /* Rust doesn't have member functions in the C++ sense.
16331                  However, it does emit ordinary functions as children
16332                  of a struct DIE.  */
16333               if (cu->language == language_rust)
16334                 read_func_scope (child_die, cu);
16335               else
16336                 {
16337                   /* C++ member function.  */
16338                   dwarf2_add_member_fn (&fi, child_die, type, cu);
16339                 }
16340             }
16341           else if (child_die->tag == DW_TAG_inheritance)
16342             {
16343               /* C++ base class field.  */
16344               dwarf2_add_field (&fi, child_die, cu);
16345             }
16346           else if (type_can_define_types (child_die))
16347             dwarf2_add_type_defn (&fi, child_die, cu);
16348           else if (child_die->tag == DW_TAG_template_type_param
16349                    || child_die->tag == DW_TAG_template_value_param)
16350             {
16351               struct symbol *arg = new_symbol (child_die, NULL, cu);
16352
16353               if (arg != NULL)
16354                 template_args.push_back (arg);
16355             }
16356
16357           child_die = sibling_die (child_die);
16358         }
16359
16360       /* Attach template arguments to type.  */
16361       if (!template_args.empty ())
16362         {
16363           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16364           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16365           TYPE_TEMPLATE_ARGUMENTS (type)
16366             = XOBNEWVEC (&objfile->objfile_obstack,
16367                          struct symbol *,
16368                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16369           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16370                   template_args.data (),
16371                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16372                    * sizeof (struct symbol *)));
16373         }
16374
16375       /* Attach fields and member functions to the type.  */
16376       if (fi.nfields)
16377         dwarf2_attach_fields_to_type (&fi, type, cu);
16378       if (fi.nfnfields)
16379         {
16380           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16381
16382           /* Get the type which refers to the base class (possibly this
16383              class itself) which contains the vtable pointer for the current
16384              class from the DW_AT_containing_type attribute.  This use of
16385              DW_AT_containing_type is a GNU extension.  */
16386
16387           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16388             {
16389               struct type *t = die_containing_type (die, cu);
16390
16391               set_type_vptr_basetype (type, t);
16392               if (type == t)
16393                 {
16394                   int i;
16395
16396                   /* Our own class provides vtbl ptr.  */
16397                   for (i = TYPE_NFIELDS (t) - 1;
16398                        i >= TYPE_N_BASECLASSES (t);
16399                        --i)
16400                     {
16401                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16402
16403                       if (is_vtable_name (fieldname, cu))
16404                         {
16405                           set_type_vptr_fieldno (type, i);
16406                           break;
16407                         }
16408                     }
16409
16410                   /* Complain if virtual function table field not found.  */
16411                   if (i < TYPE_N_BASECLASSES (t))
16412                     complaint (&symfile_complaints,
16413                                _("virtual function table pointer "
16414                                  "not found when defining class '%s'"),
16415                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16416                                "");
16417                 }
16418               else
16419                 {
16420                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16421                 }
16422             }
16423           else if (cu->producer
16424                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16425             {
16426               /* The IBM XLC compiler does not provide direct indication
16427                  of the containing type, but the vtable pointer is
16428                  always named __vfp.  */
16429
16430               int i;
16431
16432               for (i = TYPE_NFIELDS (type) - 1;
16433                    i >= TYPE_N_BASECLASSES (type);
16434                    --i)
16435                 {
16436                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16437                     {
16438                       set_type_vptr_fieldno (type, i);
16439                       set_type_vptr_basetype (type, type);
16440                       break;
16441                     }
16442                 }
16443             }
16444         }
16445
16446       /* Copy fi.typedef_field_list linked list elements content into the
16447          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16448       if (fi.typedef_field_list)
16449         {
16450           int i = fi.typedef_field_list_count;
16451
16452           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16453           TYPE_TYPEDEF_FIELD_ARRAY (type)
16454             = ((struct decl_field *)
16455                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16456           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16457
16458           /* Reverse the list order to keep the debug info elements order.  */
16459           while (--i >= 0)
16460             {
16461               struct decl_field *dest, *src;
16462
16463               dest = &TYPE_TYPEDEF_FIELD (type, i);
16464               src = &fi.typedef_field_list->field;
16465               fi.typedef_field_list = fi.typedef_field_list->next;
16466               *dest = *src;
16467             }
16468         }
16469
16470       /* Copy fi.nested_types_list linked list elements content into the
16471          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16472       if (fi.nested_types_list != NULL && cu->language != language_ada)
16473         {
16474           int i = fi.nested_types_list_count;
16475
16476           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16477           TYPE_NESTED_TYPES_ARRAY (type)
16478             = ((struct decl_field *)
16479                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16480           TYPE_NESTED_TYPES_COUNT (type) = i;
16481
16482           /* Reverse the list order to keep the debug info elements order.  */
16483           while (--i >= 0)
16484             {
16485               struct decl_field *dest, *src;
16486
16487               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16488               src = &fi.nested_types_list->field;
16489               fi.nested_types_list = fi.nested_types_list->next;
16490               *dest = *src;
16491             }
16492         }
16493
16494       do_cleanups (back_to);
16495     }
16496
16497   quirk_gcc_member_function_pointer (type, objfile);
16498   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16499     cu->rust_unions.push_back (type);
16500
16501   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16502      snapshots) has been known to create a die giving a declaration
16503      for a class that has, as a child, a die giving a definition for a
16504      nested class.  So we have to process our children even if the
16505      current die is a declaration.  Normally, of course, a declaration
16506      won't have any children at all.  */
16507
16508   child_die = die->child;
16509
16510   while (child_die != NULL && child_die->tag)
16511     {
16512       if (child_die->tag == DW_TAG_member
16513           || child_die->tag == DW_TAG_variable
16514           || child_die->tag == DW_TAG_inheritance
16515           || child_die->tag == DW_TAG_template_value_param
16516           || child_die->tag == DW_TAG_template_type_param)
16517         {
16518           /* Do nothing.  */
16519         }
16520       else
16521         process_die (child_die, cu);
16522
16523       child_die = sibling_die (child_die);
16524     }
16525
16526   /* Do not consider external references.  According to the DWARF standard,
16527      these DIEs are identified by the fact that they have no byte_size
16528      attribute, and a declaration attribute.  */
16529   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16530       || !die_is_declaration (die, cu))
16531     new_symbol (die, type, cu);
16532 }
16533
16534 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16535    update TYPE using some information only available in DIE's children.  */
16536
16537 static void
16538 update_enumeration_type_from_children (struct die_info *die,
16539                                        struct type *type,
16540                                        struct dwarf2_cu *cu)
16541 {
16542   struct die_info *child_die;
16543   int unsigned_enum = 1;
16544   int flag_enum = 1;
16545   ULONGEST mask = 0;
16546
16547   auto_obstack obstack;
16548
16549   for (child_die = die->child;
16550        child_die != NULL && child_die->tag;
16551        child_die = sibling_die (child_die))
16552     {
16553       struct attribute *attr;
16554       LONGEST value;
16555       const gdb_byte *bytes;
16556       struct dwarf2_locexpr_baton *baton;
16557       const char *name;
16558
16559       if (child_die->tag != DW_TAG_enumerator)
16560         continue;
16561
16562       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16563       if (attr == NULL)
16564         continue;
16565
16566       name = dwarf2_name (child_die, cu);
16567       if (name == NULL)
16568         name = "<anonymous enumerator>";
16569
16570       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16571                                &value, &bytes, &baton);
16572       if (value < 0)
16573         {
16574           unsigned_enum = 0;
16575           flag_enum = 0;
16576         }
16577       else if ((mask & value) != 0)
16578         flag_enum = 0;
16579       else
16580         mask |= value;
16581
16582       /* If we already know that the enum type is neither unsigned, nor
16583          a flag type, no need to look at the rest of the enumerates.  */
16584       if (!unsigned_enum && !flag_enum)
16585         break;
16586     }
16587
16588   if (unsigned_enum)
16589     TYPE_UNSIGNED (type) = 1;
16590   if (flag_enum)
16591     TYPE_FLAG_ENUM (type) = 1;
16592 }
16593
16594 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16595    complete the type's fields yet, or create any symbols.  */
16596
16597 static struct type *
16598 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16599 {
16600   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16601   struct type *type;
16602   struct attribute *attr;
16603   const char *name;
16604
16605   /* If the definition of this type lives in .debug_types, read that type.
16606      Don't follow DW_AT_specification though, that will take us back up
16607      the chain and we want to go down.  */
16608   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16609   if (attr)
16610     {
16611       type = get_DW_AT_signature_type (die, attr, cu);
16612
16613       /* The type's CU may not be the same as CU.
16614          Ensure TYPE is recorded with CU in die_type_hash.  */
16615       return set_die_type (die, type, cu);
16616     }
16617
16618   type = alloc_type (objfile);
16619
16620   TYPE_CODE (type) = TYPE_CODE_ENUM;
16621   name = dwarf2_full_name (NULL, die, cu);
16622   if (name != NULL)
16623     TYPE_TAG_NAME (type) = name;
16624
16625   attr = dwarf2_attr (die, DW_AT_type, cu);
16626   if (attr != NULL)
16627     {
16628       struct type *underlying_type = die_type (die, cu);
16629
16630       TYPE_TARGET_TYPE (type) = underlying_type;
16631     }
16632
16633   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16634   if (attr)
16635     {
16636       TYPE_LENGTH (type) = DW_UNSND (attr);
16637     }
16638   else
16639     {
16640       TYPE_LENGTH (type) = 0;
16641     }
16642
16643   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16644      declared as private in the package spec, and then defined only
16645      inside the package body.  Such types are known as Taft Amendment
16646      Types.  When another package uses such a type, an incomplete DIE
16647      may be generated by the compiler.  */
16648   if (die_is_declaration (die, cu))
16649     TYPE_STUB (type) = 1;
16650
16651   /* Finish the creation of this type by using the enum's children.
16652      We must call this even when the underlying type has been provided
16653      so that we can determine if we're looking at a "flag" enum.  */
16654   update_enumeration_type_from_children (die, type, cu);
16655
16656   /* If this type has an underlying type that is not a stub, then we
16657      may use its attributes.  We always use the "unsigned" attribute
16658      in this situation, because ordinarily we guess whether the type
16659      is unsigned -- but the guess can be wrong and the underlying type
16660      can tell us the reality.  However, we defer to a local size
16661      attribute if one exists, because this lets the compiler override
16662      the underlying type if needed.  */
16663   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16664     {
16665       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16666       if (TYPE_LENGTH (type) == 0)
16667         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16668     }
16669
16670   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16671
16672   return set_die_type (die, type, cu);
16673 }
16674
16675 /* Given a pointer to a die which begins an enumeration, process all
16676    the dies that define the members of the enumeration, and create the
16677    symbol for the enumeration type.
16678
16679    NOTE: We reverse the order of the element list.  */
16680
16681 static void
16682 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16683 {
16684   struct type *this_type;
16685
16686   this_type = get_die_type (die, cu);
16687   if (this_type == NULL)
16688     this_type = read_enumeration_type (die, cu);
16689
16690   if (die->child != NULL)
16691     {
16692       struct die_info *child_die;
16693       struct symbol *sym;
16694       struct field *fields = NULL;
16695       int num_fields = 0;
16696       const char *name;
16697
16698       child_die = die->child;
16699       while (child_die && child_die->tag)
16700         {
16701           if (child_die->tag != DW_TAG_enumerator)
16702             {
16703               process_die (child_die, cu);
16704             }
16705           else
16706             {
16707               name = dwarf2_name (child_die, cu);
16708               if (name)
16709                 {
16710                   sym = new_symbol (child_die, this_type, cu);
16711
16712                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16713                     {
16714                       fields = (struct field *)
16715                         xrealloc (fields,
16716                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16717                                   * sizeof (struct field));
16718                     }
16719
16720                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16721                   FIELD_TYPE (fields[num_fields]) = NULL;
16722                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16723                   FIELD_BITSIZE (fields[num_fields]) = 0;
16724
16725                   num_fields++;
16726                 }
16727             }
16728
16729           child_die = sibling_die (child_die);
16730         }
16731
16732       if (num_fields)
16733         {
16734           TYPE_NFIELDS (this_type) = num_fields;
16735           TYPE_FIELDS (this_type) = (struct field *)
16736             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16737           memcpy (TYPE_FIELDS (this_type), fields,
16738                   sizeof (struct field) * num_fields);
16739           xfree (fields);
16740         }
16741     }
16742
16743   /* If we are reading an enum from a .debug_types unit, and the enum
16744      is a declaration, and the enum is not the signatured type in the
16745      unit, then we do not want to add a symbol for it.  Adding a
16746      symbol would in some cases obscure the true definition of the
16747      enum, giving users an incomplete type when the definition is
16748      actually available.  Note that we do not want to do this for all
16749      enums which are just declarations, because C++0x allows forward
16750      enum declarations.  */
16751   if (cu->per_cu->is_debug_types
16752       && die_is_declaration (die, cu))
16753     {
16754       struct signatured_type *sig_type;
16755
16756       sig_type = (struct signatured_type *) cu->per_cu;
16757       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16758       if (sig_type->type_offset_in_section != die->sect_off)
16759         return;
16760     }
16761
16762   new_symbol (die, this_type, cu);
16763 }
16764
16765 /* Extract all information from a DW_TAG_array_type DIE and put it in
16766    the DIE's type field.  For now, this only handles one dimensional
16767    arrays.  */
16768
16769 static struct type *
16770 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16771 {
16772   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16773   struct die_info *child_die;
16774   struct type *type;
16775   struct type *element_type, *range_type, *index_type;
16776   struct attribute *attr;
16777   const char *name;
16778   struct dynamic_prop *byte_stride_prop = NULL;
16779   unsigned int bit_stride = 0;
16780
16781   element_type = die_type (die, cu);
16782
16783   /* The die_type call above may have already set the type for this DIE.  */
16784   type = get_die_type (die, cu);
16785   if (type)
16786     return type;
16787
16788   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16789   if (attr != NULL)
16790     {
16791       int stride_ok;
16792
16793       byte_stride_prop
16794         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16795       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16796       if (!stride_ok)
16797         {
16798           complaint (&symfile_complaints,
16799                      _("unable to read array DW_AT_byte_stride "
16800                        " - DIE at %s [in module %s]"),
16801                      sect_offset_str (die->sect_off),
16802                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16803           /* Ignore this attribute.  We will likely not be able to print
16804              arrays of this type correctly, but there is little we can do
16805              to help if we cannot read the attribute's value.  */
16806           byte_stride_prop = NULL;
16807         }
16808     }
16809
16810   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16811   if (attr != NULL)
16812     bit_stride = DW_UNSND (attr);
16813
16814   /* Irix 6.2 native cc creates array types without children for
16815      arrays with unspecified length.  */
16816   if (die->child == NULL)
16817     {
16818       index_type = objfile_type (objfile)->builtin_int;
16819       range_type = create_static_range_type (NULL, index_type, 0, -1);
16820       type = create_array_type_with_stride (NULL, element_type, range_type,
16821                                             byte_stride_prop, bit_stride);
16822       return set_die_type (die, type, cu);
16823     }
16824
16825   std::vector<struct type *> range_types;
16826   child_die = die->child;
16827   while (child_die && child_die->tag)
16828     {
16829       if (child_die->tag == DW_TAG_subrange_type)
16830         {
16831           struct type *child_type = read_type_die (child_die, cu);
16832
16833           if (child_type != NULL)
16834             {
16835               /* The range type was succesfully read.  Save it for the
16836                  array type creation.  */
16837               range_types.push_back (child_type);
16838             }
16839         }
16840       child_die = sibling_die (child_die);
16841     }
16842
16843   /* Dwarf2 dimensions are output from left to right, create the
16844      necessary array types in backwards order.  */
16845
16846   type = element_type;
16847
16848   if (read_array_order (die, cu) == DW_ORD_col_major)
16849     {
16850       int i = 0;
16851
16852       while (i < range_types.size ())
16853         type = create_array_type_with_stride (NULL, type, range_types[i++],
16854                                               byte_stride_prop, bit_stride);
16855     }
16856   else
16857     {
16858       size_t ndim = range_types.size ();
16859       while (ndim-- > 0)
16860         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16861                                               byte_stride_prop, bit_stride);
16862     }
16863
16864   /* Understand Dwarf2 support for vector types (like they occur on
16865      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16866      array type.  This is not part of the Dwarf2/3 standard yet, but a
16867      custom vendor extension.  The main difference between a regular
16868      array and the vector variant is that vectors are passed by value
16869      to functions.  */
16870   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16871   if (attr)
16872     make_vector_type (type);
16873
16874   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16875      implementation may choose to implement triple vectors using this
16876      attribute.  */
16877   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16878   if (attr)
16879     {
16880       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16881         TYPE_LENGTH (type) = DW_UNSND (attr);
16882       else
16883         complaint (&symfile_complaints,
16884                    _("DW_AT_byte_size for array type smaller "
16885                      "than the total size of elements"));
16886     }
16887
16888   name = dwarf2_name (die, cu);
16889   if (name)
16890     TYPE_NAME (type) = name;
16891
16892   /* Install the type in the die.  */
16893   set_die_type (die, type, cu);
16894
16895   /* set_die_type should be already done.  */
16896   set_descriptive_type (type, die, cu);
16897
16898   return type;
16899 }
16900
16901 static enum dwarf_array_dim_ordering
16902 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16903 {
16904   struct attribute *attr;
16905
16906   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16907
16908   if (attr)
16909     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16910
16911   /* GNU F77 is a special case, as at 08/2004 array type info is the
16912      opposite order to the dwarf2 specification, but data is still
16913      laid out as per normal fortran.
16914
16915      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16916      version checking.  */
16917
16918   if (cu->language == language_fortran
16919       && cu->producer && strstr (cu->producer, "GNU F77"))
16920     {
16921       return DW_ORD_row_major;
16922     }
16923
16924   switch (cu->language_defn->la_array_ordering)
16925     {
16926     case array_column_major:
16927       return DW_ORD_col_major;
16928     case array_row_major:
16929     default:
16930       return DW_ORD_row_major;
16931     };
16932 }
16933
16934 /* Extract all information from a DW_TAG_set_type DIE and put it in
16935    the DIE's type field.  */
16936
16937 static struct type *
16938 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16939 {
16940   struct type *domain_type, *set_type;
16941   struct attribute *attr;
16942
16943   domain_type = die_type (die, cu);
16944
16945   /* The die_type call above may have already set the type for this DIE.  */
16946   set_type = get_die_type (die, cu);
16947   if (set_type)
16948     return set_type;
16949
16950   set_type = create_set_type (NULL, domain_type);
16951
16952   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16953   if (attr)
16954     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16955
16956   return set_die_type (die, set_type, cu);
16957 }
16958
16959 /* A helper for read_common_block that creates a locexpr baton.
16960    SYM is the symbol which we are marking as computed.
16961    COMMON_DIE is the DIE for the common block.
16962    COMMON_LOC is the location expression attribute for the common
16963    block itself.
16964    MEMBER_LOC is the location expression attribute for the particular
16965    member of the common block that we are processing.
16966    CU is the CU from which the above come.  */
16967
16968 static void
16969 mark_common_block_symbol_computed (struct symbol *sym,
16970                                    struct die_info *common_die,
16971                                    struct attribute *common_loc,
16972                                    struct attribute *member_loc,
16973                                    struct dwarf2_cu *cu)
16974 {
16975   struct dwarf2_per_objfile *dwarf2_per_objfile
16976     = cu->per_cu->dwarf2_per_objfile;
16977   struct objfile *objfile = dwarf2_per_objfile->objfile;
16978   struct dwarf2_locexpr_baton *baton;
16979   gdb_byte *ptr;
16980   unsigned int cu_off;
16981   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16982   LONGEST offset = 0;
16983
16984   gdb_assert (common_loc && member_loc);
16985   gdb_assert (attr_form_is_block (common_loc));
16986   gdb_assert (attr_form_is_block (member_loc)
16987               || attr_form_is_constant (member_loc));
16988
16989   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16990   baton->per_cu = cu->per_cu;
16991   gdb_assert (baton->per_cu);
16992
16993   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16994
16995   if (attr_form_is_constant (member_loc))
16996     {
16997       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16998       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16999     }
17000   else
17001     baton->size += DW_BLOCK (member_loc)->size;
17002
17003   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
17004   baton->data = ptr;
17005
17006   *ptr++ = DW_OP_call4;
17007   cu_off = common_die->sect_off - cu->per_cu->sect_off;
17008   store_unsigned_integer (ptr, 4, byte_order, cu_off);
17009   ptr += 4;
17010
17011   if (attr_form_is_constant (member_loc))
17012     {
17013       *ptr++ = DW_OP_addr;
17014       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
17015       ptr += cu->header.addr_size;
17016     }
17017   else
17018     {
17019       /* We have to copy the data here, because DW_OP_call4 will only
17020          use a DW_AT_location attribute.  */
17021       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
17022       ptr += DW_BLOCK (member_loc)->size;
17023     }
17024
17025   *ptr++ = DW_OP_plus;
17026   gdb_assert (ptr - baton->data == baton->size);
17027
17028   SYMBOL_LOCATION_BATON (sym) = baton;
17029   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17030 }
17031
17032 /* Create appropriate locally-scoped variables for all the
17033    DW_TAG_common_block entries.  Also create a struct common_block
17034    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
17035    is used to sepate the common blocks name namespace from regular
17036    variable names.  */
17037
17038 static void
17039 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
17040 {
17041   struct attribute *attr;
17042
17043   attr = dwarf2_attr (die, DW_AT_location, cu);
17044   if (attr)
17045     {
17046       /* Support the .debug_loc offsets.  */
17047       if (attr_form_is_block (attr))
17048         {
17049           /* Ok.  */
17050         }
17051       else if (attr_form_is_section_offset (attr))
17052         {
17053           dwarf2_complex_location_expr_complaint ();
17054           attr = NULL;
17055         }
17056       else
17057         {
17058           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17059                                                  "common block member");
17060           attr = NULL;
17061         }
17062     }
17063
17064   if (die->child != NULL)
17065     {
17066       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17067       struct die_info *child_die;
17068       size_t n_entries = 0, size;
17069       struct common_block *common_block;
17070       struct symbol *sym;
17071
17072       for (child_die = die->child;
17073            child_die && child_die->tag;
17074            child_die = sibling_die (child_die))
17075         ++n_entries;
17076
17077       size = (sizeof (struct common_block)
17078               + (n_entries - 1) * sizeof (struct symbol *));
17079       common_block
17080         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
17081                                                  size);
17082       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
17083       common_block->n_entries = 0;
17084
17085       for (child_die = die->child;
17086            child_die && child_die->tag;
17087            child_die = sibling_die (child_die))
17088         {
17089           /* Create the symbol in the DW_TAG_common_block block in the current
17090              symbol scope.  */
17091           sym = new_symbol (child_die, NULL, cu);
17092           if (sym != NULL)
17093             {
17094               struct attribute *member_loc;
17095
17096               common_block->contents[common_block->n_entries++] = sym;
17097
17098               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
17099                                         cu);
17100               if (member_loc)
17101                 {
17102                   /* GDB has handled this for a long time, but it is
17103                      not specified by DWARF.  It seems to have been
17104                      emitted by gfortran at least as recently as:
17105                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
17106                   complaint (&symfile_complaints,
17107                              _("Variable in common block has "
17108                                "DW_AT_data_member_location "
17109                                "- DIE at %s [in module %s]"),
17110                                sect_offset_str (child_die->sect_off),
17111                              objfile_name (objfile));
17112
17113                   if (attr_form_is_section_offset (member_loc))
17114                     dwarf2_complex_location_expr_complaint ();
17115                   else if (attr_form_is_constant (member_loc)
17116                            || attr_form_is_block (member_loc))
17117                     {
17118                       if (attr)
17119                         mark_common_block_symbol_computed (sym, die, attr,
17120                                                            member_loc, cu);
17121                     }
17122                   else
17123                     dwarf2_complex_location_expr_complaint ();
17124                 }
17125             }
17126         }
17127
17128       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
17129       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
17130     }
17131 }
17132
17133 /* Create a type for a C++ namespace.  */
17134
17135 static struct type *
17136 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
17137 {
17138   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17139   const char *previous_prefix, *name;
17140   int is_anonymous;
17141   struct type *type;
17142
17143   /* For extensions, reuse the type of the original namespace.  */
17144   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
17145     {
17146       struct die_info *ext_die;
17147       struct dwarf2_cu *ext_cu = cu;
17148
17149       ext_die = dwarf2_extension (die, &ext_cu);
17150       type = read_type_die (ext_die, ext_cu);
17151
17152       /* EXT_CU may not be the same as CU.
17153          Ensure TYPE is recorded with CU in die_type_hash.  */
17154       return set_die_type (die, type, cu);
17155     }
17156
17157   name = namespace_name (die, &is_anonymous, cu);
17158
17159   /* Now build the name of the current namespace.  */
17160
17161   previous_prefix = determine_prefix (die, cu);
17162   if (previous_prefix[0] != '\0')
17163     name = typename_concat (&objfile->objfile_obstack,
17164                             previous_prefix, name, 0, cu);
17165
17166   /* Create the type.  */
17167   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
17168   TYPE_TAG_NAME (type) = TYPE_NAME (type);
17169
17170   return set_die_type (die, type, cu);
17171 }
17172
17173 /* Read a namespace scope.  */
17174
17175 static void
17176 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
17177 {
17178   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17179   int is_anonymous;
17180
17181   /* Add a symbol associated to this if we haven't seen the namespace
17182      before.  Also, add a using directive if it's an anonymous
17183      namespace.  */
17184
17185   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
17186     {
17187       struct type *type;
17188
17189       type = read_type_die (die, cu);
17190       new_symbol (die, type, cu);
17191
17192       namespace_name (die, &is_anonymous, cu);
17193       if (is_anonymous)
17194         {
17195           const char *previous_prefix = determine_prefix (die, cu);
17196
17197           std::vector<const char *> excludes;
17198           add_using_directive (using_directives (cu->language),
17199                                previous_prefix, TYPE_NAME (type), NULL,
17200                                NULL, excludes, 0, &objfile->objfile_obstack);
17201         }
17202     }
17203
17204   if (die->child != NULL)
17205     {
17206       struct die_info *child_die = die->child;
17207
17208       while (child_die && child_die->tag)
17209         {
17210           process_die (child_die, cu);
17211           child_die = sibling_die (child_die);
17212         }
17213     }
17214 }
17215
17216 /* Read a Fortran module as type.  This DIE can be only a declaration used for
17217    imported module.  Still we need that type as local Fortran "use ... only"
17218    declaration imports depend on the created type in determine_prefix.  */
17219
17220 static struct type *
17221 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
17222 {
17223   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17224   const char *module_name;
17225   struct type *type;
17226
17227   module_name = dwarf2_name (die, cu);
17228   if (!module_name)
17229     complaint (&symfile_complaints,
17230                _("DW_TAG_module has no name, offset %s"),
17231                sect_offset_str (die->sect_off));
17232   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
17233
17234   /* determine_prefix uses TYPE_TAG_NAME.  */
17235   TYPE_TAG_NAME (type) = TYPE_NAME (type);
17236
17237   return set_die_type (die, type, cu);
17238 }
17239
17240 /* Read a Fortran module.  */
17241
17242 static void
17243 read_module (struct die_info *die, struct dwarf2_cu *cu)
17244 {
17245   struct die_info *child_die = die->child;
17246   struct type *type;
17247
17248   type = read_type_die (die, cu);
17249   new_symbol (die, type, cu);
17250
17251   while (child_die && child_die->tag)
17252     {
17253       process_die (child_die, cu);
17254       child_die = sibling_die (child_die);
17255     }
17256 }
17257
17258 /* Return the name of the namespace represented by DIE.  Set
17259    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
17260    namespace.  */
17261
17262 static const char *
17263 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
17264 {
17265   struct die_info *current_die;
17266   const char *name = NULL;
17267
17268   /* Loop through the extensions until we find a name.  */
17269
17270   for (current_die = die;
17271        current_die != NULL;
17272        current_die = dwarf2_extension (die, &cu))
17273     {
17274       /* We don't use dwarf2_name here so that we can detect the absence
17275          of a name -> anonymous namespace.  */
17276       name = dwarf2_string_attr (die, DW_AT_name, cu);
17277
17278       if (name != NULL)
17279         break;
17280     }
17281
17282   /* Is it an anonymous namespace?  */
17283
17284   *is_anonymous = (name == NULL);
17285   if (*is_anonymous)
17286     name = CP_ANONYMOUS_NAMESPACE_STR;
17287
17288   return name;
17289 }
17290
17291 /* Extract all information from a DW_TAG_pointer_type DIE and add to
17292    the user defined type vector.  */
17293
17294 static struct type *
17295 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
17296 {
17297   struct gdbarch *gdbarch
17298     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
17299   struct comp_unit_head *cu_header = &cu->header;
17300   struct type *type;
17301   struct attribute *attr_byte_size;
17302   struct attribute *attr_address_class;
17303   int byte_size, addr_class;
17304   struct type *target_type;
17305
17306   target_type = die_type (die, cu);
17307
17308   /* The die_type call above may have already set the type for this DIE.  */
17309   type = get_die_type (die, cu);
17310   if (type)
17311     return type;
17312
17313   type = lookup_pointer_type (target_type);
17314
17315   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17316   if (attr_byte_size)
17317     byte_size = DW_UNSND (attr_byte_size);
17318   else
17319     byte_size = cu_header->addr_size;
17320
17321   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17322   if (attr_address_class)
17323     addr_class = DW_UNSND (attr_address_class);
17324   else
17325     addr_class = DW_ADDR_none;
17326
17327   /* If the pointer size or address class is different than the
17328      default, create a type variant marked as such and set the
17329      length accordingly.  */
17330   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17331     {
17332       if (gdbarch_address_class_type_flags_p (gdbarch))
17333         {
17334           int type_flags;
17335
17336           type_flags = gdbarch_address_class_type_flags
17337                          (gdbarch, byte_size, addr_class);
17338           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17339                       == 0);
17340           type = make_type_with_address_space (type, type_flags);
17341         }
17342       else if (TYPE_LENGTH (type) != byte_size)
17343         {
17344           complaint (&symfile_complaints,
17345                      _("invalid pointer size %d"), byte_size);
17346         }
17347       else
17348         {
17349           /* Should we also complain about unhandled address classes?  */
17350         }
17351     }
17352
17353   TYPE_LENGTH (type) = byte_size;
17354   return set_die_type (die, type, cu);
17355 }
17356
17357 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17358    the user defined type vector.  */
17359
17360 static struct type *
17361 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17362 {
17363   struct type *type;
17364   struct type *to_type;
17365   struct type *domain;
17366
17367   to_type = die_type (die, cu);
17368   domain = die_containing_type (die, cu);
17369
17370   /* The calls above may have already set the type for this DIE.  */
17371   type = get_die_type (die, cu);
17372   if (type)
17373     return type;
17374
17375   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17376     type = lookup_methodptr_type (to_type);
17377   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17378     {
17379       struct type *new_type
17380         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17381
17382       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17383                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17384                             TYPE_VARARGS (to_type));
17385       type = lookup_methodptr_type (new_type);
17386     }
17387   else
17388     type = lookup_memberptr_type (to_type, domain);
17389
17390   return set_die_type (die, type, cu);
17391 }
17392
17393 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17394    the user defined type vector.  */
17395
17396 static struct type *
17397 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17398                           enum type_code refcode)
17399 {
17400   struct comp_unit_head *cu_header = &cu->header;
17401   struct type *type, *target_type;
17402   struct attribute *attr;
17403
17404   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17405
17406   target_type = die_type (die, cu);
17407
17408   /* The die_type call above may have already set the type for this DIE.  */
17409   type = get_die_type (die, cu);
17410   if (type)
17411     return type;
17412
17413   type = lookup_reference_type (target_type, refcode);
17414   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17415   if (attr)
17416     {
17417       TYPE_LENGTH (type) = DW_UNSND (attr);
17418     }
17419   else
17420     {
17421       TYPE_LENGTH (type) = cu_header->addr_size;
17422     }
17423   return set_die_type (die, type, cu);
17424 }
17425
17426 /* Add the given cv-qualifiers to the element type of the array.  GCC
17427    outputs DWARF type qualifiers that apply to an array, not the
17428    element type.  But GDB relies on the array element type to carry
17429    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17430    specification.  */
17431
17432 static struct type *
17433 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17434                    struct type *base_type, int cnst, int voltl)
17435 {
17436   struct type *el_type, *inner_array;
17437
17438   base_type = copy_type (base_type);
17439   inner_array = base_type;
17440
17441   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17442     {
17443       TYPE_TARGET_TYPE (inner_array) =
17444         copy_type (TYPE_TARGET_TYPE (inner_array));
17445       inner_array = TYPE_TARGET_TYPE (inner_array);
17446     }
17447
17448   el_type = TYPE_TARGET_TYPE (inner_array);
17449   cnst |= TYPE_CONST (el_type);
17450   voltl |= TYPE_VOLATILE (el_type);
17451   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17452
17453   return set_die_type (die, base_type, cu);
17454 }
17455
17456 static struct type *
17457 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17458 {
17459   struct type *base_type, *cv_type;
17460
17461   base_type = die_type (die, cu);
17462
17463   /* The die_type call above may have already set the type for this DIE.  */
17464   cv_type = get_die_type (die, cu);
17465   if (cv_type)
17466     return cv_type;
17467
17468   /* In case the const qualifier is applied to an array type, the element type
17469      is so qualified, not the array type (section 6.7.3 of C99).  */
17470   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17471     return add_array_cv_type (die, cu, base_type, 1, 0);
17472
17473   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17474   return set_die_type (die, cv_type, cu);
17475 }
17476
17477 static struct type *
17478 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17479 {
17480   struct type *base_type, *cv_type;
17481
17482   base_type = die_type (die, cu);
17483
17484   /* The die_type call above may have already set the type for this DIE.  */
17485   cv_type = get_die_type (die, cu);
17486   if (cv_type)
17487     return cv_type;
17488
17489   /* In case the volatile qualifier is applied to an array type, the
17490      element type is so qualified, not the array type (section 6.7.3
17491      of C99).  */
17492   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17493     return add_array_cv_type (die, cu, base_type, 0, 1);
17494
17495   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17496   return set_die_type (die, cv_type, cu);
17497 }
17498
17499 /* Handle DW_TAG_restrict_type.  */
17500
17501 static struct type *
17502 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17503 {
17504   struct type *base_type, *cv_type;
17505
17506   base_type = die_type (die, cu);
17507
17508   /* The die_type call above may have already set the type for this DIE.  */
17509   cv_type = get_die_type (die, cu);
17510   if (cv_type)
17511     return cv_type;
17512
17513   cv_type = make_restrict_type (base_type);
17514   return set_die_type (die, cv_type, cu);
17515 }
17516
17517 /* Handle DW_TAG_atomic_type.  */
17518
17519 static struct type *
17520 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17521 {
17522   struct type *base_type, *cv_type;
17523
17524   base_type = die_type (die, cu);
17525
17526   /* The die_type call above may have already set the type for this DIE.  */
17527   cv_type = get_die_type (die, cu);
17528   if (cv_type)
17529     return cv_type;
17530
17531   cv_type = make_atomic_type (base_type);
17532   return set_die_type (die, cv_type, cu);
17533 }
17534
17535 /* Extract all information from a DW_TAG_string_type DIE and add to
17536    the user defined type vector.  It isn't really a user defined type,
17537    but it behaves like one, with other DIE's using an AT_user_def_type
17538    attribute to reference it.  */
17539
17540 static struct type *
17541 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17542 {
17543   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17544   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17545   struct type *type, *range_type, *index_type, *char_type;
17546   struct attribute *attr;
17547   unsigned int length;
17548
17549   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17550   if (attr)
17551     {
17552       length = DW_UNSND (attr);
17553     }
17554   else
17555     {
17556       /* Check for the DW_AT_byte_size attribute.  */
17557       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17558       if (attr)
17559         {
17560           length = DW_UNSND (attr);
17561         }
17562       else
17563         {
17564           length = 1;
17565         }
17566     }
17567
17568   index_type = objfile_type (objfile)->builtin_int;
17569   range_type = create_static_range_type (NULL, index_type, 1, length);
17570   char_type = language_string_char_type (cu->language_defn, gdbarch);
17571   type = create_string_type (NULL, char_type, range_type);
17572
17573   return set_die_type (die, type, cu);
17574 }
17575
17576 /* Assuming that DIE corresponds to a function, returns nonzero
17577    if the function is prototyped.  */
17578
17579 static int
17580 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17581 {
17582   struct attribute *attr;
17583
17584   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17585   if (attr && (DW_UNSND (attr) != 0))
17586     return 1;
17587
17588   /* The DWARF standard implies that the DW_AT_prototyped attribute
17589      is only meaninful for C, but the concept also extends to other
17590      languages that allow unprototyped functions (Eg: Objective C).
17591      For all other languages, assume that functions are always
17592      prototyped.  */
17593   if (cu->language != language_c
17594       && cu->language != language_objc
17595       && cu->language != language_opencl)
17596     return 1;
17597
17598   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17599      prototyped and unprototyped functions; default to prototyped,
17600      since that is more common in modern code (and RealView warns
17601      about unprototyped functions).  */
17602   if (producer_is_realview (cu->producer))
17603     return 1;
17604
17605   return 0;
17606 }
17607
17608 /* Handle DIES due to C code like:
17609
17610    struct foo
17611    {
17612    int (*funcp)(int a, long l);
17613    int b;
17614    };
17615
17616    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17617
17618 static struct type *
17619 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17620 {
17621   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17622   struct type *type;            /* Type that this function returns.  */
17623   struct type *ftype;           /* Function that returns above type.  */
17624   struct attribute *attr;
17625
17626   type = die_type (die, cu);
17627
17628   /* The die_type call above may have already set the type for this DIE.  */
17629   ftype = get_die_type (die, cu);
17630   if (ftype)
17631     return ftype;
17632
17633   ftype = lookup_function_type (type);
17634
17635   if (prototyped_function_p (die, cu))
17636     TYPE_PROTOTYPED (ftype) = 1;
17637
17638   /* Store the calling convention in the type if it's available in
17639      the subroutine die.  Otherwise set the calling convention to
17640      the default value DW_CC_normal.  */
17641   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17642   if (attr)
17643     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17644   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17645     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17646   else
17647     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17648
17649   /* Record whether the function returns normally to its caller or not
17650      if the DWARF producer set that information.  */
17651   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17652   if (attr && (DW_UNSND (attr) != 0))
17653     TYPE_NO_RETURN (ftype) = 1;
17654
17655   /* We need to add the subroutine type to the die immediately so
17656      we don't infinitely recurse when dealing with parameters
17657      declared as the same subroutine type.  */
17658   set_die_type (die, ftype, cu);
17659
17660   if (die->child != NULL)
17661     {
17662       struct type *void_type = objfile_type (objfile)->builtin_void;
17663       struct die_info *child_die;
17664       int nparams, iparams;
17665
17666       /* Count the number of parameters.
17667          FIXME: GDB currently ignores vararg functions, but knows about
17668          vararg member functions.  */
17669       nparams = 0;
17670       child_die = die->child;
17671       while (child_die && child_die->tag)
17672         {
17673           if (child_die->tag == DW_TAG_formal_parameter)
17674             nparams++;
17675           else if (child_die->tag == DW_TAG_unspecified_parameters)
17676             TYPE_VARARGS (ftype) = 1;
17677           child_die = sibling_die (child_die);
17678         }
17679
17680       /* Allocate storage for parameters and fill them in.  */
17681       TYPE_NFIELDS (ftype) = nparams;
17682       TYPE_FIELDS (ftype) = (struct field *)
17683         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17684
17685       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17686          even if we error out during the parameters reading below.  */
17687       for (iparams = 0; iparams < nparams; iparams++)
17688         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17689
17690       iparams = 0;
17691       child_die = die->child;
17692       while (child_die && child_die->tag)
17693         {
17694           if (child_die->tag == DW_TAG_formal_parameter)
17695             {
17696               struct type *arg_type;
17697
17698               /* DWARF version 2 has no clean way to discern C++
17699                  static and non-static member functions.  G++ helps
17700                  GDB by marking the first parameter for non-static
17701                  member functions (which is the this pointer) as
17702                  artificial.  We pass this information to
17703                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17704
17705                  DWARF version 3 added DW_AT_object_pointer, which GCC
17706                  4.5 does not yet generate.  */
17707               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17708               if (attr)
17709                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17710               else
17711                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17712               arg_type = die_type (child_die, cu);
17713
17714               /* RealView does not mark THIS as const, which the testsuite
17715                  expects.  GCC marks THIS as const in method definitions,
17716                  but not in the class specifications (GCC PR 43053).  */
17717               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17718                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17719                 {
17720                   int is_this = 0;
17721                   struct dwarf2_cu *arg_cu = cu;
17722                   const char *name = dwarf2_name (child_die, cu);
17723
17724                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17725                   if (attr)
17726                     {
17727                       /* If the compiler emits this, use it.  */
17728                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17729                         is_this = 1;
17730                     }
17731                   else if (name && strcmp (name, "this") == 0)
17732                     /* Function definitions will have the argument names.  */
17733                     is_this = 1;
17734                   else if (name == NULL && iparams == 0)
17735                     /* Declarations may not have the names, so like
17736                        elsewhere in GDB, assume an artificial first
17737                        argument is "this".  */
17738                     is_this = 1;
17739
17740                   if (is_this)
17741                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17742                                              arg_type, 0);
17743                 }
17744
17745               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17746               iparams++;
17747             }
17748           child_die = sibling_die (child_die);
17749         }
17750     }
17751
17752   return ftype;
17753 }
17754
17755 static struct type *
17756 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17757 {
17758   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17759   const char *name = NULL;
17760   struct type *this_type, *target_type;
17761
17762   name = dwarf2_full_name (NULL, die, cu);
17763   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17764   TYPE_TARGET_STUB (this_type) = 1;
17765   set_die_type (die, this_type, cu);
17766   target_type = die_type (die, cu);
17767   if (target_type != this_type)
17768     TYPE_TARGET_TYPE (this_type) = target_type;
17769   else
17770     {
17771       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17772          spec and cause infinite loops in GDB.  */
17773       complaint (&symfile_complaints,
17774                  _("Self-referential DW_TAG_typedef "
17775                    "- DIE at %s [in module %s]"),
17776                  sect_offset_str (die->sect_off), objfile_name (objfile));
17777       TYPE_TARGET_TYPE (this_type) = NULL;
17778     }
17779   return this_type;
17780 }
17781
17782 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17783    (which may be different from NAME) to the architecture back-end to allow
17784    it to guess the correct format if necessary.  */
17785
17786 static struct type *
17787 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17788                         const char *name_hint)
17789 {
17790   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17791   const struct floatformat **format;
17792   struct type *type;
17793
17794   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17795   if (format)
17796     type = init_float_type (objfile, bits, name, format);
17797   else
17798     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17799
17800   return type;
17801 }
17802
17803 /* Find a representation of a given base type and install
17804    it in the TYPE field of the die.  */
17805
17806 static struct type *
17807 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17808 {
17809   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17810   struct type *type;
17811   struct attribute *attr;
17812   int encoding = 0, bits = 0;
17813   const char *name;
17814
17815   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17816   if (attr)
17817     {
17818       encoding = DW_UNSND (attr);
17819     }
17820   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17821   if (attr)
17822     {
17823       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17824     }
17825   name = dwarf2_name (die, cu);
17826   if (!name)
17827     {
17828       complaint (&symfile_complaints,
17829                  _("DW_AT_name missing from DW_TAG_base_type"));
17830     }
17831
17832   switch (encoding)
17833     {
17834       case DW_ATE_address:
17835         /* Turn DW_ATE_address into a void * pointer.  */
17836         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17837         type = init_pointer_type (objfile, bits, name, type);
17838         break;
17839       case DW_ATE_boolean:
17840         type = init_boolean_type (objfile, bits, 1, name);
17841         break;
17842       case DW_ATE_complex_float:
17843         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17844         type = init_complex_type (objfile, name, type);
17845         break;
17846       case DW_ATE_decimal_float:
17847         type = init_decfloat_type (objfile, bits, name);
17848         break;
17849       case DW_ATE_float:
17850         type = dwarf2_init_float_type (objfile, bits, name, name);
17851         break;
17852       case DW_ATE_signed:
17853         type = init_integer_type (objfile, bits, 0, name);
17854         break;
17855       case DW_ATE_unsigned:
17856         if (cu->language == language_fortran
17857             && name
17858             && startswith (name, "character("))
17859           type = init_character_type (objfile, bits, 1, name);
17860         else
17861           type = init_integer_type (objfile, bits, 1, name);
17862         break;
17863       case DW_ATE_signed_char:
17864         if (cu->language == language_ada || cu->language == language_m2
17865             || cu->language == language_pascal
17866             || cu->language == language_fortran)
17867           type = init_character_type (objfile, bits, 0, name);
17868         else
17869           type = init_integer_type (objfile, bits, 0, name);
17870         break;
17871       case DW_ATE_unsigned_char:
17872         if (cu->language == language_ada || cu->language == language_m2
17873             || cu->language == language_pascal
17874             || cu->language == language_fortran
17875             || cu->language == language_rust)
17876           type = init_character_type (objfile, bits, 1, name);
17877         else
17878           type = init_integer_type (objfile, bits, 1, name);
17879         break;
17880       case DW_ATE_UTF:
17881         {
17882           gdbarch *arch = get_objfile_arch (objfile);
17883
17884           if (bits == 16)
17885             type = builtin_type (arch)->builtin_char16;
17886           else if (bits == 32)
17887             type = builtin_type (arch)->builtin_char32;
17888           else
17889             {
17890               complaint (&symfile_complaints,
17891                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17892                          bits);
17893               type = init_integer_type (objfile, bits, 1, name);
17894             }
17895           return set_die_type (die, type, cu);
17896         }
17897         break;
17898
17899       default:
17900         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17901                    dwarf_type_encoding_name (encoding));
17902         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17903         break;
17904     }
17905
17906   if (name && strcmp (name, "char") == 0)
17907     TYPE_NOSIGN (type) = 1;
17908
17909   return set_die_type (die, type, cu);
17910 }
17911
17912 /* Parse dwarf attribute if it's a block, reference or constant and put the
17913    resulting value of the attribute into struct bound_prop.
17914    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17915
17916 static int
17917 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17918                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17919 {
17920   struct dwarf2_property_baton *baton;
17921   struct obstack *obstack
17922     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17923
17924   if (attr == NULL || prop == NULL)
17925     return 0;
17926
17927   if (attr_form_is_block (attr))
17928     {
17929       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17930       baton->referenced_type = NULL;
17931       baton->locexpr.per_cu = cu->per_cu;
17932       baton->locexpr.size = DW_BLOCK (attr)->size;
17933       baton->locexpr.data = DW_BLOCK (attr)->data;
17934       prop->data.baton = baton;
17935       prop->kind = PROP_LOCEXPR;
17936       gdb_assert (prop->data.baton != NULL);
17937     }
17938   else if (attr_form_is_ref (attr))
17939     {
17940       struct dwarf2_cu *target_cu = cu;
17941       struct die_info *target_die;
17942       struct attribute *target_attr;
17943
17944       target_die = follow_die_ref (die, attr, &target_cu);
17945       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17946       if (target_attr == NULL)
17947         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17948                                    target_cu);
17949       if (target_attr == NULL)
17950         return 0;
17951
17952       switch (target_attr->name)
17953         {
17954           case DW_AT_location:
17955             if (attr_form_is_section_offset (target_attr))
17956               {
17957                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17958                 baton->referenced_type = die_type (target_die, target_cu);
17959                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17960                 prop->data.baton = baton;
17961                 prop->kind = PROP_LOCLIST;
17962                 gdb_assert (prop->data.baton != NULL);
17963               }
17964             else if (attr_form_is_block (target_attr))
17965               {
17966                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17967                 baton->referenced_type = die_type (target_die, target_cu);
17968                 baton->locexpr.per_cu = cu->per_cu;
17969                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17970                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17971                 prop->data.baton = baton;
17972                 prop->kind = PROP_LOCEXPR;
17973                 gdb_assert (prop->data.baton != NULL);
17974               }
17975             else
17976               {
17977                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17978                                                        "dynamic property");
17979                 return 0;
17980               }
17981             break;
17982           case DW_AT_data_member_location:
17983             {
17984               LONGEST offset;
17985
17986               if (!handle_data_member_location (target_die, target_cu,
17987                                                 &offset))
17988                 return 0;
17989
17990               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17991               baton->referenced_type = read_type_die (target_die->parent,
17992                                                       target_cu);
17993               baton->offset_info.offset = offset;
17994               baton->offset_info.type = die_type (target_die, target_cu);
17995               prop->data.baton = baton;
17996               prop->kind = PROP_ADDR_OFFSET;
17997               break;
17998             }
17999         }
18000     }
18001   else if (attr_form_is_constant (attr))
18002     {
18003       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
18004       prop->kind = PROP_CONST;
18005     }
18006   else
18007     {
18008       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
18009                                              dwarf2_name (die, cu));
18010       return 0;
18011     }
18012
18013   return 1;
18014 }
18015
18016 /* Read the given DW_AT_subrange DIE.  */
18017
18018 static struct type *
18019 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
18020 {
18021   struct type *base_type, *orig_base_type;
18022   struct type *range_type;
18023   struct attribute *attr;
18024   struct dynamic_prop low, high;
18025   int low_default_is_valid;
18026   int high_bound_is_count = 0;
18027   const char *name;
18028   LONGEST negative_mask;
18029
18030   orig_base_type = die_type (die, cu);
18031   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
18032      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
18033      creating the range type, but we use the result of check_typedef
18034      when examining properties of the type.  */
18035   base_type = check_typedef (orig_base_type);
18036
18037   /* The die_type call above may have already set the type for this DIE.  */
18038   range_type = get_die_type (die, cu);
18039   if (range_type)
18040     return range_type;
18041
18042   low.kind = PROP_CONST;
18043   high.kind = PROP_CONST;
18044   high.data.const_val = 0;
18045
18046   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
18047      omitting DW_AT_lower_bound.  */
18048   switch (cu->language)
18049     {
18050     case language_c:
18051     case language_cplus:
18052       low.data.const_val = 0;
18053       low_default_is_valid = 1;
18054       break;
18055     case language_fortran:
18056       low.data.const_val = 1;
18057       low_default_is_valid = 1;
18058       break;
18059     case language_d:
18060     case language_objc:
18061     case language_rust:
18062       low.data.const_val = 0;
18063       low_default_is_valid = (cu->header.version >= 4);
18064       break;
18065     case language_ada:
18066     case language_m2:
18067     case language_pascal:
18068       low.data.const_val = 1;
18069       low_default_is_valid = (cu->header.version >= 4);
18070       break;
18071     default:
18072       low.data.const_val = 0;
18073       low_default_is_valid = 0;
18074       break;
18075     }
18076
18077   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
18078   if (attr)
18079     attr_to_dynamic_prop (attr, die, cu, &low);
18080   else if (!low_default_is_valid)
18081     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
18082                                       "- DIE at %s [in module %s]"),
18083                sect_offset_str (die->sect_off),
18084                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
18085
18086   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
18087   if (!attr_to_dynamic_prop (attr, die, cu, &high))
18088     {
18089       attr = dwarf2_attr (die, DW_AT_count, cu);
18090       if (attr_to_dynamic_prop (attr, die, cu, &high))
18091         {
18092           /* If bounds are constant do the final calculation here.  */
18093           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
18094             high.data.const_val = low.data.const_val + high.data.const_val - 1;
18095           else
18096             high_bound_is_count = 1;
18097         }
18098     }
18099
18100   /* Dwarf-2 specifications explicitly allows to create subrange types
18101      without specifying a base type.
18102      In that case, the base type must be set to the type of
18103      the lower bound, upper bound or count, in that order, if any of these
18104      three attributes references an object that has a type.
18105      If no base type is found, the Dwarf-2 specifications say that
18106      a signed integer type of size equal to the size of an address should
18107      be used.
18108      For the following C code: `extern char gdb_int [];'
18109      GCC produces an empty range DIE.
18110      FIXME: muller/2010-05-28: Possible references to object for low bound,
18111      high bound or count are not yet handled by this code.  */
18112   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
18113     {
18114       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18115       struct gdbarch *gdbarch = get_objfile_arch (objfile);
18116       int addr_size = gdbarch_addr_bit (gdbarch) /8;
18117       struct type *int_type = objfile_type (objfile)->builtin_int;
18118
18119       /* Test "int", "long int", and "long long int" objfile types,
18120          and select the first one having a size above or equal to the
18121          architecture address size.  */
18122       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
18123         base_type = int_type;
18124       else
18125         {
18126           int_type = objfile_type (objfile)->builtin_long;
18127           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
18128             base_type = int_type;
18129           else
18130             {
18131               int_type = objfile_type (objfile)->builtin_long_long;
18132               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
18133                 base_type = int_type;
18134             }
18135         }
18136     }
18137
18138   /* Normally, the DWARF producers are expected to use a signed
18139      constant form (Eg. DW_FORM_sdata) to express negative bounds.
18140      But this is unfortunately not always the case, as witnessed
18141      with GCC, for instance, where the ambiguous DW_FORM_dataN form
18142      is used instead.  To work around that ambiguity, we treat
18143      the bounds as signed, and thus sign-extend their values, when
18144      the base type is signed.  */
18145   negative_mask =
18146     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
18147   if (low.kind == PROP_CONST
18148       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
18149     low.data.const_val |= negative_mask;
18150   if (high.kind == PROP_CONST
18151       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
18152     high.data.const_val |= negative_mask;
18153
18154   range_type = create_range_type (NULL, orig_base_type, &low, &high);
18155
18156   if (high_bound_is_count)
18157     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
18158
18159   /* Ada expects an empty array on no boundary attributes.  */
18160   if (attr == NULL && cu->language != language_ada)
18161     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
18162
18163   name = dwarf2_name (die, cu);
18164   if (name)
18165     TYPE_NAME (range_type) = name;
18166
18167   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
18168   if (attr)
18169     TYPE_LENGTH (range_type) = DW_UNSND (attr);
18170
18171   set_die_type (die, range_type, cu);
18172
18173   /* set_die_type should be already done.  */
18174   set_descriptive_type (range_type, die, cu);
18175
18176   return range_type;
18177 }
18178
18179 static struct type *
18180 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
18181 {
18182   struct type *type;
18183
18184   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
18185                     NULL);
18186   TYPE_NAME (type) = dwarf2_name (die, cu);
18187
18188   /* In Ada, an unspecified type is typically used when the description
18189      of the type is defered to a different unit.  When encountering
18190      such a type, we treat it as a stub, and try to resolve it later on,
18191      when needed.  */
18192   if (cu->language == language_ada)
18193     TYPE_STUB (type) = 1;
18194
18195   return set_die_type (die, type, cu);
18196 }
18197
18198 /* Read a single die and all its descendents.  Set the die's sibling
18199    field to NULL; set other fields in the die correctly, and set all
18200    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
18201    location of the info_ptr after reading all of those dies.  PARENT
18202    is the parent of the die in question.  */
18203
18204 static struct die_info *
18205 read_die_and_children (const struct die_reader_specs *reader,
18206                        const gdb_byte *info_ptr,
18207                        const gdb_byte **new_info_ptr,
18208                        struct die_info *parent)
18209 {
18210   struct die_info *die;
18211   const gdb_byte *cur_ptr;
18212   int has_children;
18213
18214   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
18215   if (die == NULL)
18216     {
18217       *new_info_ptr = cur_ptr;
18218       return NULL;
18219     }
18220   store_in_ref_table (die, reader->cu);
18221
18222   if (has_children)
18223     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
18224   else
18225     {
18226       die->child = NULL;
18227       *new_info_ptr = cur_ptr;
18228     }
18229
18230   die->sibling = NULL;
18231   die->parent = parent;
18232   return die;
18233 }
18234
18235 /* Read a die, all of its descendents, and all of its siblings; set
18236    all of the fields of all of the dies correctly.  Arguments are as
18237    in read_die_and_children.  */
18238
18239 static struct die_info *
18240 read_die_and_siblings_1 (const struct die_reader_specs *reader,
18241                          const gdb_byte *info_ptr,
18242                          const gdb_byte **new_info_ptr,
18243                          struct die_info *parent)
18244 {
18245   struct die_info *first_die, *last_sibling;
18246   const gdb_byte *cur_ptr;
18247
18248   cur_ptr = info_ptr;
18249   first_die = last_sibling = NULL;
18250
18251   while (1)
18252     {
18253       struct die_info *die
18254         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
18255
18256       if (die == NULL)
18257         {
18258           *new_info_ptr = cur_ptr;
18259           return first_die;
18260         }
18261
18262       if (!first_die)
18263         first_die = die;
18264       else
18265         last_sibling->sibling = die;
18266
18267       last_sibling = die;
18268     }
18269 }
18270
18271 /* Read a die, all of its descendents, and all of its siblings; set
18272    all of the fields of all of the dies correctly.  Arguments are as
18273    in read_die_and_children.
18274    This the main entry point for reading a DIE and all its children.  */
18275
18276 static struct die_info *
18277 read_die_and_siblings (const struct die_reader_specs *reader,
18278                        const gdb_byte *info_ptr,
18279                        const gdb_byte **new_info_ptr,
18280                        struct die_info *parent)
18281 {
18282   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18283                                                   new_info_ptr, parent);
18284
18285   if (dwarf_die_debug)
18286     {
18287       fprintf_unfiltered (gdb_stdlog,
18288                           "Read die from %s@0x%x of %s:\n",
18289                           get_section_name (reader->die_section),
18290                           (unsigned) (info_ptr - reader->die_section->buffer),
18291                           bfd_get_filename (reader->abfd));
18292       dump_die (die, dwarf_die_debug);
18293     }
18294
18295   return die;
18296 }
18297
18298 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18299    attributes.
18300    The caller is responsible for filling in the extra attributes
18301    and updating (*DIEP)->num_attrs.
18302    Set DIEP to point to a newly allocated die with its information,
18303    except for its child, sibling, and parent fields.
18304    Set HAS_CHILDREN to tell whether the die has children or not.  */
18305
18306 static const gdb_byte *
18307 read_full_die_1 (const struct die_reader_specs *reader,
18308                  struct die_info **diep, const gdb_byte *info_ptr,
18309                  int *has_children, int num_extra_attrs)
18310 {
18311   unsigned int abbrev_number, bytes_read, i;
18312   struct abbrev_info *abbrev;
18313   struct die_info *die;
18314   struct dwarf2_cu *cu = reader->cu;
18315   bfd *abfd = reader->abfd;
18316
18317   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18318   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18319   info_ptr += bytes_read;
18320   if (!abbrev_number)
18321     {
18322       *diep = NULL;
18323       *has_children = 0;
18324       return info_ptr;
18325     }
18326
18327   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18328   if (!abbrev)
18329     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18330            abbrev_number,
18331            bfd_get_filename (abfd));
18332
18333   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18334   die->sect_off = sect_off;
18335   die->tag = abbrev->tag;
18336   die->abbrev = abbrev_number;
18337
18338   /* Make the result usable.
18339      The caller needs to update num_attrs after adding the extra
18340      attributes.  */
18341   die->num_attrs = abbrev->num_attrs;
18342
18343   for (i = 0; i < abbrev->num_attrs; ++i)
18344     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18345                                info_ptr);
18346
18347   *diep = die;
18348   *has_children = abbrev->has_children;
18349   return info_ptr;
18350 }
18351
18352 /* Read a die and all its attributes.
18353    Set DIEP to point to a newly allocated die with its information,
18354    except for its child, sibling, and parent fields.
18355    Set HAS_CHILDREN to tell whether the die has children or not.  */
18356
18357 static const gdb_byte *
18358 read_full_die (const struct die_reader_specs *reader,
18359                struct die_info **diep, const gdb_byte *info_ptr,
18360                int *has_children)
18361 {
18362   const gdb_byte *result;
18363
18364   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18365
18366   if (dwarf_die_debug)
18367     {
18368       fprintf_unfiltered (gdb_stdlog,
18369                           "Read die from %s@0x%x of %s:\n",
18370                           get_section_name (reader->die_section),
18371                           (unsigned) (info_ptr - reader->die_section->buffer),
18372                           bfd_get_filename (reader->abfd));
18373       dump_die (*diep, dwarf_die_debug);
18374     }
18375
18376   return result;
18377 }
18378 \f
18379 /* Abbreviation tables.
18380
18381    In DWARF version 2, the description of the debugging information is
18382    stored in a separate .debug_abbrev section.  Before we read any
18383    dies from a section we read in all abbreviations and install them
18384    in a hash table.  */
18385
18386 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18387
18388 struct abbrev_info *
18389 abbrev_table::alloc_abbrev ()
18390 {
18391   struct abbrev_info *abbrev;
18392
18393   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18394   memset (abbrev, 0, sizeof (struct abbrev_info));
18395
18396   return abbrev;
18397 }
18398
18399 /* Add an abbreviation to the table.  */
18400
18401 void
18402 abbrev_table::add_abbrev (unsigned int abbrev_number,
18403                           struct abbrev_info *abbrev)
18404 {
18405   unsigned int hash_number;
18406
18407   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18408   abbrev->next = m_abbrevs[hash_number];
18409   m_abbrevs[hash_number] = abbrev;
18410 }
18411
18412 /* Look up an abbrev in the table.
18413    Returns NULL if the abbrev is not found.  */
18414
18415 struct abbrev_info *
18416 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18417 {
18418   unsigned int hash_number;
18419   struct abbrev_info *abbrev;
18420
18421   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18422   abbrev = m_abbrevs[hash_number];
18423
18424   while (abbrev)
18425     {
18426       if (abbrev->number == abbrev_number)
18427         return abbrev;
18428       abbrev = abbrev->next;
18429     }
18430   return NULL;
18431 }
18432
18433 /* Read in an abbrev table.  */
18434
18435 static abbrev_table_up
18436 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18437                          struct dwarf2_section_info *section,
18438                          sect_offset sect_off)
18439 {
18440   struct objfile *objfile = dwarf2_per_objfile->objfile;
18441   bfd *abfd = get_section_bfd_owner (section);
18442   const gdb_byte *abbrev_ptr;
18443   struct abbrev_info *cur_abbrev;
18444   unsigned int abbrev_number, bytes_read, abbrev_name;
18445   unsigned int abbrev_form;
18446   struct attr_abbrev *cur_attrs;
18447   unsigned int allocated_attrs;
18448
18449   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18450
18451   dwarf2_read_section (objfile, section);
18452   abbrev_ptr = section->buffer + to_underlying (sect_off);
18453   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18454   abbrev_ptr += bytes_read;
18455
18456   allocated_attrs = ATTR_ALLOC_CHUNK;
18457   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18458
18459   /* Loop until we reach an abbrev number of 0.  */
18460   while (abbrev_number)
18461     {
18462       cur_abbrev = abbrev_table->alloc_abbrev ();
18463
18464       /* read in abbrev header */
18465       cur_abbrev->number = abbrev_number;
18466       cur_abbrev->tag
18467         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18468       abbrev_ptr += bytes_read;
18469       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18470       abbrev_ptr += 1;
18471
18472       /* now read in declarations */
18473       for (;;)
18474         {
18475           LONGEST implicit_const;
18476
18477           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18478           abbrev_ptr += bytes_read;
18479           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18480           abbrev_ptr += bytes_read;
18481           if (abbrev_form == DW_FORM_implicit_const)
18482             {
18483               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18484                                                    &bytes_read);
18485               abbrev_ptr += bytes_read;
18486             }
18487           else
18488             {
18489               /* Initialize it due to a false compiler warning.  */
18490               implicit_const = -1;
18491             }
18492
18493           if (abbrev_name == 0)
18494             break;
18495
18496           if (cur_abbrev->num_attrs == allocated_attrs)
18497             {
18498               allocated_attrs += ATTR_ALLOC_CHUNK;
18499               cur_attrs
18500                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18501             }
18502
18503           cur_attrs[cur_abbrev->num_attrs].name
18504             = (enum dwarf_attribute) abbrev_name;
18505           cur_attrs[cur_abbrev->num_attrs].form
18506             = (enum dwarf_form) abbrev_form;
18507           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18508           ++cur_abbrev->num_attrs;
18509         }
18510
18511       cur_abbrev->attrs =
18512         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18513                    cur_abbrev->num_attrs);
18514       memcpy (cur_abbrev->attrs, cur_attrs,
18515               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18516
18517       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18518
18519       /* Get next abbreviation.
18520          Under Irix6 the abbreviations for a compilation unit are not
18521          always properly terminated with an abbrev number of 0.
18522          Exit loop if we encounter an abbreviation which we have
18523          already read (which means we are about to read the abbreviations
18524          for the next compile unit) or if the end of the abbreviation
18525          table is reached.  */
18526       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18527         break;
18528       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18529       abbrev_ptr += bytes_read;
18530       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18531         break;
18532     }
18533
18534   xfree (cur_attrs);
18535   return abbrev_table;
18536 }
18537
18538 /* Returns nonzero if TAG represents a type that we might generate a partial
18539    symbol for.  */
18540
18541 static int
18542 is_type_tag_for_partial (int tag)
18543 {
18544   switch (tag)
18545     {
18546 #if 0
18547     /* Some types that would be reasonable to generate partial symbols for,
18548        that we don't at present.  */
18549     case DW_TAG_array_type:
18550     case DW_TAG_file_type:
18551     case DW_TAG_ptr_to_member_type:
18552     case DW_TAG_set_type:
18553     case DW_TAG_string_type:
18554     case DW_TAG_subroutine_type:
18555 #endif
18556     case DW_TAG_base_type:
18557     case DW_TAG_class_type:
18558     case DW_TAG_interface_type:
18559     case DW_TAG_enumeration_type:
18560     case DW_TAG_structure_type:
18561     case DW_TAG_subrange_type:
18562     case DW_TAG_typedef:
18563     case DW_TAG_union_type:
18564       return 1;
18565     default:
18566       return 0;
18567     }
18568 }
18569
18570 /* Load all DIEs that are interesting for partial symbols into memory.  */
18571
18572 static struct partial_die_info *
18573 load_partial_dies (const struct die_reader_specs *reader,
18574                    const gdb_byte *info_ptr, int building_psymtab)
18575 {
18576   struct dwarf2_cu *cu = reader->cu;
18577   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18578   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18579   unsigned int bytes_read;
18580   unsigned int load_all = 0;
18581   int nesting_level = 1;
18582
18583   parent_die = NULL;
18584   last_die = NULL;
18585
18586   gdb_assert (cu->per_cu != NULL);
18587   if (cu->per_cu->load_all_dies)
18588     load_all = 1;
18589
18590   cu->partial_dies
18591     = htab_create_alloc_ex (cu->header.length / 12,
18592                             partial_die_hash,
18593                             partial_die_eq,
18594                             NULL,
18595                             &cu->comp_unit_obstack,
18596                             hashtab_obstack_allocate,
18597                             dummy_obstack_deallocate);
18598
18599   while (1)
18600     {
18601       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18602
18603       /* A NULL abbrev means the end of a series of children.  */
18604       if (abbrev == NULL)
18605         {
18606           if (--nesting_level == 0)
18607             return first_die;
18608
18609           info_ptr += bytes_read;
18610           last_die = parent_die;
18611           parent_die = parent_die->die_parent;
18612           continue;
18613         }
18614
18615       /* Check for template arguments.  We never save these; if
18616          they're seen, we just mark the parent, and go on our way.  */
18617       if (parent_die != NULL
18618           && cu->language == language_cplus
18619           && (abbrev->tag == DW_TAG_template_type_param
18620               || abbrev->tag == DW_TAG_template_value_param))
18621         {
18622           parent_die->has_template_arguments = 1;
18623
18624           if (!load_all)
18625             {
18626               /* We don't need a partial DIE for the template argument.  */
18627               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18628               continue;
18629             }
18630         }
18631
18632       /* We only recurse into c++ subprograms looking for template arguments.
18633          Skip their other children.  */
18634       if (!load_all
18635           && cu->language == language_cplus
18636           && parent_die != NULL
18637           && parent_die->tag == DW_TAG_subprogram)
18638         {
18639           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18640           continue;
18641         }
18642
18643       /* Check whether this DIE is interesting enough to save.  Normally
18644          we would not be interested in members here, but there may be
18645          later variables referencing them via DW_AT_specification (for
18646          static members).  */
18647       if (!load_all
18648           && !is_type_tag_for_partial (abbrev->tag)
18649           && abbrev->tag != DW_TAG_constant
18650           && abbrev->tag != DW_TAG_enumerator
18651           && abbrev->tag != DW_TAG_subprogram
18652           && abbrev->tag != DW_TAG_inlined_subroutine
18653           && abbrev->tag != DW_TAG_lexical_block
18654           && abbrev->tag != DW_TAG_variable
18655           && abbrev->tag != DW_TAG_namespace
18656           && abbrev->tag != DW_TAG_module
18657           && abbrev->tag != DW_TAG_member
18658           && abbrev->tag != DW_TAG_imported_unit
18659           && abbrev->tag != DW_TAG_imported_declaration)
18660         {
18661           /* Otherwise we skip to the next sibling, if any.  */
18662           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18663           continue;
18664         }
18665
18666       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18667                                    abbrev);
18668
18669       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18670
18671       /* This two-pass algorithm for processing partial symbols has a
18672          high cost in cache pressure.  Thus, handle some simple cases
18673          here which cover the majority of C partial symbols.  DIEs
18674          which neither have specification tags in them, nor could have
18675          specification tags elsewhere pointing at them, can simply be
18676          processed and discarded.
18677
18678          This segment is also optional; scan_partial_symbols and
18679          add_partial_symbol will handle these DIEs if we chain
18680          them in normally.  When compilers which do not emit large
18681          quantities of duplicate debug information are more common,
18682          this code can probably be removed.  */
18683
18684       /* Any complete simple types at the top level (pretty much all
18685          of them, for a language without namespaces), can be processed
18686          directly.  */
18687       if (parent_die == NULL
18688           && pdi.has_specification == 0
18689           && pdi.is_declaration == 0
18690           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18691               || pdi.tag == DW_TAG_base_type
18692               || pdi.tag == DW_TAG_subrange_type))
18693         {
18694           if (building_psymtab && pdi.name != NULL)
18695             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18696                                  VAR_DOMAIN, LOC_TYPEDEF,
18697                                  &objfile->static_psymbols,
18698                                  0, cu->language, objfile);
18699           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18700           continue;
18701         }
18702
18703       /* The exception for DW_TAG_typedef with has_children above is
18704          a workaround of GCC PR debug/47510.  In the case of this complaint
18705          type_name_no_tag_or_error will error on such types later.
18706
18707          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18708          it could not find the child DIEs referenced later, this is checked
18709          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18710
18711       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18712         complaint (&symfile_complaints,
18713                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18714                      "- DIE at %s [in module %s]"),
18715                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18716
18717       /* If we're at the second level, and we're an enumerator, and
18718          our parent has no specification (meaning possibly lives in a
18719          namespace elsewhere), then we can add the partial symbol now
18720          instead of queueing it.  */
18721       if (pdi.tag == DW_TAG_enumerator
18722           && parent_die != NULL
18723           && parent_die->die_parent == NULL
18724           && parent_die->tag == DW_TAG_enumeration_type
18725           && parent_die->has_specification == 0)
18726         {
18727           if (pdi.name == NULL)
18728             complaint (&symfile_complaints,
18729                        _("malformed enumerator DIE ignored"));
18730           else if (building_psymtab)
18731             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18732                                  VAR_DOMAIN, LOC_CONST,
18733                                  cu->language == language_cplus
18734                                  ? &objfile->global_psymbols
18735                                  : &objfile->static_psymbols,
18736                                  0, cu->language, objfile);
18737
18738           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18739           continue;
18740         }
18741
18742       struct partial_die_info *part_die
18743         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18744
18745       /* We'll save this DIE so link it in.  */
18746       part_die->die_parent = parent_die;
18747       part_die->die_sibling = NULL;
18748       part_die->die_child = NULL;
18749
18750       if (last_die && last_die == parent_die)
18751         last_die->die_child = part_die;
18752       else if (last_die)
18753         last_die->die_sibling = part_die;
18754
18755       last_die = part_die;
18756
18757       if (first_die == NULL)
18758         first_die = part_die;
18759
18760       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18761          find interesting need to be in the hash table, because we
18762          also have the parent/sibling/child chains; only those that we
18763          might refer to by offset later during partial symbol reading.
18764
18765          For now this means things that might have be the target of a
18766          DW_AT_specification, DW_AT_abstract_origin, or
18767          DW_AT_extension.  DW_AT_extension will refer only to
18768          namespaces; DW_AT_abstract_origin refers to functions (and
18769          many things under the function DIE, but we do not recurse
18770          into function DIEs during partial symbol reading) and
18771          possibly variables as well; DW_AT_specification refers to
18772          declarations.  Declarations ought to have the DW_AT_declaration
18773          flag.  It happens that GCC forgets to put it in sometimes, but
18774          only for functions, not for types.
18775
18776          Adding more things than necessary to the hash table is harmless
18777          except for the performance cost.  Adding too few will result in
18778          wasted time in find_partial_die, when we reread the compilation
18779          unit with load_all_dies set.  */
18780
18781       if (load_all
18782           || abbrev->tag == DW_TAG_constant
18783           || abbrev->tag == DW_TAG_subprogram
18784           || abbrev->tag == DW_TAG_variable
18785           || abbrev->tag == DW_TAG_namespace
18786           || part_die->is_declaration)
18787         {
18788           void **slot;
18789
18790           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18791                                            to_underlying (part_die->sect_off),
18792                                            INSERT);
18793           *slot = part_die;
18794         }
18795
18796       /* For some DIEs we want to follow their children (if any).  For C
18797          we have no reason to follow the children of structures; for other
18798          languages we have to, so that we can get at method physnames
18799          to infer fully qualified class names, for DW_AT_specification,
18800          and for C++ template arguments.  For C++, we also look one level
18801          inside functions to find template arguments (if the name of the
18802          function does not already contain the template arguments).
18803
18804          For Ada, we need to scan the children of subprograms and lexical
18805          blocks as well because Ada allows the definition of nested
18806          entities that could be interesting for the debugger, such as
18807          nested subprograms for instance.  */
18808       if (last_die->has_children
18809           && (load_all
18810               || last_die->tag == DW_TAG_namespace
18811               || last_die->tag == DW_TAG_module
18812               || last_die->tag == DW_TAG_enumeration_type
18813               || (cu->language == language_cplus
18814                   && last_die->tag == DW_TAG_subprogram
18815                   && (last_die->name == NULL
18816                       || strchr (last_die->name, '<') == NULL))
18817               || (cu->language != language_c
18818                   && (last_die->tag == DW_TAG_class_type
18819                       || last_die->tag == DW_TAG_interface_type
18820                       || last_die->tag == DW_TAG_structure_type
18821                       || last_die->tag == DW_TAG_union_type))
18822               || (cu->language == language_ada
18823                   && (last_die->tag == DW_TAG_subprogram
18824                       || last_die->tag == DW_TAG_lexical_block))))
18825         {
18826           nesting_level++;
18827           parent_die = last_die;
18828           continue;
18829         }
18830
18831       /* Otherwise we skip to the next sibling, if any.  */
18832       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18833
18834       /* Back to the top, do it again.  */
18835     }
18836 }
18837
18838 partial_die_info::partial_die_info (sect_offset sect_off_,
18839                                     struct abbrev_info *abbrev)
18840   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18841 {
18842 }
18843
18844 /* Read a minimal amount of information into the minimal die structure.
18845    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18846
18847 const gdb_byte *
18848 partial_die_info::read (const struct die_reader_specs *reader,
18849                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18850 {
18851   struct dwarf2_cu *cu = reader->cu;
18852   struct dwarf2_per_objfile *dwarf2_per_objfile
18853     = cu->per_cu->dwarf2_per_objfile;
18854   unsigned int i;
18855   int has_low_pc_attr = 0;
18856   int has_high_pc_attr = 0;
18857   int high_pc_relative = 0;
18858
18859   for (i = 0; i < abbrev.num_attrs; ++i)
18860     {
18861       struct attribute attr;
18862
18863       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18864
18865       /* Store the data if it is of an attribute we want to keep in a
18866          partial symbol table.  */
18867       switch (attr.name)
18868         {
18869         case DW_AT_name:
18870           switch (tag)
18871             {
18872             case DW_TAG_compile_unit:
18873             case DW_TAG_partial_unit:
18874             case DW_TAG_type_unit:
18875               /* Compilation units have a DW_AT_name that is a filename, not
18876                  a source language identifier.  */
18877             case DW_TAG_enumeration_type:
18878             case DW_TAG_enumerator:
18879               /* These tags always have simple identifiers already; no need
18880                  to canonicalize them.  */
18881               name = DW_STRING (&attr);
18882               break;
18883             default:
18884               {
18885                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18886
18887                 name
18888                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18889                                               &objfile->per_bfd->storage_obstack);
18890               }
18891               break;
18892             }
18893           break;
18894         case DW_AT_linkage_name:
18895         case DW_AT_MIPS_linkage_name:
18896           /* Note that both forms of linkage name might appear.  We
18897              assume they will be the same, and we only store the last
18898              one we see.  */
18899           if (cu->language == language_ada)
18900             name = DW_STRING (&attr);
18901           linkage_name = DW_STRING (&attr);
18902           break;
18903         case DW_AT_low_pc:
18904           has_low_pc_attr = 1;
18905           lowpc = attr_value_as_address (&attr);
18906           break;
18907         case DW_AT_high_pc:
18908           has_high_pc_attr = 1;
18909           highpc = attr_value_as_address (&attr);
18910           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18911                 high_pc_relative = 1;
18912           break;
18913         case DW_AT_location:
18914           /* Support the .debug_loc offsets.  */
18915           if (attr_form_is_block (&attr))
18916             {
18917                d.locdesc = DW_BLOCK (&attr);
18918             }
18919           else if (attr_form_is_section_offset (&attr))
18920             {
18921               dwarf2_complex_location_expr_complaint ();
18922             }
18923           else
18924             {
18925               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18926                                                      "partial symbol information");
18927             }
18928           break;
18929         case DW_AT_external:
18930           is_external = DW_UNSND (&attr);
18931           break;
18932         case DW_AT_declaration:
18933           is_declaration = DW_UNSND (&attr);
18934           break;
18935         case DW_AT_type:
18936           has_type = 1;
18937           break;
18938         case DW_AT_abstract_origin:
18939         case DW_AT_specification:
18940         case DW_AT_extension:
18941           has_specification = 1;
18942           spec_offset = dwarf2_get_ref_die_offset (&attr);
18943           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18944                                    || cu->per_cu->is_dwz);
18945           break;
18946         case DW_AT_sibling:
18947           /* Ignore absolute siblings, they might point outside of
18948              the current compile unit.  */
18949           if (attr.form == DW_FORM_ref_addr)
18950             complaint (&symfile_complaints,
18951                        _("ignoring absolute DW_AT_sibling"));
18952           else
18953             {
18954               const gdb_byte *buffer = reader->buffer;
18955               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18956               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18957
18958               if (sibling_ptr < info_ptr)
18959                 complaint (&symfile_complaints,
18960                            _("DW_AT_sibling points backwards"));
18961               else if (sibling_ptr > reader->buffer_end)
18962                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18963               else
18964                 sibling = sibling_ptr;
18965             }
18966           break;
18967         case DW_AT_byte_size:
18968           has_byte_size = 1;
18969           break;
18970         case DW_AT_const_value:
18971           has_const_value = 1;
18972           break;
18973         case DW_AT_calling_convention:
18974           /* DWARF doesn't provide a way to identify a program's source-level
18975              entry point.  DW_AT_calling_convention attributes are only meant
18976              to describe functions' calling conventions.
18977
18978              However, because it's a necessary piece of information in
18979              Fortran, and before DWARF 4 DW_CC_program was the only
18980              piece of debugging information whose definition refers to
18981              a 'main program' at all, several compilers marked Fortran
18982              main programs with DW_CC_program --- even when those
18983              functions use the standard calling conventions.
18984
18985              Although DWARF now specifies a way to provide this
18986              information, we support this practice for backward
18987              compatibility.  */
18988           if (DW_UNSND (&attr) == DW_CC_program
18989               && cu->language == language_fortran)
18990             main_subprogram = 1;
18991           break;
18992         case DW_AT_inline:
18993           if (DW_UNSND (&attr) == DW_INL_inlined
18994               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18995             may_be_inlined = 1;
18996           break;
18997
18998         case DW_AT_import:
18999           if (tag == DW_TAG_imported_unit)
19000             {
19001               d.sect_off = dwarf2_get_ref_die_offset (&attr);
19002               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
19003                                   || cu->per_cu->is_dwz);
19004             }
19005           break;
19006
19007         case DW_AT_main_subprogram:
19008           main_subprogram = DW_UNSND (&attr);
19009           break;
19010
19011         default:
19012           break;
19013         }
19014     }
19015
19016   if (high_pc_relative)
19017     highpc += lowpc;
19018
19019   if (has_low_pc_attr && has_high_pc_attr)
19020     {
19021       /* When using the GNU linker, .gnu.linkonce. sections are used to
19022          eliminate duplicate copies of functions and vtables and such.
19023          The linker will arbitrarily choose one and discard the others.
19024          The AT_*_pc values for such functions refer to local labels in
19025          these sections.  If the section from that file was discarded, the
19026          labels are not in the output, so the relocs get a value of 0.
19027          If this is a discarded function, mark the pc bounds as invalid,
19028          so that GDB will ignore it.  */
19029       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
19030         {
19031           struct objfile *objfile = dwarf2_per_objfile->objfile;
19032           struct gdbarch *gdbarch = get_objfile_arch (objfile);
19033
19034           complaint (&symfile_complaints,
19035                      _("DW_AT_low_pc %s is zero "
19036                        "for DIE at %s [in module %s]"),
19037                      paddress (gdbarch, lowpc),
19038                      sect_offset_str (sect_off),
19039                      objfile_name (objfile));
19040         }
19041       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
19042       else if (lowpc >= highpc)
19043         {
19044           struct objfile *objfile = dwarf2_per_objfile->objfile;
19045           struct gdbarch *gdbarch = get_objfile_arch (objfile);
19046
19047           complaint (&symfile_complaints,
19048                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
19049                        "for DIE at %s [in module %s]"),
19050                      paddress (gdbarch, lowpc),
19051                      paddress (gdbarch, highpc),
19052                      sect_offset_str (sect_off),
19053                      objfile_name (objfile));
19054         }
19055       else
19056         has_pc_info = 1;
19057     }
19058
19059   return info_ptr;
19060 }
19061
19062 /* Find a cached partial DIE at OFFSET in CU.  */
19063
19064 struct partial_die_info *
19065 dwarf2_cu::find_partial_die (sect_offset sect_off)
19066 {
19067   struct partial_die_info *lookup_die = NULL;
19068   struct partial_die_info part_die (sect_off);
19069
19070   lookup_die = ((struct partial_die_info *)
19071                 htab_find_with_hash (partial_dies, &part_die,
19072                                      to_underlying (sect_off)));
19073
19074   return lookup_die;
19075 }
19076
19077 /* Find a partial DIE at OFFSET, which may or may not be in CU,
19078    except in the case of .debug_types DIEs which do not reference
19079    outside their CU (they do however referencing other types via
19080    DW_FORM_ref_sig8).  */
19081
19082 static struct partial_die_info *
19083 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
19084 {
19085   struct dwarf2_per_objfile *dwarf2_per_objfile
19086     = cu->per_cu->dwarf2_per_objfile;
19087   struct objfile *objfile = dwarf2_per_objfile->objfile;
19088   struct dwarf2_per_cu_data *per_cu = NULL;
19089   struct partial_die_info *pd = NULL;
19090
19091   if (offset_in_dwz == cu->per_cu->is_dwz
19092       && offset_in_cu_p (&cu->header, sect_off))
19093     {
19094       pd = cu->find_partial_die (sect_off);
19095       if (pd != NULL)
19096         return pd;
19097       /* We missed recording what we needed.
19098          Load all dies and try again.  */
19099       per_cu = cu->per_cu;
19100     }
19101   else
19102     {
19103       /* TUs don't reference other CUs/TUs (except via type signatures).  */
19104       if (cu->per_cu->is_debug_types)
19105         {
19106           error (_("Dwarf Error: Type Unit at offset %s contains"
19107                    " external reference to offset %s [in module %s].\n"),
19108                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
19109                  bfd_get_filename (objfile->obfd));
19110         }
19111       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
19112                                                  dwarf2_per_objfile);
19113
19114       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
19115         load_partial_comp_unit (per_cu);
19116
19117       per_cu->cu->last_used = 0;
19118       pd = per_cu->cu->find_partial_die (sect_off);
19119     }
19120
19121   /* If we didn't find it, and not all dies have been loaded,
19122      load them all and try again.  */
19123
19124   if (pd == NULL && per_cu->load_all_dies == 0)
19125     {
19126       per_cu->load_all_dies = 1;
19127
19128       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
19129          THIS_CU->cu may already be in use.  So we can't just free it and
19130          replace its DIEs with the ones we read in.  Instead, we leave those
19131          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
19132          and clobber THIS_CU->cu->partial_dies with the hash table for the new
19133          set.  */
19134       load_partial_comp_unit (per_cu);
19135
19136       pd = per_cu->cu->find_partial_die (sect_off);
19137     }
19138
19139   if (pd == NULL)
19140     internal_error (__FILE__, __LINE__,
19141                     _("could not find partial DIE %s "
19142                       "in cache [from module %s]\n"),
19143                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
19144   return pd;
19145 }
19146
19147 /* See if we can figure out if the class lives in a namespace.  We do
19148    this by looking for a member function; its demangled name will
19149    contain namespace info, if there is any.  */
19150
19151 static void
19152 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
19153                                   struct dwarf2_cu *cu)
19154 {
19155   /* NOTE: carlton/2003-10-07: Getting the info this way changes
19156      what template types look like, because the demangler
19157      frequently doesn't give the same name as the debug info.  We
19158      could fix this by only using the demangled name to get the
19159      prefix (but see comment in read_structure_type).  */
19160
19161   struct partial_die_info *real_pdi;
19162   struct partial_die_info *child_pdi;
19163
19164   /* If this DIE (this DIE's specification, if any) has a parent, then
19165      we should not do this.  We'll prepend the parent's fully qualified
19166      name when we create the partial symbol.  */
19167
19168   real_pdi = struct_pdi;
19169   while (real_pdi->has_specification)
19170     real_pdi = find_partial_die (real_pdi->spec_offset,
19171                                  real_pdi->spec_is_dwz, cu);
19172
19173   if (real_pdi->die_parent != NULL)
19174     return;
19175
19176   for (child_pdi = struct_pdi->die_child;
19177        child_pdi != NULL;
19178        child_pdi = child_pdi->die_sibling)
19179     {
19180       if (child_pdi->tag == DW_TAG_subprogram
19181           && child_pdi->linkage_name != NULL)
19182         {
19183           char *actual_class_name
19184             = language_class_name_from_physname (cu->language_defn,
19185                                                  child_pdi->linkage_name);
19186           if (actual_class_name != NULL)
19187             {
19188               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19189               struct_pdi->name
19190                 = ((const char *)
19191                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
19192                                   actual_class_name,
19193                                   strlen (actual_class_name)));
19194               xfree (actual_class_name);
19195             }
19196           break;
19197         }
19198     }
19199 }
19200
19201 void
19202 partial_die_info::fixup (struct dwarf2_cu *cu)
19203 {
19204   /* Once we've fixed up a die, there's no point in doing so again.
19205      This also avoids a memory leak if we were to call
19206      guess_partial_die_structure_name multiple times.  */
19207   if (fixup_called)
19208     return;
19209
19210   /* If we found a reference attribute and the DIE has no name, try
19211      to find a name in the referred to DIE.  */
19212
19213   if (name == NULL && has_specification)
19214     {
19215       struct partial_die_info *spec_die;
19216
19217       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
19218
19219       spec_die->fixup (cu);
19220
19221       if (spec_die->name)
19222         {
19223           name = spec_die->name;
19224
19225           /* Copy DW_AT_external attribute if it is set.  */
19226           if (spec_die->is_external)
19227             is_external = spec_die->is_external;
19228         }
19229     }
19230
19231   /* Set default names for some unnamed DIEs.  */
19232
19233   if (name == NULL && tag == DW_TAG_namespace)
19234     name = CP_ANONYMOUS_NAMESPACE_STR;
19235
19236   /* If there is no parent die to provide a namespace, and there are
19237      children, see if we can determine the namespace from their linkage
19238      name.  */
19239   if (cu->language == language_cplus
19240       && !VEC_empty (dwarf2_section_info_def,
19241                      cu->per_cu->dwarf2_per_objfile->types)
19242       && die_parent == NULL
19243       && has_children
19244       && (tag == DW_TAG_class_type
19245           || tag == DW_TAG_structure_type
19246           || tag == DW_TAG_union_type))
19247     guess_partial_die_structure_name (this, cu);
19248
19249   /* GCC might emit a nameless struct or union that has a linkage
19250      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19251   if (name == NULL
19252       && (tag == DW_TAG_class_type
19253           || tag == DW_TAG_interface_type
19254           || tag == DW_TAG_structure_type
19255           || tag == DW_TAG_union_type)
19256       && linkage_name != NULL)
19257     {
19258       char *demangled;
19259
19260       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
19261       if (demangled)
19262         {
19263           const char *base;
19264
19265           /* Strip any leading namespaces/classes, keep only the base name.
19266              DW_AT_name for named DIEs does not contain the prefixes.  */
19267           base = strrchr (demangled, ':');
19268           if (base && base > demangled && base[-1] == ':')
19269             base++;
19270           else
19271             base = demangled;
19272
19273           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19274           name
19275             = ((const char *)
19276                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19277                               base, strlen (base)));
19278           xfree (demangled);
19279         }
19280     }
19281
19282   fixup_called = 1;
19283 }
19284
19285 /* Read an attribute value described by an attribute form.  */
19286
19287 static const gdb_byte *
19288 read_attribute_value (const struct die_reader_specs *reader,
19289                       struct attribute *attr, unsigned form,
19290                       LONGEST implicit_const, const gdb_byte *info_ptr)
19291 {
19292   struct dwarf2_cu *cu = reader->cu;
19293   struct dwarf2_per_objfile *dwarf2_per_objfile
19294     = cu->per_cu->dwarf2_per_objfile;
19295   struct objfile *objfile = dwarf2_per_objfile->objfile;
19296   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19297   bfd *abfd = reader->abfd;
19298   struct comp_unit_head *cu_header = &cu->header;
19299   unsigned int bytes_read;
19300   struct dwarf_block *blk;
19301
19302   attr->form = (enum dwarf_form) form;
19303   switch (form)
19304     {
19305     case DW_FORM_ref_addr:
19306       if (cu->header.version == 2)
19307         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19308       else
19309         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19310                                        &cu->header, &bytes_read);
19311       info_ptr += bytes_read;
19312       break;
19313     case DW_FORM_GNU_ref_alt:
19314       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19315       info_ptr += bytes_read;
19316       break;
19317     case DW_FORM_addr:
19318       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19319       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19320       info_ptr += bytes_read;
19321       break;
19322     case DW_FORM_block2:
19323       blk = dwarf_alloc_block (cu);
19324       blk->size = read_2_bytes (abfd, info_ptr);
19325       info_ptr += 2;
19326       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19327       info_ptr += blk->size;
19328       DW_BLOCK (attr) = blk;
19329       break;
19330     case DW_FORM_block4:
19331       blk = dwarf_alloc_block (cu);
19332       blk->size = read_4_bytes (abfd, info_ptr);
19333       info_ptr += 4;
19334       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19335       info_ptr += blk->size;
19336       DW_BLOCK (attr) = blk;
19337       break;
19338     case DW_FORM_data2:
19339       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19340       info_ptr += 2;
19341       break;
19342     case DW_FORM_data4:
19343       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19344       info_ptr += 4;
19345       break;
19346     case DW_FORM_data8:
19347       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19348       info_ptr += 8;
19349       break;
19350     case DW_FORM_data16:
19351       blk = dwarf_alloc_block (cu);
19352       blk->size = 16;
19353       blk->data = read_n_bytes (abfd, info_ptr, 16);
19354       info_ptr += 16;
19355       DW_BLOCK (attr) = blk;
19356       break;
19357     case DW_FORM_sec_offset:
19358       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19359       info_ptr += bytes_read;
19360       break;
19361     case DW_FORM_string:
19362       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19363       DW_STRING_IS_CANONICAL (attr) = 0;
19364       info_ptr += bytes_read;
19365       break;
19366     case DW_FORM_strp:
19367       if (!cu->per_cu->is_dwz)
19368         {
19369           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19370                                                    abfd, info_ptr, cu_header,
19371                                                    &bytes_read);
19372           DW_STRING_IS_CANONICAL (attr) = 0;
19373           info_ptr += bytes_read;
19374           break;
19375         }
19376       /* FALLTHROUGH */
19377     case DW_FORM_line_strp:
19378       if (!cu->per_cu->is_dwz)
19379         {
19380           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19381                                                         abfd, info_ptr,
19382                                                         cu_header, &bytes_read);
19383           DW_STRING_IS_CANONICAL (attr) = 0;
19384           info_ptr += bytes_read;
19385           break;
19386         }
19387       /* FALLTHROUGH */
19388     case DW_FORM_GNU_strp_alt:
19389       {
19390         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19391         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19392                                           &bytes_read);
19393
19394         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19395                                                           dwz, str_offset);
19396         DW_STRING_IS_CANONICAL (attr) = 0;
19397         info_ptr += bytes_read;
19398       }
19399       break;
19400     case DW_FORM_exprloc:
19401     case DW_FORM_block:
19402       blk = dwarf_alloc_block (cu);
19403       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19404       info_ptr += bytes_read;
19405       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19406       info_ptr += blk->size;
19407       DW_BLOCK (attr) = blk;
19408       break;
19409     case DW_FORM_block1:
19410       blk = dwarf_alloc_block (cu);
19411       blk->size = read_1_byte (abfd, info_ptr);
19412       info_ptr += 1;
19413       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19414       info_ptr += blk->size;
19415       DW_BLOCK (attr) = blk;
19416       break;
19417     case DW_FORM_data1:
19418       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19419       info_ptr += 1;
19420       break;
19421     case DW_FORM_flag:
19422       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19423       info_ptr += 1;
19424       break;
19425     case DW_FORM_flag_present:
19426       DW_UNSND (attr) = 1;
19427       break;
19428     case DW_FORM_sdata:
19429       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19430       info_ptr += bytes_read;
19431       break;
19432     case DW_FORM_udata:
19433       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19434       info_ptr += bytes_read;
19435       break;
19436     case DW_FORM_ref1:
19437       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19438                          + read_1_byte (abfd, info_ptr));
19439       info_ptr += 1;
19440       break;
19441     case DW_FORM_ref2:
19442       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19443                          + read_2_bytes (abfd, info_ptr));
19444       info_ptr += 2;
19445       break;
19446     case DW_FORM_ref4:
19447       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19448                          + read_4_bytes (abfd, info_ptr));
19449       info_ptr += 4;
19450       break;
19451     case DW_FORM_ref8:
19452       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19453                          + read_8_bytes (abfd, info_ptr));
19454       info_ptr += 8;
19455       break;
19456     case DW_FORM_ref_sig8:
19457       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19458       info_ptr += 8;
19459       break;
19460     case DW_FORM_ref_udata:
19461       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19462                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19463       info_ptr += bytes_read;
19464       break;
19465     case DW_FORM_indirect:
19466       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19467       info_ptr += bytes_read;
19468       if (form == DW_FORM_implicit_const)
19469         {
19470           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19471           info_ptr += bytes_read;
19472         }
19473       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19474                                        info_ptr);
19475       break;
19476     case DW_FORM_implicit_const:
19477       DW_SND (attr) = implicit_const;
19478       break;
19479     case DW_FORM_GNU_addr_index:
19480       if (reader->dwo_file == NULL)
19481         {
19482           /* For now flag a hard error.
19483              Later we can turn this into a complaint.  */
19484           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19485                  dwarf_form_name (form),
19486                  bfd_get_filename (abfd));
19487         }
19488       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19489       info_ptr += bytes_read;
19490       break;
19491     case DW_FORM_GNU_str_index:
19492       if (reader->dwo_file == NULL)
19493         {
19494           /* For now flag a hard error.
19495              Later we can turn this into a complaint if warranted.  */
19496           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19497                  dwarf_form_name (form),
19498                  bfd_get_filename (abfd));
19499         }
19500       {
19501         ULONGEST str_index =
19502           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19503
19504         DW_STRING (attr) = read_str_index (reader, str_index);
19505         DW_STRING_IS_CANONICAL (attr) = 0;
19506         info_ptr += bytes_read;
19507       }
19508       break;
19509     default:
19510       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19511              dwarf_form_name (form),
19512              bfd_get_filename (abfd));
19513     }
19514
19515   /* Super hack.  */
19516   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19517     attr->form = DW_FORM_GNU_ref_alt;
19518
19519   /* We have seen instances where the compiler tried to emit a byte
19520      size attribute of -1 which ended up being encoded as an unsigned
19521      0xffffffff.  Although 0xffffffff is technically a valid size value,
19522      an object of this size seems pretty unlikely so we can relatively
19523      safely treat these cases as if the size attribute was invalid and
19524      treat them as zero by default.  */
19525   if (attr->name == DW_AT_byte_size
19526       && form == DW_FORM_data4
19527       && DW_UNSND (attr) >= 0xffffffff)
19528     {
19529       complaint
19530         (&symfile_complaints,
19531          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19532          hex_string (DW_UNSND (attr)));
19533       DW_UNSND (attr) = 0;
19534     }
19535
19536   return info_ptr;
19537 }
19538
19539 /* Read an attribute described by an abbreviated attribute.  */
19540
19541 static const gdb_byte *
19542 read_attribute (const struct die_reader_specs *reader,
19543                 struct attribute *attr, struct attr_abbrev *abbrev,
19544                 const gdb_byte *info_ptr)
19545 {
19546   attr->name = abbrev->name;
19547   return read_attribute_value (reader, attr, abbrev->form,
19548                                abbrev->implicit_const, info_ptr);
19549 }
19550
19551 /* Read dwarf information from a buffer.  */
19552
19553 static unsigned int
19554 read_1_byte (bfd *abfd, const gdb_byte *buf)
19555 {
19556   return bfd_get_8 (abfd, buf);
19557 }
19558
19559 static int
19560 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19561 {
19562   return bfd_get_signed_8 (abfd, buf);
19563 }
19564
19565 static unsigned int
19566 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19567 {
19568   return bfd_get_16 (abfd, buf);
19569 }
19570
19571 static int
19572 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19573 {
19574   return bfd_get_signed_16 (abfd, buf);
19575 }
19576
19577 static unsigned int
19578 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19579 {
19580   return bfd_get_32 (abfd, buf);
19581 }
19582
19583 static int
19584 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19585 {
19586   return bfd_get_signed_32 (abfd, buf);
19587 }
19588
19589 static ULONGEST
19590 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19591 {
19592   return bfd_get_64 (abfd, buf);
19593 }
19594
19595 static CORE_ADDR
19596 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19597               unsigned int *bytes_read)
19598 {
19599   struct comp_unit_head *cu_header = &cu->header;
19600   CORE_ADDR retval = 0;
19601
19602   if (cu_header->signed_addr_p)
19603     {
19604       switch (cu_header->addr_size)
19605         {
19606         case 2:
19607           retval = bfd_get_signed_16 (abfd, buf);
19608           break;
19609         case 4:
19610           retval = bfd_get_signed_32 (abfd, buf);
19611           break;
19612         case 8:
19613           retval = bfd_get_signed_64 (abfd, buf);
19614           break;
19615         default:
19616           internal_error (__FILE__, __LINE__,
19617                           _("read_address: bad switch, signed [in module %s]"),
19618                           bfd_get_filename (abfd));
19619         }
19620     }
19621   else
19622     {
19623       switch (cu_header->addr_size)
19624         {
19625         case 2:
19626           retval = bfd_get_16 (abfd, buf);
19627           break;
19628         case 4:
19629           retval = bfd_get_32 (abfd, buf);
19630           break;
19631         case 8:
19632           retval = bfd_get_64 (abfd, buf);
19633           break;
19634         default:
19635           internal_error (__FILE__, __LINE__,
19636                           _("read_address: bad switch, "
19637                             "unsigned [in module %s]"),
19638                           bfd_get_filename (abfd));
19639         }
19640     }
19641
19642   *bytes_read = cu_header->addr_size;
19643   return retval;
19644 }
19645
19646 /* Read the initial length from a section.  The (draft) DWARF 3
19647    specification allows the initial length to take up either 4 bytes
19648    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19649    bytes describe the length and all offsets will be 8 bytes in length
19650    instead of 4.
19651
19652    An older, non-standard 64-bit format is also handled by this
19653    function.  The older format in question stores the initial length
19654    as an 8-byte quantity without an escape value.  Lengths greater
19655    than 2^32 aren't very common which means that the initial 4 bytes
19656    is almost always zero.  Since a length value of zero doesn't make
19657    sense for the 32-bit format, this initial zero can be considered to
19658    be an escape value which indicates the presence of the older 64-bit
19659    format.  As written, the code can't detect (old format) lengths
19660    greater than 4GB.  If it becomes necessary to handle lengths
19661    somewhat larger than 4GB, we could allow other small values (such
19662    as the non-sensical values of 1, 2, and 3) to also be used as
19663    escape values indicating the presence of the old format.
19664
19665    The value returned via bytes_read should be used to increment the
19666    relevant pointer after calling read_initial_length().
19667
19668    [ Note:  read_initial_length() and read_offset() are based on the
19669      document entitled "DWARF Debugging Information Format", revision
19670      3, draft 8, dated November 19, 2001.  This document was obtained
19671      from:
19672
19673         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19674
19675      This document is only a draft and is subject to change.  (So beware.)
19676
19677      Details regarding the older, non-standard 64-bit format were
19678      determined empirically by examining 64-bit ELF files produced by
19679      the SGI toolchain on an IRIX 6.5 machine.
19680
19681      - Kevin, July 16, 2002
19682    ] */
19683
19684 static LONGEST
19685 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19686 {
19687   LONGEST length = bfd_get_32 (abfd, buf);
19688
19689   if (length == 0xffffffff)
19690     {
19691       length = bfd_get_64 (abfd, buf + 4);
19692       *bytes_read = 12;
19693     }
19694   else if (length == 0)
19695     {
19696       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19697       length = bfd_get_64 (abfd, buf);
19698       *bytes_read = 8;
19699     }
19700   else
19701     {
19702       *bytes_read = 4;
19703     }
19704
19705   return length;
19706 }
19707
19708 /* Cover function for read_initial_length.
19709    Returns the length of the object at BUF, and stores the size of the
19710    initial length in *BYTES_READ and stores the size that offsets will be in
19711    *OFFSET_SIZE.
19712    If the initial length size is not equivalent to that specified in
19713    CU_HEADER then issue a complaint.
19714    This is useful when reading non-comp-unit headers.  */
19715
19716 static LONGEST
19717 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19718                                         const struct comp_unit_head *cu_header,
19719                                         unsigned int *bytes_read,
19720                                         unsigned int *offset_size)
19721 {
19722   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19723
19724   gdb_assert (cu_header->initial_length_size == 4
19725               || cu_header->initial_length_size == 8
19726               || cu_header->initial_length_size == 12);
19727
19728   if (cu_header->initial_length_size != *bytes_read)
19729     complaint (&symfile_complaints,
19730                _("intermixed 32-bit and 64-bit DWARF sections"));
19731
19732   *offset_size = (*bytes_read == 4) ? 4 : 8;
19733   return length;
19734 }
19735
19736 /* Read an offset from the data stream.  The size of the offset is
19737    given by cu_header->offset_size.  */
19738
19739 static LONGEST
19740 read_offset (bfd *abfd, const gdb_byte *buf,
19741              const struct comp_unit_head *cu_header,
19742              unsigned int *bytes_read)
19743 {
19744   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19745
19746   *bytes_read = cu_header->offset_size;
19747   return offset;
19748 }
19749
19750 /* Read an offset from the data stream.  */
19751
19752 static LONGEST
19753 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19754 {
19755   LONGEST retval = 0;
19756
19757   switch (offset_size)
19758     {
19759     case 4:
19760       retval = bfd_get_32 (abfd, buf);
19761       break;
19762     case 8:
19763       retval = bfd_get_64 (abfd, buf);
19764       break;
19765     default:
19766       internal_error (__FILE__, __LINE__,
19767                       _("read_offset_1: bad switch [in module %s]"),
19768                       bfd_get_filename (abfd));
19769     }
19770
19771   return retval;
19772 }
19773
19774 static const gdb_byte *
19775 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19776 {
19777   /* If the size of a host char is 8 bits, we can return a pointer
19778      to the buffer, otherwise we have to copy the data to a buffer
19779      allocated on the temporary obstack.  */
19780   gdb_assert (HOST_CHAR_BIT == 8);
19781   return buf;
19782 }
19783
19784 static const char *
19785 read_direct_string (bfd *abfd, const gdb_byte *buf,
19786                     unsigned int *bytes_read_ptr)
19787 {
19788   /* If the size of a host char is 8 bits, we can return a pointer
19789      to the string, otherwise we have to copy the string to a buffer
19790      allocated on the temporary obstack.  */
19791   gdb_assert (HOST_CHAR_BIT == 8);
19792   if (*buf == '\0')
19793     {
19794       *bytes_read_ptr = 1;
19795       return NULL;
19796     }
19797   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19798   return (const char *) buf;
19799 }
19800
19801 /* Return pointer to string at section SECT offset STR_OFFSET with error
19802    reporting strings FORM_NAME and SECT_NAME.  */
19803
19804 static const char *
19805 read_indirect_string_at_offset_from (struct objfile *objfile,
19806                                      bfd *abfd, LONGEST str_offset,
19807                                      struct dwarf2_section_info *sect,
19808                                      const char *form_name,
19809                                      const char *sect_name)
19810 {
19811   dwarf2_read_section (objfile, sect);
19812   if (sect->buffer == NULL)
19813     error (_("%s used without %s section [in module %s]"),
19814            form_name, sect_name, bfd_get_filename (abfd));
19815   if (str_offset >= sect->size)
19816     error (_("%s pointing outside of %s section [in module %s]"),
19817            form_name, sect_name, bfd_get_filename (abfd));
19818   gdb_assert (HOST_CHAR_BIT == 8);
19819   if (sect->buffer[str_offset] == '\0')
19820     return NULL;
19821   return (const char *) (sect->buffer + str_offset);
19822 }
19823
19824 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19825
19826 static const char *
19827 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19828                                 bfd *abfd, LONGEST str_offset)
19829 {
19830   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19831                                               abfd, str_offset,
19832                                               &dwarf2_per_objfile->str,
19833                                               "DW_FORM_strp", ".debug_str");
19834 }
19835
19836 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19837
19838 static const char *
19839 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19840                                      bfd *abfd, LONGEST str_offset)
19841 {
19842   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19843                                               abfd, str_offset,
19844                                               &dwarf2_per_objfile->line_str,
19845                                               "DW_FORM_line_strp",
19846                                               ".debug_line_str");
19847 }
19848
19849 /* Read a string at offset STR_OFFSET in the .debug_str section from
19850    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19851    the string consists of a single NUL byte, return NULL; otherwise
19852    return a pointer to the string.  */
19853
19854 static const char *
19855 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19856                                LONGEST str_offset)
19857 {
19858   dwarf2_read_section (objfile, &dwz->str);
19859
19860   if (dwz->str.buffer == NULL)
19861     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19862              "section [in module %s]"),
19863            bfd_get_filename (dwz->dwz_bfd));
19864   if (str_offset >= dwz->str.size)
19865     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19866              ".debug_str section [in module %s]"),
19867            bfd_get_filename (dwz->dwz_bfd));
19868   gdb_assert (HOST_CHAR_BIT == 8);
19869   if (dwz->str.buffer[str_offset] == '\0')
19870     return NULL;
19871   return (const char *) (dwz->str.buffer + str_offset);
19872 }
19873
19874 /* Return pointer to string at .debug_str offset as read from BUF.
19875    BUF is assumed to be in a compilation unit described by CU_HEADER.
19876    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19877
19878 static const char *
19879 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19880                       const gdb_byte *buf,
19881                       const struct comp_unit_head *cu_header,
19882                       unsigned int *bytes_read_ptr)
19883 {
19884   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19885
19886   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19887 }
19888
19889 /* Return pointer to string at .debug_line_str offset as read from BUF.
19890    BUF is assumed to be in a compilation unit described by CU_HEADER.
19891    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19892
19893 static const char *
19894 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19895                            bfd *abfd, const gdb_byte *buf,
19896                            const struct comp_unit_head *cu_header,
19897                            unsigned int *bytes_read_ptr)
19898 {
19899   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19900
19901   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19902                                               str_offset);
19903 }
19904
19905 ULONGEST
19906 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19907                           unsigned int *bytes_read_ptr)
19908 {
19909   ULONGEST result;
19910   unsigned int num_read;
19911   int shift;
19912   unsigned char byte;
19913
19914   result = 0;
19915   shift = 0;
19916   num_read = 0;
19917   while (1)
19918     {
19919       byte = bfd_get_8 (abfd, buf);
19920       buf++;
19921       num_read++;
19922       result |= ((ULONGEST) (byte & 127) << shift);
19923       if ((byte & 128) == 0)
19924         {
19925           break;
19926         }
19927       shift += 7;
19928     }
19929   *bytes_read_ptr = num_read;
19930   return result;
19931 }
19932
19933 static LONGEST
19934 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19935                     unsigned int *bytes_read_ptr)
19936 {
19937   LONGEST result;
19938   int shift, num_read;
19939   unsigned char byte;
19940
19941   result = 0;
19942   shift = 0;
19943   num_read = 0;
19944   while (1)
19945     {
19946       byte = bfd_get_8 (abfd, buf);
19947       buf++;
19948       num_read++;
19949       result |= ((LONGEST) (byte & 127) << shift);
19950       shift += 7;
19951       if ((byte & 128) == 0)
19952         {
19953           break;
19954         }
19955     }
19956   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19957     result |= -(((LONGEST) 1) << shift);
19958   *bytes_read_ptr = num_read;
19959   return result;
19960 }
19961
19962 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19963    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19964    ADDR_SIZE is the size of addresses from the CU header.  */
19965
19966 static CORE_ADDR
19967 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19968                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19969 {
19970   struct objfile *objfile = dwarf2_per_objfile->objfile;
19971   bfd *abfd = objfile->obfd;
19972   const gdb_byte *info_ptr;
19973
19974   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19975   if (dwarf2_per_objfile->addr.buffer == NULL)
19976     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19977            objfile_name (objfile));
19978   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19979     error (_("DW_FORM_addr_index pointing outside of "
19980              ".debug_addr section [in module %s]"),
19981            objfile_name (objfile));
19982   info_ptr = (dwarf2_per_objfile->addr.buffer
19983               + addr_base + addr_index * addr_size);
19984   if (addr_size == 4)
19985     return bfd_get_32 (abfd, info_ptr);
19986   else
19987     return bfd_get_64 (abfd, info_ptr);
19988 }
19989
19990 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19991
19992 static CORE_ADDR
19993 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19994 {
19995   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19996                             cu->addr_base, cu->header.addr_size);
19997 }
19998
19999 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
20000
20001 static CORE_ADDR
20002 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
20003                              unsigned int *bytes_read)
20004 {
20005   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
20006   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
20007
20008   return read_addr_index (cu, addr_index);
20009 }
20010
20011 /* Data structure to pass results from dwarf2_read_addr_index_reader
20012    back to dwarf2_read_addr_index.  */
20013
20014 struct dwarf2_read_addr_index_data
20015 {
20016   ULONGEST addr_base;
20017   int addr_size;
20018 };
20019
20020 /* die_reader_func for dwarf2_read_addr_index.  */
20021
20022 static void
20023 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
20024                                const gdb_byte *info_ptr,
20025                                struct die_info *comp_unit_die,
20026                                int has_children,
20027                                void *data)
20028 {
20029   struct dwarf2_cu *cu = reader->cu;
20030   struct dwarf2_read_addr_index_data *aidata =
20031     (struct dwarf2_read_addr_index_data *) data;
20032
20033   aidata->addr_base = cu->addr_base;
20034   aidata->addr_size = cu->header.addr_size;
20035 }
20036
20037 /* Given an index in .debug_addr, fetch the value.
20038    NOTE: This can be called during dwarf expression evaluation,
20039    long after the debug information has been read, and thus per_cu->cu
20040    may no longer exist.  */
20041
20042 CORE_ADDR
20043 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
20044                         unsigned int addr_index)
20045 {
20046   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
20047   struct objfile *objfile = dwarf2_per_objfile->objfile;
20048   struct dwarf2_cu *cu = per_cu->cu;
20049   ULONGEST addr_base;
20050   int addr_size;
20051
20052   /* We need addr_base and addr_size.
20053      If we don't have PER_CU->cu, we have to get it.
20054      Nasty, but the alternative is storing the needed info in PER_CU,
20055      which at this point doesn't seem justified: it's not clear how frequently
20056      it would get used and it would increase the size of every PER_CU.
20057      Entry points like dwarf2_per_cu_addr_size do a similar thing
20058      so we're not in uncharted territory here.
20059      Alas we need to be a bit more complicated as addr_base is contained
20060      in the DIE.
20061
20062      We don't need to read the entire CU(/TU).
20063      We just need the header and top level die.
20064
20065      IWBN to use the aging mechanism to let us lazily later discard the CU.
20066      For now we skip this optimization.  */
20067
20068   if (cu != NULL)
20069     {
20070       addr_base = cu->addr_base;
20071       addr_size = cu->header.addr_size;
20072     }
20073   else
20074     {
20075       struct dwarf2_read_addr_index_data aidata;
20076
20077       /* Note: We can't use init_cutu_and_read_dies_simple here,
20078          we need addr_base.  */
20079       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
20080                                dwarf2_read_addr_index_reader, &aidata);
20081       addr_base = aidata.addr_base;
20082       addr_size = aidata.addr_size;
20083     }
20084
20085   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
20086                             addr_size);
20087 }
20088
20089 /* Given a DW_FORM_GNU_str_index, fetch the string.
20090    This is only used by the Fission support.  */
20091
20092 static const char *
20093 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
20094 {
20095   struct dwarf2_cu *cu = reader->cu;
20096   struct dwarf2_per_objfile *dwarf2_per_objfile
20097     = cu->per_cu->dwarf2_per_objfile;
20098   struct objfile *objfile = dwarf2_per_objfile->objfile;
20099   const char *objf_name = objfile_name (objfile);
20100   bfd *abfd = objfile->obfd;
20101   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
20102   struct dwarf2_section_info *str_offsets_section =
20103     &reader->dwo_file->sections.str_offsets;
20104   const gdb_byte *info_ptr;
20105   ULONGEST str_offset;
20106   static const char form_name[] = "DW_FORM_GNU_str_index";
20107
20108   dwarf2_read_section (objfile, str_section);
20109   dwarf2_read_section (objfile, str_offsets_section);
20110   if (str_section->buffer == NULL)
20111     error (_("%s used without .debug_str.dwo section"
20112              " in CU at offset %s [in module %s]"),
20113            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20114   if (str_offsets_section->buffer == NULL)
20115     error (_("%s used without .debug_str_offsets.dwo section"
20116              " in CU at offset %s [in module %s]"),
20117            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20118   if (str_index * cu->header.offset_size >= str_offsets_section->size)
20119     error (_("%s pointing outside of .debug_str_offsets.dwo"
20120              " section in CU at offset %s [in module %s]"),
20121            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20122   info_ptr = (str_offsets_section->buffer
20123               + str_index * cu->header.offset_size);
20124   if (cu->header.offset_size == 4)
20125     str_offset = bfd_get_32 (abfd, info_ptr);
20126   else
20127     str_offset = bfd_get_64 (abfd, info_ptr);
20128   if (str_offset >= str_section->size)
20129     error (_("Offset from %s pointing outside of"
20130              " .debug_str.dwo section in CU at offset %s [in module %s]"),
20131            form_name, sect_offset_str (cu->header.sect_off), objf_name);
20132   return (const char *) (str_section->buffer + str_offset);
20133 }
20134
20135 /* Return the length of an LEB128 number in BUF.  */
20136
20137 static int
20138 leb128_size (const gdb_byte *buf)
20139 {
20140   const gdb_byte *begin = buf;
20141   gdb_byte byte;
20142
20143   while (1)
20144     {
20145       byte = *buf++;
20146       if ((byte & 128) == 0)
20147         return buf - begin;
20148     }
20149 }
20150
20151 static void
20152 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
20153 {
20154   switch (lang)
20155     {
20156     case DW_LANG_C89:
20157     case DW_LANG_C99:
20158     case DW_LANG_C11:
20159     case DW_LANG_C:
20160     case DW_LANG_UPC:
20161       cu->language = language_c;
20162       break;
20163     case DW_LANG_Java:
20164     case DW_LANG_C_plus_plus:
20165     case DW_LANG_C_plus_plus_11:
20166     case DW_LANG_C_plus_plus_14:
20167       cu->language = language_cplus;
20168       break;
20169     case DW_LANG_D:
20170       cu->language = language_d;
20171       break;
20172     case DW_LANG_Fortran77:
20173     case DW_LANG_Fortran90:
20174     case DW_LANG_Fortran95:
20175     case DW_LANG_Fortran03:
20176     case DW_LANG_Fortran08:
20177       cu->language = language_fortran;
20178       break;
20179     case DW_LANG_Go:
20180       cu->language = language_go;
20181       break;
20182     case DW_LANG_Mips_Assembler:
20183       cu->language = language_asm;
20184       break;
20185     case DW_LANG_Ada83:
20186     case DW_LANG_Ada95:
20187       cu->language = language_ada;
20188       break;
20189     case DW_LANG_Modula2:
20190       cu->language = language_m2;
20191       break;
20192     case DW_LANG_Pascal83:
20193       cu->language = language_pascal;
20194       break;
20195     case DW_LANG_ObjC:
20196       cu->language = language_objc;
20197       break;
20198     case DW_LANG_Rust:
20199     case DW_LANG_Rust_old:
20200       cu->language = language_rust;
20201       break;
20202     case DW_LANG_Cobol74:
20203     case DW_LANG_Cobol85:
20204     default:
20205       cu->language = language_minimal;
20206       break;
20207     }
20208   cu->language_defn = language_def (cu->language);
20209 }
20210
20211 /* Return the named attribute or NULL if not there.  */
20212
20213 static struct attribute *
20214 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20215 {
20216   for (;;)
20217     {
20218       unsigned int i;
20219       struct attribute *spec = NULL;
20220
20221       for (i = 0; i < die->num_attrs; ++i)
20222         {
20223           if (die->attrs[i].name == name)
20224             return &die->attrs[i];
20225           if (die->attrs[i].name == DW_AT_specification
20226               || die->attrs[i].name == DW_AT_abstract_origin)
20227             spec = &die->attrs[i];
20228         }
20229
20230       if (!spec)
20231         break;
20232
20233       die = follow_die_ref (die, spec, &cu);
20234     }
20235
20236   return NULL;
20237 }
20238
20239 /* Return the named attribute or NULL if not there,
20240    but do not follow DW_AT_specification, etc.
20241    This is for use in contexts where we're reading .debug_types dies.
20242    Following DW_AT_specification, DW_AT_abstract_origin will take us
20243    back up the chain, and we want to go down.  */
20244
20245 static struct attribute *
20246 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20247 {
20248   unsigned int i;
20249
20250   for (i = 0; i < die->num_attrs; ++i)
20251     if (die->attrs[i].name == name)
20252       return &die->attrs[i];
20253
20254   return NULL;
20255 }
20256
20257 /* Return the string associated with a string-typed attribute, or NULL if it
20258    is either not found or is of an incorrect type.  */
20259
20260 static const char *
20261 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20262 {
20263   struct attribute *attr;
20264   const char *str = NULL;
20265
20266   attr = dwarf2_attr (die, name, cu);
20267
20268   if (attr != NULL)
20269     {
20270       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20271           || attr->form == DW_FORM_string
20272           || attr->form == DW_FORM_GNU_str_index
20273           || attr->form == DW_FORM_GNU_strp_alt)
20274         str = DW_STRING (attr);
20275       else
20276         complaint (&symfile_complaints,
20277                    _("string type expected for attribute %s for "
20278                      "DIE at %s in module %s"),
20279                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20280                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20281     }
20282
20283   return str;
20284 }
20285
20286 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20287    and holds a non-zero value.  This function should only be used for
20288    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20289
20290 static int
20291 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20292 {
20293   struct attribute *attr = dwarf2_attr (die, name, cu);
20294
20295   return (attr && DW_UNSND (attr));
20296 }
20297
20298 static int
20299 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20300 {
20301   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20302      which value is non-zero.  However, we have to be careful with
20303      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20304      (via dwarf2_flag_true_p) follows this attribute.  So we may
20305      end up accidently finding a declaration attribute that belongs
20306      to a different DIE referenced by the specification attribute,
20307      even though the given DIE does not have a declaration attribute.  */
20308   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20309           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20310 }
20311
20312 /* Return the die giving the specification for DIE, if there is
20313    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20314    containing the return value on output.  If there is no
20315    specification, but there is an abstract origin, that is
20316    returned.  */
20317
20318 static struct die_info *
20319 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20320 {
20321   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20322                                              *spec_cu);
20323
20324   if (spec_attr == NULL)
20325     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20326
20327   if (spec_attr == NULL)
20328     return NULL;
20329   else
20330     return follow_die_ref (die, spec_attr, spec_cu);
20331 }
20332
20333 /* Stub for free_line_header to match void * callback types.  */
20334
20335 static void
20336 free_line_header_voidp (void *arg)
20337 {
20338   struct line_header *lh = (struct line_header *) arg;
20339
20340   delete lh;
20341 }
20342
20343 void
20344 line_header::add_include_dir (const char *include_dir)
20345 {
20346   if (dwarf_line_debug >= 2)
20347     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20348                         include_dirs.size () + 1, include_dir);
20349
20350   include_dirs.push_back (include_dir);
20351 }
20352
20353 void
20354 line_header::add_file_name (const char *name,
20355                             dir_index d_index,
20356                             unsigned int mod_time,
20357                             unsigned int length)
20358 {
20359   if (dwarf_line_debug >= 2)
20360     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20361                         (unsigned) file_names.size () + 1, name);
20362
20363   file_names.emplace_back (name, d_index, mod_time, length);
20364 }
20365
20366 /* A convenience function to find the proper .debug_line section for a CU.  */
20367
20368 static struct dwarf2_section_info *
20369 get_debug_line_section (struct dwarf2_cu *cu)
20370 {
20371   struct dwarf2_section_info *section;
20372   struct dwarf2_per_objfile *dwarf2_per_objfile
20373     = cu->per_cu->dwarf2_per_objfile;
20374
20375   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20376      DWO file.  */
20377   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20378     section = &cu->dwo_unit->dwo_file->sections.line;
20379   else if (cu->per_cu->is_dwz)
20380     {
20381       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20382
20383       section = &dwz->line;
20384     }
20385   else
20386     section = &dwarf2_per_objfile->line;
20387
20388   return section;
20389 }
20390
20391 /* Read directory or file name entry format, starting with byte of
20392    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20393    entries count and the entries themselves in the described entry
20394    format.  */
20395
20396 static void
20397 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20398                         bfd *abfd, const gdb_byte **bufp,
20399                         struct line_header *lh,
20400                         const struct comp_unit_head *cu_header,
20401                         void (*callback) (struct line_header *lh,
20402                                           const char *name,
20403                                           dir_index d_index,
20404                                           unsigned int mod_time,
20405                                           unsigned int length))
20406 {
20407   gdb_byte format_count, formati;
20408   ULONGEST data_count, datai;
20409   const gdb_byte *buf = *bufp;
20410   const gdb_byte *format_header_data;
20411   unsigned int bytes_read;
20412
20413   format_count = read_1_byte (abfd, buf);
20414   buf += 1;
20415   format_header_data = buf;
20416   for (formati = 0; formati < format_count; formati++)
20417     {
20418       read_unsigned_leb128 (abfd, buf, &bytes_read);
20419       buf += bytes_read;
20420       read_unsigned_leb128 (abfd, buf, &bytes_read);
20421       buf += bytes_read;
20422     }
20423
20424   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20425   buf += bytes_read;
20426   for (datai = 0; datai < data_count; datai++)
20427     {
20428       const gdb_byte *format = format_header_data;
20429       struct file_entry fe;
20430
20431       for (formati = 0; formati < format_count; formati++)
20432         {
20433           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20434           format += bytes_read;
20435
20436           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20437           format += bytes_read;
20438
20439           gdb::optional<const char *> string;
20440           gdb::optional<unsigned int> uint;
20441
20442           switch (form)
20443             {
20444             case DW_FORM_string:
20445               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20446               buf += bytes_read;
20447               break;
20448
20449             case DW_FORM_line_strp:
20450               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20451                                                          abfd, buf,
20452                                                          cu_header,
20453                                                          &bytes_read));
20454               buf += bytes_read;
20455               break;
20456
20457             case DW_FORM_data1:
20458               uint.emplace (read_1_byte (abfd, buf));
20459               buf += 1;
20460               break;
20461
20462             case DW_FORM_data2:
20463               uint.emplace (read_2_bytes (abfd, buf));
20464               buf += 2;
20465               break;
20466
20467             case DW_FORM_data4:
20468               uint.emplace (read_4_bytes (abfd, buf));
20469               buf += 4;
20470               break;
20471
20472             case DW_FORM_data8:
20473               uint.emplace (read_8_bytes (abfd, buf));
20474               buf += 8;
20475               break;
20476
20477             case DW_FORM_udata:
20478               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20479               buf += bytes_read;
20480               break;
20481
20482             case DW_FORM_block:
20483               /* It is valid only for DW_LNCT_timestamp which is ignored by
20484                  current GDB.  */
20485               break;
20486             }
20487
20488           switch (content_type)
20489             {
20490             case DW_LNCT_path:
20491               if (string.has_value ())
20492                 fe.name = *string;
20493               break;
20494             case DW_LNCT_directory_index:
20495               if (uint.has_value ())
20496                 fe.d_index = (dir_index) *uint;
20497               break;
20498             case DW_LNCT_timestamp:
20499               if (uint.has_value ())
20500                 fe.mod_time = *uint;
20501               break;
20502             case DW_LNCT_size:
20503               if (uint.has_value ())
20504                 fe.length = *uint;
20505               break;
20506             case DW_LNCT_MD5:
20507               break;
20508             default:
20509               complaint (&symfile_complaints,
20510                          _("Unknown format content type %s"),
20511                          pulongest (content_type));
20512             }
20513         }
20514
20515       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20516     }
20517
20518   *bufp = buf;
20519 }
20520
20521 /* Read the statement program header starting at OFFSET in
20522    .debug_line, or .debug_line.dwo.  Return a pointer
20523    to a struct line_header, allocated using xmalloc.
20524    Returns NULL if there is a problem reading the header, e.g., if it
20525    has a version we don't understand.
20526
20527    NOTE: the strings in the include directory and file name tables of
20528    the returned object point into the dwarf line section buffer,
20529    and must not be freed.  */
20530
20531 static line_header_up
20532 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20533 {
20534   const gdb_byte *line_ptr;
20535   unsigned int bytes_read, offset_size;
20536   int i;
20537   const char *cur_dir, *cur_file;
20538   struct dwarf2_section_info *section;
20539   bfd *abfd;
20540   struct dwarf2_per_objfile *dwarf2_per_objfile
20541     = cu->per_cu->dwarf2_per_objfile;
20542
20543   section = get_debug_line_section (cu);
20544   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20545   if (section->buffer == NULL)
20546     {
20547       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20548         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20549       else
20550         complaint (&symfile_complaints, _("missing .debug_line section"));
20551       return 0;
20552     }
20553
20554   /* We can't do this until we know the section is non-empty.
20555      Only then do we know we have such a section.  */
20556   abfd = get_section_bfd_owner (section);
20557
20558   /* Make sure that at least there's room for the total_length field.
20559      That could be 12 bytes long, but we're just going to fudge that.  */
20560   if (to_underlying (sect_off) + 4 >= section->size)
20561     {
20562       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20563       return 0;
20564     }
20565
20566   line_header_up lh (new line_header ());
20567
20568   lh->sect_off = sect_off;
20569   lh->offset_in_dwz = cu->per_cu->is_dwz;
20570
20571   line_ptr = section->buffer + to_underlying (sect_off);
20572
20573   /* Read in the header.  */
20574   lh->total_length =
20575     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20576                                             &bytes_read, &offset_size);
20577   line_ptr += bytes_read;
20578   if (line_ptr + lh->total_length > (section->buffer + section->size))
20579     {
20580       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20581       return 0;
20582     }
20583   lh->statement_program_end = line_ptr + lh->total_length;
20584   lh->version = read_2_bytes (abfd, line_ptr);
20585   line_ptr += 2;
20586   if (lh->version > 5)
20587     {
20588       /* This is a version we don't understand.  The format could have
20589          changed in ways we don't handle properly so just punt.  */
20590       complaint (&symfile_complaints,
20591                  _("unsupported version in .debug_line section"));
20592       return NULL;
20593     }
20594   if (lh->version >= 5)
20595     {
20596       gdb_byte segment_selector_size;
20597
20598       /* Skip address size.  */
20599       read_1_byte (abfd, line_ptr);
20600       line_ptr += 1;
20601
20602       segment_selector_size = read_1_byte (abfd, line_ptr);
20603       line_ptr += 1;
20604       if (segment_selector_size != 0)
20605         {
20606           complaint (&symfile_complaints,
20607                      _("unsupported segment selector size %u "
20608                        "in .debug_line section"),
20609                      segment_selector_size);
20610           return NULL;
20611         }
20612     }
20613   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20614   line_ptr += offset_size;
20615   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20616   line_ptr += 1;
20617   if (lh->version >= 4)
20618     {
20619       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20620       line_ptr += 1;
20621     }
20622   else
20623     lh->maximum_ops_per_instruction = 1;
20624
20625   if (lh->maximum_ops_per_instruction == 0)
20626     {
20627       lh->maximum_ops_per_instruction = 1;
20628       complaint (&symfile_complaints,
20629                  _("invalid maximum_ops_per_instruction "
20630                    "in `.debug_line' section"));
20631     }
20632
20633   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20634   line_ptr += 1;
20635   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20636   line_ptr += 1;
20637   lh->line_range = read_1_byte (abfd, line_ptr);
20638   line_ptr += 1;
20639   lh->opcode_base = read_1_byte (abfd, line_ptr);
20640   line_ptr += 1;
20641   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20642
20643   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20644   for (i = 1; i < lh->opcode_base; ++i)
20645     {
20646       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20647       line_ptr += 1;
20648     }
20649
20650   if (lh->version >= 5)
20651     {
20652       /* Read directory table.  */
20653       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20654                               &cu->header,
20655                               [] (struct line_header *lh, const char *name,
20656                                   dir_index d_index, unsigned int mod_time,
20657                                   unsigned int length)
20658         {
20659           lh->add_include_dir (name);
20660         });
20661
20662       /* Read file name table.  */
20663       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20664                               &cu->header,
20665                               [] (struct line_header *lh, const char *name,
20666                                   dir_index d_index, unsigned int mod_time,
20667                                   unsigned int length)
20668         {
20669           lh->add_file_name (name, d_index, mod_time, length);
20670         });
20671     }
20672   else
20673     {
20674       /* Read directory table.  */
20675       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20676         {
20677           line_ptr += bytes_read;
20678           lh->add_include_dir (cur_dir);
20679         }
20680       line_ptr += bytes_read;
20681
20682       /* Read file name table.  */
20683       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20684         {
20685           unsigned int mod_time, length;
20686           dir_index d_index;
20687
20688           line_ptr += bytes_read;
20689           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20690           line_ptr += bytes_read;
20691           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20692           line_ptr += bytes_read;
20693           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20694           line_ptr += bytes_read;
20695
20696           lh->add_file_name (cur_file, d_index, mod_time, length);
20697         }
20698       line_ptr += bytes_read;
20699     }
20700   lh->statement_program_start = line_ptr;
20701
20702   if (line_ptr > (section->buffer + section->size))
20703     complaint (&symfile_complaints,
20704                _("line number info header doesn't "
20705                  "fit in `.debug_line' section"));
20706
20707   return lh;
20708 }
20709
20710 /* Subroutine of dwarf_decode_lines to simplify it.
20711    Return the file name of the psymtab for included file FILE_INDEX
20712    in line header LH of PST.
20713    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20714    If space for the result is malloc'd, *NAME_HOLDER will be set.
20715    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20716
20717 static const char *
20718 psymtab_include_file_name (const struct line_header *lh, int file_index,
20719                            const struct partial_symtab *pst,
20720                            const char *comp_dir,
20721                            gdb::unique_xmalloc_ptr<char> *name_holder)
20722 {
20723   const file_entry &fe = lh->file_names[file_index];
20724   const char *include_name = fe.name;
20725   const char *include_name_to_compare = include_name;
20726   const char *pst_filename;
20727   int file_is_pst;
20728
20729   const char *dir_name = fe.include_dir (lh);
20730
20731   gdb::unique_xmalloc_ptr<char> hold_compare;
20732   if (!IS_ABSOLUTE_PATH (include_name)
20733       && (dir_name != NULL || comp_dir != NULL))
20734     {
20735       /* Avoid creating a duplicate psymtab for PST.
20736          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20737          Before we do the comparison, however, we need to account
20738          for DIR_NAME and COMP_DIR.
20739          First prepend dir_name (if non-NULL).  If we still don't
20740          have an absolute path prepend comp_dir (if non-NULL).
20741          However, the directory we record in the include-file's
20742          psymtab does not contain COMP_DIR (to match the
20743          corresponding symtab(s)).
20744
20745          Example:
20746
20747          bash$ cd /tmp
20748          bash$ gcc -g ./hello.c
20749          include_name = "hello.c"
20750          dir_name = "."
20751          DW_AT_comp_dir = comp_dir = "/tmp"
20752          DW_AT_name = "./hello.c"
20753
20754       */
20755
20756       if (dir_name != NULL)
20757         {
20758           name_holder->reset (concat (dir_name, SLASH_STRING,
20759                                       include_name, (char *) NULL));
20760           include_name = name_holder->get ();
20761           include_name_to_compare = include_name;
20762         }
20763       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20764         {
20765           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20766                                       include_name, (char *) NULL));
20767           include_name_to_compare = hold_compare.get ();
20768         }
20769     }
20770
20771   pst_filename = pst->filename;
20772   gdb::unique_xmalloc_ptr<char> copied_name;
20773   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20774     {
20775       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20776                                  pst_filename, (char *) NULL));
20777       pst_filename = copied_name.get ();
20778     }
20779
20780   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20781
20782   if (file_is_pst)
20783     return NULL;
20784   return include_name;
20785 }
20786
20787 /* State machine to track the state of the line number program.  */
20788
20789 class lnp_state_machine
20790 {
20791 public:
20792   /* Initialize a machine state for the start of a line number
20793      program.  */
20794   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20795
20796   file_entry *current_file ()
20797   {
20798     /* lh->file_names is 0-based, but the file name numbers in the
20799        statement program are 1-based.  */
20800     return m_line_header->file_name_at (m_file);
20801   }
20802
20803   /* Record the line in the state machine.  END_SEQUENCE is true if
20804      we're processing the end of a sequence.  */
20805   void record_line (bool end_sequence);
20806
20807   /* Check address and if invalid nop-out the rest of the lines in this
20808      sequence.  */
20809   void check_line_address (struct dwarf2_cu *cu,
20810                            const gdb_byte *line_ptr,
20811                            CORE_ADDR lowpc, CORE_ADDR address);
20812
20813   void handle_set_discriminator (unsigned int discriminator)
20814   {
20815     m_discriminator = discriminator;
20816     m_line_has_non_zero_discriminator |= discriminator != 0;
20817   }
20818
20819   /* Handle DW_LNE_set_address.  */
20820   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20821   {
20822     m_op_index = 0;
20823     address += baseaddr;
20824     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20825   }
20826
20827   /* Handle DW_LNS_advance_pc.  */
20828   void handle_advance_pc (CORE_ADDR adjust);
20829
20830   /* Handle a special opcode.  */
20831   void handle_special_opcode (unsigned char op_code);
20832
20833   /* Handle DW_LNS_advance_line.  */
20834   void handle_advance_line (int line_delta)
20835   {
20836     advance_line (line_delta);
20837   }
20838
20839   /* Handle DW_LNS_set_file.  */
20840   void handle_set_file (file_name_index file);
20841
20842   /* Handle DW_LNS_negate_stmt.  */
20843   void handle_negate_stmt ()
20844   {
20845     m_is_stmt = !m_is_stmt;
20846   }
20847
20848   /* Handle DW_LNS_const_add_pc.  */
20849   void handle_const_add_pc ();
20850
20851   /* Handle DW_LNS_fixed_advance_pc.  */
20852   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20853   {
20854     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20855     m_op_index = 0;
20856   }
20857
20858   /* Handle DW_LNS_copy.  */
20859   void handle_copy ()
20860   {
20861     record_line (false);
20862     m_discriminator = 0;
20863   }
20864
20865   /* Handle DW_LNE_end_sequence.  */
20866   void handle_end_sequence ()
20867   {
20868     m_record_line_callback = ::record_line;
20869   }
20870
20871 private:
20872   /* Advance the line by LINE_DELTA.  */
20873   void advance_line (int line_delta)
20874   {
20875     m_line += line_delta;
20876
20877     if (line_delta != 0)
20878       m_line_has_non_zero_discriminator = m_discriminator != 0;
20879   }
20880
20881   gdbarch *m_gdbarch;
20882
20883   /* True if we're recording lines.
20884      Otherwise we're building partial symtabs and are just interested in
20885      finding include files mentioned by the line number program.  */
20886   bool m_record_lines_p;
20887
20888   /* The line number header.  */
20889   line_header *m_line_header;
20890
20891   /* These are part of the standard DWARF line number state machine,
20892      and initialized according to the DWARF spec.  */
20893
20894   unsigned char m_op_index = 0;
20895   /* The line table index (1-based) of the current file.  */
20896   file_name_index m_file = (file_name_index) 1;
20897   unsigned int m_line = 1;
20898
20899   /* These are initialized in the constructor.  */
20900
20901   CORE_ADDR m_address;
20902   bool m_is_stmt;
20903   unsigned int m_discriminator;
20904
20905   /* Additional bits of state we need to track.  */
20906
20907   /* The last file that we called dwarf2_start_subfile for.
20908      This is only used for TLLs.  */
20909   unsigned int m_last_file = 0;
20910   /* The last file a line number was recorded for.  */
20911   struct subfile *m_last_subfile = NULL;
20912
20913   /* The function to call to record a line.  */
20914   record_line_ftype *m_record_line_callback = NULL;
20915
20916   /* The last line number that was recorded, used to coalesce
20917      consecutive entries for the same line.  This can happen, for
20918      example, when discriminators are present.  PR 17276.  */
20919   unsigned int m_last_line = 0;
20920   bool m_line_has_non_zero_discriminator = false;
20921 };
20922
20923 void
20924 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20925 {
20926   CORE_ADDR addr_adj = (((m_op_index + adjust)
20927                          / m_line_header->maximum_ops_per_instruction)
20928                         * m_line_header->minimum_instruction_length);
20929   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20930   m_op_index = ((m_op_index + adjust)
20931                 % m_line_header->maximum_ops_per_instruction);
20932 }
20933
20934 void
20935 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20936 {
20937   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20938   CORE_ADDR addr_adj = (((m_op_index
20939                           + (adj_opcode / m_line_header->line_range))
20940                          / m_line_header->maximum_ops_per_instruction)
20941                         * m_line_header->minimum_instruction_length);
20942   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20943   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20944                 % m_line_header->maximum_ops_per_instruction);
20945
20946   int line_delta = (m_line_header->line_base
20947                     + (adj_opcode % m_line_header->line_range));
20948   advance_line (line_delta);
20949   record_line (false);
20950   m_discriminator = 0;
20951 }
20952
20953 void
20954 lnp_state_machine::handle_set_file (file_name_index file)
20955 {
20956   m_file = file;
20957
20958   const file_entry *fe = current_file ();
20959   if (fe == NULL)
20960     dwarf2_debug_line_missing_file_complaint ();
20961   else if (m_record_lines_p)
20962     {
20963       const char *dir = fe->include_dir (m_line_header);
20964
20965       m_last_subfile = current_subfile;
20966       m_line_has_non_zero_discriminator = m_discriminator != 0;
20967       dwarf2_start_subfile (fe->name, dir);
20968     }
20969 }
20970
20971 void
20972 lnp_state_machine::handle_const_add_pc ()
20973 {
20974   CORE_ADDR adjust
20975     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20976
20977   CORE_ADDR addr_adj
20978     = (((m_op_index + adjust)
20979         / m_line_header->maximum_ops_per_instruction)
20980        * m_line_header->minimum_instruction_length);
20981
20982   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20983   m_op_index = ((m_op_index + adjust)
20984                 % m_line_header->maximum_ops_per_instruction);
20985 }
20986
20987 /* Ignore this record_line request.  */
20988
20989 static void
20990 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20991 {
20992   return;
20993 }
20994
20995 /* Return non-zero if we should add LINE to the line number table.
20996    LINE is the line to add, LAST_LINE is the last line that was added,
20997    LAST_SUBFILE is the subfile for LAST_LINE.
20998    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20999    had a non-zero discriminator.
21000
21001    We have to be careful in the presence of discriminators.
21002    E.g., for this line:
21003
21004      for (i = 0; i < 100000; i++);
21005
21006    clang can emit four line number entries for that one line,
21007    each with a different discriminator.
21008    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
21009
21010    However, we want gdb to coalesce all four entries into one.
21011    Otherwise the user could stepi into the middle of the line and
21012    gdb would get confused about whether the pc really was in the
21013    middle of the line.
21014
21015    Things are further complicated by the fact that two consecutive
21016    line number entries for the same line is a heuristic used by gcc
21017    to denote the end of the prologue.  So we can't just discard duplicate
21018    entries, we have to be selective about it.  The heuristic we use is
21019    that we only collapse consecutive entries for the same line if at least
21020    one of those entries has a non-zero discriminator.  PR 17276.
21021
21022    Note: Addresses in the line number state machine can never go backwards
21023    within one sequence, thus this coalescing is ok.  */
21024
21025 static int
21026 dwarf_record_line_p (unsigned int line, unsigned int last_line,
21027                      int line_has_non_zero_discriminator,
21028                      struct subfile *last_subfile)
21029 {
21030   if (current_subfile != last_subfile)
21031     return 1;
21032   if (line != last_line)
21033     return 1;
21034   /* Same line for the same file that we've seen already.
21035      As a last check, for pr 17276, only record the line if the line
21036      has never had a non-zero discriminator.  */
21037   if (!line_has_non_zero_discriminator)
21038     return 1;
21039   return 0;
21040 }
21041
21042 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
21043    in the line table of subfile SUBFILE.  */
21044
21045 static void
21046 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
21047                      unsigned int line, CORE_ADDR address,
21048                      record_line_ftype p_record_line)
21049 {
21050   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
21051
21052   if (dwarf_line_debug)
21053     {
21054       fprintf_unfiltered (gdb_stdlog,
21055                           "Recording line %u, file %s, address %s\n",
21056                           line, lbasename (subfile->name),
21057                           paddress (gdbarch, address));
21058     }
21059
21060   (*p_record_line) (subfile, line, addr);
21061 }
21062
21063 /* Subroutine of dwarf_decode_lines_1 to simplify it.
21064    Mark the end of a set of line number records.
21065    The arguments are the same as for dwarf_record_line_1.
21066    If SUBFILE is NULL the request is ignored.  */
21067
21068 static void
21069 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
21070                    CORE_ADDR address, record_line_ftype p_record_line)
21071 {
21072   if (subfile == NULL)
21073     return;
21074
21075   if (dwarf_line_debug)
21076     {
21077       fprintf_unfiltered (gdb_stdlog,
21078                           "Finishing current line, file %s, address %s\n",
21079                           lbasename (subfile->name),
21080                           paddress (gdbarch, address));
21081     }
21082
21083   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
21084 }
21085
21086 void
21087 lnp_state_machine::record_line (bool end_sequence)
21088 {
21089   if (dwarf_line_debug)
21090     {
21091       fprintf_unfiltered (gdb_stdlog,
21092                           "Processing actual line %u: file %u,"
21093                           " address %s, is_stmt %u, discrim %u\n",
21094                           m_line, to_underlying (m_file),
21095                           paddress (m_gdbarch, m_address),
21096                           m_is_stmt, m_discriminator);
21097     }
21098
21099   file_entry *fe = current_file ();
21100
21101   if (fe == NULL)
21102     dwarf2_debug_line_missing_file_complaint ();
21103   /* For now we ignore lines not starting on an instruction boundary.
21104      But not when processing end_sequence for compatibility with the
21105      previous version of the code.  */
21106   else if (m_op_index == 0 || end_sequence)
21107     {
21108       fe->included_p = 1;
21109       if (m_record_lines_p && m_is_stmt)
21110         {
21111           if (m_last_subfile != current_subfile || end_sequence)
21112             {
21113               dwarf_finish_line (m_gdbarch, m_last_subfile,
21114                                  m_address, m_record_line_callback);
21115             }
21116
21117           if (!end_sequence)
21118             {
21119               if (dwarf_record_line_p (m_line, m_last_line,
21120                                        m_line_has_non_zero_discriminator,
21121                                        m_last_subfile))
21122                 {
21123                   dwarf_record_line_1 (m_gdbarch, current_subfile,
21124                                        m_line, m_address,
21125                                        m_record_line_callback);
21126                 }
21127               m_last_subfile = current_subfile;
21128               m_last_line = m_line;
21129             }
21130         }
21131     }
21132 }
21133
21134 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
21135                                       bool record_lines_p)
21136 {
21137   m_gdbarch = arch;
21138   m_record_lines_p = record_lines_p;
21139   m_line_header = lh;
21140
21141   m_record_line_callback = ::record_line;
21142
21143   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
21144      was a line entry for it so that the backend has a chance to adjust it
21145      and also record it in case it needs it.  This is currently used by MIPS
21146      code, cf. `mips_adjust_dwarf2_line'.  */
21147   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
21148   m_is_stmt = lh->default_is_stmt;
21149   m_discriminator = 0;
21150 }
21151
21152 void
21153 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
21154                                        const gdb_byte *line_ptr,
21155                                        CORE_ADDR lowpc, CORE_ADDR address)
21156 {
21157   /* If address < lowpc then it's not a usable value, it's outside the
21158      pc range of the CU.  However, we restrict the test to only address
21159      values of zero to preserve GDB's previous behaviour which is to
21160      handle the specific case of a function being GC'd by the linker.  */
21161
21162   if (address == 0 && address < lowpc)
21163     {
21164       /* This line table is for a function which has been
21165          GCd by the linker.  Ignore it.  PR gdb/12528 */
21166
21167       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21168       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
21169
21170       complaint (&symfile_complaints,
21171                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
21172                  line_offset, objfile_name (objfile));
21173       m_record_line_callback = noop_record_line;
21174       /* Note: record_line_callback is left as noop_record_line until
21175          we see DW_LNE_end_sequence.  */
21176     }
21177 }
21178
21179 /* Subroutine of dwarf_decode_lines to simplify it.
21180    Process the line number information in LH.
21181    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
21182    program in order to set included_p for every referenced header.  */
21183
21184 static void
21185 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
21186                       const int decode_for_pst_p, CORE_ADDR lowpc)
21187 {
21188   const gdb_byte *line_ptr, *extended_end;
21189   const gdb_byte *line_end;
21190   unsigned int bytes_read, extended_len;
21191   unsigned char op_code, extended_op;
21192   CORE_ADDR baseaddr;
21193   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21194   bfd *abfd = objfile->obfd;
21195   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21196   /* True if we're recording line info (as opposed to building partial
21197      symtabs and just interested in finding include files mentioned by
21198      the line number program).  */
21199   bool record_lines_p = !decode_for_pst_p;
21200
21201   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21202
21203   line_ptr = lh->statement_program_start;
21204   line_end = lh->statement_program_end;
21205
21206   /* Read the statement sequences until there's nothing left.  */
21207   while (line_ptr < line_end)
21208     {
21209       /* The DWARF line number program state machine.  Reset the state
21210          machine at the start of each sequence.  */
21211       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
21212       bool end_sequence = false;
21213
21214       if (record_lines_p)
21215         {
21216           /* Start a subfile for the current file of the state
21217              machine.  */
21218           const file_entry *fe = state_machine.current_file ();
21219
21220           if (fe != NULL)
21221             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
21222         }
21223
21224       /* Decode the table.  */
21225       while (line_ptr < line_end && !end_sequence)
21226         {
21227           op_code = read_1_byte (abfd, line_ptr);
21228           line_ptr += 1;
21229
21230           if (op_code >= lh->opcode_base)
21231             {
21232               /* Special opcode.  */
21233               state_machine.handle_special_opcode (op_code);
21234             }
21235           else switch (op_code)
21236             {
21237             case DW_LNS_extended_op:
21238               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21239                                                    &bytes_read);
21240               line_ptr += bytes_read;
21241               extended_end = line_ptr + extended_len;
21242               extended_op = read_1_byte (abfd, line_ptr);
21243               line_ptr += 1;
21244               switch (extended_op)
21245                 {
21246                 case DW_LNE_end_sequence:
21247                   state_machine.handle_end_sequence ();
21248                   end_sequence = true;
21249                   break;
21250                 case DW_LNE_set_address:
21251                   {
21252                     CORE_ADDR address
21253                       = read_address (abfd, line_ptr, cu, &bytes_read);
21254                     line_ptr += bytes_read;
21255
21256                     state_machine.check_line_address (cu, line_ptr,
21257                                                       lowpc, address);
21258                     state_machine.handle_set_address (baseaddr, address);
21259                   }
21260                   break;
21261                 case DW_LNE_define_file:
21262                   {
21263                     const char *cur_file;
21264                     unsigned int mod_time, length;
21265                     dir_index dindex;
21266
21267                     cur_file = read_direct_string (abfd, line_ptr,
21268                                                    &bytes_read);
21269                     line_ptr += bytes_read;
21270                     dindex = (dir_index)
21271                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21272                     line_ptr += bytes_read;
21273                     mod_time =
21274                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21275                     line_ptr += bytes_read;
21276                     length =
21277                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21278                     line_ptr += bytes_read;
21279                     lh->add_file_name (cur_file, dindex, mod_time, length);
21280                   }
21281                   break;
21282                 case DW_LNE_set_discriminator:
21283                   {
21284                     /* The discriminator is not interesting to the
21285                        debugger; just ignore it.  We still need to
21286                        check its value though:
21287                        if there are consecutive entries for the same
21288                        (non-prologue) line we want to coalesce them.
21289                        PR 17276.  */
21290                     unsigned int discr
21291                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21292                     line_ptr += bytes_read;
21293
21294                     state_machine.handle_set_discriminator (discr);
21295                   }
21296                   break;
21297                 default:
21298                   complaint (&symfile_complaints,
21299                              _("mangled .debug_line section"));
21300                   return;
21301                 }
21302               /* Make sure that we parsed the extended op correctly.  If e.g.
21303                  we expected a different address size than the producer used,
21304                  we may have read the wrong number of bytes.  */
21305               if (line_ptr != extended_end)
21306                 {
21307                   complaint (&symfile_complaints,
21308                              _("mangled .debug_line section"));
21309                   return;
21310                 }
21311               break;
21312             case DW_LNS_copy:
21313               state_machine.handle_copy ();
21314               break;
21315             case DW_LNS_advance_pc:
21316               {
21317                 CORE_ADDR adjust
21318                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21319                 line_ptr += bytes_read;
21320
21321                 state_machine.handle_advance_pc (adjust);
21322               }
21323               break;
21324             case DW_LNS_advance_line:
21325               {
21326                 int line_delta
21327                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21328                 line_ptr += bytes_read;
21329
21330                 state_machine.handle_advance_line (line_delta);
21331               }
21332               break;
21333             case DW_LNS_set_file:
21334               {
21335                 file_name_index file
21336                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21337                                                             &bytes_read);
21338                 line_ptr += bytes_read;
21339
21340                 state_machine.handle_set_file (file);
21341               }
21342               break;
21343             case DW_LNS_set_column:
21344               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21345               line_ptr += bytes_read;
21346               break;
21347             case DW_LNS_negate_stmt:
21348               state_machine.handle_negate_stmt ();
21349               break;
21350             case DW_LNS_set_basic_block:
21351               break;
21352             /* Add to the address register of the state machine the
21353                address increment value corresponding to special opcode
21354                255.  I.e., this value is scaled by the minimum
21355                instruction length since special opcode 255 would have
21356                scaled the increment.  */
21357             case DW_LNS_const_add_pc:
21358               state_machine.handle_const_add_pc ();
21359               break;
21360             case DW_LNS_fixed_advance_pc:
21361               {
21362                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21363                 line_ptr += 2;
21364
21365                 state_machine.handle_fixed_advance_pc (addr_adj);
21366               }
21367               break;
21368             default:
21369               {
21370                 /* Unknown standard opcode, ignore it.  */
21371                 int i;
21372
21373                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21374                   {
21375                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21376                     line_ptr += bytes_read;
21377                   }
21378               }
21379             }
21380         }
21381
21382       if (!end_sequence)
21383         dwarf2_debug_line_missing_end_sequence_complaint ();
21384
21385       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21386          in which case we still finish recording the last line).  */
21387       state_machine.record_line (true);
21388     }
21389 }
21390
21391 /* Decode the Line Number Program (LNP) for the given line_header
21392    structure and CU.  The actual information extracted and the type
21393    of structures created from the LNP depends on the value of PST.
21394
21395    1. If PST is NULL, then this procedure uses the data from the program
21396       to create all necessary symbol tables, and their linetables.
21397
21398    2. If PST is not NULL, this procedure reads the program to determine
21399       the list of files included by the unit represented by PST, and
21400       builds all the associated partial symbol tables.
21401
21402    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21403    It is used for relative paths in the line table.
21404    NOTE: When processing partial symtabs (pst != NULL),
21405    comp_dir == pst->dirname.
21406
21407    NOTE: It is important that psymtabs have the same file name (via strcmp)
21408    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21409    symtab we don't use it in the name of the psymtabs we create.
21410    E.g. expand_line_sal requires this when finding psymtabs to expand.
21411    A good testcase for this is mb-inline.exp.
21412
21413    LOWPC is the lowest address in CU (or 0 if not known).
21414
21415    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21416    for its PC<->lines mapping information.  Otherwise only the filename
21417    table is read in.  */
21418
21419 static void
21420 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21421                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21422                     CORE_ADDR lowpc, int decode_mapping)
21423 {
21424   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21425   const int decode_for_pst_p = (pst != NULL);
21426
21427   if (decode_mapping)
21428     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21429
21430   if (decode_for_pst_p)
21431     {
21432       int file_index;
21433
21434       /* Now that we're done scanning the Line Header Program, we can
21435          create the psymtab of each included file.  */
21436       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21437         if (lh->file_names[file_index].included_p == 1)
21438           {
21439             gdb::unique_xmalloc_ptr<char> name_holder;
21440             const char *include_name =
21441               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21442                                          &name_holder);
21443             if (include_name != NULL)
21444               dwarf2_create_include_psymtab (include_name, pst, objfile);
21445           }
21446     }
21447   else
21448     {
21449       /* Make sure a symtab is created for every file, even files
21450          which contain only variables (i.e. no code with associated
21451          line numbers).  */
21452       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21453       int i;
21454
21455       for (i = 0; i < lh->file_names.size (); i++)
21456         {
21457           file_entry &fe = lh->file_names[i];
21458
21459           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21460
21461           if (current_subfile->symtab == NULL)
21462             {
21463               current_subfile->symtab
21464                 = allocate_symtab (cust, current_subfile->name);
21465             }
21466           fe.symtab = current_subfile->symtab;
21467         }
21468     }
21469 }
21470
21471 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21472    DIRNAME the name of the source directory which contains FILENAME
21473    or NULL if not known.
21474    This routine tries to keep line numbers from identical absolute and
21475    relative file names in a common subfile.
21476
21477    Using the `list' example from the GDB testsuite, which resides in
21478    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21479    of /srcdir/list0.c yields the following debugging information for list0.c:
21480
21481    DW_AT_name:          /srcdir/list0.c
21482    DW_AT_comp_dir:      /compdir
21483    files.files[0].name: list0.h
21484    files.files[0].dir:  /srcdir
21485    files.files[1].name: list0.c
21486    files.files[1].dir:  /srcdir
21487
21488    The line number information for list0.c has to end up in a single
21489    subfile, so that `break /srcdir/list0.c:1' works as expected.
21490    start_subfile will ensure that this happens provided that we pass the
21491    concatenation of files.files[1].dir and files.files[1].name as the
21492    subfile's name.  */
21493
21494 static void
21495 dwarf2_start_subfile (const char *filename, const char *dirname)
21496 {
21497   char *copy = NULL;
21498
21499   /* In order not to lose the line information directory,
21500      we concatenate it to the filename when it makes sense.
21501      Note that the Dwarf3 standard says (speaking of filenames in line
21502      information): ``The directory index is ignored for file names
21503      that represent full path names''.  Thus ignoring dirname in the
21504      `else' branch below isn't an issue.  */
21505
21506   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21507     {
21508       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21509       filename = copy;
21510     }
21511
21512   start_subfile (filename);
21513
21514   if (copy != NULL)
21515     xfree (copy);
21516 }
21517
21518 /* Start a symtab for DWARF.
21519    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21520
21521 static struct compunit_symtab *
21522 dwarf2_start_symtab (struct dwarf2_cu *cu,
21523                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21524 {
21525   struct compunit_symtab *cust
21526     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21527                     low_pc, cu->language);
21528
21529   record_debugformat ("DWARF 2");
21530   record_producer (cu->producer);
21531
21532   /* We assume that we're processing GCC output.  */
21533   processing_gcc_compilation = 2;
21534
21535   cu->processing_has_namespace_info = 0;
21536
21537   return cust;
21538 }
21539
21540 static void
21541 var_decode_location (struct attribute *attr, struct symbol *sym,
21542                      struct dwarf2_cu *cu)
21543 {
21544   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21545   struct comp_unit_head *cu_header = &cu->header;
21546
21547   /* NOTE drow/2003-01-30: There used to be a comment and some special
21548      code here to turn a symbol with DW_AT_external and a
21549      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21550      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21551      with some versions of binutils) where shared libraries could have
21552      relocations against symbols in their debug information - the
21553      minimal symbol would have the right address, but the debug info
21554      would not.  It's no longer necessary, because we will explicitly
21555      apply relocations when we read in the debug information now.  */
21556
21557   /* A DW_AT_location attribute with no contents indicates that a
21558      variable has been optimized away.  */
21559   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21560     {
21561       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21562       return;
21563     }
21564
21565   /* Handle one degenerate form of location expression specially, to
21566      preserve GDB's previous behavior when section offsets are
21567      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21568      then mark this symbol as LOC_STATIC.  */
21569
21570   if (attr_form_is_block (attr)
21571       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21572            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21573           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21574               && (DW_BLOCK (attr)->size
21575                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21576     {
21577       unsigned int dummy;
21578
21579       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21580         SYMBOL_VALUE_ADDRESS (sym) =
21581           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21582       else
21583         SYMBOL_VALUE_ADDRESS (sym) =
21584           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21585       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21586       fixup_symbol_section (sym, objfile);
21587       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21588                                               SYMBOL_SECTION (sym));
21589       return;
21590     }
21591
21592   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21593      expression evaluator, and use LOC_COMPUTED only when necessary
21594      (i.e. when the value of a register or memory location is
21595      referenced, or a thread-local block, etc.).  Then again, it might
21596      not be worthwhile.  I'm assuming that it isn't unless performance
21597      or memory numbers show me otherwise.  */
21598
21599   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21600
21601   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21602     cu->has_loclist = 1;
21603 }
21604
21605 /* Given a pointer to a DWARF information entry, figure out if we need
21606    to make a symbol table entry for it, and if so, create a new entry
21607    and return a pointer to it.
21608    If TYPE is NULL, determine symbol type from the die, otherwise
21609    used the passed type.
21610    If SPACE is not NULL, use it to hold the new symbol.  If it is
21611    NULL, allocate a new symbol on the objfile's obstack.  */
21612
21613 static struct symbol *
21614 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21615             struct symbol *space)
21616 {
21617   struct dwarf2_per_objfile *dwarf2_per_objfile
21618     = cu->per_cu->dwarf2_per_objfile;
21619   struct objfile *objfile = dwarf2_per_objfile->objfile;
21620   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21621   struct symbol *sym = NULL;
21622   const char *name;
21623   struct attribute *attr = NULL;
21624   struct attribute *attr2 = NULL;
21625   CORE_ADDR baseaddr;
21626   struct pending **list_to_add = NULL;
21627
21628   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21629
21630   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21631
21632   name = dwarf2_name (die, cu);
21633   if (name)
21634     {
21635       const char *linkagename;
21636       int suppress_add = 0;
21637
21638       if (space)
21639         sym = space;
21640       else
21641         sym = allocate_symbol (objfile);
21642       OBJSTAT (objfile, n_syms++);
21643
21644       /* Cache this symbol's name and the name's demangled form (if any).  */
21645       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21646       linkagename = dwarf2_physname (name, die, cu);
21647       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21648
21649       /* Fortran does not have mangling standard and the mangling does differ
21650          between gfortran, iFort etc.  */
21651       if (cu->language == language_fortran
21652           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21653         symbol_set_demangled_name (&(sym->ginfo),
21654                                    dwarf2_full_name (name, die, cu),
21655                                    NULL);
21656
21657       /* Default assumptions.
21658          Use the passed type or decode it from the die.  */
21659       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21660       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21661       if (type != NULL)
21662         SYMBOL_TYPE (sym) = type;
21663       else
21664         SYMBOL_TYPE (sym) = die_type (die, cu);
21665       attr = dwarf2_attr (die,
21666                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21667                           cu);
21668       if (attr)
21669         {
21670           SYMBOL_LINE (sym) = DW_UNSND (attr);
21671         }
21672
21673       attr = dwarf2_attr (die,
21674                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21675                           cu);
21676       if (attr)
21677         {
21678           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21679           struct file_entry *fe;
21680
21681           if (cu->line_header != NULL)
21682             fe = cu->line_header->file_name_at (file_index);
21683           else
21684             fe = NULL;
21685
21686           if (fe == NULL)
21687             complaint (&symfile_complaints,
21688                        _("file index out of range"));
21689           else
21690             symbol_set_symtab (sym, fe->symtab);
21691         }
21692
21693       switch (die->tag)
21694         {
21695         case DW_TAG_label:
21696           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21697           if (attr)
21698             {
21699               CORE_ADDR addr;
21700
21701               addr = attr_value_as_address (attr);
21702               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21703               SYMBOL_VALUE_ADDRESS (sym) = addr;
21704             }
21705           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21706           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21707           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21708           add_symbol_to_list (sym, cu->list_in_scope);
21709           break;
21710         case DW_TAG_subprogram:
21711           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21712              finish_block.  */
21713           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21714           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21715           if ((attr2 && (DW_UNSND (attr2) != 0))
21716               || cu->language == language_ada)
21717             {
21718               /* Subprograms marked external are stored as a global symbol.
21719                  Ada subprograms, whether marked external or not, are always
21720                  stored as a global symbol, because we want to be able to
21721                  access them globally.  For instance, we want to be able
21722                  to break on a nested subprogram without having to
21723                  specify the context.  */
21724               list_to_add = &global_symbols;
21725             }
21726           else
21727             {
21728               list_to_add = cu->list_in_scope;
21729             }
21730           break;
21731         case DW_TAG_inlined_subroutine:
21732           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21733              finish_block.  */
21734           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21735           SYMBOL_INLINED (sym) = 1;
21736           list_to_add = cu->list_in_scope;
21737           break;
21738         case DW_TAG_template_value_param:
21739           suppress_add = 1;
21740           /* Fall through.  */
21741         case DW_TAG_constant:
21742         case DW_TAG_variable:
21743         case DW_TAG_member:
21744           /* Compilation with minimal debug info may result in
21745              variables with missing type entries.  Change the
21746              misleading `void' type to something sensible.  */
21747           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21748             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21749
21750           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21751           /* In the case of DW_TAG_member, we should only be called for
21752              static const members.  */
21753           if (die->tag == DW_TAG_member)
21754             {
21755               /* dwarf2_add_field uses die_is_declaration,
21756                  so we do the same.  */
21757               gdb_assert (die_is_declaration (die, cu));
21758               gdb_assert (attr);
21759             }
21760           if (attr)
21761             {
21762               dwarf2_const_value (attr, sym, cu);
21763               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21764               if (!suppress_add)
21765                 {
21766                   if (attr2 && (DW_UNSND (attr2) != 0))
21767                     list_to_add = &global_symbols;
21768                   else
21769                     list_to_add = cu->list_in_scope;
21770                 }
21771               break;
21772             }
21773           attr = dwarf2_attr (die, DW_AT_location, cu);
21774           if (attr)
21775             {
21776               var_decode_location (attr, sym, cu);
21777               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21778
21779               /* Fortran explicitly imports any global symbols to the local
21780                  scope by DW_TAG_common_block.  */
21781               if (cu->language == language_fortran && die->parent
21782                   && die->parent->tag == DW_TAG_common_block)
21783                 attr2 = NULL;
21784
21785               if (SYMBOL_CLASS (sym) == LOC_STATIC
21786                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21787                   && !dwarf2_per_objfile->has_section_at_zero)
21788                 {
21789                   /* When a static variable is eliminated by the linker,
21790                      the corresponding debug information is not stripped
21791                      out, but the variable address is set to null;
21792                      do not add such variables into symbol table.  */
21793                 }
21794               else if (attr2 && (DW_UNSND (attr2) != 0))
21795                 {
21796                   /* Workaround gfortran PR debug/40040 - it uses
21797                      DW_AT_location for variables in -fPIC libraries which may
21798                      get overriden by other libraries/executable and get
21799                      a different address.  Resolve it by the minimal symbol
21800                      which may come from inferior's executable using copy
21801                      relocation.  Make this workaround only for gfortran as for
21802                      other compilers GDB cannot guess the minimal symbol
21803                      Fortran mangling kind.  */
21804                   if (cu->language == language_fortran && die->parent
21805                       && die->parent->tag == DW_TAG_module
21806                       && cu->producer
21807                       && startswith (cu->producer, "GNU Fortran"))
21808                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21809
21810                   /* A variable with DW_AT_external is never static,
21811                      but it may be block-scoped.  */
21812                   list_to_add = (cu->list_in_scope == &file_symbols
21813                                  ? &global_symbols : cu->list_in_scope);
21814                 }
21815               else
21816                 list_to_add = cu->list_in_scope;
21817             }
21818           else
21819             {
21820               /* We do not know the address of this symbol.
21821                  If it is an external symbol and we have type information
21822                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21823                  The address of the variable will then be determined from
21824                  the minimal symbol table whenever the variable is
21825                  referenced.  */
21826               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21827
21828               /* Fortran explicitly imports any global symbols to the local
21829                  scope by DW_TAG_common_block.  */
21830               if (cu->language == language_fortran && die->parent
21831                   && die->parent->tag == DW_TAG_common_block)
21832                 {
21833                   /* SYMBOL_CLASS doesn't matter here because
21834                      read_common_block is going to reset it.  */
21835                   if (!suppress_add)
21836                     list_to_add = cu->list_in_scope;
21837                 }
21838               else if (attr2 && (DW_UNSND (attr2) != 0)
21839                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21840                 {
21841                   /* A variable with DW_AT_external is never static, but it
21842                      may be block-scoped.  */
21843                   list_to_add = (cu->list_in_scope == &file_symbols
21844                                  ? &global_symbols : cu->list_in_scope);
21845
21846                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21847                 }
21848               else if (!die_is_declaration (die, cu))
21849                 {
21850                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21851                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21852                   if (!suppress_add)
21853                     list_to_add = cu->list_in_scope;
21854                 }
21855             }
21856           break;
21857         case DW_TAG_formal_parameter:
21858           /* If we are inside a function, mark this as an argument.  If
21859              not, we might be looking at an argument to an inlined function
21860              when we do not have enough information to show inlined frames;
21861              pretend it's a local variable in that case so that the user can
21862              still see it.  */
21863           if (context_stack_depth > 0
21864               && context_stack[context_stack_depth - 1].name != NULL)
21865             SYMBOL_IS_ARGUMENT (sym) = 1;
21866           attr = dwarf2_attr (die, DW_AT_location, cu);
21867           if (attr)
21868             {
21869               var_decode_location (attr, sym, cu);
21870             }
21871           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21872           if (attr)
21873             {
21874               dwarf2_const_value (attr, sym, cu);
21875             }
21876
21877           list_to_add = cu->list_in_scope;
21878           break;
21879         case DW_TAG_unspecified_parameters:
21880           /* From varargs functions; gdb doesn't seem to have any
21881              interest in this information, so just ignore it for now.
21882              (FIXME?) */
21883           break;
21884         case DW_TAG_template_type_param:
21885           suppress_add = 1;
21886           /* Fall through.  */
21887         case DW_TAG_class_type:
21888         case DW_TAG_interface_type:
21889         case DW_TAG_structure_type:
21890         case DW_TAG_union_type:
21891         case DW_TAG_set_type:
21892         case DW_TAG_enumeration_type:
21893           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21894           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21895
21896           {
21897             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21898                really ever be static objects: otherwise, if you try
21899                to, say, break of a class's method and you're in a file
21900                which doesn't mention that class, it won't work unless
21901                the check for all static symbols in lookup_symbol_aux
21902                saves you.  See the OtherFileClass tests in
21903                gdb.c++/namespace.exp.  */
21904
21905             if (!suppress_add)
21906               {
21907                 list_to_add = (cu->list_in_scope == &file_symbols
21908                                && cu->language == language_cplus
21909                                ? &global_symbols : cu->list_in_scope);
21910
21911                 /* The semantics of C++ state that "struct foo {
21912                    ... }" also defines a typedef for "foo".  */
21913                 if (cu->language == language_cplus
21914                     || cu->language == language_ada
21915                     || cu->language == language_d
21916                     || cu->language == language_rust)
21917                   {
21918                     /* The symbol's name is already allocated along
21919                        with this objfile, so we don't need to
21920                        duplicate it for the type.  */
21921                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21922                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21923                   }
21924               }
21925           }
21926           break;
21927         case DW_TAG_typedef:
21928           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21929           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21930           list_to_add = cu->list_in_scope;
21931           break;
21932         case DW_TAG_base_type:
21933         case DW_TAG_subrange_type:
21934           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21935           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21936           list_to_add = cu->list_in_scope;
21937           break;
21938         case DW_TAG_enumerator:
21939           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21940           if (attr)
21941             {
21942               dwarf2_const_value (attr, sym, cu);
21943             }
21944           {
21945             /* NOTE: carlton/2003-11-10: See comment above in the
21946                DW_TAG_class_type, etc. block.  */
21947
21948             list_to_add = (cu->list_in_scope == &file_symbols
21949                            && cu->language == language_cplus
21950                            ? &global_symbols : cu->list_in_scope);
21951           }
21952           break;
21953         case DW_TAG_imported_declaration:
21954         case DW_TAG_namespace:
21955           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21956           list_to_add = &global_symbols;
21957           break;
21958         case DW_TAG_module:
21959           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21960           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21961           list_to_add = &global_symbols;
21962           break;
21963         case DW_TAG_common_block:
21964           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21965           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21966           add_symbol_to_list (sym, cu->list_in_scope);
21967           break;
21968         default:
21969           /* Not a tag we recognize.  Hopefully we aren't processing
21970              trash data, but since we must specifically ignore things
21971              we don't recognize, there is nothing else we should do at
21972              this point.  */
21973           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21974                      dwarf_tag_name (die->tag));
21975           break;
21976         }
21977
21978       if (suppress_add)
21979         {
21980           sym->hash_next = objfile->template_symbols;
21981           objfile->template_symbols = sym;
21982           list_to_add = NULL;
21983         }
21984
21985       if (list_to_add != NULL)
21986         add_symbol_to_list (sym, list_to_add);
21987
21988       /* For the benefit of old versions of GCC, check for anonymous
21989          namespaces based on the demangled name.  */
21990       if (!cu->processing_has_namespace_info
21991           && cu->language == language_cplus)
21992         cp_scan_for_anonymous_namespaces (sym, objfile);
21993     }
21994   return (sym);
21995 }
21996
21997 /* Given an attr with a DW_FORM_dataN value in host byte order,
21998    zero-extend it as appropriate for the symbol's type.  The DWARF
21999    standard (v4) is not entirely clear about the meaning of using
22000    DW_FORM_dataN for a constant with a signed type, where the type is
22001    wider than the data.  The conclusion of a discussion on the DWARF
22002    list was that this is unspecified.  We choose to always zero-extend
22003    because that is the interpretation long in use by GCC.  */
22004
22005 static gdb_byte *
22006 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
22007                          struct dwarf2_cu *cu, LONGEST *value, int bits)
22008 {
22009   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22010   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
22011                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
22012   LONGEST l = DW_UNSND (attr);
22013
22014   if (bits < sizeof (*value) * 8)
22015     {
22016       l &= ((LONGEST) 1 << bits) - 1;
22017       *value = l;
22018     }
22019   else if (bits == sizeof (*value) * 8)
22020     *value = l;
22021   else
22022     {
22023       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
22024       store_unsigned_integer (bytes, bits / 8, byte_order, l);
22025       return bytes;
22026     }
22027
22028   return NULL;
22029 }
22030
22031 /* Read a constant value from an attribute.  Either set *VALUE, or if
22032    the value does not fit in *VALUE, set *BYTES - either already
22033    allocated on the objfile obstack, or newly allocated on OBSTACK,
22034    or, set *BATON, if we translated the constant to a location
22035    expression.  */
22036
22037 static void
22038 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
22039                          const char *name, struct obstack *obstack,
22040                          struct dwarf2_cu *cu,
22041                          LONGEST *value, const gdb_byte **bytes,
22042                          struct dwarf2_locexpr_baton **baton)
22043 {
22044   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22045   struct comp_unit_head *cu_header = &cu->header;
22046   struct dwarf_block *blk;
22047   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
22048                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22049
22050   *value = 0;
22051   *bytes = NULL;
22052   *baton = NULL;
22053
22054   switch (attr->form)
22055     {
22056     case DW_FORM_addr:
22057     case DW_FORM_GNU_addr_index:
22058       {
22059         gdb_byte *data;
22060
22061         if (TYPE_LENGTH (type) != cu_header->addr_size)
22062           dwarf2_const_value_length_mismatch_complaint (name,
22063                                                         cu_header->addr_size,
22064                                                         TYPE_LENGTH (type));
22065         /* Symbols of this form are reasonably rare, so we just
22066            piggyback on the existing location code rather than writing
22067            a new implementation of symbol_computed_ops.  */
22068         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
22069         (*baton)->per_cu = cu->per_cu;
22070         gdb_assert ((*baton)->per_cu);
22071
22072         (*baton)->size = 2 + cu_header->addr_size;
22073         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
22074         (*baton)->data = data;
22075
22076         data[0] = DW_OP_addr;
22077         store_unsigned_integer (&data[1], cu_header->addr_size,
22078                                 byte_order, DW_ADDR (attr));
22079         data[cu_header->addr_size + 1] = DW_OP_stack_value;
22080       }
22081       break;
22082     case DW_FORM_string:
22083     case DW_FORM_strp:
22084     case DW_FORM_GNU_str_index:
22085     case DW_FORM_GNU_strp_alt:
22086       /* DW_STRING is already allocated on the objfile obstack, point
22087          directly to it.  */
22088       *bytes = (const gdb_byte *) DW_STRING (attr);
22089       break;
22090     case DW_FORM_block1:
22091     case DW_FORM_block2:
22092     case DW_FORM_block4:
22093     case DW_FORM_block:
22094     case DW_FORM_exprloc:
22095     case DW_FORM_data16:
22096       blk = DW_BLOCK (attr);
22097       if (TYPE_LENGTH (type) != blk->size)
22098         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
22099                                                       TYPE_LENGTH (type));
22100       *bytes = blk->data;
22101       break;
22102
22103       /* The DW_AT_const_value attributes are supposed to carry the
22104          symbol's value "represented as it would be on the target
22105          architecture."  By the time we get here, it's already been
22106          converted to host endianness, so we just need to sign- or
22107          zero-extend it as appropriate.  */
22108     case DW_FORM_data1:
22109       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
22110       break;
22111     case DW_FORM_data2:
22112       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
22113       break;
22114     case DW_FORM_data4:
22115       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
22116       break;
22117     case DW_FORM_data8:
22118       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
22119       break;
22120
22121     case DW_FORM_sdata:
22122     case DW_FORM_implicit_const:
22123       *value = DW_SND (attr);
22124       break;
22125
22126     case DW_FORM_udata:
22127       *value = DW_UNSND (attr);
22128       break;
22129
22130     default:
22131       complaint (&symfile_complaints,
22132                  _("unsupported const value attribute form: '%s'"),
22133                  dwarf_form_name (attr->form));
22134       *value = 0;
22135       break;
22136     }
22137 }
22138
22139
22140 /* Copy constant value from an attribute to a symbol.  */
22141
22142 static void
22143 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
22144                     struct dwarf2_cu *cu)
22145 {
22146   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22147   LONGEST value;
22148   const gdb_byte *bytes;
22149   struct dwarf2_locexpr_baton *baton;
22150
22151   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
22152                            SYMBOL_PRINT_NAME (sym),
22153                            &objfile->objfile_obstack, cu,
22154                            &value, &bytes, &baton);
22155
22156   if (baton != NULL)
22157     {
22158       SYMBOL_LOCATION_BATON (sym) = baton;
22159       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
22160     }
22161   else if (bytes != NULL)
22162      {
22163       SYMBOL_VALUE_BYTES (sym) = bytes;
22164       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
22165     }
22166   else
22167     {
22168       SYMBOL_VALUE (sym) = value;
22169       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
22170     }
22171 }
22172
22173 /* Return the type of the die in question using its DW_AT_type attribute.  */
22174
22175 static struct type *
22176 die_type (struct die_info *die, struct dwarf2_cu *cu)
22177 {
22178   struct attribute *type_attr;
22179
22180   type_attr = dwarf2_attr (die, DW_AT_type, cu);
22181   if (!type_attr)
22182     {
22183       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22184       /* A missing DW_AT_type represents a void type.  */
22185       return objfile_type (objfile)->builtin_void;
22186     }
22187
22188   return lookup_die_type (die, type_attr, cu);
22189 }
22190
22191 /* True iff CU's producer generates GNAT Ada auxiliary information
22192    that allows to find parallel types through that information instead
22193    of having to do expensive parallel lookups by type name.  */
22194
22195 static int
22196 need_gnat_info (struct dwarf2_cu *cu)
22197 {
22198   /* Assume that the Ada compiler was GNAT, which always produces
22199      the auxiliary information.  */
22200   return (cu->language == language_ada);
22201 }
22202
22203 /* Return the auxiliary type of the die in question using its
22204    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
22205    attribute is not present.  */
22206
22207 static struct type *
22208 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
22209 {
22210   struct attribute *type_attr;
22211
22212   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
22213   if (!type_attr)
22214     return NULL;
22215
22216   return lookup_die_type (die, type_attr, cu);
22217 }
22218
22219 /* If DIE has a descriptive_type attribute, then set the TYPE's
22220    descriptive type accordingly.  */
22221
22222 static void
22223 set_descriptive_type (struct type *type, struct die_info *die,
22224                       struct dwarf2_cu *cu)
22225 {
22226   struct type *descriptive_type = die_descriptive_type (die, cu);
22227
22228   if (descriptive_type)
22229     {
22230       ALLOCATE_GNAT_AUX_TYPE (type);
22231       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22232     }
22233 }
22234
22235 /* Return the containing type of the die in question using its
22236    DW_AT_containing_type attribute.  */
22237
22238 static struct type *
22239 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22240 {
22241   struct attribute *type_attr;
22242   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22243
22244   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22245   if (!type_attr)
22246     error (_("Dwarf Error: Problem turning containing type into gdb type "
22247              "[in module %s]"), objfile_name (objfile));
22248
22249   return lookup_die_type (die, type_attr, cu);
22250 }
22251
22252 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22253
22254 static struct type *
22255 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22256 {
22257   struct dwarf2_per_objfile *dwarf2_per_objfile
22258     = cu->per_cu->dwarf2_per_objfile;
22259   struct objfile *objfile = dwarf2_per_objfile->objfile;
22260   char *message, *saved;
22261
22262   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
22263                         objfile_name (objfile),
22264                         sect_offset_str (cu->header.sect_off),
22265                         sect_offset_str (die->sect_off));
22266   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22267                                   message, strlen (message));
22268   xfree (message);
22269
22270   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22271 }
22272
22273 /* Look up the type of DIE in CU using its type attribute ATTR.
22274    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22275    DW_AT_containing_type.
22276    If there is no type substitute an error marker.  */
22277
22278 static struct type *
22279 lookup_die_type (struct die_info *die, const struct attribute *attr,
22280                  struct dwarf2_cu *cu)
22281 {
22282   struct dwarf2_per_objfile *dwarf2_per_objfile
22283     = cu->per_cu->dwarf2_per_objfile;
22284   struct objfile *objfile = dwarf2_per_objfile->objfile;
22285   struct type *this_type;
22286
22287   gdb_assert (attr->name == DW_AT_type
22288               || attr->name == DW_AT_GNAT_descriptive_type
22289               || attr->name == DW_AT_containing_type);
22290
22291   /* First see if we have it cached.  */
22292
22293   if (attr->form == DW_FORM_GNU_ref_alt)
22294     {
22295       struct dwarf2_per_cu_data *per_cu;
22296       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22297
22298       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22299                                                  dwarf2_per_objfile);
22300       this_type = get_die_type_at_offset (sect_off, per_cu);
22301     }
22302   else if (attr_form_is_ref (attr))
22303     {
22304       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22305
22306       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22307     }
22308   else if (attr->form == DW_FORM_ref_sig8)
22309     {
22310       ULONGEST signature = DW_SIGNATURE (attr);
22311
22312       return get_signatured_type (die, signature, cu);
22313     }
22314   else
22315     {
22316       complaint (&symfile_complaints,
22317                  _("Dwarf Error: Bad type attribute %s in DIE"
22318                    " at %s [in module %s]"),
22319                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22320                  objfile_name (objfile));
22321       return build_error_marker_type (cu, die);
22322     }
22323
22324   /* If not cached we need to read it in.  */
22325
22326   if (this_type == NULL)
22327     {
22328       struct die_info *type_die = NULL;
22329       struct dwarf2_cu *type_cu = cu;
22330
22331       if (attr_form_is_ref (attr))
22332         type_die = follow_die_ref (die, attr, &type_cu);
22333       if (type_die == NULL)
22334         return build_error_marker_type (cu, die);
22335       /* If we find the type now, it's probably because the type came
22336          from an inter-CU reference and the type's CU got expanded before
22337          ours.  */
22338       this_type = read_type_die (type_die, type_cu);
22339     }
22340
22341   /* If we still don't have a type use an error marker.  */
22342
22343   if (this_type == NULL)
22344     return build_error_marker_type (cu, die);
22345
22346   return this_type;
22347 }
22348
22349 /* Return the type in DIE, CU.
22350    Returns NULL for invalid types.
22351
22352    This first does a lookup in die_type_hash,
22353    and only reads the die in if necessary.
22354
22355    NOTE: This can be called when reading in partial or full symbols.  */
22356
22357 static struct type *
22358 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22359 {
22360   struct type *this_type;
22361
22362   this_type = get_die_type (die, cu);
22363   if (this_type)
22364     return this_type;
22365
22366   return read_type_die_1 (die, cu);
22367 }
22368
22369 /* Read the type in DIE, CU.
22370    Returns NULL for invalid types.  */
22371
22372 static struct type *
22373 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22374 {
22375   struct type *this_type = NULL;
22376
22377   switch (die->tag)
22378     {
22379     case DW_TAG_class_type:
22380     case DW_TAG_interface_type:
22381     case DW_TAG_structure_type:
22382     case DW_TAG_union_type:
22383       this_type = read_structure_type (die, cu);
22384       break;
22385     case DW_TAG_enumeration_type:
22386       this_type = read_enumeration_type (die, cu);
22387       break;
22388     case DW_TAG_subprogram:
22389     case DW_TAG_subroutine_type:
22390     case DW_TAG_inlined_subroutine:
22391       this_type = read_subroutine_type (die, cu);
22392       break;
22393     case DW_TAG_array_type:
22394       this_type = read_array_type (die, cu);
22395       break;
22396     case DW_TAG_set_type:
22397       this_type = read_set_type (die, cu);
22398       break;
22399     case DW_TAG_pointer_type:
22400       this_type = read_tag_pointer_type (die, cu);
22401       break;
22402     case DW_TAG_ptr_to_member_type:
22403       this_type = read_tag_ptr_to_member_type (die, cu);
22404       break;
22405     case DW_TAG_reference_type:
22406       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22407       break;
22408     case DW_TAG_rvalue_reference_type:
22409       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22410       break;
22411     case DW_TAG_const_type:
22412       this_type = read_tag_const_type (die, cu);
22413       break;
22414     case DW_TAG_volatile_type:
22415       this_type = read_tag_volatile_type (die, cu);
22416       break;
22417     case DW_TAG_restrict_type:
22418       this_type = read_tag_restrict_type (die, cu);
22419       break;
22420     case DW_TAG_string_type:
22421       this_type = read_tag_string_type (die, cu);
22422       break;
22423     case DW_TAG_typedef:
22424       this_type = read_typedef (die, cu);
22425       break;
22426     case DW_TAG_subrange_type:
22427       this_type = read_subrange_type (die, cu);
22428       break;
22429     case DW_TAG_base_type:
22430       this_type = read_base_type (die, cu);
22431       break;
22432     case DW_TAG_unspecified_type:
22433       this_type = read_unspecified_type (die, cu);
22434       break;
22435     case DW_TAG_namespace:
22436       this_type = read_namespace_type (die, cu);
22437       break;
22438     case DW_TAG_module:
22439       this_type = read_module_type (die, cu);
22440       break;
22441     case DW_TAG_atomic_type:
22442       this_type = read_tag_atomic_type (die, cu);
22443       break;
22444     default:
22445       complaint (&symfile_complaints,
22446                  _("unexpected tag in read_type_die: '%s'"),
22447                  dwarf_tag_name (die->tag));
22448       break;
22449     }
22450
22451   return this_type;
22452 }
22453
22454 /* See if we can figure out if the class lives in a namespace.  We do
22455    this by looking for a member function; its demangled name will
22456    contain namespace info, if there is any.
22457    Return the computed name or NULL.
22458    Space for the result is allocated on the objfile's obstack.
22459    This is the full-die version of guess_partial_die_structure_name.
22460    In this case we know DIE has no useful parent.  */
22461
22462 static char *
22463 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22464 {
22465   struct die_info *spec_die;
22466   struct dwarf2_cu *spec_cu;
22467   struct die_info *child;
22468   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22469
22470   spec_cu = cu;
22471   spec_die = die_specification (die, &spec_cu);
22472   if (spec_die != NULL)
22473     {
22474       die = spec_die;
22475       cu = spec_cu;
22476     }
22477
22478   for (child = die->child;
22479        child != NULL;
22480        child = child->sibling)
22481     {
22482       if (child->tag == DW_TAG_subprogram)
22483         {
22484           const char *linkage_name = dw2_linkage_name (child, cu);
22485
22486           if (linkage_name != NULL)
22487             {
22488               char *actual_name
22489                 = language_class_name_from_physname (cu->language_defn,
22490                                                      linkage_name);
22491               char *name = NULL;
22492
22493               if (actual_name != NULL)
22494                 {
22495                   const char *die_name = dwarf2_name (die, cu);
22496
22497                   if (die_name != NULL
22498                       && strcmp (die_name, actual_name) != 0)
22499                     {
22500                       /* Strip off the class name from the full name.
22501                          We want the prefix.  */
22502                       int die_name_len = strlen (die_name);
22503                       int actual_name_len = strlen (actual_name);
22504
22505                       /* Test for '::' as a sanity check.  */
22506                       if (actual_name_len > die_name_len + 2
22507                           && actual_name[actual_name_len
22508                                          - die_name_len - 1] == ':')
22509                         name = (char *) obstack_copy0 (
22510                           &objfile->per_bfd->storage_obstack,
22511                           actual_name, actual_name_len - die_name_len - 2);
22512                     }
22513                 }
22514               xfree (actual_name);
22515               return name;
22516             }
22517         }
22518     }
22519
22520   return NULL;
22521 }
22522
22523 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22524    prefix part in such case.  See
22525    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22526
22527 static const char *
22528 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22529 {
22530   struct attribute *attr;
22531   const char *base;
22532
22533   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22534       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22535     return NULL;
22536
22537   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22538     return NULL;
22539
22540   attr = dw2_linkage_name_attr (die, cu);
22541   if (attr == NULL || DW_STRING (attr) == NULL)
22542     return NULL;
22543
22544   /* dwarf2_name had to be already called.  */
22545   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22546
22547   /* Strip the base name, keep any leading namespaces/classes.  */
22548   base = strrchr (DW_STRING (attr), ':');
22549   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22550     return "";
22551
22552   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22553   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22554                                  DW_STRING (attr),
22555                                  &base[-1] - DW_STRING (attr));
22556 }
22557
22558 /* Return the name of the namespace/class that DIE is defined within,
22559    or "" if we can't tell.  The caller should not xfree the result.
22560
22561    For example, if we're within the method foo() in the following
22562    code:
22563
22564    namespace N {
22565      class C {
22566        void foo () {
22567        }
22568      };
22569    }
22570
22571    then determine_prefix on foo's die will return "N::C".  */
22572
22573 static const char *
22574 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22575 {
22576   struct dwarf2_per_objfile *dwarf2_per_objfile
22577     = cu->per_cu->dwarf2_per_objfile;
22578   struct die_info *parent, *spec_die;
22579   struct dwarf2_cu *spec_cu;
22580   struct type *parent_type;
22581   const char *retval;
22582
22583   if (cu->language != language_cplus
22584       && cu->language != language_fortran && cu->language != language_d
22585       && cu->language != language_rust)
22586     return "";
22587
22588   retval = anonymous_struct_prefix (die, cu);
22589   if (retval)
22590     return retval;
22591
22592   /* We have to be careful in the presence of DW_AT_specification.
22593      For example, with GCC 3.4, given the code
22594
22595      namespace N {
22596        void foo() {
22597          // Definition of N::foo.
22598        }
22599      }
22600
22601      then we'll have a tree of DIEs like this:
22602
22603      1: DW_TAG_compile_unit
22604        2: DW_TAG_namespace        // N
22605          3: DW_TAG_subprogram     // declaration of N::foo
22606        4: DW_TAG_subprogram       // definition of N::foo
22607             DW_AT_specification   // refers to die #3
22608
22609      Thus, when processing die #4, we have to pretend that we're in
22610      the context of its DW_AT_specification, namely the contex of die
22611      #3.  */
22612   spec_cu = cu;
22613   spec_die = die_specification (die, &spec_cu);
22614   if (spec_die == NULL)
22615     parent = die->parent;
22616   else
22617     {
22618       parent = spec_die->parent;
22619       cu = spec_cu;
22620     }
22621
22622   if (parent == NULL)
22623     return "";
22624   else if (parent->building_fullname)
22625     {
22626       const char *name;
22627       const char *parent_name;
22628
22629       /* It has been seen on RealView 2.2 built binaries,
22630          DW_TAG_template_type_param types actually _defined_ as
22631          children of the parent class:
22632
22633          enum E {};
22634          template class <class Enum> Class{};
22635          Class<enum E> class_e;
22636
22637          1: DW_TAG_class_type (Class)
22638            2: DW_TAG_enumeration_type (E)
22639              3: DW_TAG_enumerator (enum1:0)
22640              3: DW_TAG_enumerator (enum2:1)
22641              ...
22642            2: DW_TAG_template_type_param
22643               DW_AT_type  DW_FORM_ref_udata (E)
22644
22645          Besides being broken debug info, it can put GDB into an
22646          infinite loop.  Consider:
22647
22648          When we're building the full name for Class<E>, we'll start
22649          at Class, and go look over its template type parameters,
22650          finding E.  We'll then try to build the full name of E, and
22651          reach here.  We're now trying to build the full name of E,
22652          and look over the parent DIE for containing scope.  In the
22653          broken case, if we followed the parent DIE of E, we'd again
22654          find Class, and once again go look at its template type
22655          arguments, etc., etc.  Simply don't consider such parent die
22656          as source-level parent of this die (it can't be, the language
22657          doesn't allow it), and break the loop here.  */
22658       name = dwarf2_name (die, cu);
22659       parent_name = dwarf2_name (parent, cu);
22660       complaint (&symfile_complaints,
22661                  _("template param type '%s' defined within parent '%s'"),
22662                  name ? name : "<unknown>",
22663                  parent_name ? parent_name : "<unknown>");
22664       return "";
22665     }
22666   else
22667     switch (parent->tag)
22668       {
22669       case DW_TAG_namespace:
22670         parent_type = read_type_die (parent, cu);
22671         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22672            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22673            Work around this problem here.  */
22674         if (cu->language == language_cplus
22675             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22676           return "";
22677         /* We give a name to even anonymous namespaces.  */
22678         return TYPE_TAG_NAME (parent_type);
22679       case DW_TAG_class_type:
22680       case DW_TAG_interface_type:
22681       case DW_TAG_structure_type:
22682       case DW_TAG_union_type:
22683       case DW_TAG_module:
22684         parent_type = read_type_die (parent, cu);
22685         if (TYPE_TAG_NAME (parent_type) != NULL)
22686           return TYPE_TAG_NAME (parent_type);
22687         else
22688           /* An anonymous structure is only allowed non-static data
22689              members; no typedefs, no member functions, et cetera.
22690              So it does not need a prefix.  */
22691           return "";
22692       case DW_TAG_compile_unit:
22693       case DW_TAG_partial_unit:
22694         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22695         if (cu->language == language_cplus
22696             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22697             && die->child != NULL
22698             && (die->tag == DW_TAG_class_type
22699                 || die->tag == DW_TAG_structure_type
22700                 || die->tag == DW_TAG_union_type))
22701           {
22702             char *name = guess_full_die_structure_name (die, cu);
22703             if (name != NULL)
22704               return name;
22705           }
22706         return "";
22707       case DW_TAG_enumeration_type:
22708         parent_type = read_type_die (parent, cu);
22709         if (TYPE_DECLARED_CLASS (parent_type))
22710           {
22711             if (TYPE_TAG_NAME (parent_type) != NULL)
22712               return TYPE_TAG_NAME (parent_type);
22713             return "";
22714           }
22715         /* Fall through.  */
22716       default:
22717         return determine_prefix (parent, cu);
22718       }
22719 }
22720
22721 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22722    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22723    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22724    an obconcat, otherwise allocate storage for the result.  The CU argument is
22725    used to determine the language and hence, the appropriate separator.  */
22726
22727 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22728
22729 static char *
22730 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22731                  int physname, struct dwarf2_cu *cu)
22732 {
22733   const char *lead = "";
22734   const char *sep;
22735
22736   if (suffix == NULL || suffix[0] == '\0'
22737       || prefix == NULL || prefix[0] == '\0')
22738     sep = "";
22739   else if (cu->language == language_d)
22740     {
22741       /* For D, the 'main' function could be defined in any module, but it
22742          should never be prefixed.  */
22743       if (strcmp (suffix, "D main") == 0)
22744         {
22745           prefix = "";
22746           sep = "";
22747         }
22748       else
22749         sep = ".";
22750     }
22751   else if (cu->language == language_fortran && physname)
22752     {
22753       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22754          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22755
22756       lead = "__";
22757       sep = "_MOD_";
22758     }
22759   else
22760     sep = "::";
22761
22762   if (prefix == NULL)
22763     prefix = "";
22764   if (suffix == NULL)
22765     suffix = "";
22766
22767   if (obs == NULL)
22768     {
22769       char *retval
22770         = ((char *)
22771            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22772
22773       strcpy (retval, lead);
22774       strcat (retval, prefix);
22775       strcat (retval, sep);
22776       strcat (retval, suffix);
22777       return retval;
22778     }
22779   else
22780     {
22781       /* We have an obstack.  */
22782       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22783     }
22784 }
22785
22786 /* Return sibling of die, NULL if no sibling.  */
22787
22788 static struct die_info *
22789 sibling_die (struct die_info *die)
22790 {
22791   return die->sibling;
22792 }
22793
22794 /* Get name of a die, return NULL if not found.  */
22795
22796 static const char *
22797 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22798                           struct obstack *obstack)
22799 {
22800   if (name && cu->language == language_cplus)
22801     {
22802       std::string canon_name = cp_canonicalize_string (name);
22803
22804       if (!canon_name.empty ())
22805         {
22806           if (canon_name != name)
22807             name = (const char *) obstack_copy0 (obstack,
22808                                                  canon_name.c_str (),
22809                                                  canon_name.length ());
22810         }
22811     }
22812
22813   return name;
22814 }
22815
22816 /* Get name of a die, return NULL if not found.
22817    Anonymous namespaces are converted to their magic string.  */
22818
22819 static const char *
22820 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22821 {
22822   struct attribute *attr;
22823   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22824
22825   attr = dwarf2_attr (die, DW_AT_name, cu);
22826   if ((!attr || !DW_STRING (attr))
22827       && die->tag != DW_TAG_namespace
22828       && die->tag != DW_TAG_class_type
22829       && die->tag != DW_TAG_interface_type
22830       && die->tag != DW_TAG_structure_type
22831       && die->tag != DW_TAG_union_type)
22832     return NULL;
22833
22834   switch (die->tag)
22835     {
22836     case DW_TAG_compile_unit:
22837     case DW_TAG_partial_unit:
22838       /* Compilation units have a DW_AT_name that is a filename, not
22839          a source language identifier.  */
22840     case DW_TAG_enumeration_type:
22841     case DW_TAG_enumerator:
22842       /* These tags always have simple identifiers already; no need
22843          to canonicalize them.  */
22844       return DW_STRING (attr);
22845
22846     case DW_TAG_namespace:
22847       if (attr != NULL && DW_STRING (attr) != NULL)
22848         return DW_STRING (attr);
22849       return CP_ANONYMOUS_NAMESPACE_STR;
22850
22851     case DW_TAG_class_type:
22852     case DW_TAG_interface_type:
22853     case DW_TAG_structure_type:
22854     case DW_TAG_union_type:
22855       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22856          structures or unions.  These were of the form "._%d" in GCC 4.1,
22857          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22858          and GCC 4.4.  We work around this problem by ignoring these.  */
22859       if (attr && DW_STRING (attr)
22860           && (startswith (DW_STRING (attr), "._")
22861               || startswith (DW_STRING (attr), "<anonymous")))
22862         return NULL;
22863
22864       /* GCC might emit a nameless typedef that has a linkage name.  See
22865          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22866       if (!attr || DW_STRING (attr) == NULL)
22867         {
22868           char *demangled = NULL;
22869
22870           attr = dw2_linkage_name_attr (die, cu);
22871           if (attr == NULL || DW_STRING (attr) == NULL)
22872             return NULL;
22873
22874           /* Avoid demangling DW_STRING (attr) the second time on a second
22875              call for the same DIE.  */
22876           if (!DW_STRING_IS_CANONICAL (attr))
22877             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22878
22879           if (demangled)
22880             {
22881               const char *base;
22882
22883               /* FIXME: we already did this for the partial symbol... */
22884               DW_STRING (attr)
22885                 = ((const char *)
22886                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22887                                   demangled, strlen (demangled)));
22888               DW_STRING_IS_CANONICAL (attr) = 1;
22889               xfree (demangled);
22890
22891               /* Strip any leading namespaces/classes, keep only the base name.
22892                  DW_AT_name for named DIEs does not contain the prefixes.  */
22893               base = strrchr (DW_STRING (attr), ':');
22894               if (base && base > DW_STRING (attr) && base[-1] == ':')
22895                 return &base[1];
22896               else
22897                 return DW_STRING (attr);
22898             }
22899         }
22900       break;
22901
22902     default:
22903       break;
22904     }
22905
22906   if (!DW_STRING_IS_CANONICAL (attr))
22907     {
22908       DW_STRING (attr)
22909         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22910                                     &objfile->per_bfd->storage_obstack);
22911       DW_STRING_IS_CANONICAL (attr) = 1;
22912     }
22913   return DW_STRING (attr);
22914 }
22915
22916 /* Return the die that this die in an extension of, or NULL if there
22917    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22918    containing the return value on output.  */
22919
22920 static struct die_info *
22921 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22922 {
22923   struct attribute *attr;
22924
22925   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22926   if (attr == NULL)
22927     return NULL;
22928
22929   return follow_die_ref (die, attr, ext_cu);
22930 }
22931
22932 /* Convert a DIE tag into its string name.  */
22933
22934 static const char *
22935 dwarf_tag_name (unsigned tag)
22936 {
22937   const char *name = get_DW_TAG_name (tag);
22938
22939   if (name == NULL)
22940     return "DW_TAG_<unknown>";
22941
22942   return name;
22943 }
22944
22945 /* Convert a DWARF attribute code into its string name.  */
22946
22947 static const char *
22948 dwarf_attr_name (unsigned attr)
22949 {
22950   const char *name;
22951
22952 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22953   if (attr == DW_AT_MIPS_fde)
22954     return "DW_AT_MIPS_fde";
22955 #else
22956   if (attr == DW_AT_HP_block_index)
22957     return "DW_AT_HP_block_index";
22958 #endif
22959
22960   name = get_DW_AT_name (attr);
22961
22962   if (name == NULL)
22963     return "DW_AT_<unknown>";
22964
22965   return name;
22966 }
22967
22968 /* Convert a DWARF value form code into its string name.  */
22969
22970 static const char *
22971 dwarf_form_name (unsigned form)
22972 {
22973   const char *name = get_DW_FORM_name (form);
22974
22975   if (name == NULL)
22976     return "DW_FORM_<unknown>";
22977
22978   return name;
22979 }
22980
22981 static const char *
22982 dwarf_bool_name (unsigned mybool)
22983 {
22984   if (mybool)
22985     return "TRUE";
22986   else
22987     return "FALSE";
22988 }
22989
22990 /* Convert a DWARF type code into its string name.  */
22991
22992 static const char *
22993 dwarf_type_encoding_name (unsigned enc)
22994 {
22995   const char *name = get_DW_ATE_name (enc);
22996
22997   if (name == NULL)
22998     return "DW_ATE_<unknown>";
22999
23000   return name;
23001 }
23002
23003 static void
23004 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
23005 {
23006   unsigned int i;
23007
23008   print_spaces (indent, f);
23009   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
23010                       dwarf_tag_name (die->tag), die->abbrev,
23011                       sect_offset_str (die->sect_off));
23012
23013   if (die->parent != NULL)
23014     {
23015       print_spaces (indent, f);
23016       fprintf_unfiltered (f, "  parent at offset: %s\n",
23017                           sect_offset_str (die->parent->sect_off));
23018     }
23019
23020   print_spaces (indent, f);
23021   fprintf_unfiltered (f, "  has children: %s\n",
23022            dwarf_bool_name (die->child != NULL));
23023
23024   print_spaces (indent, f);
23025   fprintf_unfiltered (f, "  attributes:\n");
23026
23027   for (i = 0; i < die->num_attrs; ++i)
23028     {
23029       print_spaces (indent, f);
23030       fprintf_unfiltered (f, "    %s (%s) ",
23031                dwarf_attr_name (die->attrs[i].name),
23032                dwarf_form_name (die->attrs[i].form));
23033
23034       switch (die->attrs[i].form)
23035         {
23036         case DW_FORM_addr:
23037         case DW_FORM_GNU_addr_index:
23038           fprintf_unfiltered (f, "address: ");
23039           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
23040           break;
23041         case DW_FORM_block2:
23042         case DW_FORM_block4:
23043         case DW_FORM_block:
23044         case DW_FORM_block1:
23045           fprintf_unfiltered (f, "block: size %s",
23046                               pulongest (DW_BLOCK (&die->attrs[i])->size));
23047           break;
23048         case DW_FORM_exprloc:
23049           fprintf_unfiltered (f, "expression: size %s",
23050                               pulongest (DW_BLOCK (&die->attrs[i])->size));
23051           break;
23052         case DW_FORM_data16:
23053           fprintf_unfiltered (f, "constant of 16 bytes");
23054           break;
23055         case DW_FORM_ref_addr:
23056           fprintf_unfiltered (f, "ref address: ");
23057           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
23058           break;
23059         case DW_FORM_GNU_ref_alt:
23060           fprintf_unfiltered (f, "alt ref address: ");
23061           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
23062           break;
23063         case DW_FORM_ref1:
23064         case DW_FORM_ref2:
23065         case DW_FORM_ref4:
23066         case DW_FORM_ref8:
23067         case DW_FORM_ref_udata:
23068           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
23069                               (long) (DW_UNSND (&die->attrs[i])));
23070           break;
23071         case DW_FORM_data1:
23072         case DW_FORM_data2:
23073         case DW_FORM_data4:
23074         case DW_FORM_data8:
23075         case DW_FORM_udata:
23076         case DW_FORM_sdata:
23077           fprintf_unfiltered (f, "constant: %s",
23078                               pulongest (DW_UNSND (&die->attrs[i])));
23079           break;
23080         case DW_FORM_sec_offset:
23081           fprintf_unfiltered (f, "section offset: %s",
23082                               pulongest (DW_UNSND (&die->attrs[i])));
23083           break;
23084         case DW_FORM_ref_sig8:
23085           fprintf_unfiltered (f, "signature: %s",
23086                               hex_string (DW_SIGNATURE (&die->attrs[i])));
23087           break;
23088         case DW_FORM_string:
23089         case DW_FORM_strp:
23090         case DW_FORM_line_strp:
23091         case DW_FORM_GNU_str_index:
23092         case DW_FORM_GNU_strp_alt:
23093           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
23094                    DW_STRING (&die->attrs[i])
23095                    ? DW_STRING (&die->attrs[i]) : "",
23096                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
23097           break;
23098         case DW_FORM_flag:
23099           if (DW_UNSND (&die->attrs[i]))
23100             fprintf_unfiltered (f, "flag: TRUE");
23101           else
23102             fprintf_unfiltered (f, "flag: FALSE");
23103           break;
23104         case DW_FORM_flag_present:
23105           fprintf_unfiltered (f, "flag: TRUE");
23106           break;
23107         case DW_FORM_indirect:
23108           /* The reader will have reduced the indirect form to
23109              the "base form" so this form should not occur.  */
23110           fprintf_unfiltered (f, 
23111                               "unexpected attribute form: DW_FORM_indirect");
23112           break;
23113         case DW_FORM_implicit_const:
23114           fprintf_unfiltered (f, "constant: %s",
23115                               plongest (DW_SND (&die->attrs[i])));
23116           break;
23117         default:
23118           fprintf_unfiltered (f, "unsupported attribute form: %d.",
23119                    die->attrs[i].form);
23120           break;
23121         }
23122       fprintf_unfiltered (f, "\n");
23123     }
23124 }
23125
23126 static void
23127 dump_die_for_error (struct die_info *die)
23128 {
23129   dump_die_shallow (gdb_stderr, 0, die);
23130 }
23131
23132 static void
23133 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
23134 {
23135   int indent = level * 4;
23136
23137   gdb_assert (die != NULL);
23138
23139   if (level >= max_level)
23140     return;
23141
23142   dump_die_shallow (f, indent, die);
23143
23144   if (die->child != NULL)
23145     {
23146       print_spaces (indent, f);
23147       fprintf_unfiltered (f, "  Children:");
23148       if (level + 1 < max_level)
23149         {
23150           fprintf_unfiltered (f, "\n");
23151           dump_die_1 (f, level + 1, max_level, die->child);
23152         }
23153       else
23154         {
23155           fprintf_unfiltered (f,
23156                               " [not printed, max nesting level reached]\n");
23157         }
23158     }
23159
23160   if (die->sibling != NULL && level > 0)
23161     {
23162       dump_die_1 (f, level, max_level, die->sibling);
23163     }
23164 }
23165
23166 /* This is called from the pdie macro in gdbinit.in.
23167    It's not static so gcc will keep a copy callable from gdb.  */
23168
23169 void
23170 dump_die (struct die_info *die, int max_level)
23171 {
23172   dump_die_1 (gdb_stdlog, 0, max_level, die);
23173 }
23174
23175 static void
23176 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
23177 {
23178   void **slot;
23179
23180   slot = htab_find_slot_with_hash (cu->die_hash, die,
23181                                    to_underlying (die->sect_off),
23182                                    INSERT);
23183
23184   *slot = die;
23185 }
23186
23187 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
23188    required kind.  */
23189
23190 static sect_offset
23191 dwarf2_get_ref_die_offset (const struct attribute *attr)
23192 {
23193   if (attr_form_is_ref (attr))
23194     return (sect_offset) DW_UNSND (attr);
23195
23196   complaint (&symfile_complaints,
23197              _("unsupported die ref attribute form: '%s'"),
23198              dwarf_form_name (attr->form));
23199   return {};
23200 }
23201
23202 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
23203  * the value held by the attribute is not constant.  */
23204
23205 static LONGEST
23206 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
23207 {
23208   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
23209     return DW_SND (attr);
23210   else if (attr->form == DW_FORM_udata
23211            || attr->form == DW_FORM_data1
23212            || attr->form == DW_FORM_data2
23213            || attr->form == DW_FORM_data4
23214            || attr->form == DW_FORM_data8)
23215     return DW_UNSND (attr);
23216   else
23217     {
23218       /* For DW_FORM_data16 see attr_form_is_constant.  */
23219       complaint (&symfile_complaints,
23220                  _("Attribute value is not a constant (%s)"),
23221                  dwarf_form_name (attr->form));
23222       return default_value;
23223     }
23224 }
23225
23226 /* Follow reference or signature attribute ATTR of SRC_DIE.
23227    On entry *REF_CU is the CU of SRC_DIE.
23228    On exit *REF_CU is the CU of the result.  */
23229
23230 static struct die_info *
23231 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23232                        struct dwarf2_cu **ref_cu)
23233 {
23234   struct die_info *die;
23235
23236   if (attr_form_is_ref (attr))
23237     die = follow_die_ref (src_die, attr, ref_cu);
23238   else if (attr->form == DW_FORM_ref_sig8)
23239     die = follow_die_sig (src_die, attr, ref_cu);
23240   else
23241     {
23242       dump_die_for_error (src_die);
23243       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23244              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23245     }
23246
23247   return die;
23248 }
23249
23250 /* Follow reference OFFSET.
23251    On entry *REF_CU is the CU of the source die referencing OFFSET.
23252    On exit *REF_CU is the CU of the result.
23253    Returns NULL if OFFSET is invalid.  */
23254
23255 static struct die_info *
23256 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23257                    struct dwarf2_cu **ref_cu)
23258 {
23259   struct die_info temp_die;
23260   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23261   struct dwarf2_per_objfile *dwarf2_per_objfile
23262     = cu->per_cu->dwarf2_per_objfile;
23263   struct objfile *objfile = dwarf2_per_objfile->objfile;
23264
23265   gdb_assert (cu->per_cu != NULL);
23266
23267   target_cu = cu;
23268
23269   if (cu->per_cu->is_debug_types)
23270     {
23271       /* .debug_types CUs cannot reference anything outside their CU.
23272          If they need to, they have to reference a signatured type via
23273          DW_FORM_ref_sig8.  */
23274       if (!offset_in_cu_p (&cu->header, sect_off))
23275         return NULL;
23276     }
23277   else if (offset_in_dwz != cu->per_cu->is_dwz
23278            || !offset_in_cu_p (&cu->header, sect_off))
23279     {
23280       struct dwarf2_per_cu_data *per_cu;
23281
23282       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23283                                                  dwarf2_per_objfile);
23284
23285       /* If necessary, add it to the queue and load its DIEs.  */
23286       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23287         load_full_comp_unit (per_cu, cu->language);
23288
23289       target_cu = per_cu->cu;
23290     }
23291   else if (cu->dies == NULL)
23292     {
23293       /* We're loading full DIEs during partial symbol reading.  */
23294       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23295       load_full_comp_unit (cu->per_cu, language_minimal);
23296     }
23297
23298   *ref_cu = target_cu;
23299   temp_die.sect_off = sect_off;
23300   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23301                                                   &temp_die,
23302                                                   to_underlying (sect_off));
23303 }
23304
23305 /* Follow reference attribute ATTR of SRC_DIE.
23306    On entry *REF_CU is the CU of SRC_DIE.
23307    On exit *REF_CU is the CU of the result.  */
23308
23309 static struct die_info *
23310 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23311                 struct dwarf2_cu **ref_cu)
23312 {
23313   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23314   struct dwarf2_cu *cu = *ref_cu;
23315   struct die_info *die;
23316
23317   die = follow_die_offset (sect_off,
23318                            (attr->form == DW_FORM_GNU_ref_alt
23319                             || cu->per_cu->is_dwz),
23320                            ref_cu);
23321   if (!die)
23322     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23323            "at %s [in module %s]"),
23324            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23325            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23326
23327   return die;
23328 }
23329
23330 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23331    Returned value is intended for DW_OP_call*.  Returned
23332    dwarf2_locexpr_baton->data has lifetime of
23333    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23334
23335 struct dwarf2_locexpr_baton
23336 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23337                                struct dwarf2_per_cu_data *per_cu,
23338                                CORE_ADDR (*get_frame_pc) (void *baton),
23339                                void *baton)
23340 {
23341   struct dwarf2_cu *cu;
23342   struct die_info *die;
23343   struct attribute *attr;
23344   struct dwarf2_locexpr_baton retval;
23345   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23346   struct dwarf2_per_objfile *dwarf2_per_objfile
23347     = get_dwarf2_per_objfile (objfile);
23348
23349   if (per_cu->cu == NULL)
23350     load_cu (per_cu);
23351   cu = per_cu->cu;
23352   if (cu == NULL)
23353     {
23354       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23355          Instead just throw an error, not much else we can do.  */
23356       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23357              sect_offset_str (sect_off), objfile_name (objfile));
23358     }
23359
23360   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23361   if (!die)
23362     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23363            sect_offset_str (sect_off), objfile_name (objfile));
23364
23365   attr = dwarf2_attr (die, DW_AT_location, cu);
23366   if (!attr)
23367     {
23368       /* DWARF: "If there is no such attribute, then there is no effect.".
23369          DATA is ignored if SIZE is 0.  */
23370
23371       retval.data = NULL;
23372       retval.size = 0;
23373     }
23374   else if (attr_form_is_section_offset (attr))
23375     {
23376       struct dwarf2_loclist_baton loclist_baton;
23377       CORE_ADDR pc = (*get_frame_pc) (baton);
23378       size_t size;
23379
23380       fill_in_loclist_baton (cu, &loclist_baton, attr);
23381
23382       retval.data = dwarf2_find_location_expression (&loclist_baton,
23383                                                      &size, pc);
23384       retval.size = size;
23385     }
23386   else
23387     {
23388       if (!attr_form_is_block (attr))
23389         error (_("Dwarf Error: DIE at %s referenced in module %s "
23390                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23391                sect_offset_str (sect_off), objfile_name (objfile));
23392
23393       retval.data = DW_BLOCK (attr)->data;
23394       retval.size = DW_BLOCK (attr)->size;
23395     }
23396   retval.per_cu = cu->per_cu;
23397
23398   age_cached_comp_units (dwarf2_per_objfile);
23399
23400   return retval;
23401 }
23402
23403 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23404    offset.  */
23405
23406 struct dwarf2_locexpr_baton
23407 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23408                              struct dwarf2_per_cu_data *per_cu,
23409                              CORE_ADDR (*get_frame_pc) (void *baton),
23410                              void *baton)
23411 {
23412   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23413
23414   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23415 }
23416
23417 /* Write a constant of a given type as target-ordered bytes into
23418    OBSTACK.  */
23419
23420 static const gdb_byte *
23421 write_constant_as_bytes (struct obstack *obstack,
23422                          enum bfd_endian byte_order,
23423                          struct type *type,
23424                          ULONGEST value,
23425                          LONGEST *len)
23426 {
23427   gdb_byte *result;
23428
23429   *len = TYPE_LENGTH (type);
23430   result = (gdb_byte *) obstack_alloc (obstack, *len);
23431   store_unsigned_integer (result, *len, byte_order, value);
23432
23433   return result;
23434 }
23435
23436 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23437    pointer to the constant bytes and set LEN to the length of the
23438    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23439    does not have a DW_AT_const_value, return NULL.  */
23440
23441 const gdb_byte *
23442 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23443                              struct dwarf2_per_cu_data *per_cu,
23444                              struct obstack *obstack,
23445                              LONGEST *len)
23446 {
23447   struct dwarf2_cu *cu;
23448   struct die_info *die;
23449   struct attribute *attr;
23450   const gdb_byte *result = NULL;
23451   struct type *type;
23452   LONGEST value;
23453   enum bfd_endian byte_order;
23454   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23455
23456   if (per_cu->cu == NULL)
23457     load_cu (per_cu);
23458   cu = per_cu->cu;
23459   if (cu == NULL)
23460     {
23461       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23462          Instead just throw an error, not much else we can do.  */
23463       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23464              sect_offset_str (sect_off), objfile_name (objfile));
23465     }
23466
23467   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23468   if (!die)
23469     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23470            sect_offset_str (sect_off), objfile_name (objfile));
23471
23472   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23473   if (attr == NULL)
23474     return NULL;
23475
23476   byte_order = (bfd_big_endian (objfile->obfd)
23477                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23478
23479   switch (attr->form)
23480     {
23481     case DW_FORM_addr:
23482     case DW_FORM_GNU_addr_index:
23483       {
23484         gdb_byte *tem;
23485
23486         *len = cu->header.addr_size;
23487         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23488         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23489         result = tem;
23490       }
23491       break;
23492     case DW_FORM_string:
23493     case DW_FORM_strp:
23494     case DW_FORM_GNU_str_index:
23495     case DW_FORM_GNU_strp_alt:
23496       /* DW_STRING is already allocated on the objfile obstack, point
23497          directly to it.  */
23498       result = (const gdb_byte *) DW_STRING (attr);
23499       *len = strlen (DW_STRING (attr));
23500       break;
23501     case DW_FORM_block1:
23502     case DW_FORM_block2:
23503     case DW_FORM_block4:
23504     case DW_FORM_block:
23505     case DW_FORM_exprloc:
23506     case DW_FORM_data16:
23507       result = DW_BLOCK (attr)->data;
23508       *len = DW_BLOCK (attr)->size;
23509       break;
23510
23511       /* The DW_AT_const_value attributes are supposed to carry the
23512          symbol's value "represented as it would be on the target
23513          architecture."  By the time we get here, it's already been
23514          converted to host endianness, so we just need to sign- or
23515          zero-extend it as appropriate.  */
23516     case DW_FORM_data1:
23517       type = die_type (die, cu);
23518       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23519       if (result == NULL)
23520         result = write_constant_as_bytes (obstack, byte_order,
23521                                           type, value, len);
23522       break;
23523     case DW_FORM_data2:
23524       type = die_type (die, cu);
23525       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23526       if (result == NULL)
23527         result = write_constant_as_bytes (obstack, byte_order,
23528                                           type, value, len);
23529       break;
23530     case DW_FORM_data4:
23531       type = die_type (die, cu);
23532       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23533       if (result == NULL)
23534         result = write_constant_as_bytes (obstack, byte_order,
23535                                           type, value, len);
23536       break;
23537     case DW_FORM_data8:
23538       type = die_type (die, cu);
23539       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23540       if (result == NULL)
23541         result = write_constant_as_bytes (obstack, byte_order,
23542                                           type, value, len);
23543       break;
23544
23545     case DW_FORM_sdata:
23546     case DW_FORM_implicit_const:
23547       type = die_type (die, cu);
23548       result = write_constant_as_bytes (obstack, byte_order,
23549                                         type, DW_SND (attr), len);
23550       break;
23551
23552     case DW_FORM_udata:
23553       type = die_type (die, cu);
23554       result = write_constant_as_bytes (obstack, byte_order,
23555                                         type, DW_UNSND (attr), len);
23556       break;
23557
23558     default:
23559       complaint (&symfile_complaints,
23560                  _("unsupported const value attribute form: '%s'"),
23561                  dwarf_form_name (attr->form));
23562       break;
23563     }
23564
23565   return result;
23566 }
23567
23568 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23569    valid type for this die is found.  */
23570
23571 struct type *
23572 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23573                                 struct dwarf2_per_cu_data *per_cu)
23574 {
23575   struct dwarf2_cu *cu;
23576   struct die_info *die;
23577
23578   if (per_cu->cu == NULL)
23579     load_cu (per_cu);
23580   cu = per_cu->cu;
23581   if (!cu)
23582     return NULL;
23583
23584   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23585   if (!die)
23586     return NULL;
23587
23588   return die_type (die, cu);
23589 }
23590
23591 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23592    PER_CU.  */
23593
23594 struct type *
23595 dwarf2_get_die_type (cu_offset die_offset,
23596                      struct dwarf2_per_cu_data *per_cu)
23597 {
23598   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23599   return get_die_type_at_offset (die_offset_sect, per_cu);
23600 }
23601
23602 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23603    On entry *REF_CU is the CU of SRC_DIE.
23604    On exit *REF_CU is the CU of the result.
23605    Returns NULL if the referenced DIE isn't found.  */
23606
23607 static struct die_info *
23608 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23609                   struct dwarf2_cu **ref_cu)
23610 {
23611   struct die_info temp_die;
23612   struct dwarf2_cu *sig_cu;
23613   struct die_info *die;
23614
23615   /* While it might be nice to assert sig_type->type == NULL here,
23616      we can get here for DW_AT_imported_declaration where we need
23617      the DIE not the type.  */
23618
23619   /* If necessary, add it to the queue and load its DIEs.  */
23620
23621   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23622     read_signatured_type (sig_type);
23623
23624   sig_cu = sig_type->per_cu.cu;
23625   gdb_assert (sig_cu != NULL);
23626   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23627   temp_die.sect_off = sig_type->type_offset_in_section;
23628   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23629                                                  to_underlying (temp_die.sect_off));
23630   if (die)
23631     {
23632       struct dwarf2_per_objfile *dwarf2_per_objfile
23633         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23634
23635       /* For .gdb_index version 7 keep track of included TUs.
23636          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23637       if (dwarf2_per_objfile->index_table != NULL
23638           && dwarf2_per_objfile->index_table->version <= 7)
23639         {
23640           VEC_safe_push (dwarf2_per_cu_ptr,
23641                          (*ref_cu)->per_cu->imported_symtabs,
23642                          sig_cu->per_cu);
23643         }
23644
23645       *ref_cu = sig_cu;
23646       return die;
23647     }
23648
23649   return NULL;
23650 }
23651
23652 /* Follow signatured type referenced by ATTR in SRC_DIE.
23653    On entry *REF_CU is the CU of SRC_DIE.
23654    On exit *REF_CU is the CU of the result.
23655    The result is the DIE of the type.
23656    If the referenced type cannot be found an error is thrown.  */
23657
23658 static struct die_info *
23659 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23660                 struct dwarf2_cu **ref_cu)
23661 {
23662   ULONGEST signature = DW_SIGNATURE (attr);
23663   struct signatured_type *sig_type;
23664   struct die_info *die;
23665
23666   gdb_assert (attr->form == DW_FORM_ref_sig8);
23667
23668   sig_type = lookup_signatured_type (*ref_cu, signature);
23669   /* sig_type will be NULL if the signatured type is missing from
23670      the debug info.  */
23671   if (sig_type == NULL)
23672     {
23673       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23674                " from DIE at %s [in module %s]"),
23675              hex_string (signature), sect_offset_str (src_die->sect_off),
23676              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23677     }
23678
23679   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23680   if (die == NULL)
23681     {
23682       dump_die_for_error (src_die);
23683       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23684                " from DIE at %s [in module %s]"),
23685              hex_string (signature), sect_offset_str (src_die->sect_off),
23686              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23687     }
23688
23689   return die;
23690 }
23691
23692 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23693    reading in and processing the type unit if necessary.  */
23694
23695 static struct type *
23696 get_signatured_type (struct die_info *die, ULONGEST signature,
23697                      struct dwarf2_cu *cu)
23698 {
23699   struct dwarf2_per_objfile *dwarf2_per_objfile
23700     = cu->per_cu->dwarf2_per_objfile;
23701   struct signatured_type *sig_type;
23702   struct dwarf2_cu *type_cu;
23703   struct die_info *type_die;
23704   struct type *type;
23705
23706   sig_type = lookup_signatured_type (cu, signature);
23707   /* sig_type will be NULL if the signatured type is missing from
23708      the debug info.  */
23709   if (sig_type == NULL)
23710     {
23711       complaint (&symfile_complaints,
23712                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23713                    " from DIE at %s [in module %s]"),
23714                  hex_string (signature), sect_offset_str (die->sect_off),
23715                  objfile_name (dwarf2_per_objfile->objfile));
23716       return build_error_marker_type (cu, die);
23717     }
23718
23719   /* If we already know the type we're done.  */
23720   if (sig_type->type != NULL)
23721     return sig_type->type;
23722
23723   type_cu = cu;
23724   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23725   if (type_die != NULL)
23726     {
23727       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23728          is created.  This is important, for example, because for c++ classes
23729          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23730       type = read_type_die (type_die, type_cu);
23731       if (type == NULL)
23732         {
23733           complaint (&symfile_complaints,
23734                      _("Dwarf Error: Cannot build signatured type %s"
23735                        " referenced from DIE at %s [in module %s]"),
23736                      hex_string (signature), sect_offset_str (die->sect_off),
23737                      objfile_name (dwarf2_per_objfile->objfile));
23738           type = build_error_marker_type (cu, die);
23739         }
23740     }
23741   else
23742     {
23743       complaint (&symfile_complaints,
23744                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23745                    " from DIE at %s [in module %s]"),
23746                  hex_string (signature), sect_offset_str (die->sect_off),
23747                  objfile_name (dwarf2_per_objfile->objfile));
23748       type = build_error_marker_type (cu, die);
23749     }
23750   sig_type->type = type;
23751
23752   return type;
23753 }
23754
23755 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23756    reading in and processing the type unit if necessary.  */
23757
23758 static struct type *
23759 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23760                           struct dwarf2_cu *cu) /* ARI: editCase function */
23761 {
23762   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23763   if (attr_form_is_ref (attr))
23764     {
23765       struct dwarf2_cu *type_cu = cu;
23766       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23767
23768       return read_type_die (type_die, type_cu);
23769     }
23770   else if (attr->form == DW_FORM_ref_sig8)
23771     {
23772       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23773     }
23774   else
23775     {
23776       struct dwarf2_per_objfile *dwarf2_per_objfile
23777         = cu->per_cu->dwarf2_per_objfile;
23778
23779       complaint (&symfile_complaints,
23780                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23781                    " at %s [in module %s]"),
23782                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23783                  objfile_name (dwarf2_per_objfile->objfile));
23784       return build_error_marker_type (cu, die);
23785     }
23786 }
23787
23788 /* Load the DIEs associated with type unit PER_CU into memory.  */
23789
23790 static void
23791 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23792 {
23793   struct signatured_type *sig_type;
23794
23795   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23796   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23797
23798   /* We have the per_cu, but we need the signatured_type.
23799      Fortunately this is an easy translation.  */
23800   gdb_assert (per_cu->is_debug_types);
23801   sig_type = (struct signatured_type *) per_cu;
23802
23803   gdb_assert (per_cu->cu == NULL);
23804
23805   read_signatured_type (sig_type);
23806
23807   gdb_assert (per_cu->cu != NULL);
23808 }
23809
23810 /* die_reader_func for read_signatured_type.
23811    This is identical to load_full_comp_unit_reader,
23812    but is kept separate for now.  */
23813
23814 static void
23815 read_signatured_type_reader (const struct die_reader_specs *reader,
23816                              const gdb_byte *info_ptr,
23817                              struct die_info *comp_unit_die,
23818                              int has_children,
23819                              void *data)
23820 {
23821   struct dwarf2_cu *cu = reader->cu;
23822
23823   gdb_assert (cu->die_hash == NULL);
23824   cu->die_hash =
23825     htab_create_alloc_ex (cu->header.length / 12,
23826                           die_hash,
23827                           die_eq,
23828                           NULL,
23829                           &cu->comp_unit_obstack,
23830                           hashtab_obstack_allocate,
23831                           dummy_obstack_deallocate);
23832
23833   if (has_children)
23834     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23835                                                   &info_ptr, comp_unit_die);
23836   cu->dies = comp_unit_die;
23837   /* comp_unit_die is not stored in die_hash, no need.  */
23838
23839   /* We try not to read any attributes in this function, because not
23840      all CUs needed for references have been loaded yet, and symbol
23841      table processing isn't initialized.  But we have to set the CU language,
23842      or we won't be able to build types correctly.
23843      Similarly, if we do not read the producer, we can not apply
23844      producer-specific interpretation.  */
23845   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23846 }
23847
23848 /* Read in a signatured type and build its CU and DIEs.
23849    If the type is a stub for the real type in a DWO file,
23850    read in the real type from the DWO file as well.  */
23851
23852 static void
23853 read_signatured_type (struct signatured_type *sig_type)
23854 {
23855   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23856
23857   gdb_assert (per_cu->is_debug_types);
23858   gdb_assert (per_cu->cu == NULL);
23859
23860   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23861                            read_signatured_type_reader, NULL);
23862   sig_type->per_cu.tu_read = 1;
23863 }
23864
23865 /* Decode simple location descriptions.
23866    Given a pointer to a dwarf block that defines a location, compute
23867    the location and return the value.
23868
23869    NOTE drow/2003-11-18: This function is called in two situations
23870    now: for the address of static or global variables (partial symbols
23871    only) and for offsets into structures which are expected to be
23872    (more or less) constant.  The partial symbol case should go away,
23873    and only the constant case should remain.  That will let this
23874    function complain more accurately.  A few special modes are allowed
23875    without complaint for global variables (for instance, global
23876    register values and thread-local values).
23877
23878    A location description containing no operations indicates that the
23879    object is optimized out.  The return value is 0 for that case.
23880    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23881    callers will only want a very basic result and this can become a
23882    complaint.
23883
23884    Note that stack[0] is unused except as a default error return.  */
23885
23886 static CORE_ADDR
23887 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23888 {
23889   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23890   size_t i;
23891   size_t size = blk->size;
23892   const gdb_byte *data = blk->data;
23893   CORE_ADDR stack[64];
23894   int stacki;
23895   unsigned int bytes_read, unsnd;
23896   gdb_byte op;
23897
23898   i = 0;
23899   stacki = 0;
23900   stack[stacki] = 0;
23901   stack[++stacki] = 0;
23902
23903   while (i < size)
23904     {
23905       op = data[i++];
23906       switch (op)
23907         {
23908         case DW_OP_lit0:
23909         case DW_OP_lit1:
23910         case DW_OP_lit2:
23911         case DW_OP_lit3:
23912         case DW_OP_lit4:
23913         case DW_OP_lit5:
23914         case DW_OP_lit6:
23915         case DW_OP_lit7:
23916         case DW_OP_lit8:
23917         case DW_OP_lit9:
23918         case DW_OP_lit10:
23919         case DW_OP_lit11:
23920         case DW_OP_lit12:
23921         case DW_OP_lit13:
23922         case DW_OP_lit14:
23923         case DW_OP_lit15:
23924         case DW_OP_lit16:
23925         case DW_OP_lit17:
23926         case DW_OP_lit18:
23927         case DW_OP_lit19:
23928         case DW_OP_lit20:
23929         case DW_OP_lit21:
23930         case DW_OP_lit22:
23931         case DW_OP_lit23:
23932         case DW_OP_lit24:
23933         case DW_OP_lit25:
23934         case DW_OP_lit26:
23935         case DW_OP_lit27:
23936         case DW_OP_lit28:
23937         case DW_OP_lit29:
23938         case DW_OP_lit30:
23939         case DW_OP_lit31:
23940           stack[++stacki] = op - DW_OP_lit0;
23941           break;
23942
23943         case DW_OP_reg0:
23944         case DW_OP_reg1:
23945         case DW_OP_reg2:
23946         case DW_OP_reg3:
23947         case DW_OP_reg4:
23948         case DW_OP_reg5:
23949         case DW_OP_reg6:
23950         case DW_OP_reg7:
23951         case DW_OP_reg8:
23952         case DW_OP_reg9:
23953         case DW_OP_reg10:
23954         case DW_OP_reg11:
23955         case DW_OP_reg12:
23956         case DW_OP_reg13:
23957         case DW_OP_reg14:
23958         case DW_OP_reg15:
23959         case DW_OP_reg16:
23960         case DW_OP_reg17:
23961         case DW_OP_reg18:
23962         case DW_OP_reg19:
23963         case DW_OP_reg20:
23964         case DW_OP_reg21:
23965         case DW_OP_reg22:
23966         case DW_OP_reg23:
23967         case DW_OP_reg24:
23968         case DW_OP_reg25:
23969         case DW_OP_reg26:
23970         case DW_OP_reg27:
23971         case DW_OP_reg28:
23972         case DW_OP_reg29:
23973         case DW_OP_reg30:
23974         case DW_OP_reg31:
23975           stack[++stacki] = op - DW_OP_reg0;
23976           if (i < size)
23977             dwarf2_complex_location_expr_complaint ();
23978           break;
23979
23980         case DW_OP_regx:
23981           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23982           i += bytes_read;
23983           stack[++stacki] = unsnd;
23984           if (i < size)
23985             dwarf2_complex_location_expr_complaint ();
23986           break;
23987
23988         case DW_OP_addr:
23989           stack[++stacki] = read_address (objfile->obfd, &data[i],
23990                                           cu, &bytes_read);
23991           i += bytes_read;
23992           break;
23993
23994         case DW_OP_const1u:
23995           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23996           i += 1;
23997           break;
23998
23999         case DW_OP_const1s:
24000           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
24001           i += 1;
24002           break;
24003
24004         case DW_OP_const2u:
24005           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
24006           i += 2;
24007           break;
24008
24009         case DW_OP_const2s:
24010           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
24011           i += 2;
24012           break;
24013
24014         case DW_OP_const4u:
24015           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
24016           i += 4;
24017           break;
24018
24019         case DW_OP_const4s:
24020           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
24021           i += 4;
24022           break;
24023
24024         case DW_OP_const8u:
24025           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
24026           i += 8;
24027           break;
24028
24029         case DW_OP_constu:
24030           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
24031                                                   &bytes_read);
24032           i += bytes_read;
24033           break;
24034
24035         case DW_OP_consts:
24036           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
24037           i += bytes_read;
24038           break;
24039
24040         case DW_OP_dup:
24041           stack[stacki + 1] = stack[stacki];
24042           stacki++;
24043           break;
24044
24045         case DW_OP_plus:
24046           stack[stacki - 1] += stack[stacki];
24047           stacki--;
24048           break;
24049
24050         case DW_OP_plus_uconst:
24051           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
24052                                                  &bytes_read);
24053           i += bytes_read;
24054           break;
24055
24056         case DW_OP_minus:
24057           stack[stacki - 1] -= stack[stacki];
24058           stacki--;
24059           break;
24060
24061         case DW_OP_deref:
24062           /* If we're not the last op, then we definitely can't encode
24063              this using GDB's address_class enum.  This is valid for partial
24064              global symbols, although the variable's address will be bogus
24065              in the psymtab.  */
24066           if (i < size)
24067             dwarf2_complex_location_expr_complaint ();
24068           break;
24069
24070         case DW_OP_GNU_push_tls_address:
24071         case DW_OP_form_tls_address:
24072           /* The top of the stack has the offset from the beginning
24073              of the thread control block at which the variable is located.  */
24074           /* Nothing should follow this operator, so the top of stack would
24075              be returned.  */
24076           /* This is valid for partial global symbols, but the variable's
24077              address will be bogus in the psymtab.  Make it always at least
24078              non-zero to not look as a variable garbage collected by linker
24079              which have DW_OP_addr 0.  */
24080           if (i < size)
24081             dwarf2_complex_location_expr_complaint ();
24082           stack[stacki]++;
24083           break;
24084
24085         case DW_OP_GNU_uninit:
24086           break;
24087
24088         case DW_OP_GNU_addr_index:
24089         case DW_OP_GNU_const_index:
24090           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
24091                                                          &bytes_read);
24092           i += bytes_read;
24093           break;
24094
24095         default:
24096           {
24097             const char *name = get_DW_OP_name (op);
24098
24099             if (name)
24100               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
24101                          name);
24102             else
24103               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
24104                          op);
24105           }
24106
24107           return (stack[stacki]);
24108         }
24109
24110       /* Enforce maximum stack depth of SIZE-1 to avoid writing
24111          outside of the allocated space.  Also enforce minimum>0.  */
24112       if (stacki >= ARRAY_SIZE (stack) - 1)
24113         {
24114           complaint (&symfile_complaints,
24115                      _("location description stack overflow"));
24116           return 0;
24117         }
24118
24119       if (stacki <= 0)
24120         {
24121           complaint (&symfile_complaints,
24122                      _("location description stack underflow"));
24123           return 0;
24124         }
24125     }
24126   return (stack[stacki]);
24127 }
24128
24129 /* memory allocation interface */
24130
24131 static struct dwarf_block *
24132 dwarf_alloc_block (struct dwarf2_cu *cu)
24133 {
24134   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
24135 }
24136
24137 static struct die_info *
24138 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
24139 {
24140   struct die_info *die;
24141   size_t size = sizeof (struct die_info);
24142
24143   if (num_attrs > 1)
24144     size += (num_attrs - 1) * sizeof (struct attribute);
24145
24146   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
24147   memset (die, 0, sizeof (struct die_info));
24148   return (die);
24149 }
24150
24151 \f
24152 /* Macro support.  */
24153
24154 /* Return file name relative to the compilation directory of file number I in
24155    *LH's file name table.  The result is allocated using xmalloc; the caller is
24156    responsible for freeing it.  */
24157
24158 static char *
24159 file_file_name (int file, struct line_header *lh)
24160 {
24161   /* Is the file number a valid index into the line header's file name
24162      table?  Remember that file numbers start with one, not zero.  */
24163   if (1 <= file && file <= lh->file_names.size ())
24164     {
24165       const file_entry &fe = lh->file_names[file - 1];
24166
24167       if (!IS_ABSOLUTE_PATH (fe.name))
24168         {
24169           const char *dir = fe.include_dir (lh);
24170           if (dir != NULL)
24171             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
24172         }
24173       return xstrdup (fe.name);
24174     }
24175   else
24176     {
24177       /* The compiler produced a bogus file number.  We can at least
24178          record the macro definitions made in the file, even if we
24179          won't be able to find the file by name.  */
24180       char fake_name[80];
24181
24182       xsnprintf (fake_name, sizeof (fake_name),
24183                  "<bad macro file number %d>", file);
24184
24185       complaint (&symfile_complaints,
24186                  _("bad file number in macro information (%d)"),
24187                  file);
24188
24189       return xstrdup (fake_name);
24190     }
24191 }
24192
24193 /* Return the full name of file number I in *LH's file name table.
24194    Use COMP_DIR as the name of the current directory of the
24195    compilation.  The result is allocated using xmalloc; the caller is
24196    responsible for freeing it.  */
24197 static char *
24198 file_full_name (int file, struct line_header *lh, const char *comp_dir)
24199 {
24200   /* Is the file number a valid index into the line header's file name
24201      table?  Remember that file numbers start with one, not zero.  */
24202   if (1 <= file && file <= lh->file_names.size ())
24203     {
24204       char *relative = file_file_name (file, lh);
24205
24206       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
24207         return relative;
24208       return reconcat (relative, comp_dir, SLASH_STRING,
24209                        relative, (char *) NULL);
24210     }
24211   else
24212     return file_file_name (file, lh);
24213 }
24214
24215
24216 static struct macro_source_file *
24217 macro_start_file (int file, int line,
24218                   struct macro_source_file *current_file,
24219                   struct line_header *lh)
24220 {
24221   /* File name relative to the compilation directory of this source file.  */
24222   char *file_name = file_file_name (file, lh);
24223
24224   if (! current_file)
24225     {
24226       /* Note: We don't create a macro table for this compilation unit
24227          at all until we actually get a filename.  */
24228       struct macro_table *macro_table = get_macro_table ();
24229
24230       /* If we have no current file, then this must be the start_file
24231          directive for the compilation unit's main source file.  */
24232       current_file = macro_set_main (macro_table, file_name);
24233       macro_define_special (macro_table);
24234     }
24235   else
24236     current_file = macro_include (current_file, line, file_name);
24237
24238   xfree (file_name);
24239
24240   return current_file;
24241 }
24242
24243 static const char *
24244 consume_improper_spaces (const char *p, const char *body)
24245 {
24246   if (*p == ' ')
24247     {
24248       complaint (&symfile_complaints,
24249                  _("macro definition contains spaces "
24250                    "in formal argument list:\n`%s'"),
24251                  body);
24252
24253       while (*p == ' ')
24254         p++;
24255     }
24256
24257   return p;
24258 }
24259
24260
24261 static void
24262 parse_macro_definition (struct macro_source_file *file, int line,
24263                         const char *body)
24264 {
24265   const char *p;
24266
24267   /* The body string takes one of two forms.  For object-like macro
24268      definitions, it should be:
24269
24270         <macro name> " " <definition>
24271
24272      For function-like macro definitions, it should be:
24273
24274         <macro name> "() " <definition>
24275      or
24276         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24277
24278      Spaces may appear only where explicitly indicated, and in the
24279      <definition>.
24280
24281      The Dwarf 2 spec says that an object-like macro's name is always
24282      followed by a space, but versions of GCC around March 2002 omit
24283      the space when the macro's definition is the empty string.
24284
24285      The Dwarf 2 spec says that there should be no spaces between the
24286      formal arguments in a function-like macro's formal argument list,
24287      but versions of GCC around March 2002 include spaces after the
24288      commas.  */
24289
24290
24291   /* Find the extent of the macro name.  The macro name is terminated
24292      by either a space or null character (for an object-like macro) or
24293      an opening paren (for a function-like macro).  */
24294   for (p = body; *p; p++)
24295     if (*p == ' ' || *p == '(')
24296       break;
24297
24298   if (*p == ' ' || *p == '\0')
24299     {
24300       /* It's an object-like macro.  */
24301       int name_len = p - body;
24302       char *name = savestring (body, name_len);
24303       const char *replacement;
24304
24305       if (*p == ' ')
24306         replacement = body + name_len + 1;
24307       else
24308         {
24309           dwarf2_macro_malformed_definition_complaint (body);
24310           replacement = body + name_len;
24311         }
24312
24313       macro_define_object (file, line, name, replacement);
24314
24315       xfree (name);
24316     }
24317   else if (*p == '(')
24318     {
24319       /* It's a function-like macro.  */
24320       char *name = savestring (body, p - body);
24321       int argc = 0;
24322       int argv_size = 1;
24323       char **argv = XNEWVEC (char *, argv_size);
24324
24325       p++;
24326
24327       p = consume_improper_spaces (p, body);
24328
24329       /* Parse the formal argument list.  */
24330       while (*p && *p != ')')
24331         {
24332           /* Find the extent of the current argument name.  */
24333           const char *arg_start = p;
24334
24335           while (*p && *p != ',' && *p != ')' && *p != ' ')
24336             p++;
24337
24338           if (! *p || p == arg_start)
24339             dwarf2_macro_malformed_definition_complaint (body);
24340           else
24341             {
24342               /* Make sure argv has room for the new argument.  */
24343               if (argc >= argv_size)
24344                 {
24345                   argv_size *= 2;
24346                   argv = XRESIZEVEC (char *, argv, argv_size);
24347                 }
24348
24349               argv[argc++] = savestring (arg_start, p - arg_start);
24350             }
24351
24352           p = consume_improper_spaces (p, body);
24353
24354           /* Consume the comma, if present.  */
24355           if (*p == ',')
24356             {
24357               p++;
24358
24359               p = consume_improper_spaces (p, body);
24360             }
24361         }
24362
24363       if (*p == ')')
24364         {
24365           p++;
24366
24367           if (*p == ' ')
24368             /* Perfectly formed definition, no complaints.  */
24369             macro_define_function (file, line, name,
24370                                    argc, (const char **) argv,
24371                                    p + 1);
24372           else if (*p == '\0')
24373             {
24374               /* Complain, but do define it.  */
24375               dwarf2_macro_malformed_definition_complaint (body);
24376               macro_define_function (file, line, name,
24377                                      argc, (const char **) argv,
24378                                      p);
24379             }
24380           else
24381             /* Just complain.  */
24382             dwarf2_macro_malformed_definition_complaint (body);
24383         }
24384       else
24385         /* Just complain.  */
24386         dwarf2_macro_malformed_definition_complaint (body);
24387
24388       xfree (name);
24389       {
24390         int i;
24391
24392         for (i = 0; i < argc; i++)
24393           xfree (argv[i]);
24394       }
24395       xfree (argv);
24396     }
24397   else
24398     dwarf2_macro_malformed_definition_complaint (body);
24399 }
24400
24401 /* Skip some bytes from BYTES according to the form given in FORM.
24402    Returns the new pointer.  */
24403
24404 static const gdb_byte *
24405 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24406                  enum dwarf_form form,
24407                  unsigned int offset_size,
24408                  struct dwarf2_section_info *section)
24409 {
24410   unsigned int bytes_read;
24411
24412   switch (form)
24413     {
24414     case DW_FORM_data1:
24415     case DW_FORM_flag:
24416       ++bytes;
24417       break;
24418
24419     case DW_FORM_data2:
24420       bytes += 2;
24421       break;
24422
24423     case DW_FORM_data4:
24424       bytes += 4;
24425       break;
24426
24427     case DW_FORM_data8:
24428       bytes += 8;
24429       break;
24430
24431     case DW_FORM_data16:
24432       bytes += 16;
24433       break;
24434
24435     case DW_FORM_string:
24436       read_direct_string (abfd, bytes, &bytes_read);
24437       bytes += bytes_read;
24438       break;
24439
24440     case DW_FORM_sec_offset:
24441     case DW_FORM_strp:
24442     case DW_FORM_GNU_strp_alt:
24443       bytes += offset_size;
24444       break;
24445
24446     case DW_FORM_block:
24447       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24448       bytes += bytes_read;
24449       break;
24450
24451     case DW_FORM_block1:
24452       bytes += 1 + read_1_byte (abfd, bytes);
24453       break;
24454     case DW_FORM_block2:
24455       bytes += 2 + read_2_bytes (abfd, bytes);
24456       break;
24457     case DW_FORM_block4:
24458       bytes += 4 + read_4_bytes (abfd, bytes);
24459       break;
24460
24461     case DW_FORM_sdata:
24462     case DW_FORM_udata:
24463     case DW_FORM_GNU_addr_index:
24464     case DW_FORM_GNU_str_index:
24465       bytes = gdb_skip_leb128 (bytes, buffer_end);
24466       if (bytes == NULL)
24467         {
24468           dwarf2_section_buffer_overflow_complaint (section);
24469           return NULL;
24470         }
24471       break;
24472
24473     case DW_FORM_implicit_const:
24474       break;
24475
24476     default:
24477       {
24478         complaint (&symfile_complaints,
24479                    _("invalid form 0x%x in `%s'"),
24480                    form, get_section_name (section));
24481         return NULL;
24482       }
24483     }
24484
24485   return bytes;
24486 }
24487
24488 /* A helper for dwarf_decode_macros that handles skipping an unknown
24489    opcode.  Returns an updated pointer to the macro data buffer; or,
24490    on error, issues a complaint and returns NULL.  */
24491
24492 static const gdb_byte *
24493 skip_unknown_opcode (unsigned int opcode,
24494                      const gdb_byte **opcode_definitions,
24495                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24496                      bfd *abfd,
24497                      unsigned int offset_size,
24498                      struct dwarf2_section_info *section)
24499 {
24500   unsigned int bytes_read, i;
24501   unsigned long arg;
24502   const gdb_byte *defn;
24503
24504   if (opcode_definitions[opcode] == NULL)
24505     {
24506       complaint (&symfile_complaints,
24507                  _("unrecognized DW_MACFINO opcode 0x%x"),
24508                  opcode);
24509       return NULL;
24510     }
24511
24512   defn = opcode_definitions[opcode];
24513   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24514   defn += bytes_read;
24515
24516   for (i = 0; i < arg; ++i)
24517     {
24518       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24519                                  (enum dwarf_form) defn[i], offset_size,
24520                                  section);
24521       if (mac_ptr == NULL)
24522         {
24523           /* skip_form_bytes already issued the complaint.  */
24524           return NULL;
24525         }
24526     }
24527
24528   return mac_ptr;
24529 }
24530
24531 /* A helper function which parses the header of a macro section.
24532    If the macro section is the extended (for now called "GNU") type,
24533    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24534    the header, or issues a complaint and returns NULL on error.  */
24535
24536 static const gdb_byte *
24537 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24538                           bfd *abfd,
24539                           const gdb_byte *mac_ptr,
24540                           unsigned int *offset_size,
24541                           int section_is_gnu)
24542 {
24543   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24544
24545   if (section_is_gnu)
24546     {
24547       unsigned int version, flags;
24548
24549       version = read_2_bytes (abfd, mac_ptr);
24550       if (version != 4 && version != 5)
24551         {
24552           complaint (&symfile_complaints,
24553                      _("unrecognized version `%d' in .debug_macro section"),
24554                      version);
24555           return NULL;
24556         }
24557       mac_ptr += 2;
24558
24559       flags = read_1_byte (abfd, mac_ptr);
24560       ++mac_ptr;
24561       *offset_size = (flags & 1) ? 8 : 4;
24562
24563       if ((flags & 2) != 0)
24564         /* We don't need the line table offset.  */
24565         mac_ptr += *offset_size;
24566
24567       /* Vendor opcode descriptions.  */
24568       if ((flags & 4) != 0)
24569         {
24570           unsigned int i, count;
24571
24572           count = read_1_byte (abfd, mac_ptr);
24573           ++mac_ptr;
24574           for (i = 0; i < count; ++i)
24575             {
24576               unsigned int opcode, bytes_read;
24577               unsigned long arg;
24578
24579               opcode = read_1_byte (abfd, mac_ptr);
24580               ++mac_ptr;
24581               opcode_definitions[opcode] = mac_ptr;
24582               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24583               mac_ptr += bytes_read;
24584               mac_ptr += arg;
24585             }
24586         }
24587     }
24588
24589   return mac_ptr;
24590 }
24591
24592 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24593    including DW_MACRO_import.  */
24594
24595 static void
24596 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24597                           bfd *abfd,
24598                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24599                           struct macro_source_file *current_file,
24600                           struct line_header *lh,
24601                           struct dwarf2_section_info *section,
24602                           int section_is_gnu, int section_is_dwz,
24603                           unsigned int offset_size,
24604                           htab_t include_hash)
24605 {
24606   struct objfile *objfile = dwarf2_per_objfile->objfile;
24607   enum dwarf_macro_record_type macinfo_type;
24608   int at_commandline;
24609   const gdb_byte *opcode_definitions[256];
24610
24611   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24612                                       &offset_size, section_is_gnu);
24613   if (mac_ptr == NULL)
24614     {
24615       /* We already issued a complaint.  */
24616       return;
24617     }
24618
24619   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24620      GDB is still reading the definitions from command line.  First
24621      DW_MACINFO_start_file will need to be ignored as it was already executed
24622      to create CURRENT_FILE for the main source holding also the command line
24623      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24624      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24625
24626   at_commandline = 1;
24627
24628   do
24629     {
24630       /* Do we at least have room for a macinfo type byte?  */
24631       if (mac_ptr >= mac_end)
24632         {
24633           dwarf2_section_buffer_overflow_complaint (section);
24634           break;
24635         }
24636
24637       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24638       mac_ptr++;
24639
24640       /* Note that we rely on the fact that the corresponding GNU and
24641          DWARF constants are the same.  */
24642       DIAGNOSTIC_PUSH
24643       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24644       switch (macinfo_type)
24645         {
24646           /* A zero macinfo type indicates the end of the macro
24647              information.  */
24648         case 0:
24649           break;
24650
24651         case DW_MACRO_define:
24652         case DW_MACRO_undef:
24653         case DW_MACRO_define_strp:
24654         case DW_MACRO_undef_strp:
24655         case DW_MACRO_define_sup:
24656         case DW_MACRO_undef_sup:
24657           {
24658             unsigned int bytes_read;
24659             int line;
24660             const char *body;
24661             int is_define;
24662
24663             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24664             mac_ptr += bytes_read;
24665
24666             if (macinfo_type == DW_MACRO_define
24667                 || macinfo_type == DW_MACRO_undef)
24668               {
24669                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24670                 mac_ptr += bytes_read;
24671               }
24672             else
24673               {
24674                 LONGEST str_offset;
24675
24676                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24677                 mac_ptr += offset_size;
24678
24679                 if (macinfo_type == DW_MACRO_define_sup
24680                     || macinfo_type == DW_MACRO_undef_sup
24681                     || section_is_dwz)
24682                   {
24683                     struct dwz_file *dwz
24684                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24685
24686                     body = read_indirect_string_from_dwz (objfile,
24687                                                           dwz, str_offset);
24688                   }
24689                 else
24690                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24691                                                          abfd, str_offset);
24692               }
24693
24694             is_define = (macinfo_type == DW_MACRO_define
24695                          || macinfo_type == DW_MACRO_define_strp
24696                          || macinfo_type == DW_MACRO_define_sup);
24697             if (! current_file)
24698               {
24699                 /* DWARF violation as no main source is present.  */
24700                 complaint (&symfile_complaints,
24701                            _("debug info with no main source gives macro %s "
24702                              "on line %d: %s"),
24703                            is_define ? _("definition") : _("undefinition"),
24704                            line, body);
24705                 break;
24706               }
24707             if ((line == 0 && !at_commandline)
24708                 || (line != 0 && at_commandline))
24709               complaint (&symfile_complaints,
24710                          _("debug info gives %s macro %s with %s line %d: %s"),
24711                          at_commandline ? _("command-line") : _("in-file"),
24712                          is_define ? _("definition") : _("undefinition"),
24713                          line == 0 ? _("zero") : _("non-zero"), line, body);
24714
24715             if (is_define)
24716               parse_macro_definition (current_file, line, body);
24717             else
24718               {
24719                 gdb_assert (macinfo_type == DW_MACRO_undef
24720                             || macinfo_type == DW_MACRO_undef_strp
24721                             || macinfo_type == DW_MACRO_undef_sup);
24722                 macro_undef (current_file, line, body);
24723               }
24724           }
24725           break;
24726
24727         case DW_MACRO_start_file:
24728           {
24729             unsigned int bytes_read;
24730             int line, file;
24731
24732             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24733             mac_ptr += bytes_read;
24734             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24735             mac_ptr += bytes_read;
24736
24737             if ((line == 0 && !at_commandline)
24738                 || (line != 0 && at_commandline))
24739               complaint (&symfile_complaints,
24740                          _("debug info gives source %d included "
24741                            "from %s at %s line %d"),
24742                          file, at_commandline ? _("command-line") : _("file"),
24743                          line == 0 ? _("zero") : _("non-zero"), line);
24744
24745             if (at_commandline)
24746               {
24747                 /* This DW_MACRO_start_file was executed in the
24748                    pass one.  */
24749                 at_commandline = 0;
24750               }
24751             else
24752               current_file = macro_start_file (file, line, current_file, lh);
24753           }
24754           break;
24755
24756         case DW_MACRO_end_file:
24757           if (! current_file)
24758             complaint (&symfile_complaints,
24759                        _("macro debug info has an unmatched "
24760                          "`close_file' directive"));
24761           else
24762             {
24763               current_file = current_file->included_by;
24764               if (! current_file)
24765                 {
24766                   enum dwarf_macro_record_type next_type;
24767
24768                   /* GCC circa March 2002 doesn't produce the zero
24769                      type byte marking the end of the compilation
24770                      unit.  Complain if it's not there, but exit no
24771                      matter what.  */
24772
24773                   /* Do we at least have room for a macinfo type byte?  */
24774                   if (mac_ptr >= mac_end)
24775                     {
24776                       dwarf2_section_buffer_overflow_complaint (section);
24777                       return;
24778                     }
24779
24780                   /* We don't increment mac_ptr here, so this is just
24781                      a look-ahead.  */
24782                   next_type
24783                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24784                                                                   mac_ptr);
24785                   if (next_type != 0)
24786                     complaint (&symfile_complaints,
24787                                _("no terminating 0-type entry for "
24788                                  "macros in `.debug_macinfo' section"));
24789
24790                   return;
24791                 }
24792             }
24793           break;
24794
24795         case DW_MACRO_import:
24796         case DW_MACRO_import_sup:
24797           {
24798             LONGEST offset;
24799             void **slot;
24800             bfd *include_bfd = abfd;
24801             struct dwarf2_section_info *include_section = section;
24802             const gdb_byte *include_mac_end = mac_end;
24803             int is_dwz = section_is_dwz;
24804             const gdb_byte *new_mac_ptr;
24805
24806             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24807             mac_ptr += offset_size;
24808
24809             if (macinfo_type == DW_MACRO_import_sup)
24810               {
24811                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24812
24813                 dwarf2_read_section (objfile, &dwz->macro);
24814
24815                 include_section = &dwz->macro;
24816                 include_bfd = get_section_bfd_owner (include_section);
24817                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24818                 is_dwz = 1;
24819               }
24820
24821             new_mac_ptr = include_section->buffer + offset;
24822             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24823
24824             if (*slot != NULL)
24825               {
24826                 /* This has actually happened; see
24827                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24828                 complaint (&symfile_complaints,
24829                            _("recursive DW_MACRO_import in "
24830                              ".debug_macro section"));
24831               }
24832             else
24833               {
24834                 *slot = (void *) new_mac_ptr;
24835
24836                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24837                                           include_bfd, new_mac_ptr,
24838                                           include_mac_end, current_file, lh,
24839                                           section, section_is_gnu, is_dwz,
24840                                           offset_size, include_hash);
24841
24842                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24843               }
24844           }
24845           break;
24846
24847         case DW_MACINFO_vendor_ext:
24848           if (!section_is_gnu)
24849             {
24850               unsigned int bytes_read;
24851
24852               /* This reads the constant, but since we don't recognize
24853                  any vendor extensions, we ignore it.  */
24854               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24855               mac_ptr += bytes_read;
24856               read_direct_string (abfd, mac_ptr, &bytes_read);
24857               mac_ptr += bytes_read;
24858
24859               /* We don't recognize any vendor extensions.  */
24860               break;
24861             }
24862           /* FALLTHROUGH */
24863
24864         default:
24865           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24866                                          mac_ptr, mac_end, abfd, offset_size,
24867                                          section);
24868           if (mac_ptr == NULL)
24869             return;
24870           break;
24871         }
24872       DIAGNOSTIC_POP
24873     } while (macinfo_type != 0);
24874 }
24875
24876 static void
24877 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24878                      int section_is_gnu)
24879 {
24880   struct dwarf2_per_objfile *dwarf2_per_objfile
24881     = cu->per_cu->dwarf2_per_objfile;
24882   struct objfile *objfile = dwarf2_per_objfile->objfile;
24883   struct line_header *lh = cu->line_header;
24884   bfd *abfd;
24885   const gdb_byte *mac_ptr, *mac_end;
24886   struct macro_source_file *current_file = 0;
24887   enum dwarf_macro_record_type macinfo_type;
24888   unsigned int offset_size = cu->header.offset_size;
24889   const gdb_byte *opcode_definitions[256];
24890   void **slot;
24891   struct dwarf2_section_info *section;
24892   const char *section_name;
24893
24894   if (cu->dwo_unit != NULL)
24895     {
24896       if (section_is_gnu)
24897         {
24898           section = &cu->dwo_unit->dwo_file->sections.macro;
24899           section_name = ".debug_macro.dwo";
24900         }
24901       else
24902         {
24903           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24904           section_name = ".debug_macinfo.dwo";
24905         }
24906     }
24907   else
24908     {
24909       if (section_is_gnu)
24910         {
24911           section = &dwarf2_per_objfile->macro;
24912           section_name = ".debug_macro";
24913         }
24914       else
24915         {
24916           section = &dwarf2_per_objfile->macinfo;
24917           section_name = ".debug_macinfo";
24918         }
24919     }
24920
24921   dwarf2_read_section (objfile, section);
24922   if (section->buffer == NULL)
24923     {
24924       complaint (&symfile_complaints, _("missing %s section"), section_name);
24925       return;
24926     }
24927   abfd = get_section_bfd_owner (section);
24928
24929   /* First pass: Find the name of the base filename.
24930      This filename is needed in order to process all macros whose definition
24931      (or undefinition) comes from the command line.  These macros are defined
24932      before the first DW_MACINFO_start_file entry, and yet still need to be
24933      associated to the base file.
24934
24935      To determine the base file name, we scan the macro definitions until we
24936      reach the first DW_MACINFO_start_file entry.  We then initialize
24937      CURRENT_FILE accordingly so that any macro definition found before the
24938      first DW_MACINFO_start_file can still be associated to the base file.  */
24939
24940   mac_ptr = section->buffer + offset;
24941   mac_end = section->buffer + section->size;
24942
24943   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24944                                       &offset_size, section_is_gnu);
24945   if (mac_ptr == NULL)
24946     {
24947       /* We already issued a complaint.  */
24948       return;
24949     }
24950
24951   do
24952     {
24953       /* Do we at least have room for a macinfo type byte?  */
24954       if (mac_ptr >= mac_end)
24955         {
24956           /* Complaint is printed during the second pass as GDB will probably
24957              stop the first pass earlier upon finding
24958              DW_MACINFO_start_file.  */
24959           break;
24960         }
24961
24962       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24963       mac_ptr++;
24964
24965       /* Note that we rely on the fact that the corresponding GNU and
24966          DWARF constants are the same.  */
24967       DIAGNOSTIC_PUSH
24968       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24969       switch (macinfo_type)
24970         {
24971           /* A zero macinfo type indicates the end of the macro
24972              information.  */
24973         case 0:
24974           break;
24975
24976         case DW_MACRO_define:
24977         case DW_MACRO_undef:
24978           /* Only skip the data by MAC_PTR.  */
24979           {
24980             unsigned int bytes_read;
24981
24982             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24983             mac_ptr += bytes_read;
24984             read_direct_string (abfd, mac_ptr, &bytes_read);
24985             mac_ptr += bytes_read;
24986           }
24987           break;
24988
24989         case DW_MACRO_start_file:
24990           {
24991             unsigned int bytes_read;
24992             int line, file;
24993
24994             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24995             mac_ptr += bytes_read;
24996             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24997             mac_ptr += bytes_read;
24998
24999             current_file = macro_start_file (file, line, current_file, lh);
25000           }
25001           break;
25002
25003         case DW_MACRO_end_file:
25004           /* No data to skip by MAC_PTR.  */
25005           break;
25006
25007         case DW_MACRO_define_strp:
25008         case DW_MACRO_undef_strp:
25009         case DW_MACRO_define_sup:
25010         case DW_MACRO_undef_sup:
25011           {
25012             unsigned int bytes_read;
25013
25014             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25015             mac_ptr += bytes_read;
25016             mac_ptr += offset_size;
25017           }
25018           break;
25019
25020         case DW_MACRO_import:
25021         case DW_MACRO_import_sup:
25022           /* Note that, according to the spec, a transparent include
25023              chain cannot call DW_MACRO_start_file.  So, we can just
25024              skip this opcode.  */
25025           mac_ptr += offset_size;
25026           break;
25027
25028         case DW_MACINFO_vendor_ext:
25029           /* Only skip the data by MAC_PTR.  */
25030           if (!section_is_gnu)
25031             {
25032               unsigned int bytes_read;
25033
25034               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
25035               mac_ptr += bytes_read;
25036               read_direct_string (abfd, mac_ptr, &bytes_read);
25037               mac_ptr += bytes_read;
25038             }
25039           /* FALLTHROUGH */
25040
25041         default:
25042           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
25043                                          mac_ptr, mac_end, abfd, offset_size,
25044                                          section);
25045           if (mac_ptr == NULL)
25046             return;
25047           break;
25048         }
25049       DIAGNOSTIC_POP
25050     } while (macinfo_type != 0 && current_file == NULL);
25051
25052   /* Second pass: Process all entries.
25053
25054      Use the AT_COMMAND_LINE flag to determine whether we are still processing
25055      command-line macro definitions/undefinitions.  This flag is unset when we
25056      reach the first DW_MACINFO_start_file entry.  */
25057
25058   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
25059                                            htab_eq_pointer,
25060                                            NULL, xcalloc, xfree));
25061   mac_ptr = section->buffer + offset;
25062   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
25063   *slot = (void *) mac_ptr;
25064   dwarf_decode_macro_bytes (dwarf2_per_objfile,
25065                             abfd, mac_ptr, mac_end,
25066                             current_file, lh, section,
25067                             section_is_gnu, 0, offset_size,
25068                             include_hash.get ());
25069 }
25070
25071 /* Check if the attribute's form is a DW_FORM_block*
25072    if so return true else false.  */
25073
25074 static int
25075 attr_form_is_block (const struct attribute *attr)
25076 {
25077   return (attr == NULL ? 0 :
25078       attr->form == DW_FORM_block1
25079       || attr->form == DW_FORM_block2
25080       || attr->form == DW_FORM_block4
25081       || attr->form == DW_FORM_block
25082       || attr->form == DW_FORM_exprloc);
25083 }
25084
25085 /* Return non-zero if ATTR's value is a section offset --- classes
25086    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
25087    You may use DW_UNSND (attr) to retrieve such offsets.
25088
25089    Section 7.5.4, "Attribute Encodings", explains that no attribute
25090    may have a value that belongs to more than one of these classes; it
25091    would be ambiguous if we did, because we use the same forms for all
25092    of them.  */
25093
25094 static int
25095 attr_form_is_section_offset (const struct attribute *attr)
25096 {
25097   return (attr->form == DW_FORM_data4
25098           || attr->form == DW_FORM_data8
25099           || attr->form == DW_FORM_sec_offset);
25100 }
25101
25102 /* Return non-zero if ATTR's value falls in the 'constant' class, or
25103    zero otherwise.  When this function returns true, you can apply
25104    dwarf2_get_attr_constant_value to it.
25105
25106    However, note that for some attributes you must check
25107    attr_form_is_section_offset before using this test.  DW_FORM_data4
25108    and DW_FORM_data8 are members of both the constant class, and of
25109    the classes that contain offsets into other debug sections
25110    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
25111    that, if an attribute's can be either a constant or one of the
25112    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
25113    taken as section offsets, not constants.
25114
25115    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
25116    cannot handle that.  */
25117
25118 static int
25119 attr_form_is_constant (const struct attribute *attr)
25120 {
25121   switch (attr->form)
25122     {
25123     case DW_FORM_sdata:
25124     case DW_FORM_udata:
25125     case DW_FORM_data1:
25126     case DW_FORM_data2:
25127     case DW_FORM_data4:
25128     case DW_FORM_data8:
25129     case DW_FORM_implicit_const:
25130       return 1;
25131     default:
25132       return 0;
25133     }
25134 }
25135
25136
25137 /* DW_ADDR is always stored already as sect_offset; despite for the forms
25138    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
25139
25140 static int
25141 attr_form_is_ref (const struct attribute *attr)
25142 {
25143   switch (attr->form)
25144     {
25145     case DW_FORM_ref_addr:
25146     case DW_FORM_ref1:
25147     case DW_FORM_ref2:
25148     case DW_FORM_ref4:
25149     case DW_FORM_ref8:
25150     case DW_FORM_ref_udata:
25151     case DW_FORM_GNU_ref_alt:
25152       return 1;
25153     default:
25154       return 0;
25155     }
25156 }
25157
25158 /* Return the .debug_loc section to use for CU.
25159    For DWO files use .debug_loc.dwo.  */
25160
25161 static struct dwarf2_section_info *
25162 cu_debug_loc_section (struct dwarf2_cu *cu)
25163 {
25164   struct dwarf2_per_objfile *dwarf2_per_objfile
25165     = cu->per_cu->dwarf2_per_objfile;
25166
25167   if (cu->dwo_unit)
25168     {
25169       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
25170       
25171       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
25172     }
25173   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
25174                                   : &dwarf2_per_objfile->loc);
25175 }
25176
25177 /* A helper function that fills in a dwarf2_loclist_baton.  */
25178
25179 static void
25180 fill_in_loclist_baton (struct dwarf2_cu *cu,
25181                        struct dwarf2_loclist_baton *baton,
25182                        const struct attribute *attr)
25183 {
25184   struct dwarf2_per_objfile *dwarf2_per_objfile
25185     = cu->per_cu->dwarf2_per_objfile;
25186   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25187
25188   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
25189
25190   baton->per_cu = cu->per_cu;
25191   gdb_assert (baton->per_cu);
25192   /* We don't know how long the location list is, but make sure we
25193      don't run off the edge of the section.  */
25194   baton->size = section->size - DW_UNSND (attr);
25195   baton->data = section->buffer + DW_UNSND (attr);
25196   baton->base_address = cu->base_address;
25197   baton->from_dwo = cu->dwo_unit != NULL;
25198 }
25199
25200 static void
25201 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
25202                              struct dwarf2_cu *cu, int is_block)
25203 {
25204   struct dwarf2_per_objfile *dwarf2_per_objfile
25205     = cu->per_cu->dwarf2_per_objfile;
25206   struct objfile *objfile = dwarf2_per_objfile->objfile;
25207   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
25208
25209   if (attr_form_is_section_offset (attr)
25210       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
25211          the section.  If so, fall through to the complaint in the
25212          other branch.  */
25213       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
25214     {
25215       struct dwarf2_loclist_baton *baton;
25216
25217       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
25218
25219       fill_in_loclist_baton (cu, baton, attr);
25220
25221       if (cu->base_known == 0)
25222         complaint (&symfile_complaints,
25223                    _("Location list used without "
25224                      "specifying the CU base address."));
25225
25226       SYMBOL_ACLASS_INDEX (sym) = (is_block
25227                                    ? dwarf2_loclist_block_index
25228                                    : dwarf2_loclist_index);
25229       SYMBOL_LOCATION_BATON (sym) = baton;
25230     }
25231   else
25232     {
25233       struct dwarf2_locexpr_baton *baton;
25234
25235       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25236       baton->per_cu = cu->per_cu;
25237       gdb_assert (baton->per_cu);
25238
25239       if (attr_form_is_block (attr))
25240         {
25241           /* Note that we're just copying the block's data pointer
25242              here, not the actual data.  We're still pointing into the
25243              info_buffer for SYM's objfile; right now we never release
25244              that buffer, but when we do clean up properly this may
25245              need to change.  */
25246           baton->size = DW_BLOCK (attr)->size;
25247           baton->data = DW_BLOCK (attr)->data;
25248         }
25249       else
25250         {
25251           dwarf2_invalid_attrib_class_complaint ("location description",
25252                                                  SYMBOL_NATURAL_NAME (sym));
25253           baton->size = 0;
25254         }
25255
25256       SYMBOL_ACLASS_INDEX (sym) = (is_block
25257                                    ? dwarf2_locexpr_block_index
25258                                    : dwarf2_locexpr_index);
25259       SYMBOL_LOCATION_BATON (sym) = baton;
25260     }
25261 }
25262
25263 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25264    came from a separate debuginfo file, then the master objfile is
25265    returned.  */
25266
25267 struct objfile *
25268 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25269 {
25270   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25271
25272   /* Return the master objfile, so that we can report and look up the
25273      correct file containing this variable.  */
25274   if (objfile->separate_debug_objfile_backlink)
25275     objfile = objfile->separate_debug_objfile_backlink;
25276
25277   return objfile;
25278 }
25279
25280 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25281    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25282    CU_HEADERP first.  */
25283
25284 static const struct comp_unit_head *
25285 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25286                        struct dwarf2_per_cu_data *per_cu)
25287 {
25288   const gdb_byte *info_ptr;
25289
25290   if (per_cu->cu)
25291     return &per_cu->cu->header;
25292
25293   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25294
25295   memset (cu_headerp, 0, sizeof (*cu_headerp));
25296   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25297                        rcuh_kind::COMPILE);
25298
25299   return cu_headerp;
25300 }
25301
25302 /* Return the address size given in the compilation unit header for CU.  */
25303
25304 int
25305 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25306 {
25307   struct comp_unit_head cu_header_local;
25308   const struct comp_unit_head *cu_headerp;
25309
25310   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25311
25312   return cu_headerp->addr_size;
25313 }
25314
25315 /* Return the offset size given in the compilation unit header for CU.  */
25316
25317 int
25318 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25319 {
25320   struct comp_unit_head cu_header_local;
25321   const struct comp_unit_head *cu_headerp;
25322
25323   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25324
25325   return cu_headerp->offset_size;
25326 }
25327
25328 /* See its dwarf2loc.h declaration.  */
25329
25330 int
25331 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25332 {
25333   struct comp_unit_head cu_header_local;
25334   const struct comp_unit_head *cu_headerp;
25335
25336   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25337
25338   if (cu_headerp->version == 2)
25339     return cu_headerp->addr_size;
25340   else
25341     return cu_headerp->offset_size;
25342 }
25343
25344 /* Return the text offset of the CU.  The returned offset comes from
25345    this CU's objfile.  If this objfile came from a separate debuginfo
25346    file, then the offset may be different from the corresponding
25347    offset in the parent objfile.  */
25348
25349 CORE_ADDR
25350 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25351 {
25352   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25353
25354   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25355 }
25356
25357 /* Return DWARF version number of PER_CU.  */
25358
25359 short
25360 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25361 {
25362   return per_cu->dwarf_version;
25363 }
25364
25365 /* Locate the .debug_info compilation unit from CU's objfile which contains
25366    the DIE at OFFSET.  Raises an error on failure.  */
25367
25368 static struct dwarf2_per_cu_data *
25369 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25370                                   unsigned int offset_in_dwz,
25371                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25372 {
25373   struct dwarf2_per_cu_data *this_cu;
25374   int low, high;
25375   const sect_offset *cu_off;
25376
25377   low = 0;
25378   high = dwarf2_per_objfile->n_comp_units - 1;
25379   while (high > low)
25380     {
25381       struct dwarf2_per_cu_data *mid_cu;
25382       int mid = low + (high - low) / 2;
25383
25384       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25385       cu_off = &mid_cu->sect_off;
25386       if (mid_cu->is_dwz > offset_in_dwz
25387           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25388         high = mid;
25389       else
25390         low = mid + 1;
25391     }
25392   gdb_assert (low == high);
25393   this_cu = dwarf2_per_objfile->all_comp_units[low];
25394   cu_off = &this_cu->sect_off;
25395   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25396     {
25397       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25398         error (_("Dwarf Error: could not find partial DIE containing "
25399                "offset %s [in module %s]"),
25400                sect_offset_str (sect_off),
25401                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25402
25403       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25404                   <= sect_off);
25405       return dwarf2_per_objfile->all_comp_units[low-1];
25406     }
25407   else
25408     {
25409       this_cu = dwarf2_per_objfile->all_comp_units[low];
25410       if (low == dwarf2_per_objfile->n_comp_units - 1
25411           && sect_off >= this_cu->sect_off + this_cu->length)
25412         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25413       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25414       return this_cu;
25415     }
25416 }
25417
25418 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25419
25420 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25421   : per_cu (per_cu_),
25422     mark (0),
25423     has_loclist (0),
25424     checked_producer (0),
25425     producer_is_gxx_lt_4_6 (0),
25426     producer_is_gcc_lt_4_3 (0),
25427     producer_is_icc_lt_14 (0),
25428     processing_has_namespace_info (0)
25429 {
25430   per_cu->cu = this;
25431 }
25432
25433 /* Destroy a dwarf2_cu.  */
25434
25435 dwarf2_cu::~dwarf2_cu ()
25436 {
25437   per_cu->cu = NULL;
25438 }
25439
25440 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25441
25442 static void
25443 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25444                        enum language pretend_language)
25445 {
25446   struct attribute *attr;
25447
25448   /* Set the language we're debugging.  */
25449   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25450   if (attr)
25451     set_cu_language (DW_UNSND (attr), cu);
25452   else
25453     {
25454       cu->language = pretend_language;
25455       cu->language_defn = language_def (cu->language);
25456     }
25457
25458   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25459 }
25460
25461 /* Free all cached compilation units.  */
25462
25463 static void
25464 free_cached_comp_units (void *data)
25465 {
25466   struct dwarf2_per_objfile *dwarf2_per_objfile
25467     = (struct dwarf2_per_objfile *) data;
25468
25469   dwarf2_per_objfile->free_cached_comp_units ();
25470 }
25471
25472 /* Increase the age counter on each cached compilation unit, and free
25473    any that are too old.  */
25474
25475 static void
25476 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25477 {
25478   struct dwarf2_per_cu_data *per_cu, **last_chain;
25479
25480   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25481   per_cu = dwarf2_per_objfile->read_in_chain;
25482   while (per_cu != NULL)
25483     {
25484       per_cu->cu->last_used ++;
25485       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25486         dwarf2_mark (per_cu->cu);
25487       per_cu = per_cu->cu->read_in_chain;
25488     }
25489
25490   per_cu = dwarf2_per_objfile->read_in_chain;
25491   last_chain = &dwarf2_per_objfile->read_in_chain;
25492   while (per_cu != NULL)
25493     {
25494       struct dwarf2_per_cu_data *next_cu;
25495
25496       next_cu = per_cu->cu->read_in_chain;
25497
25498       if (!per_cu->cu->mark)
25499         {
25500           delete per_cu->cu;
25501           *last_chain = next_cu;
25502         }
25503       else
25504         last_chain = &per_cu->cu->read_in_chain;
25505
25506       per_cu = next_cu;
25507     }
25508 }
25509
25510 /* Remove a single compilation unit from the cache.  */
25511
25512 static void
25513 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25514 {
25515   struct dwarf2_per_cu_data *per_cu, **last_chain;
25516   struct dwarf2_per_objfile *dwarf2_per_objfile
25517     = target_per_cu->dwarf2_per_objfile;
25518
25519   per_cu = dwarf2_per_objfile->read_in_chain;
25520   last_chain = &dwarf2_per_objfile->read_in_chain;
25521   while (per_cu != NULL)
25522     {
25523       struct dwarf2_per_cu_data *next_cu;
25524
25525       next_cu = per_cu->cu->read_in_chain;
25526
25527       if (per_cu == target_per_cu)
25528         {
25529           delete per_cu->cu;
25530           per_cu->cu = NULL;
25531           *last_chain = next_cu;
25532           break;
25533         }
25534       else
25535         last_chain = &per_cu->cu->read_in_chain;
25536
25537       per_cu = next_cu;
25538     }
25539 }
25540
25541 /* Release all extra memory associated with OBJFILE.  */
25542
25543 void
25544 dwarf2_free_objfile (struct objfile *objfile)
25545 {
25546   struct dwarf2_per_objfile *dwarf2_per_objfile
25547     = get_dwarf2_per_objfile (objfile);
25548
25549   delete dwarf2_per_objfile;
25550 }
25551
25552 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25553    We store these in a hash table separate from the DIEs, and preserve them
25554    when the DIEs are flushed out of cache.
25555
25556    The CU "per_cu" pointer is needed because offset alone is not enough to
25557    uniquely identify the type.  A file may have multiple .debug_types sections,
25558    or the type may come from a DWO file.  Furthermore, while it's more logical
25559    to use per_cu->section+offset, with Fission the section with the data is in
25560    the DWO file but we don't know that section at the point we need it.
25561    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25562    because we can enter the lookup routine, get_die_type_at_offset, from
25563    outside this file, and thus won't necessarily have PER_CU->cu.
25564    Fortunately, PER_CU is stable for the life of the objfile.  */
25565
25566 struct dwarf2_per_cu_offset_and_type
25567 {
25568   const struct dwarf2_per_cu_data *per_cu;
25569   sect_offset sect_off;
25570   struct type *type;
25571 };
25572
25573 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25574
25575 static hashval_t
25576 per_cu_offset_and_type_hash (const void *item)
25577 {
25578   const struct dwarf2_per_cu_offset_and_type *ofs
25579     = (const struct dwarf2_per_cu_offset_and_type *) item;
25580
25581   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25582 }
25583
25584 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25585
25586 static int
25587 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25588 {
25589   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25590     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25591   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25592     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25593
25594   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25595           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25596 }
25597
25598 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25599    table if necessary.  For convenience, return TYPE.
25600
25601    The DIEs reading must have careful ordering to:
25602     * Not cause infite loops trying to read in DIEs as a prerequisite for
25603       reading current DIE.
25604     * Not trying to dereference contents of still incompletely read in types
25605       while reading in other DIEs.
25606     * Enable referencing still incompletely read in types just by a pointer to
25607       the type without accessing its fields.
25608
25609    Therefore caller should follow these rules:
25610      * Try to fetch any prerequisite types we may need to build this DIE type
25611        before building the type and calling set_die_type.
25612      * After building type call set_die_type for current DIE as soon as
25613        possible before fetching more types to complete the current type.
25614      * Make the type as complete as possible before fetching more types.  */
25615
25616 static struct type *
25617 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25618 {
25619   struct dwarf2_per_objfile *dwarf2_per_objfile
25620     = cu->per_cu->dwarf2_per_objfile;
25621   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25622   struct objfile *objfile = dwarf2_per_objfile->objfile;
25623   struct attribute *attr;
25624   struct dynamic_prop prop;
25625
25626   /* For Ada types, make sure that the gnat-specific data is always
25627      initialized (if not already set).  There are a few types where
25628      we should not be doing so, because the type-specific area is
25629      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25630      where the type-specific area is used to store the floatformat).
25631      But this is not a problem, because the gnat-specific information
25632      is actually not needed for these types.  */
25633   if (need_gnat_info (cu)
25634       && TYPE_CODE (type) != TYPE_CODE_FUNC
25635       && TYPE_CODE (type) != TYPE_CODE_FLT
25636       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25637       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25638       && TYPE_CODE (type) != TYPE_CODE_METHOD
25639       && !HAVE_GNAT_AUX_INFO (type))
25640     INIT_GNAT_SPECIFIC (type);
25641
25642   /* Read DW_AT_allocated and set in type.  */
25643   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25644   if (attr_form_is_block (attr))
25645     {
25646       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25647         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25648     }
25649   else if (attr != NULL)
25650     {
25651       complaint (&symfile_complaints,
25652                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25653                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25654                  sect_offset_str (die->sect_off));
25655     }
25656
25657   /* Read DW_AT_associated and set in type.  */
25658   attr = dwarf2_attr (die, DW_AT_associated, cu);
25659   if (attr_form_is_block (attr))
25660     {
25661       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25662         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25663     }
25664   else if (attr != NULL)
25665     {
25666       complaint (&symfile_complaints,
25667                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25668                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25669                  sect_offset_str (die->sect_off));
25670     }
25671
25672   /* Read DW_AT_data_location and set in type.  */
25673   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25674   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25675     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25676
25677   if (dwarf2_per_objfile->die_type_hash == NULL)
25678     {
25679       dwarf2_per_objfile->die_type_hash =
25680         htab_create_alloc_ex (127,
25681                               per_cu_offset_and_type_hash,
25682                               per_cu_offset_and_type_eq,
25683                               NULL,
25684                               &objfile->objfile_obstack,
25685                               hashtab_obstack_allocate,
25686                               dummy_obstack_deallocate);
25687     }
25688
25689   ofs.per_cu = cu->per_cu;
25690   ofs.sect_off = die->sect_off;
25691   ofs.type = type;
25692   slot = (struct dwarf2_per_cu_offset_and_type **)
25693     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25694   if (*slot)
25695     complaint (&symfile_complaints,
25696                _("A problem internal to GDB: DIE %s has type already set"),
25697                sect_offset_str (die->sect_off));
25698   *slot = XOBNEW (&objfile->objfile_obstack,
25699                   struct dwarf2_per_cu_offset_and_type);
25700   **slot = ofs;
25701   return type;
25702 }
25703
25704 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25705    or return NULL if the die does not have a saved type.  */
25706
25707 static struct type *
25708 get_die_type_at_offset (sect_offset sect_off,
25709                         struct dwarf2_per_cu_data *per_cu)
25710 {
25711   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25712   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25713
25714   if (dwarf2_per_objfile->die_type_hash == NULL)
25715     return NULL;
25716
25717   ofs.per_cu = per_cu;
25718   ofs.sect_off = sect_off;
25719   slot = ((struct dwarf2_per_cu_offset_and_type *)
25720           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25721   if (slot)
25722     return slot->type;
25723   else
25724     return NULL;
25725 }
25726
25727 /* Look up the type for DIE in CU in die_type_hash,
25728    or return NULL if DIE does not have a saved type.  */
25729
25730 static struct type *
25731 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25732 {
25733   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25734 }
25735
25736 /* Add a dependence relationship from CU to REF_PER_CU.  */
25737
25738 static void
25739 dwarf2_add_dependence (struct dwarf2_cu *cu,
25740                        struct dwarf2_per_cu_data *ref_per_cu)
25741 {
25742   void **slot;
25743
25744   if (cu->dependencies == NULL)
25745     cu->dependencies
25746       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25747                               NULL, &cu->comp_unit_obstack,
25748                               hashtab_obstack_allocate,
25749                               dummy_obstack_deallocate);
25750
25751   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25752   if (*slot == NULL)
25753     *slot = ref_per_cu;
25754 }
25755
25756 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25757    Set the mark field in every compilation unit in the
25758    cache that we must keep because we are keeping CU.  */
25759
25760 static int
25761 dwarf2_mark_helper (void **slot, void *data)
25762 {
25763   struct dwarf2_per_cu_data *per_cu;
25764
25765   per_cu = (struct dwarf2_per_cu_data *) *slot;
25766
25767   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25768      reading of the chain.  As such dependencies remain valid it is not much
25769      useful to track and undo them during QUIT cleanups.  */
25770   if (per_cu->cu == NULL)
25771     return 1;
25772
25773   if (per_cu->cu->mark)
25774     return 1;
25775   per_cu->cu->mark = 1;
25776
25777   if (per_cu->cu->dependencies != NULL)
25778     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25779
25780   return 1;
25781 }
25782
25783 /* Set the mark field in CU and in every other compilation unit in the
25784    cache that we must keep because we are keeping CU.  */
25785
25786 static void
25787 dwarf2_mark (struct dwarf2_cu *cu)
25788 {
25789   if (cu->mark)
25790     return;
25791   cu->mark = 1;
25792   if (cu->dependencies != NULL)
25793     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25794 }
25795
25796 static void
25797 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25798 {
25799   while (per_cu)
25800     {
25801       per_cu->cu->mark = 0;
25802       per_cu = per_cu->cu->read_in_chain;
25803     }
25804 }
25805
25806 /* Trivial hash function for partial_die_info: the hash value of a DIE
25807    is its offset in .debug_info for this objfile.  */
25808
25809 static hashval_t
25810 partial_die_hash (const void *item)
25811 {
25812   const struct partial_die_info *part_die
25813     = (const struct partial_die_info *) item;
25814
25815   return to_underlying (part_die->sect_off);
25816 }
25817
25818 /* Trivial comparison function for partial_die_info structures: two DIEs
25819    are equal if they have the same offset.  */
25820
25821 static int
25822 partial_die_eq (const void *item_lhs, const void *item_rhs)
25823 {
25824   const struct partial_die_info *part_die_lhs
25825     = (const struct partial_die_info *) item_lhs;
25826   const struct partial_die_info *part_die_rhs
25827     = (const struct partial_die_info *) item_rhs;
25828
25829   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25830 }
25831
25832 static struct cmd_list_element *set_dwarf_cmdlist;
25833 static struct cmd_list_element *show_dwarf_cmdlist;
25834
25835 static void
25836 set_dwarf_cmd (const char *args, int from_tty)
25837 {
25838   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25839              gdb_stdout);
25840 }
25841
25842 static void
25843 show_dwarf_cmd (const char *args, int from_tty)
25844 {
25845   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25846 }
25847
25848 /* The "save gdb-index" command.  */
25849
25850 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25851    error checking.  */
25852
25853 static void
25854 file_write (FILE *file, const void *data, size_t size)
25855 {
25856   if (fwrite (data, 1, size, file) != size)
25857     error (_("couldn't data write to file"));
25858 }
25859
25860 /* Write the contents of VEC to FILE, with error checking.  */
25861
25862 template<typename Elem, typename Alloc>
25863 static void
25864 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25865 {
25866   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25867 }
25868
25869 /* In-memory buffer to prepare data to be written later to a file.  */
25870 class data_buf
25871 {
25872 public:
25873   /* Copy DATA to the end of the buffer.  */
25874   template<typename T>
25875   void append_data (const T &data)
25876   {
25877     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25878                reinterpret_cast<const gdb_byte *> (&data + 1),
25879                grow (sizeof (data)));
25880   }
25881
25882   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25883      terminating zero is appended too.  */
25884   void append_cstr0 (const char *cstr)
25885   {
25886     const size_t size = strlen (cstr) + 1;
25887     std::copy (cstr, cstr + size, grow (size));
25888   }
25889
25890   /* Store INPUT as ULEB128 to the end of buffer.  */
25891   void append_unsigned_leb128 (ULONGEST input)
25892   {
25893     for (;;)
25894       {
25895         gdb_byte output = input & 0x7f;
25896         input >>= 7;
25897         if (input)
25898           output |= 0x80;
25899         append_data (output);
25900         if (input == 0)
25901           break;
25902       }
25903   }
25904
25905   /* Accept a host-format integer in VAL and append it to the buffer
25906      as a target-format integer which is LEN bytes long.  */
25907   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25908   {
25909     ::store_unsigned_integer (grow (len), len, byte_order, val);
25910   }
25911
25912   /* Return the size of the buffer.  */
25913   size_t size () const
25914   {
25915     return m_vec.size ();
25916   }
25917
25918   /* Return true iff the buffer is empty.  */
25919   bool empty () const
25920   {
25921     return m_vec.empty ();
25922   }
25923
25924   /* Write the buffer to FILE.  */
25925   void file_write (FILE *file) const
25926   {
25927     ::file_write (file, m_vec);
25928   }
25929
25930 private:
25931   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25932      the start of the new block.  */
25933   gdb_byte *grow (size_t size)
25934   {
25935     m_vec.resize (m_vec.size () + size);
25936     return &*m_vec.end () - size;
25937   }
25938
25939   gdb::byte_vector m_vec;
25940 };
25941
25942 /* An entry in the symbol table.  */
25943 struct symtab_index_entry
25944 {
25945   /* The name of the symbol.  */
25946   const char *name;
25947   /* The offset of the name in the constant pool.  */
25948   offset_type index_offset;
25949   /* A sorted vector of the indices of all the CUs that hold an object
25950      of this name.  */
25951   std::vector<offset_type> cu_indices;
25952 };
25953
25954 /* The symbol table.  This is a power-of-2-sized hash table.  */
25955 struct mapped_symtab
25956 {
25957   mapped_symtab ()
25958   {
25959     data.resize (1024);
25960   }
25961
25962   offset_type n_elements = 0;
25963   std::vector<symtab_index_entry> data;
25964 };
25965
25966 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25967    the slot.
25968    
25969    Function is used only during write_hash_table so no index format backward
25970    compatibility is needed.  */
25971
25972 static symtab_index_entry &
25973 find_slot (struct mapped_symtab *symtab, const char *name)
25974 {
25975   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25976
25977   index = hash & (symtab->data.size () - 1);
25978   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25979
25980   for (;;)
25981     {
25982       if (symtab->data[index].name == NULL
25983           || strcmp (name, symtab->data[index].name) == 0)
25984         return symtab->data[index];
25985       index = (index + step) & (symtab->data.size () - 1);
25986     }
25987 }
25988
25989 /* Expand SYMTAB's hash table.  */
25990
25991 static void
25992 hash_expand (struct mapped_symtab *symtab)
25993 {
25994   auto old_entries = std::move (symtab->data);
25995
25996   symtab->data.clear ();
25997   symtab->data.resize (old_entries.size () * 2);
25998
25999   for (auto &it : old_entries)
26000     if (it.name != NULL)
26001       {
26002         auto &ref = find_slot (symtab, it.name);
26003         ref = std::move (it);
26004       }
26005 }
26006
26007 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
26008    CU_INDEX is the index of the CU in which the symbol appears.
26009    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
26010
26011 static void
26012 add_index_entry (struct mapped_symtab *symtab, const char *name,
26013                  int is_static, gdb_index_symbol_kind kind,
26014                  offset_type cu_index)
26015 {
26016   offset_type cu_index_and_attrs;
26017
26018   ++symtab->n_elements;
26019   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
26020     hash_expand (symtab);
26021
26022   symtab_index_entry &slot = find_slot (symtab, name);
26023   if (slot.name == NULL)
26024     {
26025       slot.name = name;
26026       /* index_offset is set later.  */
26027     }
26028
26029   cu_index_and_attrs = 0;
26030   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
26031   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
26032   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
26033
26034   /* We don't want to record an index value twice as we want to avoid the
26035      duplication.
26036      We process all global symbols and then all static symbols
26037      (which would allow us to avoid the duplication by only having to check
26038      the last entry pushed), but a symbol could have multiple kinds in one CU.
26039      To keep things simple we don't worry about the duplication here and
26040      sort and uniqufy the list after we've processed all symbols.  */
26041   slot.cu_indices.push_back (cu_index_and_attrs);
26042 }
26043
26044 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
26045
26046 static void
26047 uniquify_cu_indices (struct mapped_symtab *symtab)
26048 {
26049   for (auto &entry : symtab->data)
26050     {
26051       if (entry.name != NULL && !entry.cu_indices.empty ())
26052         {
26053           auto &cu_indices = entry.cu_indices;
26054           std::sort (cu_indices.begin (), cu_indices.end ());
26055           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
26056           cu_indices.erase (from, cu_indices.end ());
26057         }
26058     }
26059 }
26060
26061 /* A form of 'const char *' suitable for container keys.  Only the
26062    pointer is stored.  The strings themselves are compared, not the
26063    pointers.  */
26064 class c_str_view
26065 {
26066 public:
26067   c_str_view (const char *cstr)
26068     : m_cstr (cstr)
26069   {}
26070
26071   bool operator== (const c_str_view &other) const
26072   {
26073     return strcmp (m_cstr, other.m_cstr) == 0;
26074   }
26075
26076   /* Return the underlying C string.  Note, the returned string is
26077      only a reference with lifetime of this object.  */
26078   const char *c_str () const
26079   {
26080     return m_cstr;
26081   }
26082
26083 private:
26084   friend class c_str_view_hasher;
26085   const char *const m_cstr;
26086 };
26087
26088 /* A std::unordered_map::hasher for c_str_view that uses the right
26089    hash function for strings in a mapped index.  */
26090 class c_str_view_hasher
26091 {
26092 public:
26093   size_t operator () (const c_str_view &x) const
26094   {
26095     return mapped_index_string_hash (INT_MAX, x.m_cstr);
26096   }
26097 };
26098
26099 /* A std::unordered_map::hasher for std::vector<>.  */
26100 template<typename T>
26101 class vector_hasher
26102 {
26103 public:
26104   size_t operator () (const std::vector<T> &key) const
26105   {
26106     return iterative_hash (key.data (),
26107                            sizeof (key.front ()) * key.size (), 0);
26108   }
26109 };
26110
26111 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
26112    constant pool entries going into the data buffer CPOOL.  */
26113
26114 static void
26115 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
26116 {
26117   {
26118     /* Elements are sorted vectors of the indices of all the CUs that
26119        hold an object of this name.  */
26120     std::unordered_map<std::vector<offset_type>, offset_type,
26121                        vector_hasher<offset_type>>
26122       symbol_hash_table;
26123
26124     /* We add all the index vectors to the constant pool first, to
26125        ensure alignment is ok.  */
26126     for (symtab_index_entry &entry : symtab->data)
26127       {
26128         if (entry.name == NULL)
26129           continue;
26130         gdb_assert (entry.index_offset == 0);
26131
26132         /* Finding before inserting is faster than always trying to
26133            insert, because inserting always allocates a node, does the
26134            lookup, and then destroys the new node if another node
26135            already had the same key.  C++17 try_emplace will avoid
26136            this.  */
26137         const auto found
26138           = symbol_hash_table.find (entry.cu_indices);
26139         if (found != symbol_hash_table.end ())
26140           {
26141             entry.index_offset = found->second;
26142             continue;
26143           }
26144
26145         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
26146         entry.index_offset = cpool.size ();
26147         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
26148         for (const auto index : entry.cu_indices)
26149           cpool.append_data (MAYBE_SWAP (index));
26150       }
26151   }
26152
26153   /* Now write out the hash table.  */
26154   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
26155   for (const auto &entry : symtab->data)
26156     {
26157       offset_type str_off, vec_off;
26158
26159       if (entry.name != NULL)
26160         {
26161           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
26162           if (insertpair.second)
26163             cpool.append_cstr0 (entry.name);
26164           str_off = insertpair.first->second;
26165           vec_off = entry.index_offset;
26166         }
26167       else
26168         {
26169           /* While 0 is a valid constant pool index, it is not valid
26170              to have 0 for both offsets.  */
26171           str_off = 0;
26172           vec_off = 0;
26173         }
26174
26175       output.append_data (MAYBE_SWAP (str_off));
26176       output.append_data (MAYBE_SWAP (vec_off));
26177     }
26178 }
26179
26180 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
26181
26182 /* Helper struct for building the address table.  */
26183 struct addrmap_index_data
26184 {
26185   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
26186     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
26187   {}
26188
26189   struct objfile *objfile;
26190   data_buf &addr_vec;
26191   psym_index_map &cu_index_htab;
26192
26193   /* Non-zero if the previous_* fields are valid.
26194      We can't write an entry until we see the next entry (since it is only then
26195      that we know the end of the entry).  */
26196   int previous_valid;
26197   /* Index of the CU in the table of all CUs in the index file.  */
26198   unsigned int previous_cu_index;
26199   /* Start address of the CU.  */
26200   CORE_ADDR previous_cu_start;
26201 };
26202
26203 /* Write an address entry to ADDR_VEC.  */
26204
26205 static void
26206 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
26207                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
26208 {
26209   CORE_ADDR baseaddr;
26210
26211   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
26212
26213   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
26214   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
26215   addr_vec.append_data (MAYBE_SWAP (cu_index));
26216 }
26217
26218 /* Worker function for traversing an addrmap to build the address table.  */
26219
26220 static int
26221 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
26222 {
26223   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
26224   struct partial_symtab *pst = (struct partial_symtab *) obj;
26225
26226   if (data->previous_valid)
26227     add_address_entry (data->objfile, data->addr_vec,
26228                        data->previous_cu_start, start_addr,
26229                        data->previous_cu_index);
26230
26231   data->previous_cu_start = start_addr;
26232   if (pst != NULL)
26233     {
26234       const auto it = data->cu_index_htab.find (pst);
26235       gdb_assert (it != data->cu_index_htab.cend ());
26236       data->previous_cu_index = it->second;
26237       data->previous_valid = 1;
26238     }
26239   else
26240     data->previous_valid = 0;
26241
26242   return 0;
26243 }
26244
26245 /* Write OBJFILE's address map to ADDR_VEC.
26246    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
26247    in the index file.  */
26248
26249 static void
26250 write_address_map (struct objfile *objfile, data_buf &addr_vec,
26251                    psym_index_map &cu_index_htab)
26252 {
26253   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
26254
26255   /* When writing the address table, we have to cope with the fact that
26256      the addrmap iterator only provides the start of a region; we have to
26257      wait until the next invocation to get the start of the next region.  */
26258
26259   addrmap_index_data.objfile = objfile;
26260   addrmap_index_data.previous_valid = 0;
26261
26262   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
26263                    &addrmap_index_data);
26264
26265   /* It's highly unlikely the last entry (end address = 0xff...ff)
26266      is valid, but we should still handle it.
26267      The end address is recorded as the start of the next region, but that
26268      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
26269      anyway.  */
26270   if (addrmap_index_data.previous_valid)
26271     add_address_entry (objfile, addr_vec,
26272                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
26273                        addrmap_index_data.previous_cu_index);
26274 }
26275
26276 /* Return the symbol kind of PSYM.  */
26277
26278 static gdb_index_symbol_kind
26279 symbol_kind (struct partial_symbol *psym)
26280 {
26281   domain_enum domain = PSYMBOL_DOMAIN (psym);
26282   enum address_class aclass = PSYMBOL_CLASS (psym);
26283
26284   switch (domain)
26285     {
26286     case VAR_DOMAIN:
26287       switch (aclass)
26288         {
26289         case LOC_BLOCK:
26290           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
26291         case LOC_TYPEDEF:
26292           return GDB_INDEX_SYMBOL_KIND_TYPE;
26293         case LOC_COMPUTED:
26294         case LOC_CONST_BYTES:
26295         case LOC_OPTIMIZED_OUT:
26296         case LOC_STATIC:
26297           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26298         case LOC_CONST:
26299           /* Note: It's currently impossible to recognize psyms as enum values
26300              short of reading the type info.  For now punt.  */
26301           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26302         default:
26303           /* There are other LOC_FOO values that one might want to classify
26304              as variables, but dwarf2read.c doesn't currently use them.  */
26305           return GDB_INDEX_SYMBOL_KIND_OTHER;
26306         }
26307     case STRUCT_DOMAIN:
26308       return GDB_INDEX_SYMBOL_KIND_TYPE;
26309     default:
26310       return GDB_INDEX_SYMBOL_KIND_OTHER;
26311     }
26312 }
26313
26314 /* Add a list of partial symbols to SYMTAB.  */
26315
26316 static void
26317 write_psymbols (struct mapped_symtab *symtab,
26318                 std::unordered_set<partial_symbol *> &psyms_seen,
26319                 struct partial_symbol **psymp,
26320                 int count,
26321                 offset_type cu_index,
26322                 int is_static)
26323 {
26324   for (; count-- > 0; ++psymp)
26325     {
26326       struct partial_symbol *psym = *psymp;
26327
26328       if (SYMBOL_LANGUAGE (psym) == language_ada)
26329         error (_("Ada is not currently supported by the index"));
26330
26331       /* Only add a given psymbol once.  */
26332       if (psyms_seen.insert (psym).second)
26333         {
26334           gdb_index_symbol_kind kind = symbol_kind (psym);
26335
26336           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26337                            is_static, kind, cu_index);
26338         }
26339     }
26340 }
26341
26342 /* A helper struct used when iterating over debug_types.  */
26343 struct signatured_type_index_data
26344 {
26345   signatured_type_index_data (data_buf &types_list_,
26346                               std::unordered_set<partial_symbol *> &psyms_seen_)
26347     : types_list (types_list_), psyms_seen (psyms_seen_)
26348   {}
26349
26350   struct objfile *objfile;
26351   struct mapped_symtab *symtab;
26352   data_buf &types_list;
26353   std::unordered_set<partial_symbol *> &psyms_seen;
26354   int cu_index;
26355 };
26356
26357 /* A helper function that writes a single signatured_type to an
26358    obstack.  */
26359
26360 static int
26361 write_one_signatured_type (void **slot, void *d)
26362 {
26363   struct signatured_type_index_data *info
26364     = (struct signatured_type_index_data *) d;
26365   struct signatured_type *entry = (struct signatured_type *) *slot;
26366   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26367
26368   write_psymbols (info->symtab,
26369                   info->psyms_seen,
26370                   &info->objfile->global_psymbols[psymtab->globals_offset],
26371                   psymtab->n_global_syms, info->cu_index,
26372                   0);
26373   write_psymbols (info->symtab,
26374                   info->psyms_seen,
26375                   &info->objfile->static_psymbols[psymtab->statics_offset],
26376                   psymtab->n_static_syms, info->cu_index,
26377                   1);
26378
26379   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26380                                 to_underlying (entry->per_cu.sect_off));
26381   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26382                                 to_underlying (entry->type_offset_in_tu));
26383   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26384
26385   ++info->cu_index;
26386
26387   return 1;
26388 }
26389
26390 /* Recurse into all "included" dependencies and count their symbols as
26391    if they appeared in this psymtab.  */
26392
26393 static void
26394 recursively_count_psymbols (struct partial_symtab *psymtab,
26395                             size_t &psyms_seen)
26396 {
26397   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26398     if (psymtab->dependencies[i]->user != NULL)
26399       recursively_count_psymbols (psymtab->dependencies[i],
26400                                   psyms_seen);
26401
26402   psyms_seen += psymtab->n_global_syms;
26403   psyms_seen += psymtab->n_static_syms;
26404 }
26405
26406 /* Recurse into all "included" dependencies and write their symbols as
26407    if they appeared in this psymtab.  */
26408
26409 static void
26410 recursively_write_psymbols (struct objfile *objfile,
26411                             struct partial_symtab *psymtab,
26412                             struct mapped_symtab *symtab,
26413                             std::unordered_set<partial_symbol *> &psyms_seen,
26414                             offset_type cu_index)
26415 {
26416   int i;
26417
26418   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26419     if (psymtab->dependencies[i]->user != NULL)
26420       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26421                                   symtab, psyms_seen, cu_index);
26422
26423   write_psymbols (symtab,
26424                   psyms_seen,
26425                   &objfile->global_psymbols[psymtab->globals_offset],
26426                   psymtab->n_global_syms, cu_index,
26427                   0);
26428   write_psymbols (symtab,
26429                   psyms_seen,
26430                   &objfile->static_psymbols[psymtab->statics_offset],
26431                   psymtab->n_static_syms, cu_index,
26432                   1);
26433 }
26434
26435 /* DWARF-5 .debug_names builder.  */
26436 class debug_names
26437 {
26438 public:
26439   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26440                bfd_endian dwarf5_byte_order)
26441     : m_dwarf5_byte_order (dwarf5_byte_order),
26442       m_dwarf32 (dwarf5_byte_order),
26443       m_dwarf64 (dwarf5_byte_order),
26444       m_dwarf (is_dwarf64
26445                ? static_cast<dwarf &> (m_dwarf64)
26446                : static_cast<dwarf &> (m_dwarf32)),
26447       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26448       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26449       m_debugstrlookup (dwarf2_per_objfile)
26450   {}
26451
26452   int dwarf5_offset_size () const
26453   {
26454     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26455     return dwarf5_is_dwarf64 ? 8 : 4;
26456   }
26457
26458   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26459   enum class unit_kind { cu, tu };
26460
26461   /* Insert one symbol.  */
26462   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26463                unit_kind kind)
26464   {
26465     const int dwarf_tag = psymbol_tag (psym);
26466     if (dwarf_tag == 0)
26467       return;
26468     const char *const name = SYMBOL_SEARCH_NAME (psym);
26469     const auto insertpair
26470       = m_name_to_value_set.emplace (c_str_view (name),
26471                                      std::set<symbol_value> ());
26472     std::set<symbol_value> &value_set = insertpair.first->second;
26473     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26474   }
26475
26476   /* Build all the tables.  All symbols must be already inserted.
26477      This function does not call file_write, caller has to do it
26478      afterwards.  */
26479   void build ()
26480   {
26481     /* Verify the build method has not be called twice.  */
26482     gdb_assert (m_abbrev_table.empty ());
26483     const size_t name_count = m_name_to_value_set.size ();
26484     m_bucket_table.resize
26485       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26486     m_hash_table.reserve (name_count);
26487     m_name_table_string_offs.reserve (name_count);
26488     m_name_table_entry_offs.reserve (name_count);
26489
26490     /* Map each hash of symbol to its name and value.  */
26491     struct hash_it_pair
26492     {
26493       uint32_t hash;
26494       decltype (m_name_to_value_set)::const_iterator it;
26495     };
26496     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26497     bucket_hash.resize (m_bucket_table.size ());
26498     for (decltype (m_name_to_value_set)::const_iterator it
26499            = m_name_to_value_set.cbegin ();
26500          it != m_name_to_value_set.cend ();
26501          ++it)
26502       {
26503         const char *const name = it->first.c_str ();
26504         const uint32_t hash = dwarf5_djb_hash (name);
26505         hash_it_pair hashitpair;
26506         hashitpair.hash = hash;
26507         hashitpair.it = it;
26508         auto &slot = bucket_hash[hash % bucket_hash.size()];
26509         slot.push_front (std::move (hashitpair));
26510       }
26511     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26512       {
26513         const std::forward_list<hash_it_pair> &hashitlist
26514           = bucket_hash[bucket_ix];
26515         if (hashitlist.empty ())
26516           continue;
26517         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26518         /* The hashes array is indexed starting at 1.  */
26519         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26520                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26521                                 m_hash_table.size () + 1);
26522         for (const hash_it_pair &hashitpair : hashitlist)
26523           {
26524             m_hash_table.push_back (0);
26525             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26526                                                         (&m_hash_table.back ()),
26527                                     sizeof (m_hash_table.back ()),
26528                                     m_dwarf5_byte_order, hashitpair.hash);
26529             const c_str_view &name = hashitpair.it->first;
26530             const std::set<symbol_value> &value_set = hashitpair.it->second;
26531             m_name_table_string_offs.push_back_reorder
26532               (m_debugstrlookup.lookup (name.c_str ()));
26533             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26534             gdb_assert (!value_set.empty ());
26535             for (const symbol_value &value : value_set)
26536               {
26537                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26538                                                         value.is_static,
26539                                                         value.kind)];
26540                 if (idx == 0)
26541                   {
26542                     idx = m_idx_next++;
26543                     m_abbrev_table.append_unsigned_leb128 (idx);
26544                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26545                     m_abbrev_table.append_unsigned_leb128
26546                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26547                                                            : DW_IDX_type_unit);
26548                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26549                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26550                                                            ? DW_IDX_GNU_internal
26551                                                            : DW_IDX_GNU_external);
26552                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26553
26554                     /* Terminate attributes list.  */
26555                     m_abbrev_table.append_unsigned_leb128 (0);
26556                     m_abbrev_table.append_unsigned_leb128 (0);
26557                   }
26558
26559                 m_entry_pool.append_unsigned_leb128 (idx);
26560                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26561               }
26562
26563             /* Terminate the list of CUs.  */
26564             m_entry_pool.append_unsigned_leb128 (0);
26565           }
26566       }
26567     gdb_assert (m_hash_table.size () == name_count);
26568
26569     /* Terminate tags list.  */
26570     m_abbrev_table.append_unsigned_leb128 (0);
26571   }
26572
26573   /* Return .debug_names bucket count.  This must be called only after
26574      calling the build method.  */
26575   uint32_t bucket_count () const
26576   {
26577     /* Verify the build method has been already called.  */
26578     gdb_assert (!m_abbrev_table.empty ());
26579     const uint32_t retval = m_bucket_table.size ();
26580
26581     /* Check for overflow.  */
26582     gdb_assert (retval == m_bucket_table.size ());
26583     return retval;
26584   }
26585
26586   /* Return .debug_names names count.  This must be called only after
26587      calling the build method.  */
26588   uint32_t name_count () const
26589   {
26590     /* Verify the build method has been already called.  */
26591     gdb_assert (!m_abbrev_table.empty ());
26592     const uint32_t retval = m_hash_table.size ();
26593
26594     /* Check for overflow.  */
26595     gdb_assert (retval == m_hash_table.size ());
26596     return retval;
26597   }
26598
26599   /* Return number of bytes of .debug_names abbreviation table.  This
26600      must be called only after calling the build method.  */
26601   uint32_t abbrev_table_bytes () const
26602   {
26603     gdb_assert (!m_abbrev_table.empty ());
26604     return m_abbrev_table.size ();
26605   }
26606
26607   /* Recurse into all "included" dependencies and store their symbols
26608      as if they appeared in this psymtab.  */
26609   void recursively_write_psymbols
26610     (struct objfile *objfile,
26611      struct partial_symtab *psymtab,
26612      std::unordered_set<partial_symbol *> &psyms_seen,
26613      int cu_index)
26614   {
26615     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26616       if (psymtab->dependencies[i]->user != NULL)
26617         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26618                                     psyms_seen, cu_index);
26619
26620     write_psymbols (psyms_seen,
26621                     &objfile->global_psymbols[psymtab->globals_offset],
26622                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26623     write_psymbols (psyms_seen,
26624                     &objfile->static_psymbols[psymtab->statics_offset],
26625                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26626   }
26627
26628   /* Return number of bytes the .debug_names section will have.  This
26629      must be called only after calling the build method.  */
26630   size_t bytes () const
26631   {
26632     /* Verify the build method has been already called.  */
26633     gdb_assert (!m_abbrev_table.empty ());
26634     size_t expected_bytes = 0;
26635     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26636     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26637     expected_bytes += m_name_table_string_offs.bytes ();
26638     expected_bytes += m_name_table_entry_offs.bytes ();
26639     expected_bytes += m_abbrev_table.size ();
26640     expected_bytes += m_entry_pool.size ();
26641     return expected_bytes;
26642   }
26643
26644   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26645      FILE_STR.  This must be called only after calling the build
26646      method.  */
26647   void file_write (FILE *file_names, FILE *file_str) const
26648   {
26649     /* Verify the build method has been already called.  */
26650     gdb_assert (!m_abbrev_table.empty ());
26651     ::file_write (file_names, m_bucket_table);
26652     ::file_write (file_names, m_hash_table);
26653     m_name_table_string_offs.file_write (file_names);
26654     m_name_table_entry_offs.file_write (file_names);
26655     m_abbrev_table.file_write (file_names);
26656     m_entry_pool.file_write (file_names);
26657     m_debugstrlookup.file_write (file_str);
26658   }
26659
26660   /* A helper user data for write_one_signatured_type.  */
26661   class write_one_signatured_type_data
26662   {
26663   public:
26664     write_one_signatured_type_data (debug_names &nametable_,
26665                                     signatured_type_index_data &&info_)
26666     : nametable (nametable_), info (std::move (info_))
26667     {}
26668     debug_names &nametable;
26669     struct signatured_type_index_data info;
26670   };
26671
26672   /* A helper function to pass write_one_signatured_type to
26673      htab_traverse_noresize.  */
26674   static int
26675   write_one_signatured_type (void **slot, void *d)
26676   {
26677     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26678     struct signatured_type_index_data *info = &data->info;
26679     struct signatured_type *entry = (struct signatured_type *) *slot;
26680
26681     data->nametable.write_one_signatured_type (entry, info);
26682
26683     return 1;
26684   }
26685
26686 private:
26687
26688   /* Storage for symbol names mapping them to their .debug_str section
26689      offsets.  */
26690   class debug_str_lookup
26691   {
26692   public:
26693
26694     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26695        All .debug_str section strings are automatically stored.  */
26696     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26697       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26698         m_dwarf2_per_objfile (dwarf2_per_objfile)
26699     {
26700       dwarf2_read_section (dwarf2_per_objfile->objfile,
26701                            &dwarf2_per_objfile->str);
26702       if (dwarf2_per_objfile->str.buffer == NULL)
26703         return;
26704       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26705            data < (dwarf2_per_objfile->str.buffer
26706                    + dwarf2_per_objfile->str.size);)
26707         {
26708           const char *const s = reinterpret_cast<const char *> (data);
26709           const auto insertpair
26710             = m_str_table.emplace (c_str_view (s),
26711                                    data - dwarf2_per_objfile->str.buffer);
26712           if (!insertpair.second)
26713             complaint (&symfile_complaints,
26714                        _("Duplicate string \"%s\" in "
26715                          ".debug_str section [in module %s]"),
26716                        s, bfd_get_filename (m_abfd));
26717           data += strlen (s) + 1;
26718         }
26719     }
26720
26721     /* Return offset of symbol name S in the .debug_str section.  Add
26722        such symbol to the section's end if it does not exist there
26723        yet.  */
26724     size_t lookup (const char *s)
26725     {
26726       const auto it = m_str_table.find (c_str_view (s));
26727       if (it != m_str_table.end ())
26728         return it->second;
26729       const size_t offset = (m_dwarf2_per_objfile->str.size
26730                              + m_str_add_buf.size ());
26731       m_str_table.emplace (c_str_view (s), offset);
26732       m_str_add_buf.append_cstr0 (s);
26733       return offset;
26734     }
26735
26736     /* Append the end of the .debug_str section to FILE.  */
26737     void file_write (FILE *file) const
26738     {
26739       m_str_add_buf.file_write (file);
26740     }
26741
26742   private:
26743     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26744     bfd *const m_abfd;
26745     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26746
26747     /* Data to add at the end of .debug_str for new needed symbol names.  */
26748     data_buf m_str_add_buf;
26749   };
26750
26751   /* Container to map used DWARF tags to their .debug_names abbreviation
26752      tags.  */
26753   class index_key
26754   {
26755   public:
26756     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26757       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26758     {
26759     }
26760
26761     bool
26762     operator== (const index_key &other) const
26763     {
26764       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26765               && kind == other.kind);
26766     }
26767
26768     const int dwarf_tag;
26769     const bool is_static;
26770     const unit_kind kind;
26771   };
26772
26773   /* Provide std::unordered_map::hasher for index_key.  */
26774   class index_key_hasher
26775   {
26776   public:
26777     size_t
26778     operator () (const index_key &key) const
26779     {
26780       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26781     }
26782   };
26783
26784   /* Parameters of one symbol entry.  */
26785   class symbol_value
26786   {
26787   public:
26788     const int dwarf_tag, cu_index;
26789     const bool is_static;
26790     const unit_kind kind;
26791
26792     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26793                   unit_kind kind_)
26794       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26795         kind (kind_)
26796     {}
26797
26798     bool
26799     operator< (const symbol_value &other) const
26800     {
26801 #define X(n) \
26802   do \
26803     { \
26804       if (n < other.n) \
26805         return true; \
26806       if (n > other.n) \
26807         return false; \
26808     } \
26809   while (0)
26810       X (dwarf_tag);
26811       X (is_static);
26812       X (kind);
26813       X (cu_index);
26814 #undef X
26815       return false;
26816     }
26817   };
26818
26819   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26820      output.  */
26821   class offset_vec
26822   {
26823   protected:
26824     const bfd_endian dwarf5_byte_order;
26825   public:
26826     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26827       : dwarf5_byte_order (dwarf5_byte_order_)
26828     {}
26829
26830     /* Call std::vector::reserve for NELEM elements.  */
26831     virtual void reserve (size_t nelem) = 0;
26832
26833     /* Call std::vector::push_back with store_unsigned_integer byte
26834        reordering for ELEM.  */
26835     virtual void push_back_reorder (size_t elem) = 0;
26836
26837     /* Return expected output size in bytes.  */
26838     virtual size_t bytes () const = 0;
26839
26840     /* Write name table to FILE.  */
26841     virtual void file_write (FILE *file) const = 0;
26842   };
26843
26844   /* Template to unify DWARF-32 and DWARF-64 output.  */
26845   template<typename OffsetSize>
26846   class offset_vec_tmpl : public offset_vec
26847   {
26848   public:
26849     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26850       : offset_vec (dwarf5_byte_order_)
26851     {}
26852
26853     /* Implement offset_vec::reserve.  */
26854     void reserve (size_t nelem) override
26855     {
26856       m_vec.reserve (nelem);
26857     }
26858
26859     /* Implement offset_vec::push_back_reorder.  */
26860     void push_back_reorder (size_t elem) override
26861     {
26862       m_vec.push_back (elem);
26863       /* Check for overflow.  */
26864       gdb_assert (m_vec.back () == elem);
26865       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26866                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26867     }
26868
26869     /* Implement offset_vec::bytes.  */
26870     size_t bytes () const override
26871     {
26872       return m_vec.size () * sizeof (m_vec[0]);
26873     }
26874
26875     /* Implement offset_vec::file_write.  */
26876     void file_write (FILE *file) const override
26877     {
26878       ::file_write (file, m_vec);
26879     }
26880
26881   private:
26882     std::vector<OffsetSize> m_vec;
26883   };
26884
26885   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26886      respecting name table width.  */
26887   class dwarf
26888   {
26889   public:
26890     offset_vec &name_table_string_offs, &name_table_entry_offs;
26891
26892     dwarf (offset_vec &name_table_string_offs_,
26893            offset_vec &name_table_entry_offs_)
26894       : name_table_string_offs (name_table_string_offs_),
26895         name_table_entry_offs (name_table_entry_offs_)
26896     {
26897     }
26898   };
26899
26900   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26901      respecting name table width.  */
26902   template<typename OffsetSize>
26903   class dwarf_tmpl : public dwarf
26904   {
26905   public:
26906     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26907       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26908         m_name_table_string_offs (dwarf5_byte_order_),
26909         m_name_table_entry_offs (dwarf5_byte_order_)
26910     {}
26911
26912   private:
26913     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26914     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26915   };
26916
26917   /* Try to reconstruct original DWARF tag for given partial_symbol.
26918      This function is not DWARF-5 compliant but it is sufficient for
26919      GDB as a DWARF-5 index consumer.  */
26920   static int psymbol_tag (const struct partial_symbol *psym)
26921   {
26922     domain_enum domain = PSYMBOL_DOMAIN (psym);
26923     enum address_class aclass = PSYMBOL_CLASS (psym);
26924
26925     switch (domain)
26926       {
26927       case VAR_DOMAIN:
26928         switch (aclass)
26929           {
26930           case LOC_BLOCK:
26931             return DW_TAG_subprogram;
26932           case LOC_TYPEDEF:
26933             return DW_TAG_typedef;
26934           case LOC_COMPUTED:
26935           case LOC_CONST_BYTES:
26936           case LOC_OPTIMIZED_OUT:
26937           case LOC_STATIC:
26938             return DW_TAG_variable;
26939           case LOC_CONST:
26940             /* Note: It's currently impossible to recognize psyms as enum values
26941                short of reading the type info.  For now punt.  */
26942             return DW_TAG_variable;
26943           default:
26944             /* There are other LOC_FOO values that one might want to classify
26945                as variables, but dwarf2read.c doesn't currently use them.  */
26946             return DW_TAG_variable;
26947           }
26948       case STRUCT_DOMAIN:
26949         return DW_TAG_structure_type;
26950       default:
26951         return 0;
26952       }
26953   }
26954
26955   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26956   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26957                        struct partial_symbol **psymp, int count, int cu_index,
26958                        bool is_static, unit_kind kind)
26959   {
26960     for (; count-- > 0; ++psymp)
26961       {
26962         struct partial_symbol *psym = *psymp;
26963
26964         if (SYMBOL_LANGUAGE (psym) == language_ada)
26965           error (_("Ada is not currently supported by the index"));
26966
26967         /* Only add a given psymbol once.  */
26968         if (psyms_seen.insert (psym).second)
26969           insert (psym, cu_index, is_static, kind);
26970       }
26971   }
26972
26973   /* A helper function that writes a single signatured_type
26974      to a debug_names.  */
26975   void
26976   write_one_signatured_type (struct signatured_type *entry,
26977                              struct signatured_type_index_data *info)
26978   {
26979     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26980
26981     write_psymbols (info->psyms_seen,
26982                     &info->objfile->global_psymbols[psymtab->globals_offset],
26983                     psymtab->n_global_syms, info->cu_index, false,
26984                     unit_kind::tu);
26985     write_psymbols (info->psyms_seen,
26986                     &info->objfile->static_psymbols[psymtab->statics_offset],
26987                     psymtab->n_static_syms, info->cu_index, true,
26988                     unit_kind::tu);
26989
26990     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26991                                   to_underlying (entry->per_cu.sect_off));
26992
26993     ++info->cu_index;
26994   }
26995
26996   /* Store value of each symbol.  */
26997   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26998     m_name_to_value_set;
26999
27000   /* Tables of DWARF-5 .debug_names.  They are in object file byte
27001      order.  */
27002   std::vector<uint32_t> m_bucket_table;
27003   std::vector<uint32_t> m_hash_table;
27004
27005   const bfd_endian m_dwarf5_byte_order;
27006   dwarf_tmpl<uint32_t> m_dwarf32;
27007   dwarf_tmpl<uint64_t> m_dwarf64;
27008   dwarf &m_dwarf;
27009   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
27010   debug_str_lookup m_debugstrlookup;
27011
27012   /* Map each used .debug_names abbreviation tag parameter to its
27013      index value.  */
27014   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
27015
27016   /* Next unused .debug_names abbreviation tag for
27017      m_indexkey_to_idx.  */
27018   int m_idx_next = 1;
27019
27020   /* .debug_names abbreviation table.  */
27021   data_buf m_abbrev_table;
27022
27023   /* .debug_names entry pool.  */
27024   data_buf m_entry_pool;
27025 };
27026
27027 /* Return iff any of the needed offsets does not fit into 32-bit
27028    .debug_names section.  */
27029
27030 static bool
27031 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
27032 {
27033   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27034     {
27035       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
27036
27037       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
27038         return true;
27039     }
27040   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
27041     {
27042       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
27043       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
27044
27045       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
27046         return true;
27047     }
27048   return false;
27049 }
27050
27051 /* The psyms_seen set is potentially going to be largish (~40k
27052    elements when indexing a -g3 build of GDB itself).  Estimate the
27053    number of elements in order to avoid too many rehashes, which
27054    require rebuilding buckets and thus many trips to
27055    malloc/free.  */
27056
27057 static size_t
27058 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
27059 {
27060   size_t psyms_count = 0;
27061   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27062     {
27063       struct dwarf2_per_cu_data *per_cu
27064         = dwarf2_per_objfile->all_comp_units[i];
27065       struct partial_symtab *psymtab = per_cu->v.psymtab;
27066
27067       if (psymtab != NULL && psymtab->user == NULL)
27068         recursively_count_psymbols (psymtab, psyms_count);
27069     }
27070   /* Generating an index for gdb itself shows a ratio of
27071      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
27072   return psyms_count / 4;
27073 }
27074
27075 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
27076    Return how many bytes were expected to be written into OUT_FILE.  */
27077
27078 static size_t
27079 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
27080 {
27081   struct objfile *objfile = dwarf2_per_objfile->objfile;
27082   mapped_symtab symtab;
27083   data_buf cu_list;
27084
27085   /* While we're scanning CU's create a table that maps a psymtab pointer
27086      (which is what addrmap records) to its index (which is what is recorded
27087      in the index file).  This will later be needed to write the address
27088      table.  */
27089   psym_index_map cu_index_htab;
27090   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
27091
27092   /* The CU list is already sorted, so we don't need to do additional
27093      work here.  Also, the debug_types entries do not appear in
27094      all_comp_units, but only in their own hash table.  */
27095
27096   std::unordered_set<partial_symbol *> psyms_seen
27097     (psyms_seen_size (dwarf2_per_objfile));
27098   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27099     {
27100       struct dwarf2_per_cu_data *per_cu
27101         = dwarf2_per_objfile->all_comp_units[i];
27102       struct partial_symtab *psymtab = per_cu->v.psymtab;
27103
27104       /* CU of a shared file from 'dwz -m' may be unused by this main file.
27105          It may be referenced from a local scope but in such case it does not
27106          need to be present in .gdb_index.  */
27107       if (psymtab == NULL)
27108         continue;
27109
27110       if (psymtab->user == NULL)
27111         recursively_write_psymbols (objfile, psymtab, &symtab,
27112                                     psyms_seen, i);
27113
27114       const auto insertpair = cu_index_htab.emplace (psymtab, i);
27115       gdb_assert (insertpair.second);
27116
27117       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
27118                            to_underlying (per_cu->sect_off));
27119       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
27120     }
27121
27122   /* Dump the address map.  */
27123   data_buf addr_vec;
27124   write_address_map (objfile, addr_vec, cu_index_htab);
27125
27126   /* Write out the .debug_type entries, if any.  */
27127   data_buf types_cu_list;
27128   if (dwarf2_per_objfile->signatured_types)
27129     {
27130       signatured_type_index_data sig_data (types_cu_list,
27131                                            psyms_seen);
27132
27133       sig_data.objfile = objfile;
27134       sig_data.symtab = &symtab;
27135       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
27136       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27137                               write_one_signatured_type, &sig_data);
27138     }
27139
27140   /* Now that we've processed all symbols we can shrink their cu_indices
27141      lists.  */
27142   uniquify_cu_indices (&symtab);
27143
27144   data_buf symtab_vec, constant_pool;
27145   write_hash_table (&symtab, symtab_vec, constant_pool);
27146
27147   data_buf contents;
27148   const offset_type size_of_contents = 6 * sizeof (offset_type);
27149   offset_type total_len = size_of_contents;
27150
27151   /* The version number.  */
27152   contents.append_data (MAYBE_SWAP (8));
27153
27154   /* The offset of the CU list from the start of the file.  */
27155   contents.append_data (MAYBE_SWAP (total_len));
27156   total_len += cu_list.size ();
27157
27158   /* The offset of the types CU list from the start of the file.  */
27159   contents.append_data (MAYBE_SWAP (total_len));
27160   total_len += types_cu_list.size ();
27161
27162   /* The offset of the address table from the start of the file.  */
27163   contents.append_data (MAYBE_SWAP (total_len));
27164   total_len += addr_vec.size ();
27165
27166   /* The offset of the symbol table from the start of the file.  */
27167   contents.append_data (MAYBE_SWAP (total_len));
27168   total_len += symtab_vec.size ();
27169
27170   /* The offset of the constant pool from the start of the file.  */
27171   contents.append_data (MAYBE_SWAP (total_len));
27172   total_len += constant_pool.size ();
27173
27174   gdb_assert (contents.size () == size_of_contents);
27175
27176   contents.file_write (out_file);
27177   cu_list.file_write (out_file);
27178   types_cu_list.file_write (out_file);
27179   addr_vec.file_write (out_file);
27180   symtab_vec.file_write (out_file);
27181   constant_pool.file_write (out_file);
27182
27183   return total_len;
27184 }
27185
27186 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
27187 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
27188
27189 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
27190    needed addition to .debug_str section to OUT_FILE_STR.  Return how
27191    many bytes were expected to be written into OUT_FILE.  */
27192
27193 static size_t
27194 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
27195                    FILE *out_file, FILE *out_file_str)
27196 {
27197   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
27198   struct objfile *objfile = dwarf2_per_objfile->objfile;
27199   const enum bfd_endian dwarf5_byte_order
27200     = gdbarch_byte_order (get_objfile_arch (objfile));
27201
27202   /* The CU list is already sorted, so we don't need to do additional
27203      work here.  Also, the debug_types entries do not appear in
27204      all_comp_units, but only in their own hash table.  */
27205   data_buf cu_list;
27206   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
27207                          dwarf5_byte_order);
27208   std::unordered_set<partial_symbol *>
27209     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
27210   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27211     {
27212       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
27213       partial_symtab *psymtab = per_cu->v.psymtab;
27214
27215       /* CU of a shared file from 'dwz -m' may be unused by this main
27216          file.  It may be referenced from a local scope but in such
27217          case it does not need to be present in .debug_names.  */
27218       if (psymtab == NULL)
27219         continue;
27220
27221       if (psymtab->user == NULL)
27222         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
27223
27224       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
27225                            to_underlying (per_cu->sect_off));
27226     }
27227
27228   /* Write out the .debug_type entries, if any.  */
27229   data_buf types_cu_list;
27230   if (dwarf2_per_objfile->signatured_types)
27231     {
27232       debug_names::write_one_signatured_type_data sig_data (nametable,
27233                         signatured_type_index_data (types_cu_list, psyms_seen));
27234
27235       sig_data.info.objfile = objfile;
27236       /* It is used only for gdb_index.  */
27237       sig_data.info.symtab = nullptr;
27238       sig_data.info.cu_index = 0;
27239       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27240                               debug_names::write_one_signatured_type,
27241                               &sig_data);
27242     }
27243
27244   nametable.build ();
27245
27246   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
27247
27248   const offset_type bytes_of_header
27249     = ((dwarf5_is_dwarf64 ? 12 : 4)
27250        + 2 + 2 + 7 * 4
27251        + sizeof (dwarf5_gdb_augmentation));
27252   size_t expected_bytes = 0;
27253   expected_bytes += bytes_of_header;
27254   expected_bytes += cu_list.size ();
27255   expected_bytes += types_cu_list.size ();
27256   expected_bytes += nametable.bytes ();
27257   data_buf header;
27258
27259   if (!dwarf5_is_dwarf64)
27260     {
27261       const uint64_t size64 = expected_bytes - 4;
27262       gdb_assert (size64 < 0xfffffff0);
27263       header.append_uint (4, dwarf5_byte_order, size64);
27264     }
27265   else
27266     {
27267       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
27268       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
27269     }
27270
27271   /* The version number.  */
27272   header.append_uint (2, dwarf5_byte_order, 5);
27273
27274   /* Padding.  */
27275   header.append_uint (2, dwarf5_byte_order, 0);
27276
27277   /* comp_unit_count - The number of CUs in the CU list.  */
27278   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
27279
27280   /* local_type_unit_count - The number of TUs in the local TU
27281      list.  */
27282   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
27283
27284   /* foreign_type_unit_count - The number of TUs in the foreign TU
27285      list.  */
27286   header.append_uint (4, dwarf5_byte_order, 0);
27287
27288   /* bucket_count - The number of hash buckets in the hash lookup
27289      table.  */
27290   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
27291
27292   /* name_count - The number of unique names in the index.  */
27293   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
27294
27295   /* abbrev_table_size - The size in bytes of the abbreviations
27296      table.  */
27297   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
27298
27299   /* augmentation_string_size - The size in bytes of the augmentation
27300      string.  This value is rounded up to a multiple of 4.  */
27301   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
27302   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
27303   header.append_data (dwarf5_gdb_augmentation);
27304
27305   gdb_assert (header.size () == bytes_of_header);
27306
27307   header.file_write (out_file);
27308   cu_list.file_write (out_file);
27309   types_cu_list.file_write (out_file);
27310   nametable.file_write (out_file, out_file_str);
27311
27312   return expected_bytes;
27313 }
27314
27315 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
27316    position is at the end of the file.  */
27317
27318 static void
27319 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27320 {
27321   const auto file_size = ftell (file);
27322   if (file_size == -1)
27323     error (_("Can't get `%s' size"), filename);
27324   gdb_assert (file_size == expected_size);
27325 }
27326
27327 /* Create an index file for OBJFILE in the directory DIR.  */
27328
27329 static void
27330 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27331                          const char *dir,
27332                          dw_index_kind index_kind)
27333 {
27334   struct objfile *objfile = dwarf2_per_objfile->objfile;
27335
27336   if (dwarf2_per_objfile->using_index)
27337     error (_("Cannot use an index to create the index"));
27338
27339   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27340     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27341
27342   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27343     return;
27344
27345   struct stat st;
27346   if (stat (objfile_name (objfile), &st) < 0)
27347     perror_with_name (objfile_name (objfile));
27348
27349   std::string filename (std::string (dir) + SLASH_STRING
27350                         + lbasename (objfile_name (objfile))
27351                         + (index_kind == dw_index_kind::DEBUG_NAMES
27352                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27353
27354   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27355   if (!out_file)
27356     error (_("Can't open `%s' for writing"), filename.c_str ());
27357
27358   /* Order matters here; we want FILE to be closed before FILENAME is
27359      unlinked, because on MS-Windows one cannot delete a file that is
27360      still open.  (Don't call anything here that might throw until
27361      file_closer is created.)  */
27362   gdb::unlinker unlink_file (filename.c_str ());
27363   gdb_file_up close_out_file (out_file);
27364
27365   if (index_kind == dw_index_kind::DEBUG_NAMES)
27366     {
27367       std::string filename_str (std::string (dir) + SLASH_STRING
27368                                 + lbasename (objfile_name (objfile))
27369                                 + DEBUG_STR_SUFFIX);
27370       FILE *out_file_str
27371         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27372       if (!out_file_str)
27373         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27374       gdb::unlinker unlink_file_str (filename_str.c_str ());
27375       gdb_file_up close_out_file_str (out_file_str);
27376
27377       const size_t total_len
27378         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27379       assert_file_size (out_file, filename.c_str (), total_len);
27380
27381       /* We want to keep the file .debug_str file too.  */
27382       unlink_file_str.keep ();
27383     }
27384   else
27385     {
27386       const size_t total_len
27387         = write_gdbindex (dwarf2_per_objfile, out_file);
27388       assert_file_size (out_file, filename.c_str (), total_len);
27389     }
27390
27391   /* We want to keep the file.  */
27392   unlink_file.keep ();
27393 }
27394
27395 /* Implementation of the `save gdb-index' command.
27396    
27397    Note that the .gdb_index file format used by this command is
27398    documented in the GDB manual.  Any changes here must be documented
27399    there.  */
27400
27401 static void
27402 save_gdb_index_command (const char *arg, int from_tty)
27403 {
27404   struct objfile *objfile;
27405   const char dwarf5space[] = "-dwarf-5 ";
27406   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27407
27408   if (!arg)
27409     arg = "";
27410
27411   arg = skip_spaces (arg);
27412   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27413     {
27414       index_kind = dw_index_kind::DEBUG_NAMES;
27415       arg += strlen (dwarf5space);
27416       arg = skip_spaces (arg);
27417     }
27418
27419   if (!*arg)
27420     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27421
27422   ALL_OBJFILES (objfile)
27423   {
27424     struct stat st;
27425
27426     /* If the objfile does not correspond to an actual file, skip it.  */
27427     if (stat (objfile_name (objfile), &st) < 0)
27428       continue;
27429
27430     struct dwarf2_per_objfile *dwarf2_per_objfile
27431       = get_dwarf2_per_objfile (objfile);
27432
27433     if (dwarf2_per_objfile != NULL)
27434       {
27435         TRY
27436           {
27437             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27438           }
27439         CATCH (except, RETURN_MASK_ERROR)
27440           {
27441             exception_fprintf (gdb_stderr, except,
27442                                _("Error while writing index for `%s': "),
27443                                objfile_name (objfile));
27444           }
27445         END_CATCH
27446       }
27447
27448   }
27449 }
27450
27451 \f
27452
27453 int dwarf_always_disassemble;
27454
27455 static void
27456 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27457                                struct cmd_list_element *c, const char *value)
27458 {
27459   fprintf_filtered (file,
27460                     _("Whether to always disassemble "
27461                       "DWARF expressions is %s.\n"),
27462                     value);
27463 }
27464
27465 static void
27466 show_check_physname (struct ui_file *file, int from_tty,
27467                      struct cmd_list_element *c, const char *value)
27468 {
27469   fprintf_filtered (file,
27470                     _("Whether to check \"physname\" is %s.\n"),
27471                     value);
27472 }
27473
27474 void
27475 _initialize_dwarf2_read (void)
27476 {
27477   struct cmd_list_element *c;
27478
27479   dwarf2_objfile_data_key = register_objfile_data ();
27480
27481   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27482 Set DWARF specific variables.\n\
27483 Configure DWARF variables such as the cache size"),
27484                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27485                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27486
27487   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27488 Show DWARF specific variables\n\
27489 Show DWARF variables such as the cache size"),
27490                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27491                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27492
27493   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27494                             &dwarf_max_cache_age, _("\
27495 Set the upper bound on the age of cached DWARF compilation units."), _("\
27496 Show the upper bound on the age of cached DWARF compilation units."), _("\
27497 A higher limit means that cached compilation units will be stored\n\
27498 in memory longer, and more total memory will be used.  Zero disables\n\
27499 caching, which can slow down startup."),
27500                             NULL,
27501                             show_dwarf_max_cache_age,
27502                             &set_dwarf_cmdlist,
27503                             &show_dwarf_cmdlist);
27504
27505   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27506                            &dwarf_always_disassemble, _("\
27507 Set whether `info address' always disassembles DWARF expressions."), _("\
27508 Show whether `info address' always disassembles DWARF expressions."), _("\
27509 When enabled, DWARF expressions are always printed in an assembly-like\n\
27510 syntax.  When disabled, expressions will be printed in a more\n\
27511 conversational style, when possible."),
27512                            NULL,
27513                            show_dwarf_always_disassemble,
27514                            &set_dwarf_cmdlist,
27515                            &show_dwarf_cmdlist);
27516
27517   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27518 Set debugging of the DWARF reader."), _("\
27519 Show debugging of the DWARF reader."), _("\
27520 When enabled (non-zero), debugging messages are printed during DWARF\n\
27521 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27522 information.  A value greater than 1 provides more verbose information."),
27523                             NULL,
27524                             NULL,
27525                             &setdebuglist, &showdebuglist);
27526
27527   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27528 Set debugging of the DWARF DIE reader."), _("\
27529 Show debugging of the DWARF DIE reader."), _("\
27530 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27531 The value is the maximum depth to print."),
27532                              NULL,
27533                              NULL,
27534                              &setdebuglist, &showdebuglist);
27535
27536   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27537 Set debugging of the dwarf line reader."), _("\
27538 Show debugging of the dwarf line reader."), _("\
27539 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27540 A value of 1 (one) provides basic information.\n\
27541 A value greater than 1 provides more verbose information."),
27542                              NULL,
27543                              NULL,
27544                              &setdebuglist, &showdebuglist);
27545
27546   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27547 Set cross-checking of \"physname\" code against demangler."), _("\
27548 Show cross-checking of \"physname\" code against demangler."), _("\
27549 When enabled, GDB's internal \"physname\" code is checked against\n\
27550 the demangler."),
27551                            NULL, show_check_physname,
27552                            &setdebuglist, &showdebuglist);
27553
27554   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27555                            no_class, &use_deprecated_index_sections, _("\
27556 Set whether to use deprecated gdb_index sections."), _("\
27557 Show whether to use deprecated gdb_index sections."), _("\
27558 When enabled, deprecated .gdb_index sections are used anyway.\n\
27559 Normally they are ignored either because of a missing feature or\n\
27560 performance issue.\n\
27561 Warning: This option must be enabled before gdb reads the file."),
27562                            NULL,
27563                            NULL,
27564                            &setlist, &showlist);
27565
27566   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27567                _("\
27568 Save a gdb-index file.\n\
27569 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27570 \n\
27571 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27572 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27573 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27574                &save_cmdlist);
27575   set_cmd_completer (c, filename_completer);
27576
27577   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27578                                                         &dwarf2_locexpr_funcs);
27579   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27580                                                         &dwarf2_loclist_funcs);
27581
27582   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27583                                         &dwarf2_block_frame_base_locexpr_funcs);
27584   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27585                                         &dwarf2_block_frame_base_loclist_funcs);
27586
27587 #if GDB_SELF_TEST
27588   selftests::register_test ("dw2_expand_symtabs_matching",
27589                             selftests::dw2_expand_symtabs_matching::run_test);
27590 #endif
27591 }