Allocate abbrev_table with new
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 typedef struct symbol *symbolp;
91 DEF_VEC_P (symbolp);
92
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97
98 /* When non-zero, dump DIEs after they are read in.  */
99 static unsigned int dwarf_die_debug = 0;
100
101 /* When non-zero, dump line number entries as they are read in.  */
102 static unsigned int dwarf_line_debug = 0;
103
104 /* When non-zero, cross-check physname against demangler.  */
105 static int check_physname = 0;
106
107 /* When non-zero, do not reject deprecated .gdb_index sections.  */
108 static int use_deprecated_index_sections = 0;
109
110 static const struct objfile_data *dwarf2_objfile_data_key;
111
112 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
113
114 static int dwarf2_locexpr_index;
115 static int dwarf2_loclist_index;
116 static int dwarf2_locexpr_block_index;
117 static int dwarf2_loclist_block_index;
118
119 /* A descriptor for dwarf sections.
120
121    S.ASECTION, SIZE are typically initialized when the objfile is first
122    scanned.  BUFFER, READIN are filled in later when the section is read.
123    If the section contained compressed data then SIZE is updated to record
124    the uncompressed size of the section.
125
126    DWP file format V2 introduces a wrinkle that is easiest to handle by
127    creating the concept of virtual sections contained within a real section.
128    In DWP V2 the sections of the input DWO files are concatenated together
129    into one section, but section offsets are kept relative to the original
130    input section.
131    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
132    the real section this "virtual" section is contained in, and BUFFER,SIZE
133    describe the virtual section.  */
134
135 struct dwarf2_section_info
136 {
137   union
138   {
139     /* If this is a real section, the bfd section.  */
140     asection *section;
141     /* If this is a virtual section, pointer to the containing ("real")
142        section.  */
143     struct dwarf2_section_info *containing_section;
144   } s;
145   /* Pointer to section data, only valid if readin.  */
146   const gdb_byte *buffer;
147   /* The size of the section, real or virtual.  */
148   bfd_size_type size;
149   /* If this is a virtual section, the offset in the real section.
150      Only valid if is_virtual.  */
151   bfd_size_type virtual_offset;
152   /* True if we have tried to read this section.  */
153   char readin;
154   /* True if this is a virtual section, False otherwise.
155      This specifies which of s.section and s.containing_section to use.  */
156   char is_virtual;
157 };
158
159 typedef struct dwarf2_section_info dwarf2_section_info_def;
160 DEF_VEC_O (dwarf2_section_info_def);
161
162 /* All offsets in the index are of this type.  It must be
163    architecture-independent.  */
164 typedef uint32_t offset_type;
165
166 DEF_VEC_I (offset_type);
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((unsigned int) (value) <= 1); \
172     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
173   } while (0)
174
175 /* Ensure only legit values are used.  */
176 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
177   do { \
178     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
179                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
180     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
184 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
185   do { \
186     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
187     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
188   } while (0)
189
190 #if WORDS_BIGENDIAN
191
192 /* Convert VALUE between big- and little-endian.  */
193
194 static offset_type
195 byte_swap (offset_type value)
196 {
197   offset_type result;
198
199   result = (value & 0xff) << 24;
200   result |= (value & 0xff00) << 8;
201   result |= (value & 0xff0000) >> 8;
202   result |= (value & 0xff000000) >> 24;
203   return result;
204 }
205
206 #define MAYBE_SWAP(V)  byte_swap (V)
207
208 #else
209 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
210 #endif /* WORDS_BIGENDIAN */
211
212 /* An index into a (C++) symbol name component in a symbol name as
213    recorded in the mapped_index's symbol table.  For each C++ symbol
214    in the symbol table, we record one entry for the start of each
215    component in the symbol in a table of name components, and then
216    sort the table, in order to be able to binary search symbol names,
217    ignoring leading namespaces, both completion and regular look up.
218    For example, for symbol "A::B::C", we'll have an entry that points
219    to "A::B::C", another that points to "B::C", and another for "C".
220    Note that function symbols in GDB index have no parameter
221    information, just the function/method names.  You can convert a
222    name_component to a "const char *" using the
223    'mapped_index::symbol_name_at(offset_type)' method.  */
224
225 struct name_component
226 {
227   /* Offset in the symbol name where the component starts.  Stored as
228      a (32-bit) offset instead of a pointer to save memory and improve
229      locality on 64-bit architectures.  */
230   offset_type name_offset;
231
232   /* The symbol's index in the symbol and constant pool tables of a
233      mapped_index.  */
234   offset_type idx;
235 };
236
237 /* Base class containing bits shared by both .gdb_index and
238    .debug_name indexes.  */
239
240 struct mapped_index_base
241 {
242   /* The name_component table (a sorted vector).  See name_component's
243      description above.  */
244   std::vector<name_component> name_components;
245
246   /* How NAME_COMPONENTS is sorted.  */
247   enum case_sensitivity name_components_casing;
248
249   /* Return the number of names in the symbol table.  */
250   virtual size_t symbol_name_count () const = 0;
251
252   /* Get the name of the symbol at IDX in the symbol table.  */
253   virtual const char *symbol_name_at (offset_type idx) const = 0;
254
255   /* Return whether the name at IDX in the symbol table should be
256      ignored.  */
257   virtual bool symbol_name_slot_invalid (offset_type idx) const
258   {
259     return false;
260   }
261
262   /* Build the symbol name component sorted vector, if we haven't
263      yet.  */
264   void build_name_components ();
265
266   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
267      possible matches for LN_NO_PARAMS in the name component
268      vector.  */
269   std::pair<std::vector<name_component>::const_iterator,
270             std::vector<name_component>::const_iterator>
271     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
272
273   /* Prevent deleting/destroying via a base class pointer.  */
274 protected:
275   ~mapped_index_base() = default;
276 };
277
278 /* A description of the mapped index.  The file format is described in
279    a comment by the code that writes the index.  */
280 struct mapped_index final : public mapped_index_base
281 {
282   /* A slot/bucket in the symbol table hash.  */
283   struct symbol_table_slot
284   {
285     const offset_type name;
286     const offset_type vec;
287   };
288
289   /* Index data format version.  */
290   int version;
291
292   /* The total length of the buffer.  */
293   off_t total_size;
294
295   /* The address table data.  */
296   gdb::array_view<const gdb_byte> address_table;
297
298   /* The symbol table, implemented as a hash table.  */
299   gdb::array_view<symbol_table_slot> symbol_table;
300
301   /* A pointer to the constant pool.  */
302   const char *constant_pool;
303
304   bool symbol_name_slot_invalid (offset_type idx) const override
305   {
306     const auto &bucket = this->symbol_table[idx];
307     return bucket.name == 0 && bucket.vec;
308   }
309
310   /* Convenience method to get at the name of the symbol at IDX in the
311      symbol table.  */
312   const char *symbol_name_at (offset_type idx) const override
313   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
314
315   size_t symbol_name_count () const override
316   { return this->symbol_table.size (); }
317 };
318
319 /* A description of the mapped .debug_names.
320    Uninitialized map has CU_COUNT 0.  */
321 struct mapped_debug_names final : public mapped_index_base
322 {
323   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
324   : dwarf2_per_objfile (dwarf2_per_objfile_)
325   {}
326
327   struct dwarf2_per_objfile *dwarf2_per_objfile;
328   bfd_endian dwarf5_byte_order;
329   bool dwarf5_is_dwarf64;
330   bool augmentation_is_gdb;
331   uint8_t offset_size;
332   uint32_t cu_count = 0;
333   uint32_t tu_count, bucket_count, name_count;
334   const gdb_byte *cu_table_reordered, *tu_table_reordered;
335   const uint32_t *bucket_table_reordered, *hash_table_reordered;
336   const gdb_byte *name_table_string_offs_reordered;
337   const gdb_byte *name_table_entry_offs_reordered;
338   const gdb_byte *entry_pool;
339
340   struct index_val
341   {
342     ULONGEST dwarf_tag;
343     struct attr
344     {
345       /* Attribute name DW_IDX_*.  */
346       ULONGEST dw_idx;
347
348       /* Attribute form DW_FORM_*.  */
349       ULONGEST form;
350
351       /* Value if FORM is DW_FORM_implicit_const.  */
352       LONGEST implicit_const;
353     };
354     std::vector<attr> attr_vec;
355   };
356
357   std::unordered_map<ULONGEST, index_val> abbrev_map;
358
359   const char *namei_to_name (uint32_t namei) const;
360
361   /* Implementation of the mapped_index_base virtual interface, for
362      the name_components cache.  */
363
364   const char *symbol_name_at (offset_type idx) const override
365   { return namei_to_name (idx); }
366
367   size_t symbol_name_count () const override
368   { return this->name_count; }
369 };
370
371 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
372 DEF_VEC_P (dwarf2_per_cu_ptr);
373
374 struct tu_stats
375 {
376   int nr_uniq_abbrev_tables;
377   int nr_symtabs;
378   int nr_symtab_sharers;
379   int nr_stmt_less_type_units;
380   int nr_all_type_units_reallocs;
381 };
382
383 /* Collection of data recorded per objfile.
384    This hangs off of dwarf2_objfile_data_key.  */
385
386 struct dwarf2_per_objfile
387 {
388   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
389      dwarf2 section names, or is NULL if the standard ELF names are
390      used.  */
391   dwarf2_per_objfile (struct objfile *objfile,
392                       const dwarf2_debug_sections *names);
393
394   ~dwarf2_per_objfile ();
395
396   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
397
398   /* Free all cached compilation units.  */
399   void free_cached_comp_units ();
400 private:
401   /* This function is mapped across the sections and remembers the
402      offset and size of each of the debugging sections we are
403      interested in.  */
404   void locate_sections (bfd *abfd, asection *sectp,
405                         const dwarf2_debug_sections &names);
406
407 public:
408   dwarf2_section_info info {};
409   dwarf2_section_info abbrev {};
410   dwarf2_section_info line {};
411   dwarf2_section_info loc {};
412   dwarf2_section_info loclists {};
413   dwarf2_section_info macinfo {};
414   dwarf2_section_info macro {};
415   dwarf2_section_info str {};
416   dwarf2_section_info line_str {};
417   dwarf2_section_info ranges {};
418   dwarf2_section_info rnglists {};
419   dwarf2_section_info addr {};
420   dwarf2_section_info frame {};
421   dwarf2_section_info eh_frame {};
422   dwarf2_section_info gdb_index {};
423   dwarf2_section_info debug_names {};
424   dwarf2_section_info debug_aranges {};
425
426   VEC (dwarf2_section_info_def) *types = NULL;
427
428   /* Back link.  */
429   struct objfile *objfile = NULL;
430
431   /* Table of all the compilation units.  This is used to locate
432      the target compilation unit of a particular reference.  */
433   struct dwarf2_per_cu_data **all_comp_units = NULL;
434
435   /* The number of compilation units in ALL_COMP_UNITS.  */
436   int n_comp_units = 0;
437
438   /* The number of .debug_types-related CUs.  */
439   int n_type_units = 0;
440
441   /* The number of elements allocated in all_type_units.
442      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
443   int n_allocated_type_units = 0;
444
445   /* The .debug_types-related CUs (TUs).
446      This is stored in malloc space because we may realloc it.  */
447   struct signatured_type **all_type_units = NULL;
448
449   /* Table of struct type_unit_group objects.
450      The hash key is the DW_AT_stmt_list value.  */
451   htab_t type_unit_groups {};
452
453   /* A table mapping .debug_types signatures to its signatured_type entry.
454      This is NULL if the .debug_types section hasn't been read in yet.  */
455   htab_t signatured_types {};
456
457   /* Type unit statistics, to see how well the scaling improvements
458      are doing.  */
459   struct tu_stats tu_stats {};
460
461   /* A chain of compilation units that are currently read in, so that
462      they can be freed later.  */
463   dwarf2_per_cu_data *read_in_chain = NULL;
464
465   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
466      This is NULL if the table hasn't been allocated yet.  */
467   htab_t dwo_files {};
468
469   /* True if we've checked for whether there is a DWP file.  */
470   bool dwp_checked = false;
471
472   /* The DWP file if there is one, or NULL.  */
473   struct dwp_file *dwp_file = NULL;
474
475   /* The shared '.dwz' file, if one exists.  This is used when the
476      original data was compressed using 'dwz -m'.  */
477   struct dwz_file *dwz_file = NULL;
478
479   /* A flag indicating whether this objfile has a section loaded at a
480      VMA of 0.  */
481   bool has_section_at_zero = false;
482
483   /* True if we are using the mapped index,
484      or we are faking it for OBJF_READNOW's sake.  */
485   bool using_index = false;
486
487   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
488   mapped_index *index_table = NULL;
489
490   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
491   std::unique_ptr<mapped_debug_names> debug_names_table;
492
493   /* When using index_table, this keeps track of all quick_file_names entries.
494      TUs typically share line table entries with a CU, so we maintain a
495      separate table of all line table entries to support the sharing.
496      Note that while there can be way more TUs than CUs, we've already
497      sorted all the TUs into "type unit groups", grouped by their
498      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
499      CU and its associated TU group if there is one.  */
500   htab_t quick_file_names_table {};
501
502   /* Set during partial symbol reading, to prevent queueing of full
503      symbols.  */
504   bool reading_partial_symbols = false;
505
506   /* Table mapping type DIEs to their struct type *.
507      This is NULL if not allocated yet.
508      The mapping is done via (CU/TU + DIE offset) -> type.  */
509   htab_t die_type_hash {};
510
511   /* The CUs we recently read.  */
512   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
513
514   /* Table containing line_header indexed by offset and offset_in_dwz.  */
515   htab_t line_header_hash {};
516
517   /* Table containing all filenames.  This is an optional because the
518      table is lazily constructed on first access.  */
519   gdb::optional<filename_seen_cache> filenames_cache;
520 };
521
522 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
523
524 struct dwarf2_per_objfile *
525 get_dwarf2_per_objfile (struct objfile *objfile)
526 {
527   return ((struct dwarf2_per_objfile *)
528           objfile_data (objfile, dwarf2_objfile_data_key));
529 }
530
531 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
532
533 void
534 set_dwarf2_per_objfile (struct objfile *objfile,
535                         struct dwarf2_per_objfile *dwarf2_per_objfile)
536 {
537   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
538   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
539 }
540
541 /* Default names of the debugging sections.  */
542
543 /* Note that if the debugging section has been compressed, it might
544    have a name like .zdebug_info.  */
545
546 static const struct dwarf2_debug_sections dwarf2_elf_names =
547 {
548   { ".debug_info", ".zdebug_info" },
549   { ".debug_abbrev", ".zdebug_abbrev" },
550   { ".debug_line", ".zdebug_line" },
551   { ".debug_loc", ".zdebug_loc" },
552   { ".debug_loclists", ".zdebug_loclists" },
553   { ".debug_macinfo", ".zdebug_macinfo" },
554   { ".debug_macro", ".zdebug_macro" },
555   { ".debug_str", ".zdebug_str" },
556   { ".debug_line_str", ".zdebug_line_str" },
557   { ".debug_ranges", ".zdebug_ranges" },
558   { ".debug_rnglists", ".zdebug_rnglists" },
559   { ".debug_types", ".zdebug_types" },
560   { ".debug_addr", ".zdebug_addr" },
561   { ".debug_frame", ".zdebug_frame" },
562   { ".eh_frame", NULL },
563   { ".gdb_index", ".zgdb_index" },
564   { ".debug_names", ".zdebug_names" },
565   { ".debug_aranges", ".zdebug_aranges" },
566   23
567 };
568
569 /* List of DWO/DWP sections.  */
570
571 static const struct dwop_section_names
572 {
573   struct dwarf2_section_names abbrev_dwo;
574   struct dwarf2_section_names info_dwo;
575   struct dwarf2_section_names line_dwo;
576   struct dwarf2_section_names loc_dwo;
577   struct dwarf2_section_names loclists_dwo;
578   struct dwarf2_section_names macinfo_dwo;
579   struct dwarf2_section_names macro_dwo;
580   struct dwarf2_section_names str_dwo;
581   struct dwarf2_section_names str_offsets_dwo;
582   struct dwarf2_section_names types_dwo;
583   struct dwarf2_section_names cu_index;
584   struct dwarf2_section_names tu_index;
585 }
586 dwop_section_names =
587 {
588   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
589   { ".debug_info.dwo", ".zdebug_info.dwo" },
590   { ".debug_line.dwo", ".zdebug_line.dwo" },
591   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
592   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
593   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
594   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
595   { ".debug_str.dwo", ".zdebug_str.dwo" },
596   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
597   { ".debug_types.dwo", ".zdebug_types.dwo" },
598   { ".debug_cu_index", ".zdebug_cu_index" },
599   { ".debug_tu_index", ".zdebug_tu_index" },
600 };
601
602 /* local data types */
603
604 /* The data in a compilation unit header, after target2host
605    translation, looks like this.  */
606 struct comp_unit_head
607 {
608   unsigned int length;
609   short version;
610   unsigned char addr_size;
611   unsigned char signed_addr_p;
612   sect_offset abbrev_sect_off;
613
614   /* Size of file offsets; either 4 or 8.  */
615   unsigned int offset_size;
616
617   /* Size of the length field; either 4 or 12.  */
618   unsigned int initial_length_size;
619
620   enum dwarf_unit_type unit_type;
621
622   /* Offset to the first byte of this compilation unit header in the
623      .debug_info section, for resolving relative reference dies.  */
624   sect_offset sect_off;
625
626   /* Offset to first die in this cu from the start of the cu.
627      This will be the first byte following the compilation unit header.  */
628   cu_offset first_die_cu_offset;
629
630   /* 64-bit signature of this type unit - it is valid only for
631      UNIT_TYPE DW_UT_type.  */
632   ULONGEST signature;
633
634   /* For types, offset in the type's DIE of the type defined by this TU.  */
635   cu_offset type_cu_offset_in_tu;
636 };
637
638 /* Type used for delaying computation of method physnames.
639    See comments for compute_delayed_physnames.  */
640 struct delayed_method_info
641 {
642   /* The type to which the method is attached, i.e., its parent class.  */
643   struct type *type;
644
645   /* The index of the method in the type's function fieldlists.  */
646   int fnfield_index;
647
648   /* The index of the method in the fieldlist.  */
649   int index;
650
651   /* The name of the DIE.  */
652   const char *name;
653
654   /*  The DIE associated with this method.  */
655   struct die_info *die;
656 };
657
658 typedef struct delayed_method_info delayed_method_info;
659 DEF_VEC_O (delayed_method_info);
660
661 /* Internal state when decoding a particular compilation unit.  */
662 struct 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;
669
670   /* Non-zero if base_address has been set.  */
671   int base_known;
672
673   /* The language we are debugging.  */
674   enum language language;
675   const struct language_defn *language_defn;
676
677   const char *producer;
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;
689
690   /* Hash table holding all the loaded partial DIEs
691      with partial_die->offset.SECT_OFF as hash.  */
692   htab_t partial_dies;
693
694   /* Storage for things with the same lifetime as this read-in compilation
695      unit, including partial DIEs.  */
696   struct 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;
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;
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;
713
714   /* Full DIEs if read in.  */
715   struct die_info *dies;
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;
721
722   /* Header data from the line table, during full symbol processing.  */
723   struct line_header *line_header;
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;
730
731   /* A list of methods which need to have physnames computed
732      after all type information has been read.  */
733   VEC (delayed_method_info) *method_list;
734
735   /* To be copied to symtab->call_site_htab.  */
736   htab_t call_site_htab;
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;
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;
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;
765
766   /* Mark used when releasing cached dies.  */
767   unsigned int mark : 1;
768
769   /* This CU references .debug_loc.  See the symtab->locations_valid field.
770      This test is imperfect as there may exist optimized debug code not using
771      any location list and still facing inlining issues if handled as
772      unoptimized code.  For a future better test see GCC PR other/32998.  */
773   unsigned int has_loclist : 1;
774
775   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
776      if all the producer_is_* fields are valid.  This information is cached
777      because profiling CU expansion showed excessive time spent in
778      producer_is_gxx_lt_4_6.  */
779   unsigned int checked_producer : 1;
780   unsigned int producer_is_gxx_lt_4_6 : 1;
781   unsigned int producer_is_gcc_lt_4_3 : 1;
782   unsigned int producer_is_icc_lt_14 : 1;
783
784   /* When set, the file that we're processing is known to have
785      debugging info for C++ namespaces.  GCC 3.3.x did not produce
786      this information, but later versions do.  */
787
788   unsigned int processing_has_namespace_info : 1;
789 };
790
791 /* Persistent data held for a compilation unit, even when not
792    processing it.  We put a pointer to this structure in the
793    read_symtab_private field of the psymtab.  */
794
795 struct dwarf2_per_cu_data
796 {
797   /* The start offset and length of this compilation unit.
798      NOTE: Unlike comp_unit_head.length, this length includes
799      initial_length_size.
800      If the DIE refers to a DWO file, this is always of the original die,
801      not the DWO file.  */
802   sect_offset sect_off;
803   unsigned int length;
804
805   /* DWARF standard version this data has been read from (such as 4 or 5).  */
806   short dwarf_version;
807
808   /* Flag indicating this compilation unit will be read in before
809      any of the current compilation units are processed.  */
810   unsigned int queued : 1;
811
812   /* This flag will be set when reading partial DIEs if we need to load
813      absolutely all DIEs for this compilation unit, instead of just the ones
814      we think are interesting.  It gets set if we look for a DIE in the
815      hash table and don't find it.  */
816   unsigned int load_all_dies : 1;
817
818   /* Non-zero if this CU is from .debug_types.
819      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
820      this is non-zero.  */
821   unsigned int is_debug_types : 1;
822
823   /* Non-zero if this CU is from the .dwz file.  */
824   unsigned int is_dwz : 1;
825
826   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
827      This flag is only valid if is_debug_types is true.
828      We can't read a CU directly from a DWO file: There are required
829      attributes in the stub.  */
830   unsigned int reading_dwo_directly : 1;
831
832   /* Non-zero if the TU has been read.
833      This is used to assist the "Stay in DWO Optimization" for Fission:
834      When reading a DWO, it's faster to read TUs from the DWO instead of
835      fetching them from random other DWOs (due to comdat folding).
836      If the TU has already been read, the optimization is unnecessary
837      (and unwise - we don't want to change where gdb thinks the TU lives
838      "midflight").
839      This flag is only valid if is_debug_types is true.  */
840   unsigned int tu_read : 1;
841
842   /* The section this CU/TU lives in.
843      If the DIE refers to a DWO file, this is always the original die,
844      not the DWO file.  */
845   struct dwarf2_section_info *section;
846
847   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
848      of the CU cache it gets reset to NULL again.  This is left as NULL for
849      dummy CUs (a CU header, but nothing else).  */
850   struct dwarf2_cu *cu;
851
852   /* The corresponding dwarf2_per_objfile.  */
853   struct dwarf2_per_objfile *dwarf2_per_objfile;
854
855   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
856      is active.  Otherwise, the 'psymtab' field is active.  */
857   union
858   {
859     /* The partial symbol table associated with this compilation unit,
860        or NULL for unread partial units.  */
861     struct partial_symtab *psymtab;
862
863     /* Data needed by the "quick" functions.  */
864     struct dwarf2_per_cu_quick_data *quick;
865   } v;
866
867   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
868      while reading psymtabs, used to compute the psymtab dependencies,
869      and then cleared.  Then it is filled in again while reading full
870      symbols, and only deleted when the objfile is destroyed.
871
872      This is also used to work around a difference between the way gold
873      generates .gdb_index version <=7 and the way gdb does.  Arguably this
874      is a gold bug.  For symbols coming from TUs, gold records in the index
875      the CU that includes the TU instead of the TU itself.  This breaks
876      dw2_lookup_symbol: It assumes that if the index says symbol X lives
877      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
878      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
879      we need to look in TU Z to find X.  Fortunately, this is akin to
880      DW_TAG_imported_unit, so we just use the same mechanism: For
881      .gdb_index version <=7 this also records the TUs that the CU referred
882      to.  Concurrently with this change gdb was modified to emit version 8
883      indices so we only pay a price for gold generated indices.
884      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
885   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
886 };
887
888 /* Entry in the signatured_types hash table.  */
889
890 struct signatured_type
891 {
892   /* The "per_cu" object of this type.
893      This struct is used iff per_cu.is_debug_types.
894      N.B.: This is the first member so that it's easy to convert pointers
895      between them.  */
896   struct dwarf2_per_cu_data per_cu;
897
898   /* The type's signature.  */
899   ULONGEST signature;
900
901   /* Offset in the TU of the type's DIE, as read from the TU header.
902      If this TU is a DWO stub and the definition lives in a DWO file
903      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
904   cu_offset type_offset_in_tu;
905
906   /* Offset in the section of the type's DIE.
907      If the definition lives in a DWO file, this is the offset in the
908      .debug_types.dwo section.
909      The value is zero until the actual value is known.
910      Zero is otherwise not a valid section offset.  */
911   sect_offset type_offset_in_section;
912
913   /* Type units are grouped by their DW_AT_stmt_list entry so that they
914      can share them.  This points to the containing symtab.  */
915   struct type_unit_group *type_unit_group;
916
917   /* The type.
918      The first time we encounter this type we fully read it in and install it
919      in the symbol tables.  Subsequent times we only need the type.  */
920   struct type *type;
921
922   /* Containing DWO unit.
923      This field is valid iff per_cu.reading_dwo_directly.  */
924   struct dwo_unit *dwo_unit;
925 };
926
927 typedef struct signatured_type *sig_type_ptr;
928 DEF_VEC_P (sig_type_ptr);
929
930 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
931    This includes type_unit_group and quick_file_names.  */
932
933 struct stmt_list_hash
934 {
935   /* The DWO unit this table is from or NULL if there is none.  */
936   struct dwo_unit *dwo_unit;
937
938   /* Offset in .debug_line or .debug_line.dwo.  */
939   sect_offset line_sect_off;
940 };
941
942 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
943    an object of this type.  */
944
945 struct type_unit_group
946 {
947   /* dwarf2read.c's main "handle" on a TU symtab.
948      To simplify things we create an artificial CU that "includes" all the
949      type units using this stmt_list so that the rest of the code still has
950      a "per_cu" handle on the symtab.
951      This PER_CU is recognized by having no section.  */
952 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
953   struct dwarf2_per_cu_data per_cu;
954
955   /* The TUs that share this DW_AT_stmt_list entry.
956      This is added to while parsing type units to build partial symtabs,
957      and is deleted afterwards and not used again.  */
958   VEC (sig_type_ptr) *tus;
959
960   /* The compunit symtab.
961      Type units in a group needn't all be defined in the same source file,
962      so we create an essentially anonymous symtab as the compunit symtab.  */
963   struct compunit_symtab *compunit_symtab;
964
965   /* The data used to construct the hash key.  */
966   struct stmt_list_hash hash;
967
968   /* The number of symtabs from the line header.
969      The value here must match line_header.num_file_names.  */
970   unsigned int num_symtabs;
971
972   /* The symbol tables for this TU (obtained from the files listed in
973      DW_AT_stmt_list).
974      WARNING: The order of entries here must match the order of entries
975      in the line header.  After the first TU using this type_unit_group, the
976      line header for the subsequent TUs is recreated from this.  This is done
977      because we need to use the same symtabs for each TU using the same
978      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
979      there's no guarantee the line header doesn't have duplicate entries.  */
980   struct symtab **symtabs;
981 };
982
983 /* These sections are what may appear in a (real or virtual) DWO file.  */
984
985 struct dwo_sections
986 {
987   struct dwarf2_section_info abbrev;
988   struct dwarf2_section_info line;
989   struct dwarf2_section_info loc;
990   struct dwarf2_section_info loclists;
991   struct dwarf2_section_info macinfo;
992   struct dwarf2_section_info macro;
993   struct dwarf2_section_info str;
994   struct dwarf2_section_info str_offsets;
995   /* In the case of a virtual DWO file, these two are unused.  */
996   struct dwarf2_section_info info;
997   VEC (dwarf2_section_info_def) *types;
998 };
999
1000 /* CUs/TUs in DWP/DWO files.  */
1001
1002 struct dwo_unit
1003 {
1004   /* Backlink to the containing struct dwo_file.  */
1005   struct dwo_file *dwo_file;
1006
1007   /* The "id" that distinguishes this CU/TU.
1008      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1009      Since signatures came first, we stick with it for consistency.  */
1010   ULONGEST signature;
1011
1012   /* The section this CU/TU lives in, in the DWO file.  */
1013   struct dwarf2_section_info *section;
1014
1015   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1016   sect_offset sect_off;
1017   unsigned int length;
1018
1019   /* For types, offset in the type's DIE of the type defined by this TU.  */
1020   cu_offset type_offset_in_tu;
1021 };
1022
1023 /* include/dwarf2.h defines the DWP section codes.
1024    It defines a max value but it doesn't define a min value, which we
1025    use for error checking, so provide one.  */
1026
1027 enum dwp_v2_section_ids
1028 {
1029   DW_SECT_MIN = 1
1030 };
1031
1032 /* Data for one DWO file.
1033
1034    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1035    appears in a DWP file).  DWP files don't really have DWO files per se -
1036    comdat folding of types "loses" the DWO file they came from, and from
1037    a high level view DWP files appear to contain a mass of random types.
1038    However, to maintain consistency with the non-DWP case we pretend DWP
1039    files contain virtual DWO files, and we assign each TU with one virtual
1040    DWO file (generally based on the line and abbrev section offsets -
1041    a heuristic that seems to work in practice).  */
1042
1043 struct dwo_file
1044 {
1045   /* The DW_AT_GNU_dwo_name attribute.
1046      For virtual DWO files the name is constructed from the section offsets
1047      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1048      from related CU+TUs.  */
1049   const char *dwo_name;
1050
1051   /* The DW_AT_comp_dir attribute.  */
1052   const char *comp_dir;
1053
1054   /* The bfd, when the file is open.  Otherwise this is NULL.
1055      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1056   bfd *dbfd;
1057
1058   /* The sections that make up this DWO file.
1059      Remember that for virtual DWO files in DWP V2, these are virtual
1060      sections (for lack of a better name).  */
1061   struct dwo_sections sections;
1062
1063   /* The CUs in the file.
1064      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1065      an extension to handle LLVM's Link Time Optimization output (where
1066      multiple source files may be compiled into a single object/dwo pair). */
1067   htab_t cus;
1068
1069   /* Table of TUs in the file.
1070      Each element is a struct dwo_unit.  */
1071   htab_t tus;
1072 };
1073
1074 /* These sections are what may appear in a DWP file.  */
1075
1076 struct dwp_sections
1077 {
1078   /* These are used by both DWP version 1 and 2.  */
1079   struct dwarf2_section_info str;
1080   struct dwarf2_section_info cu_index;
1081   struct dwarf2_section_info tu_index;
1082
1083   /* These are only used by DWP version 2 files.
1084      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1085      sections are referenced by section number, and are not recorded here.
1086      In DWP version 2 there is at most one copy of all these sections, each
1087      section being (effectively) comprised of the concatenation of all of the
1088      individual sections that exist in the version 1 format.
1089      To keep the code simple we treat each of these concatenated pieces as a
1090      section itself (a virtual section?).  */
1091   struct dwarf2_section_info abbrev;
1092   struct dwarf2_section_info info;
1093   struct dwarf2_section_info line;
1094   struct dwarf2_section_info loc;
1095   struct dwarf2_section_info macinfo;
1096   struct dwarf2_section_info macro;
1097   struct dwarf2_section_info str_offsets;
1098   struct dwarf2_section_info types;
1099 };
1100
1101 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1102    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1103
1104 struct virtual_v1_dwo_sections
1105 {
1106   struct dwarf2_section_info abbrev;
1107   struct dwarf2_section_info line;
1108   struct dwarf2_section_info loc;
1109   struct dwarf2_section_info macinfo;
1110   struct dwarf2_section_info macro;
1111   struct dwarf2_section_info str_offsets;
1112   /* Each DWP hash table entry records one CU or one TU.
1113      That is recorded here, and copied to dwo_unit.section.  */
1114   struct dwarf2_section_info info_or_types;
1115 };
1116
1117 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1118    In version 2, the sections of the DWO files are concatenated together
1119    and stored in one section of that name.  Thus each ELF section contains
1120    several "virtual" sections.  */
1121
1122 struct virtual_v2_dwo_sections
1123 {
1124   bfd_size_type abbrev_offset;
1125   bfd_size_type abbrev_size;
1126
1127   bfd_size_type line_offset;
1128   bfd_size_type line_size;
1129
1130   bfd_size_type loc_offset;
1131   bfd_size_type loc_size;
1132
1133   bfd_size_type macinfo_offset;
1134   bfd_size_type macinfo_size;
1135
1136   bfd_size_type macro_offset;
1137   bfd_size_type macro_size;
1138
1139   bfd_size_type str_offsets_offset;
1140   bfd_size_type str_offsets_size;
1141
1142   /* Each DWP hash table entry records one CU or one TU.
1143      That is recorded here, and copied to dwo_unit.section.  */
1144   bfd_size_type info_or_types_offset;
1145   bfd_size_type info_or_types_size;
1146 };
1147
1148 /* Contents of DWP hash tables.  */
1149
1150 struct dwp_hash_table
1151 {
1152   uint32_t version, nr_columns;
1153   uint32_t nr_units, nr_slots;
1154   const gdb_byte *hash_table, *unit_table;
1155   union
1156   {
1157     struct
1158     {
1159       const gdb_byte *indices;
1160     } v1;
1161     struct
1162     {
1163       /* This is indexed by column number and gives the id of the section
1164          in that column.  */
1165 #define MAX_NR_V2_DWO_SECTIONS \
1166   (1 /* .debug_info or .debug_types */ \
1167    + 1 /* .debug_abbrev */ \
1168    + 1 /* .debug_line */ \
1169    + 1 /* .debug_loc */ \
1170    + 1 /* .debug_str_offsets */ \
1171    + 1 /* .debug_macro or .debug_macinfo */)
1172       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1173       const gdb_byte *offsets;
1174       const gdb_byte *sizes;
1175     } v2;
1176   } section_pool;
1177 };
1178
1179 /* Data for one DWP file.  */
1180
1181 struct dwp_file
1182 {
1183   /* Name of the file.  */
1184   const char *name;
1185
1186   /* File format version.  */
1187   int version;
1188
1189   /* The bfd.  */
1190   bfd *dbfd;
1191
1192   /* Section info for this file.  */
1193   struct dwp_sections sections;
1194
1195   /* Table of CUs in the file.  */
1196   const struct dwp_hash_table *cus;
1197
1198   /* Table of TUs in the file.  */
1199   const struct dwp_hash_table *tus;
1200
1201   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1202   htab_t loaded_cus;
1203   htab_t loaded_tus;
1204
1205   /* Table to map ELF section numbers to their sections.
1206      This is only needed for the DWP V1 file format.  */
1207   unsigned int num_sections;
1208   asection **elf_sections;
1209 };
1210
1211 /* This represents a '.dwz' file.  */
1212
1213 struct dwz_file
1214 {
1215   /* A dwz file can only contain a few sections.  */
1216   struct dwarf2_section_info abbrev;
1217   struct dwarf2_section_info info;
1218   struct dwarf2_section_info str;
1219   struct dwarf2_section_info line;
1220   struct dwarf2_section_info macro;
1221   struct dwarf2_section_info gdb_index;
1222   struct dwarf2_section_info debug_names;
1223
1224   /* The dwz's BFD.  */
1225   bfd *dwz_bfd;
1226 };
1227
1228 /* Struct used to pass misc. parameters to read_die_and_children, et
1229    al.  which are used for both .debug_info and .debug_types dies.
1230    All parameters here are unchanging for the life of the call.  This
1231    struct exists to abstract away the constant parameters of die reading.  */
1232
1233 struct die_reader_specs
1234 {
1235   /* The bfd of die_section.  */
1236   bfd* abfd;
1237
1238   /* The CU of the DIE we are parsing.  */
1239   struct dwarf2_cu *cu;
1240
1241   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1242   struct dwo_file *dwo_file;
1243
1244   /* The section the die comes from.
1245      This is either .debug_info or .debug_types, or the .dwo variants.  */
1246   struct dwarf2_section_info *die_section;
1247
1248   /* die_section->buffer.  */
1249   const gdb_byte *buffer;
1250
1251   /* The end of the buffer.  */
1252   const gdb_byte *buffer_end;
1253
1254   /* The value of the DW_AT_comp_dir attribute.  */
1255   const char *comp_dir;
1256
1257   /* The abbreviation table to use when reading the DIEs.  */
1258   struct abbrev_table *abbrev_table;
1259 };
1260
1261 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1262 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1263                                       const gdb_byte *info_ptr,
1264                                       struct die_info *comp_unit_die,
1265                                       int has_children,
1266                                       void *data);
1267
1268 /* A 1-based directory index.  This is a strong typedef to prevent
1269    accidentally using a directory index as a 0-based index into an
1270    array/vector.  */
1271 enum class dir_index : unsigned int {};
1272
1273 /* Likewise, a 1-based file name index.  */
1274 enum class file_name_index : unsigned int {};
1275
1276 struct file_entry
1277 {
1278   file_entry () = default;
1279
1280   file_entry (const char *name_, dir_index d_index_,
1281               unsigned int mod_time_, unsigned int length_)
1282     : name (name_),
1283       d_index (d_index_),
1284       mod_time (mod_time_),
1285       length (length_)
1286   {}
1287
1288   /* Return the include directory at D_INDEX stored in LH.  Returns
1289      NULL if D_INDEX is out of bounds.  */
1290   const char *include_dir (const line_header *lh) const;
1291
1292   /* The file name.  Note this is an observing pointer.  The memory is
1293      owned by debug_line_buffer.  */
1294   const char *name {};
1295
1296   /* The directory index (1-based).  */
1297   dir_index d_index {};
1298
1299   unsigned int mod_time {};
1300
1301   unsigned int length {};
1302
1303   /* True if referenced by the Line Number Program.  */
1304   bool included_p {};
1305
1306   /* The associated symbol table, if any.  */
1307   struct symtab *symtab {};
1308 };
1309
1310 /* The line number information for a compilation unit (found in the
1311    .debug_line section) begins with a "statement program header",
1312    which contains the following information.  */
1313 struct line_header
1314 {
1315   line_header ()
1316     : offset_in_dwz {}
1317   {}
1318
1319   /* Add an entry to the include directory table.  */
1320   void add_include_dir (const char *include_dir);
1321
1322   /* Add an entry to the file name table.  */
1323   void add_file_name (const char *name, dir_index d_index,
1324                       unsigned int mod_time, unsigned int length);
1325
1326   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1327      is out of bounds.  */
1328   const char *include_dir_at (dir_index index) const
1329   {
1330     /* Convert directory index number (1-based) to vector index
1331        (0-based).  */
1332     size_t vec_index = to_underlying (index) - 1;
1333
1334     if (vec_index >= include_dirs.size ())
1335       return NULL;
1336     return include_dirs[vec_index];
1337   }
1338
1339   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1340      is out of bounds.  */
1341   file_entry *file_name_at (file_name_index index)
1342   {
1343     /* Convert file name index number (1-based) to vector index
1344        (0-based).  */
1345     size_t vec_index = to_underlying (index) - 1;
1346
1347     if (vec_index >= file_names.size ())
1348       return NULL;
1349     return &file_names[vec_index];
1350   }
1351
1352   /* Const version of the above.  */
1353   const file_entry *file_name_at (unsigned int index) const
1354   {
1355     if (index >= file_names.size ())
1356       return NULL;
1357     return &file_names[index];
1358   }
1359
1360   /* Offset of line number information in .debug_line section.  */
1361   sect_offset sect_off {};
1362
1363   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1364   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1365
1366   unsigned int total_length {};
1367   unsigned short version {};
1368   unsigned int header_length {};
1369   unsigned char minimum_instruction_length {};
1370   unsigned char maximum_ops_per_instruction {};
1371   unsigned char default_is_stmt {};
1372   int line_base {};
1373   unsigned char line_range {};
1374   unsigned char opcode_base {};
1375
1376   /* standard_opcode_lengths[i] is the number of operands for the
1377      standard opcode whose value is i.  This means that
1378      standard_opcode_lengths[0] is unused, and the last meaningful
1379      element is standard_opcode_lengths[opcode_base - 1].  */
1380   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1381
1382   /* The include_directories table.  Note these are observing
1383      pointers.  The memory is owned by debug_line_buffer.  */
1384   std::vector<const char *> include_dirs;
1385
1386   /* The file_names table.  */
1387   std::vector<file_entry> file_names;
1388
1389   /* The start and end of the statement program following this
1390      header.  These point into dwarf2_per_objfile->line_buffer.  */
1391   const gdb_byte *statement_program_start {}, *statement_program_end {};
1392 };
1393
1394 typedef std::unique_ptr<line_header> line_header_up;
1395
1396 const char *
1397 file_entry::include_dir (const line_header *lh) const
1398 {
1399   return lh->include_dir_at (d_index);
1400 }
1401
1402 /* When we construct a partial symbol table entry we only
1403    need this much information.  */
1404 struct partial_die_info
1405   {
1406     /* Offset of this DIE.  */
1407     sect_offset sect_off;
1408
1409     /* DWARF-2 tag for this DIE.  */
1410     ENUM_BITFIELD(dwarf_tag) tag : 16;
1411
1412     /* Assorted flags describing the data found in this DIE.  */
1413     unsigned int has_children : 1;
1414     unsigned int is_external : 1;
1415     unsigned int is_declaration : 1;
1416     unsigned int has_type : 1;
1417     unsigned int has_specification : 1;
1418     unsigned int has_pc_info : 1;
1419     unsigned int may_be_inlined : 1;
1420
1421     /* This DIE has been marked DW_AT_main_subprogram.  */
1422     unsigned int main_subprogram : 1;
1423
1424     /* Flag set if the SCOPE field of this structure has been
1425        computed.  */
1426     unsigned int scope_set : 1;
1427
1428     /* Flag set if the DIE has a byte_size attribute.  */
1429     unsigned int has_byte_size : 1;
1430
1431     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1432     unsigned int has_const_value : 1;
1433
1434     /* Flag set if any of the DIE's children are template arguments.  */
1435     unsigned int has_template_arguments : 1;
1436
1437     /* Flag set if fixup_partial_die has been called on this die.  */
1438     unsigned int fixup_called : 1;
1439
1440     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1441     unsigned int is_dwz : 1;
1442
1443     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1444     unsigned int spec_is_dwz : 1;
1445
1446     /* The name of this DIE.  Normally the value of DW_AT_name, but
1447        sometimes a default name for unnamed DIEs.  */
1448     const char *name;
1449
1450     /* The linkage name, if present.  */
1451     const char *linkage_name;
1452
1453     /* The scope to prepend to our children.  This is generally
1454        allocated on the comp_unit_obstack, so will disappear
1455        when this compilation unit leaves the cache.  */
1456     const char *scope;
1457
1458     /* Some data associated with the partial DIE.  The tag determines
1459        which field is live.  */
1460     union
1461     {
1462       /* The location description associated with this DIE, if any.  */
1463       struct dwarf_block *locdesc;
1464       /* The offset of an import, for DW_TAG_imported_unit.  */
1465       sect_offset sect_off;
1466     } d;
1467
1468     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1469     CORE_ADDR lowpc;
1470     CORE_ADDR highpc;
1471
1472     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1473        DW_AT_sibling, if any.  */
1474     /* NOTE: This member isn't strictly necessary, read_partial_die could
1475        return DW_AT_sibling values to its caller load_partial_dies.  */
1476     const gdb_byte *sibling;
1477
1478     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1479        DW_AT_specification (or DW_AT_abstract_origin or
1480        DW_AT_extension).  */
1481     sect_offset spec_offset;
1482
1483     /* Pointers to this DIE's parent, first child, and next sibling,
1484        if any.  */
1485     struct partial_die_info *die_parent, *die_child, *die_sibling;
1486   };
1487
1488 /* This data structure holds the information of an abbrev.  */
1489 struct abbrev_info
1490   {
1491     unsigned int number;        /* number identifying abbrev */
1492     enum dwarf_tag tag;         /* dwarf tag */
1493     unsigned short has_children;                /* boolean */
1494     unsigned short num_attrs;   /* number of attributes */
1495     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1496     struct abbrev_info *next;   /* next in chain */
1497   };
1498
1499 struct attr_abbrev
1500   {
1501     ENUM_BITFIELD(dwarf_attribute) name : 16;
1502     ENUM_BITFIELD(dwarf_form) form : 16;
1503
1504     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1505     LONGEST implicit_const;
1506   };
1507
1508 /* Size of abbrev_table.abbrev_hash_table.  */
1509 #define ABBREV_HASH_SIZE 121
1510
1511 /* Top level data structure to contain an abbreviation table.  */
1512
1513 struct abbrev_table
1514 {
1515   explicit abbrev_table (sect_offset off)
1516     : sect_off (off)
1517   {
1518     abbrevs =
1519       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1520     memset (abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1521   }
1522
1523   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1524
1525   /* Allocate space for a struct abbrev_info object in
1526      ABBREV_TABLE.  */
1527   struct abbrev_info *alloc_abbrev ();
1528
1529   /* Add an abbreviation to the table.  */
1530   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1531
1532   /* Look up an abbrev in the table.
1533      Returns NULL if the abbrev is not found.  */
1534
1535   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1536
1537
1538   /* Where the abbrev table came from.
1539      This is used as a sanity check when the table is used.  */
1540   const sect_offset sect_off;
1541
1542   /* Storage for the abbrev table.  */
1543   auto_obstack abbrev_obstack;
1544
1545   /* Hash table of abbrevs.
1546      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1547      It could be statically allocated, but the previous code didn't so we
1548      don't either.  */
1549   struct abbrev_info **abbrevs;
1550 };
1551
1552 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1553
1554 /* Attributes have a name and a value.  */
1555 struct attribute
1556   {
1557     ENUM_BITFIELD(dwarf_attribute) name : 16;
1558     ENUM_BITFIELD(dwarf_form) form : 15;
1559
1560     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1561        field should be in u.str (existing only for DW_STRING) but it is kept
1562        here for better struct attribute alignment.  */
1563     unsigned int string_is_canonical : 1;
1564
1565     union
1566       {
1567         const char *str;
1568         struct dwarf_block *blk;
1569         ULONGEST unsnd;
1570         LONGEST snd;
1571         CORE_ADDR addr;
1572         ULONGEST signature;
1573       }
1574     u;
1575   };
1576
1577 /* This data structure holds a complete die structure.  */
1578 struct die_info
1579   {
1580     /* DWARF-2 tag for this DIE.  */
1581     ENUM_BITFIELD(dwarf_tag) tag : 16;
1582
1583     /* Number of attributes */
1584     unsigned char num_attrs;
1585
1586     /* True if we're presently building the full type name for the
1587        type derived from this DIE.  */
1588     unsigned char building_fullname : 1;
1589
1590     /* True if this die is in process.  PR 16581.  */
1591     unsigned char in_process : 1;
1592
1593     /* Abbrev number */
1594     unsigned int abbrev;
1595
1596     /* Offset in .debug_info or .debug_types section.  */
1597     sect_offset sect_off;
1598
1599     /* The dies in a compilation unit form an n-ary tree.  PARENT
1600        points to this die's parent; CHILD points to the first child of
1601        this node; and all the children of a given node are chained
1602        together via their SIBLING fields.  */
1603     struct die_info *child;     /* Its first child, if any.  */
1604     struct die_info *sibling;   /* Its next sibling, if any.  */
1605     struct die_info *parent;    /* Its parent, if any.  */
1606
1607     /* An array of attributes, with NUM_ATTRS elements.  There may be
1608        zero, but it's not common and zero-sized arrays are not
1609        sufficiently portable C.  */
1610     struct attribute attrs[1];
1611   };
1612
1613 /* Get at parts of an attribute structure.  */
1614
1615 #define DW_STRING(attr)    ((attr)->u.str)
1616 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1617 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1618 #define DW_BLOCK(attr)     ((attr)->u.blk)
1619 #define DW_SND(attr)       ((attr)->u.snd)
1620 #define DW_ADDR(attr)      ((attr)->u.addr)
1621 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1622
1623 /* Blocks are a bunch of untyped bytes.  */
1624 struct dwarf_block
1625   {
1626     size_t size;
1627
1628     /* Valid only if SIZE is not zero.  */
1629     const gdb_byte *data;
1630   };
1631
1632 #ifndef ATTR_ALLOC_CHUNK
1633 #define ATTR_ALLOC_CHUNK 4
1634 #endif
1635
1636 /* Allocate fields for structs, unions and enums in this size.  */
1637 #ifndef DW_FIELD_ALLOC_CHUNK
1638 #define DW_FIELD_ALLOC_CHUNK 4
1639 #endif
1640
1641 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1642    but this would require a corresponding change in unpack_field_as_long
1643    and friends.  */
1644 static int bits_per_byte = 8;
1645
1646 struct nextfield
1647 {
1648   struct nextfield *next;
1649   int accessibility;
1650   int virtuality;
1651   struct field field;
1652 };
1653
1654 struct nextfnfield
1655 {
1656   struct nextfnfield *next;
1657   struct fn_field fnfield;
1658 };
1659
1660 struct fnfieldlist
1661 {
1662   const char *name;
1663   int length;
1664   struct nextfnfield *head;
1665 };
1666
1667 struct decl_field_list
1668 {
1669   struct decl_field field;
1670   struct decl_field_list *next;
1671 };
1672
1673 /* The routines that read and process dies for a C struct or C++ class
1674    pass lists of data member fields and lists of member function fields
1675    in an instance of a field_info structure, as defined below.  */
1676 struct field_info
1677   {
1678     /* List of data member and baseclasses fields.  */
1679     struct nextfield *fields, *baseclasses;
1680
1681     /* Number of fields (including baseclasses).  */
1682     int nfields;
1683
1684     /* Number of baseclasses.  */
1685     int nbaseclasses;
1686
1687     /* Set if the accesibility of one of the fields is not public.  */
1688     int non_public_fields;
1689
1690     /* Member function fieldlist array, contains name of possibly overloaded
1691        member function, number of overloaded member functions and a pointer
1692        to the head of the member function field chain.  */
1693     struct fnfieldlist *fnfieldlists;
1694
1695     /* Number of entries in the fnfieldlists array.  */
1696     int nfnfields;
1697
1698     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1699        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1700     struct decl_field_list *typedef_field_list;
1701     unsigned typedef_field_list_count;
1702
1703     /* Nested types defined by this class and the number of elements in this
1704        list.  */
1705     struct decl_field_list *nested_types_list;
1706     unsigned nested_types_list_count;
1707   };
1708
1709 /* One item on the queue of compilation units to read in full symbols
1710    for.  */
1711 struct dwarf2_queue_item
1712 {
1713   struct dwarf2_per_cu_data *per_cu;
1714   enum language pretend_language;
1715   struct dwarf2_queue_item *next;
1716 };
1717
1718 /* The current queue.  */
1719 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1720
1721 /* Loaded secondary compilation units are kept in memory until they
1722    have not been referenced for the processing of this many
1723    compilation units.  Set this to zero to disable caching.  Cache
1724    sizes of up to at least twenty will improve startup time for
1725    typical inter-CU-reference binaries, at an obvious memory cost.  */
1726 static int dwarf_max_cache_age = 5;
1727 static void
1728 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1729                           struct cmd_list_element *c, const char *value)
1730 {
1731   fprintf_filtered (file, _("The upper bound on the age of cached "
1732                             "DWARF compilation units is %s.\n"),
1733                     value);
1734 }
1735 \f
1736 /* local function prototypes */
1737
1738 static const char *get_section_name (const struct dwarf2_section_info *);
1739
1740 static const char *get_section_file_name (const struct dwarf2_section_info *);
1741
1742 static void dwarf2_find_base_address (struct die_info *die,
1743                                       struct dwarf2_cu *cu);
1744
1745 static struct partial_symtab *create_partial_symtab
1746   (struct dwarf2_per_cu_data *per_cu, const char *name);
1747
1748 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1749                                         const gdb_byte *info_ptr,
1750                                         struct die_info *type_unit_die,
1751                                         int has_children, void *data);
1752
1753 static void dwarf2_build_psymtabs_hard
1754   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1755
1756 static void scan_partial_symbols (struct partial_die_info *,
1757                                   CORE_ADDR *, CORE_ADDR *,
1758                                   int, struct dwarf2_cu *);
1759
1760 static void add_partial_symbol (struct partial_die_info *,
1761                                 struct dwarf2_cu *);
1762
1763 static void add_partial_namespace (struct partial_die_info *pdi,
1764                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1765                                    int set_addrmap, struct dwarf2_cu *cu);
1766
1767 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1768                                 CORE_ADDR *highpc, int set_addrmap,
1769                                 struct dwarf2_cu *cu);
1770
1771 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1772                                      struct dwarf2_cu *cu);
1773
1774 static void add_partial_subprogram (struct partial_die_info *pdi,
1775                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1776                                     int need_pc, struct dwarf2_cu *cu);
1777
1778 static void dwarf2_read_symtab (struct partial_symtab *,
1779                                 struct objfile *);
1780
1781 static void psymtab_to_symtab_1 (struct partial_symtab *);
1782
1783 static abbrev_table_up abbrev_table_read_table
1784   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1785    sect_offset);
1786
1787 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1788
1789 static struct partial_die_info *load_partial_dies
1790   (const struct die_reader_specs *, const gdb_byte *, int);
1791
1792 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1793                                          struct partial_die_info *,
1794                                          struct abbrev_info *,
1795                                          unsigned int,
1796                                          const gdb_byte *);
1797
1798 static struct partial_die_info *find_partial_die (sect_offset, int,
1799                                                   struct dwarf2_cu *);
1800
1801 static void fixup_partial_die (struct partial_die_info *,
1802                                struct dwarf2_cu *);
1803
1804 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1805                                        struct attribute *, struct attr_abbrev *,
1806                                        const gdb_byte *);
1807
1808 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1809
1810 static int read_1_signed_byte (bfd *, const gdb_byte *);
1811
1812 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1813
1814 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1815
1816 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1817
1818 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1819                                unsigned int *);
1820
1821 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1822
1823 static LONGEST read_checked_initial_length_and_offset
1824   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1825    unsigned int *, unsigned int *);
1826
1827 static LONGEST read_offset (bfd *, const gdb_byte *,
1828                             const struct comp_unit_head *,
1829                             unsigned int *);
1830
1831 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1832
1833 static sect_offset read_abbrev_offset
1834   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1835    struct dwarf2_section_info *, sect_offset);
1836
1837 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1838
1839 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1840
1841 static const char *read_indirect_string
1842   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1843    const struct comp_unit_head *, unsigned int *);
1844
1845 static const char *read_indirect_line_string
1846   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1847    const struct comp_unit_head *, unsigned int *);
1848
1849 static const char *read_indirect_string_at_offset
1850   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1851    LONGEST str_offset);
1852
1853 static const char *read_indirect_string_from_dwz
1854   (struct objfile *objfile, struct dwz_file *, LONGEST);
1855
1856 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1857
1858 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1859                                               const gdb_byte *,
1860                                               unsigned int *);
1861
1862 static const char *read_str_index (const struct die_reader_specs *reader,
1863                                    ULONGEST str_index);
1864
1865 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1866
1867 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1868                                       struct dwarf2_cu *);
1869
1870 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1871                                                 unsigned int);
1872
1873 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1874                                        struct dwarf2_cu *cu);
1875
1876 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1877                                struct dwarf2_cu *cu);
1878
1879 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1880
1881 static struct die_info *die_specification (struct die_info *die,
1882                                            struct dwarf2_cu **);
1883
1884 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1885                                                 struct dwarf2_cu *cu);
1886
1887 static void dwarf_decode_lines (struct line_header *, const char *,
1888                                 struct dwarf2_cu *, struct partial_symtab *,
1889                                 CORE_ADDR, int decode_mapping);
1890
1891 static void dwarf2_start_subfile (const char *, const char *);
1892
1893 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1894                                                     const char *, const char *,
1895                                                     CORE_ADDR);
1896
1897 static struct symbol *new_symbol (struct die_info *, struct type *,
1898                                   struct dwarf2_cu *, struct symbol * = NULL);
1899
1900 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1901                                 struct dwarf2_cu *);
1902
1903 static void dwarf2_const_value_attr (const struct attribute *attr,
1904                                      struct type *type,
1905                                      const char *name,
1906                                      struct obstack *obstack,
1907                                      struct dwarf2_cu *cu, LONGEST *value,
1908                                      const gdb_byte **bytes,
1909                                      struct dwarf2_locexpr_baton **baton);
1910
1911 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1912
1913 static int need_gnat_info (struct dwarf2_cu *);
1914
1915 static struct type *die_descriptive_type (struct die_info *,
1916                                           struct dwarf2_cu *);
1917
1918 static void set_descriptive_type (struct type *, struct die_info *,
1919                                   struct dwarf2_cu *);
1920
1921 static struct type *die_containing_type (struct die_info *,
1922                                          struct dwarf2_cu *);
1923
1924 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1925                                      struct dwarf2_cu *);
1926
1927 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1928
1929 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1930
1931 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1932
1933 static char *typename_concat (struct obstack *obs, const char *prefix,
1934                               const char *suffix, int physname,
1935                               struct dwarf2_cu *cu);
1936
1937 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1938
1939 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1940
1941 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1942
1943 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1944
1945 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1946
1947 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1948
1949 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1950                                struct dwarf2_cu *, struct partial_symtab *);
1951
1952 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1953    values.  Keep the items ordered with increasing constraints compliance.  */
1954 enum pc_bounds_kind
1955 {
1956   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1957   PC_BOUNDS_NOT_PRESENT,
1958
1959   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1960      were present but they do not form a valid range of PC addresses.  */
1961   PC_BOUNDS_INVALID,
1962
1963   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1964   PC_BOUNDS_RANGES,
1965
1966   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1967   PC_BOUNDS_HIGH_LOW,
1968 };
1969
1970 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1971                                                  CORE_ADDR *, CORE_ADDR *,
1972                                                  struct dwarf2_cu *,
1973                                                  struct partial_symtab *);
1974
1975 static void get_scope_pc_bounds (struct die_info *,
1976                                  CORE_ADDR *, CORE_ADDR *,
1977                                  struct dwarf2_cu *);
1978
1979 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1980                                         CORE_ADDR, struct dwarf2_cu *);
1981
1982 static void dwarf2_add_field (struct field_info *, struct die_info *,
1983                               struct dwarf2_cu *);
1984
1985 static void dwarf2_attach_fields_to_type (struct field_info *,
1986                                           struct type *, struct dwarf2_cu *);
1987
1988 static void dwarf2_add_member_fn (struct field_info *,
1989                                   struct die_info *, struct type *,
1990                                   struct dwarf2_cu *);
1991
1992 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1993                                              struct type *,
1994                                              struct dwarf2_cu *);
1995
1996 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1997
1998 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1999
2000 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
2001
2002 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
2003
2004 static struct using_direct **using_directives (enum language);
2005
2006 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2007
2008 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2009
2010 static struct type *read_module_type (struct die_info *die,
2011                                       struct dwarf2_cu *cu);
2012
2013 static const char *namespace_name (struct die_info *die,
2014                                    int *is_anonymous, struct dwarf2_cu *);
2015
2016 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2017
2018 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2019
2020 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2021                                                        struct dwarf2_cu *);
2022
2023 static struct die_info *read_die_and_siblings_1
2024   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2025    struct die_info *);
2026
2027 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2028                                                const gdb_byte *info_ptr,
2029                                                const gdb_byte **new_info_ptr,
2030                                                struct die_info *parent);
2031
2032 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2033                                         struct die_info **, const gdb_byte *,
2034                                         int *, int);
2035
2036 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2037                                       struct die_info **, const gdb_byte *,
2038                                       int *);
2039
2040 static void process_die (struct die_info *, struct dwarf2_cu *);
2041
2042 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2043                                              struct obstack *);
2044
2045 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2046
2047 static const char *dwarf2_full_name (const char *name,
2048                                      struct die_info *die,
2049                                      struct dwarf2_cu *cu);
2050
2051 static const char *dwarf2_physname (const char *name, struct die_info *die,
2052                                     struct dwarf2_cu *cu);
2053
2054 static struct die_info *dwarf2_extension (struct die_info *die,
2055                                           struct dwarf2_cu **);
2056
2057 static const char *dwarf_tag_name (unsigned int);
2058
2059 static const char *dwarf_attr_name (unsigned int);
2060
2061 static const char *dwarf_form_name (unsigned int);
2062
2063 static const char *dwarf_bool_name (unsigned int);
2064
2065 static const char *dwarf_type_encoding_name (unsigned int);
2066
2067 static struct die_info *sibling_die (struct die_info *);
2068
2069 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2070
2071 static void dump_die_for_error (struct die_info *);
2072
2073 static void dump_die_1 (struct ui_file *, int level, int max_level,
2074                         struct die_info *);
2075
2076 /*static*/ void dump_die (struct die_info *, int max_level);
2077
2078 static void store_in_ref_table (struct die_info *,
2079                                 struct dwarf2_cu *);
2080
2081 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2082
2083 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2084
2085 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2086                                                const struct attribute *,
2087                                                struct dwarf2_cu **);
2088
2089 static struct die_info *follow_die_ref (struct die_info *,
2090                                         const struct attribute *,
2091                                         struct dwarf2_cu **);
2092
2093 static struct die_info *follow_die_sig (struct die_info *,
2094                                         const struct attribute *,
2095                                         struct dwarf2_cu **);
2096
2097 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2098                                          struct dwarf2_cu *);
2099
2100 static struct type *get_DW_AT_signature_type (struct die_info *,
2101                                               const struct attribute *,
2102                                               struct dwarf2_cu *);
2103
2104 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2105
2106 static void read_signatured_type (struct signatured_type *);
2107
2108 static int attr_to_dynamic_prop (const struct attribute *attr,
2109                                  struct die_info *die, struct dwarf2_cu *cu,
2110                                  struct dynamic_prop *prop);
2111
2112 /* memory allocation interface */
2113
2114 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2115
2116 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2117
2118 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2119
2120 static int attr_form_is_block (const struct attribute *);
2121
2122 static int attr_form_is_section_offset (const struct attribute *);
2123
2124 static int attr_form_is_constant (const struct attribute *);
2125
2126 static int attr_form_is_ref (const struct attribute *);
2127
2128 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2129                                    struct dwarf2_loclist_baton *baton,
2130                                    const struct attribute *attr);
2131
2132 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2133                                          struct symbol *sym,
2134                                          struct dwarf2_cu *cu,
2135                                          int is_block);
2136
2137 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2138                                      const gdb_byte *info_ptr,
2139                                      struct abbrev_info *abbrev);
2140
2141 static void free_stack_comp_unit (void *);
2142
2143 static hashval_t partial_die_hash (const void *item);
2144
2145 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2146
2147 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2148   (sect_offset sect_off, unsigned int offset_in_dwz,
2149    struct dwarf2_per_objfile *dwarf2_per_objfile);
2150
2151 static void init_one_comp_unit (struct dwarf2_cu *cu,
2152                                 struct dwarf2_per_cu_data *per_cu);
2153
2154 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2155                                    struct die_info *comp_unit_die,
2156                                    enum language pretend_language);
2157
2158 static void free_heap_comp_unit (void *);
2159
2160 static void free_cached_comp_units (void *);
2161
2162 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2163
2164 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2165
2166 static struct type *set_die_type (struct die_info *, struct type *,
2167                                   struct dwarf2_cu *);
2168
2169 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2170
2171 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2172
2173 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2174                                  enum language);
2175
2176 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2177                                     enum language);
2178
2179 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2180                                     enum language);
2181
2182 static void dwarf2_add_dependence (struct dwarf2_cu *,
2183                                    struct dwarf2_per_cu_data *);
2184
2185 static void dwarf2_mark (struct dwarf2_cu *);
2186
2187 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2188
2189 static struct type *get_die_type_at_offset (sect_offset,
2190                                             struct dwarf2_per_cu_data *);
2191
2192 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2193
2194 static void dwarf2_release_queue (void *dummy);
2195
2196 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2197                              enum language pretend_language);
2198
2199 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2200
2201 /* The return type of find_file_and_directory.  Note, the enclosed
2202    string pointers are only valid while this object is valid.  */
2203
2204 struct file_and_directory
2205 {
2206   /* The filename.  This is never NULL.  */
2207   const char *name;
2208
2209   /* The compilation directory.  NULL if not known.  If we needed to
2210      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2211      points directly to the DW_AT_comp_dir string attribute owned by
2212      the obstack that owns the DIE.  */
2213   const char *comp_dir;
2214
2215   /* If we needed to build a new string for comp_dir, this is what
2216      owns the storage.  */
2217   std::string comp_dir_storage;
2218 };
2219
2220 static file_and_directory find_file_and_directory (struct die_info *die,
2221                                                    struct dwarf2_cu *cu);
2222
2223 static char *file_full_name (int file, struct line_header *lh,
2224                              const char *comp_dir);
2225
2226 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2227 enum class rcuh_kind { COMPILE, TYPE };
2228
2229 static const gdb_byte *read_and_check_comp_unit_head
2230   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2231    struct comp_unit_head *header,
2232    struct dwarf2_section_info *section,
2233    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2234    rcuh_kind section_kind);
2235
2236 static void init_cutu_and_read_dies
2237   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2238    int use_existing_cu, int keep,
2239    die_reader_func_ftype *die_reader_func, void *data);
2240
2241 static void init_cutu_and_read_dies_simple
2242   (struct dwarf2_per_cu_data *this_cu,
2243    die_reader_func_ftype *die_reader_func, void *data);
2244
2245 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2246
2247 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2248
2249 static struct dwo_unit *lookup_dwo_unit_in_dwp
2250   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2251    struct dwp_file *dwp_file, const char *comp_dir,
2252    ULONGEST signature, int is_debug_types);
2253
2254 static struct dwp_file *get_dwp_file
2255   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2256
2257 static struct dwo_unit *lookup_dwo_comp_unit
2258   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2259
2260 static struct dwo_unit *lookup_dwo_type_unit
2261   (struct signatured_type *, const char *, const char *);
2262
2263 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2264
2265 static void free_dwo_file_cleanup (void *);
2266
2267 struct free_dwo_file_cleanup_data
2268 {
2269   struct dwo_file *dwo_file;
2270   struct dwarf2_per_objfile *dwarf2_per_objfile;
2271 };
2272
2273 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2274
2275 static void check_producer (struct dwarf2_cu *cu);
2276
2277 static void free_line_header_voidp (void *arg);
2278 \f
2279 /* Various complaints about symbol reading that don't abort the process.  */
2280
2281 static void
2282 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2283 {
2284   complaint (&symfile_complaints,
2285              _("statement list doesn't fit in .debug_line section"));
2286 }
2287
2288 static void
2289 dwarf2_debug_line_missing_file_complaint (void)
2290 {
2291   complaint (&symfile_complaints,
2292              _(".debug_line section has line data without a file"));
2293 }
2294
2295 static void
2296 dwarf2_debug_line_missing_end_sequence_complaint (void)
2297 {
2298   complaint (&symfile_complaints,
2299              _(".debug_line section has line "
2300                "program sequence without an end"));
2301 }
2302
2303 static void
2304 dwarf2_complex_location_expr_complaint (void)
2305 {
2306   complaint (&symfile_complaints, _("location expression too complex"));
2307 }
2308
2309 static void
2310 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2311                                               int arg3)
2312 {
2313   complaint (&symfile_complaints,
2314              _("const value length mismatch for '%s', got %d, expected %d"),
2315              arg1, arg2, arg3);
2316 }
2317
2318 static void
2319 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2320 {
2321   complaint (&symfile_complaints,
2322              _("debug info runs off end of %s section"
2323                " [in module %s]"),
2324              get_section_name (section),
2325              get_section_file_name (section));
2326 }
2327
2328 static void
2329 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2330 {
2331   complaint (&symfile_complaints,
2332              _("macro debug info contains a "
2333                "malformed macro definition:\n`%s'"),
2334              arg1);
2335 }
2336
2337 static void
2338 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2339 {
2340   complaint (&symfile_complaints,
2341              _("invalid attribute class or form for '%s' in '%s'"),
2342              arg1, arg2);
2343 }
2344
2345 /* Hash function for line_header_hash.  */
2346
2347 static hashval_t
2348 line_header_hash (const struct line_header *ofs)
2349 {
2350   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2351 }
2352
2353 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2354
2355 static hashval_t
2356 line_header_hash_voidp (const void *item)
2357 {
2358   const struct line_header *ofs = (const struct line_header *) item;
2359
2360   return line_header_hash (ofs);
2361 }
2362
2363 /* Equality function for line_header_hash.  */
2364
2365 static int
2366 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2367 {
2368   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2369   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2370
2371   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2372           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2373 }
2374
2375 \f
2376
2377 /* Read the given attribute value as an address, taking the attribute's
2378    form into account.  */
2379
2380 static CORE_ADDR
2381 attr_value_as_address (struct attribute *attr)
2382 {
2383   CORE_ADDR addr;
2384
2385   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2386     {
2387       /* Aside from a few clearly defined exceptions, attributes that
2388          contain an address must always be in DW_FORM_addr form.
2389          Unfortunately, some compilers happen to be violating this
2390          requirement by encoding addresses using other forms, such
2391          as DW_FORM_data4 for example.  For those broken compilers,
2392          we try to do our best, without any guarantee of success,
2393          to interpret the address correctly.  It would also be nice
2394          to generate a complaint, but that would require us to maintain
2395          a list of legitimate cases where a non-address form is allowed,
2396          as well as update callers to pass in at least the CU's DWARF
2397          version.  This is more overhead than what we're willing to
2398          expand for a pretty rare case.  */
2399       addr = DW_UNSND (attr);
2400     }
2401   else
2402     addr = DW_ADDR (attr);
2403
2404   return addr;
2405 }
2406
2407 /* The suffix for an index file.  */
2408 #define INDEX4_SUFFIX ".gdb-index"
2409 #define INDEX5_SUFFIX ".debug_names"
2410 #define DEBUG_STR_SUFFIX ".debug_str"
2411
2412 /* See declaration.  */
2413
2414 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2415                                         const dwarf2_debug_sections *names)
2416   : objfile (objfile_)
2417 {
2418   if (names == NULL)
2419     names = &dwarf2_elf_names;
2420
2421   bfd *obfd = objfile->obfd;
2422
2423   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2424     locate_sections (obfd, sec, *names);
2425 }
2426
2427 dwarf2_per_objfile::~dwarf2_per_objfile ()
2428 {
2429   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2430   free_cached_comp_units ();
2431
2432   if (quick_file_names_table)
2433     htab_delete (quick_file_names_table);
2434
2435   if (line_header_hash)
2436     htab_delete (line_header_hash);
2437
2438   /* Everything else should be on the objfile obstack.  */
2439 }
2440
2441 /* See declaration.  */
2442
2443 void
2444 dwarf2_per_objfile::free_cached_comp_units ()
2445 {
2446   dwarf2_per_cu_data *per_cu = read_in_chain;
2447   dwarf2_per_cu_data **last_chain = &read_in_chain;
2448   while (per_cu != NULL)
2449     {
2450       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2451
2452       free_heap_comp_unit (per_cu->cu);
2453       *last_chain = next_cu;
2454       per_cu = next_cu;
2455     }
2456 }
2457
2458 /* Try to locate the sections we need for DWARF 2 debugging
2459    information and return true if we have enough to do something.
2460    NAMES points to the dwarf2 section names, or is NULL if the standard
2461    ELF names are used.  */
2462
2463 int
2464 dwarf2_has_info (struct objfile *objfile,
2465                  const struct dwarf2_debug_sections *names)
2466 {
2467   if (objfile->flags & OBJF_READNEVER)
2468     return 0;
2469
2470   struct dwarf2_per_objfile *dwarf2_per_objfile
2471     = get_dwarf2_per_objfile (objfile);
2472
2473   if (dwarf2_per_objfile == NULL)
2474     {
2475       /* Initialize per-objfile state.  */
2476       struct dwarf2_per_objfile *data
2477         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2478
2479       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2480       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2481     }
2482   return (!dwarf2_per_objfile->info.is_virtual
2483           && dwarf2_per_objfile->info.s.section != NULL
2484           && !dwarf2_per_objfile->abbrev.is_virtual
2485           && dwarf2_per_objfile->abbrev.s.section != NULL);
2486 }
2487
2488 /* Return the containing section of virtual section SECTION.  */
2489
2490 static struct dwarf2_section_info *
2491 get_containing_section (const struct dwarf2_section_info *section)
2492 {
2493   gdb_assert (section->is_virtual);
2494   return section->s.containing_section;
2495 }
2496
2497 /* Return the bfd owner of SECTION.  */
2498
2499 static struct bfd *
2500 get_section_bfd_owner (const struct dwarf2_section_info *section)
2501 {
2502   if (section->is_virtual)
2503     {
2504       section = get_containing_section (section);
2505       gdb_assert (!section->is_virtual);
2506     }
2507   return section->s.section->owner;
2508 }
2509
2510 /* Return the bfd section of SECTION.
2511    Returns NULL if the section is not present.  */
2512
2513 static asection *
2514 get_section_bfd_section (const struct dwarf2_section_info *section)
2515 {
2516   if (section->is_virtual)
2517     {
2518       section = get_containing_section (section);
2519       gdb_assert (!section->is_virtual);
2520     }
2521   return section->s.section;
2522 }
2523
2524 /* Return the name of SECTION.  */
2525
2526 static const char *
2527 get_section_name (const struct dwarf2_section_info *section)
2528 {
2529   asection *sectp = get_section_bfd_section (section);
2530
2531   gdb_assert (sectp != NULL);
2532   return bfd_section_name (get_section_bfd_owner (section), sectp);
2533 }
2534
2535 /* Return the name of the file SECTION is in.  */
2536
2537 static const char *
2538 get_section_file_name (const struct dwarf2_section_info *section)
2539 {
2540   bfd *abfd = get_section_bfd_owner (section);
2541
2542   return bfd_get_filename (abfd);
2543 }
2544
2545 /* Return the id of SECTION.
2546    Returns 0 if SECTION doesn't exist.  */
2547
2548 static int
2549 get_section_id (const struct dwarf2_section_info *section)
2550 {
2551   asection *sectp = get_section_bfd_section (section);
2552
2553   if (sectp == NULL)
2554     return 0;
2555   return sectp->id;
2556 }
2557
2558 /* Return the flags of SECTION.
2559    SECTION (or containing section if this is a virtual section) must exist.  */
2560
2561 static int
2562 get_section_flags (const struct dwarf2_section_info *section)
2563 {
2564   asection *sectp = get_section_bfd_section (section);
2565
2566   gdb_assert (sectp != NULL);
2567   return bfd_get_section_flags (sectp->owner, sectp);
2568 }
2569
2570 /* When loading sections, we look either for uncompressed section or for
2571    compressed section names.  */
2572
2573 static int
2574 section_is_p (const char *section_name,
2575               const struct dwarf2_section_names *names)
2576 {
2577   if (names->normal != NULL
2578       && strcmp (section_name, names->normal) == 0)
2579     return 1;
2580   if (names->compressed != NULL
2581       && strcmp (section_name, names->compressed) == 0)
2582     return 1;
2583   return 0;
2584 }
2585
2586 /* See declaration.  */
2587
2588 void
2589 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2590                                      const dwarf2_debug_sections &names)
2591 {
2592   flagword aflag = bfd_get_section_flags (abfd, sectp);
2593
2594   if ((aflag & SEC_HAS_CONTENTS) == 0)
2595     {
2596     }
2597   else if (section_is_p (sectp->name, &names.info))
2598     {
2599       this->info.s.section = sectp;
2600       this->info.size = bfd_get_section_size (sectp);
2601     }
2602   else if (section_is_p (sectp->name, &names.abbrev))
2603     {
2604       this->abbrev.s.section = sectp;
2605       this->abbrev.size = bfd_get_section_size (sectp);
2606     }
2607   else if (section_is_p (sectp->name, &names.line))
2608     {
2609       this->line.s.section = sectp;
2610       this->line.size = bfd_get_section_size (sectp);
2611     }
2612   else if (section_is_p (sectp->name, &names.loc))
2613     {
2614       this->loc.s.section = sectp;
2615       this->loc.size = bfd_get_section_size (sectp);
2616     }
2617   else if (section_is_p (sectp->name, &names.loclists))
2618     {
2619       this->loclists.s.section = sectp;
2620       this->loclists.size = bfd_get_section_size (sectp);
2621     }
2622   else if (section_is_p (sectp->name, &names.macinfo))
2623     {
2624       this->macinfo.s.section = sectp;
2625       this->macinfo.size = bfd_get_section_size (sectp);
2626     }
2627   else if (section_is_p (sectp->name, &names.macro))
2628     {
2629       this->macro.s.section = sectp;
2630       this->macro.size = bfd_get_section_size (sectp);
2631     }
2632   else if (section_is_p (sectp->name, &names.str))
2633     {
2634       this->str.s.section = sectp;
2635       this->str.size = bfd_get_section_size (sectp);
2636     }
2637   else if (section_is_p (sectp->name, &names.line_str))
2638     {
2639       this->line_str.s.section = sectp;
2640       this->line_str.size = bfd_get_section_size (sectp);
2641     }
2642   else if (section_is_p (sectp->name, &names.addr))
2643     {
2644       this->addr.s.section = sectp;
2645       this->addr.size = bfd_get_section_size (sectp);
2646     }
2647   else if (section_is_p (sectp->name, &names.frame))
2648     {
2649       this->frame.s.section = sectp;
2650       this->frame.size = bfd_get_section_size (sectp);
2651     }
2652   else if (section_is_p (sectp->name, &names.eh_frame))
2653     {
2654       this->eh_frame.s.section = sectp;
2655       this->eh_frame.size = bfd_get_section_size (sectp);
2656     }
2657   else if (section_is_p (sectp->name, &names.ranges))
2658     {
2659       this->ranges.s.section = sectp;
2660       this->ranges.size = bfd_get_section_size (sectp);
2661     }
2662   else if (section_is_p (sectp->name, &names.rnglists))
2663     {
2664       this->rnglists.s.section = sectp;
2665       this->rnglists.size = bfd_get_section_size (sectp);
2666     }
2667   else if (section_is_p (sectp->name, &names.types))
2668     {
2669       struct dwarf2_section_info type_section;
2670
2671       memset (&type_section, 0, sizeof (type_section));
2672       type_section.s.section = sectp;
2673       type_section.size = bfd_get_section_size (sectp);
2674
2675       VEC_safe_push (dwarf2_section_info_def, this->types,
2676                      &type_section);
2677     }
2678   else if (section_is_p (sectp->name, &names.gdb_index))
2679     {
2680       this->gdb_index.s.section = sectp;
2681       this->gdb_index.size = bfd_get_section_size (sectp);
2682     }
2683   else if (section_is_p (sectp->name, &names.debug_names))
2684     {
2685       this->debug_names.s.section = sectp;
2686       this->debug_names.size = bfd_get_section_size (sectp);
2687     }
2688   else if (section_is_p (sectp->name, &names.debug_aranges))
2689     {
2690       this->debug_aranges.s.section = sectp;
2691       this->debug_aranges.size = bfd_get_section_size (sectp);
2692     }
2693
2694   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2695       && bfd_section_vma (abfd, sectp) == 0)
2696     this->has_section_at_zero = true;
2697 }
2698
2699 /* A helper function that decides whether a section is empty,
2700    or not present.  */
2701
2702 static int
2703 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2704 {
2705   if (section->is_virtual)
2706     return section->size == 0;
2707   return section->s.section == NULL || section->size == 0;
2708 }
2709
2710 /* Read the contents of the section INFO.
2711    OBJFILE is the main object file, but not necessarily the file where
2712    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2713    of the DWO file.
2714    If the section is compressed, uncompress it before returning.  */
2715
2716 static void
2717 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2718 {
2719   asection *sectp;
2720   bfd *abfd;
2721   gdb_byte *buf, *retbuf;
2722
2723   if (info->readin)
2724     return;
2725   info->buffer = NULL;
2726   info->readin = 1;
2727
2728   if (dwarf2_section_empty_p (info))
2729     return;
2730
2731   sectp = get_section_bfd_section (info);
2732
2733   /* If this is a virtual section we need to read in the real one first.  */
2734   if (info->is_virtual)
2735     {
2736       struct dwarf2_section_info *containing_section =
2737         get_containing_section (info);
2738
2739       gdb_assert (sectp != NULL);
2740       if ((sectp->flags & SEC_RELOC) != 0)
2741         {
2742           error (_("Dwarf Error: DWP format V2 with relocations is not"
2743                    " supported in section %s [in module %s]"),
2744                  get_section_name (info), get_section_file_name (info));
2745         }
2746       dwarf2_read_section (objfile, containing_section);
2747       /* Other code should have already caught virtual sections that don't
2748          fit.  */
2749       gdb_assert (info->virtual_offset + info->size
2750                   <= containing_section->size);
2751       /* If the real section is empty or there was a problem reading the
2752          section we shouldn't get here.  */
2753       gdb_assert (containing_section->buffer != NULL);
2754       info->buffer = containing_section->buffer + info->virtual_offset;
2755       return;
2756     }
2757
2758   /* If the section has relocations, we must read it ourselves.
2759      Otherwise we attach it to the BFD.  */
2760   if ((sectp->flags & SEC_RELOC) == 0)
2761     {
2762       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2763       return;
2764     }
2765
2766   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2767   info->buffer = buf;
2768
2769   /* When debugging .o files, we may need to apply relocations; see
2770      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2771      We never compress sections in .o files, so we only need to
2772      try this when the section is not compressed.  */
2773   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2774   if (retbuf != NULL)
2775     {
2776       info->buffer = retbuf;
2777       return;
2778     }
2779
2780   abfd = get_section_bfd_owner (info);
2781   gdb_assert (abfd != NULL);
2782
2783   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2784       || bfd_bread (buf, info->size, abfd) != info->size)
2785     {
2786       error (_("Dwarf Error: Can't read DWARF data"
2787                " in section %s [in module %s]"),
2788              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2789     }
2790 }
2791
2792 /* A helper function that returns the size of a section in a safe way.
2793    If you are positive that the section has been read before using the
2794    size, then it is safe to refer to the dwarf2_section_info object's
2795    "size" field directly.  In other cases, you must call this
2796    function, because for compressed sections the size field is not set
2797    correctly until the section has been read.  */
2798
2799 static bfd_size_type
2800 dwarf2_section_size (struct objfile *objfile,
2801                      struct dwarf2_section_info *info)
2802 {
2803   if (!info->readin)
2804     dwarf2_read_section (objfile, info);
2805   return info->size;
2806 }
2807
2808 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2809    SECTION_NAME.  */
2810
2811 void
2812 dwarf2_get_section_info (struct objfile *objfile,
2813                          enum dwarf2_section_enum sect,
2814                          asection **sectp, const gdb_byte **bufp,
2815                          bfd_size_type *sizep)
2816 {
2817   struct dwarf2_per_objfile *data
2818     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2819                                                   dwarf2_objfile_data_key);
2820   struct dwarf2_section_info *info;
2821
2822   /* We may see an objfile without any DWARF, in which case we just
2823      return nothing.  */
2824   if (data == NULL)
2825     {
2826       *sectp = NULL;
2827       *bufp = NULL;
2828       *sizep = 0;
2829       return;
2830     }
2831   switch (sect)
2832     {
2833     case DWARF2_DEBUG_FRAME:
2834       info = &data->frame;
2835       break;
2836     case DWARF2_EH_FRAME:
2837       info = &data->eh_frame;
2838       break;
2839     default:
2840       gdb_assert_not_reached ("unexpected section");
2841     }
2842
2843   dwarf2_read_section (objfile, info);
2844
2845   *sectp = get_section_bfd_section (info);
2846   *bufp = info->buffer;
2847   *sizep = info->size;
2848 }
2849
2850 /* A helper function to find the sections for a .dwz file.  */
2851
2852 static void
2853 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2854 {
2855   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2856
2857   /* Note that we only support the standard ELF names, because .dwz
2858      is ELF-only (at the time of writing).  */
2859   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2860     {
2861       dwz_file->abbrev.s.section = sectp;
2862       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2863     }
2864   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2865     {
2866       dwz_file->info.s.section = sectp;
2867       dwz_file->info.size = bfd_get_section_size (sectp);
2868     }
2869   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2870     {
2871       dwz_file->str.s.section = sectp;
2872       dwz_file->str.size = bfd_get_section_size (sectp);
2873     }
2874   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2875     {
2876       dwz_file->line.s.section = sectp;
2877       dwz_file->line.size = bfd_get_section_size (sectp);
2878     }
2879   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2880     {
2881       dwz_file->macro.s.section = sectp;
2882       dwz_file->macro.size = bfd_get_section_size (sectp);
2883     }
2884   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2885     {
2886       dwz_file->gdb_index.s.section = sectp;
2887       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2888     }
2889   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2890     {
2891       dwz_file->debug_names.s.section = sectp;
2892       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2893     }
2894 }
2895
2896 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2897    there is no .gnu_debugaltlink section in the file.  Error if there
2898    is such a section but the file cannot be found.  */
2899
2900 static struct dwz_file *
2901 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2902 {
2903   const char *filename;
2904   struct dwz_file *result;
2905   bfd_size_type buildid_len_arg;
2906   size_t buildid_len;
2907   bfd_byte *buildid;
2908
2909   if (dwarf2_per_objfile->dwz_file != NULL)
2910     return dwarf2_per_objfile->dwz_file;
2911
2912   bfd_set_error (bfd_error_no_error);
2913   gdb::unique_xmalloc_ptr<char> data
2914     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2915                                   &buildid_len_arg, &buildid));
2916   if (data == NULL)
2917     {
2918       if (bfd_get_error () == bfd_error_no_error)
2919         return NULL;
2920       error (_("could not read '.gnu_debugaltlink' section: %s"),
2921              bfd_errmsg (bfd_get_error ()));
2922     }
2923
2924   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2925
2926   buildid_len = (size_t) buildid_len_arg;
2927
2928   filename = data.get ();
2929
2930   std::string abs_storage;
2931   if (!IS_ABSOLUTE_PATH (filename))
2932     {
2933       gdb::unique_xmalloc_ptr<char> abs
2934         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2935
2936       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2937       filename = abs_storage.c_str ();
2938     }
2939
2940   /* First try the file name given in the section.  If that doesn't
2941      work, try to use the build-id instead.  */
2942   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2943   if (dwz_bfd != NULL)
2944     {
2945       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2946         dwz_bfd.release ();
2947     }
2948
2949   if (dwz_bfd == NULL)
2950     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2951
2952   if (dwz_bfd == NULL)
2953     error (_("could not find '.gnu_debugaltlink' file for %s"),
2954            objfile_name (dwarf2_per_objfile->objfile));
2955
2956   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2957                            struct dwz_file);
2958   result->dwz_bfd = dwz_bfd.release ();
2959
2960   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2961
2962   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2963   dwarf2_per_objfile->dwz_file = result;
2964   return result;
2965 }
2966 \f
2967 /* DWARF quick_symbols_functions support.  */
2968
2969 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2970    unique line tables, so we maintain a separate table of all .debug_line
2971    derived entries to support the sharing.
2972    All the quick functions need is the list of file names.  We discard the
2973    line_header when we're done and don't need to record it here.  */
2974 struct quick_file_names
2975 {
2976   /* The data used to construct the hash key.  */
2977   struct stmt_list_hash hash;
2978
2979   /* The number of entries in file_names, real_names.  */
2980   unsigned int num_file_names;
2981
2982   /* The file names from the line table, after being run through
2983      file_full_name.  */
2984   const char **file_names;
2985
2986   /* The file names from the line table after being run through
2987      gdb_realpath.  These are computed lazily.  */
2988   const char **real_names;
2989 };
2990
2991 /* When using the index (and thus not using psymtabs), each CU has an
2992    object of this type.  This is used to hold information needed by
2993    the various "quick" methods.  */
2994 struct dwarf2_per_cu_quick_data
2995 {
2996   /* The file table.  This can be NULL if there was no file table
2997      or it's currently not read in.
2998      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2999   struct quick_file_names *file_names;
3000
3001   /* The corresponding symbol table.  This is NULL if symbols for this
3002      CU have not yet been read.  */
3003   struct compunit_symtab *compunit_symtab;
3004
3005   /* A temporary mark bit used when iterating over all CUs in
3006      expand_symtabs_matching.  */
3007   unsigned int mark : 1;
3008
3009   /* True if we've tried to read the file table and found there isn't one.
3010      There will be no point in trying to read it again next time.  */
3011   unsigned int no_file_data : 1;
3012 };
3013
3014 /* Utility hash function for a stmt_list_hash.  */
3015
3016 static hashval_t
3017 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3018 {
3019   hashval_t v = 0;
3020
3021   if (stmt_list_hash->dwo_unit != NULL)
3022     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3023   v += to_underlying (stmt_list_hash->line_sect_off);
3024   return v;
3025 }
3026
3027 /* Utility equality function for a stmt_list_hash.  */
3028
3029 static int
3030 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3031                     const struct stmt_list_hash *rhs)
3032 {
3033   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3034     return 0;
3035   if (lhs->dwo_unit != NULL
3036       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3037     return 0;
3038
3039   return lhs->line_sect_off == rhs->line_sect_off;
3040 }
3041
3042 /* Hash function for a quick_file_names.  */
3043
3044 static hashval_t
3045 hash_file_name_entry (const void *e)
3046 {
3047   const struct quick_file_names *file_data
3048     = (const struct quick_file_names *) e;
3049
3050   return hash_stmt_list_entry (&file_data->hash);
3051 }
3052
3053 /* Equality function for a quick_file_names.  */
3054
3055 static int
3056 eq_file_name_entry (const void *a, const void *b)
3057 {
3058   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3059   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3060
3061   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3062 }
3063
3064 /* Delete function for a quick_file_names.  */
3065
3066 static void
3067 delete_file_name_entry (void *e)
3068 {
3069   struct quick_file_names *file_data = (struct quick_file_names *) e;
3070   int i;
3071
3072   for (i = 0; i < file_data->num_file_names; ++i)
3073     {
3074       xfree ((void*) file_data->file_names[i]);
3075       if (file_data->real_names)
3076         xfree ((void*) file_data->real_names[i]);
3077     }
3078
3079   /* The space for the struct itself lives on objfile_obstack,
3080      so we don't free it here.  */
3081 }
3082
3083 /* Create a quick_file_names hash table.  */
3084
3085 static htab_t
3086 create_quick_file_names_table (unsigned int nr_initial_entries)
3087 {
3088   return htab_create_alloc (nr_initial_entries,
3089                             hash_file_name_entry, eq_file_name_entry,
3090                             delete_file_name_entry, xcalloc, xfree);
3091 }
3092
3093 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3094    have to be created afterwards.  You should call age_cached_comp_units after
3095    processing PER_CU->CU.  dw2_setup must have been already called.  */
3096
3097 static void
3098 load_cu (struct dwarf2_per_cu_data *per_cu)
3099 {
3100   if (per_cu->is_debug_types)
3101     load_full_type_unit (per_cu);
3102   else
3103     load_full_comp_unit (per_cu, language_minimal);
3104
3105   if (per_cu->cu == NULL)
3106     return;  /* Dummy CU.  */
3107
3108   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3109 }
3110
3111 /* Read in the symbols for PER_CU.  */
3112
3113 static void
3114 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3115 {
3116   struct cleanup *back_to;
3117   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3118
3119   /* Skip type_unit_groups, reading the type units they contain
3120      is handled elsewhere.  */
3121   if (IS_TYPE_UNIT_GROUP (per_cu))
3122     return;
3123
3124   back_to = make_cleanup (dwarf2_release_queue, NULL);
3125
3126   if (dwarf2_per_objfile->using_index
3127       ? per_cu->v.quick->compunit_symtab == NULL
3128       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3129     {
3130       queue_comp_unit (per_cu, language_minimal);
3131       load_cu (per_cu);
3132
3133       /* If we just loaded a CU from a DWO, and we're working with an index
3134          that may badly handle TUs, load all the TUs in that DWO as well.
3135          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3136       if (!per_cu->is_debug_types
3137           && per_cu->cu != NULL
3138           && per_cu->cu->dwo_unit != NULL
3139           && dwarf2_per_objfile->index_table != NULL
3140           && dwarf2_per_objfile->index_table->version <= 7
3141           /* DWP files aren't supported yet.  */
3142           && get_dwp_file (dwarf2_per_objfile) == NULL)
3143         queue_and_load_all_dwo_tus (per_cu);
3144     }
3145
3146   process_queue (dwarf2_per_objfile);
3147
3148   /* Age the cache, releasing compilation units that have not
3149      been used recently.  */
3150   age_cached_comp_units (dwarf2_per_objfile);
3151
3152   do_cleanups (back_to);
3153 }
3154
3155 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3156    the objfile from which this CU came.  Returns the resulting symbol
3157    table.  */
3158
3159 static struct compunit_symtab *
3160 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3161 {
3162   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3163
3164   gdb_assert (dwarf2_per_objfile->using_index);
3165   if (!per_cu->v.quick->compunit_symtab)
3166     {
3167       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3168                                               dwarf2_per_objfile);
3169       scoped_restore decrementer = increment_reading_symtab ();
3170       dw2_do_instantiate_symtab (per_cu);
3171       process_cu_includes (dwarf2_per_objfile);
3172       do_cleanups (back_to);
3173     }
3174
3175   return per_cu->v.quick->compunit_symtab;
3176 }
3177
3178 /* Return the CU/TU given its index.
3179
3180    This is intended for loops like:
3181
3182    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3183                     + dwarf2_per_objfile->n_type_units); ++i)
3184      {
3185        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3186
3187        ...;
3188      }
3189 */
3190
3191 static struct dwarf2_per_cu_data *
3192 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3193               int index)
3194 {
3195   if (index >= dwarf2_per_objfile->n_comp_units)
3196     {
3197       index -= dwarf2_per_objfile->n_comp_units;
3198       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3199       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3200     }
3201
3202   return dwarf2_per_objfile->all_comp_units[index];
3203 }
3204
3205 /* Return the CU given its index.
3206    This differs from dw2_get_cutu in that it's for when you know INDEX
3207    refers to a CU.  */
3208
3209 static struct dwarf2_per_cu_data *
3210 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3211 {
3212   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3213
3214   return dwarf2_per_objfile->all_comp_units[index];
3215 }
3216
3217 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3218    objfile_obstack, and constructed with the specified field
3219    values.  */
3220
3221 static dwarf2_per_cu_data *
3222 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3223                           struct dwarf2_section_info *section,
3224                           int is_dwz,
3225                           sect_offset sect_off, ULONGEST length)
3226 {
3227   struct objfile *objfile = dwarf2_per_objfile->objfile;
3228   dwarf2_per_cu_data *the_cu
3229     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3230                      struct dwarf2_per_cu_data);
3231   the_cu->sect_off = sect_off;
3232   the_cu->length = length;
3233   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3234   the_cu->section = section;
3235   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3236                                    struct dwarf2_per_cu_quick_data);
3237   the_cu->is_dwz = is_dwz;
3238   return the_cu;
3239 }
3240
3241 /* A helper for create_cus_from_index that handles a given list of
3242    CUs.  */
3243
3244 static void
3245 create_cus_from_index_list (struct objfile *objfile,
3246                             const gdb_byte *cu_list, offset_type n_elements,
3247                             struct dwarf2_section_info *section,
3248                             int is_dwz,
3249                             int base_offset)
3250 {
3251   offset_type i;
3252   struct dwarf2_per_objfile *dwarf2_per_objfile
3253     = get_dwarf2_per_objfile (objfile);
3254
3255   for (i = 0; i < n_elements; i += 2)
3256     {
3257       gdb_static_assert (sizeof (ULONGEST) >= 8);
3258
3259       sect_offset sect_off
3260         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3261       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3262       cu_list += 2 * 8;
3263
3264       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3265         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3266                                      sect_off, length);
3267     }
3268 }
3269
3270 /* Read the CU list from the mapped index, and use it to create all
3271    the CU objects for this objfile.  */
3272
3273 static void
3274 create_cus_from_index (struct objfile *objfile,
3275                        const gdb_byte *cu_list, offset_type cu_list_elements,
3276                        const gdb_byte *dwz_list, offset_type dwz_elements)
3277 {
3278   struct dwz_file *dwz;
3279   struct dwarf2_per_objfile *dwarf2_per_objfile
3280     = get_dwarf2_per_objfile (objfile);
3281
3282   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3283   dwarf2_per_objfile->all_comp_units =
3284     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3285                dwarf2_per_objfile->n_comp_units);
3286
3287   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3288                               &dwarf2_per_objfile->info, 0, 0);
3289
3290   if (dwz_elements == 0)
3291     return;
3292
3293   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3294   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3295                               cu_list_elements / 2);
3296 }
3297
3298 /* Create the signatured type hash table from the index.  */
3299
3300 static void
3301 create_signatured_type_table_from_index (struct objfile *objfile,
3302                                          struct dwarf2_section_info *section,
3303                                          const gdb_byte *bytes,
3304                                          offset_type elements)
3305 {
3306   offset_type i;
3307   htab_t sig_types_hash;
3308   struct dwarf2_per_objfile *dwarf2_per_objfile
3309     = get_dwarf2_per_objfile (objfile);
3310
3311   dwarf2_per_objfile->n_type_units
3312     = dwarf2_per_objfile->n_allocated_type_units
3313     = elements / 3;
3314   dwarf2_per_objfile->all_type_units =
3315     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3316
3317   sig_types_hash = allocate_signatured_type_table (objfile);
3318
3319   for (i = 0; i < elements; i += 3)
3320     {
3321       struct signatured_type *sig_type;
3322       ULONGEST signature;
3323       void **slot;
3324       cu_offset type_offset_in_tu;
3325
3326       gdb_static_assert (sizeof (ULONGEST) >= 8);
3327       sect_offset sect_off
3328         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3329       type_offset_in_tu
3330         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3331                                                 BFD_ENDIAN_LITTLE);
3332       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3333       bytes += 3 * 8;
3334
3335       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3336                                  struct signatured_type);
3337       sig_type->signature = signature;
3338       sig_type->type_offset_in_tu = type_offset_in_tu;
3339       sig_type->per_cu.is_debug_types = 1;
3340       sig_type->per_cu.section = section;
3341       sig_type->per_cu.sect_off = sect_off;
3342       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3343       sig_type->per_cu.v.quick
3344         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3345                           struct dwarf2_per_cu_quick_data);
3346
3347       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3348       *slot = sig_type;
3349
3350       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3351     }
3352
3353   dwarf2_per_objfile->signatured_types = sig_types_hash;
3354 }
3355
3356 /* Create the signatured type hash table from .debug_names.  */
3357
3358 static void
3359 create_signatured_type_table_from_debug_names
3360   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3361    const mapped_debug_names &map,
3362    struct dwarf2_section_info *section,
3363    struct dwarf2_section_info *abbrev_section)
3364 {
3365   struct objfile *objfile = dwarf2_per_objfile->objfile;
3366
3367   dwarf2_read_section (objfile, section);
3368   dwarf2_read_section (objfile, abbrev_section);
3369
3370   dwarf2_per_objfile->n_type_units
3371     = dwarf2_per_objfile->n_allocated_type_units
3372     = map.tu_count;
3373   dwarf2_per_objfile->all_type_units
3374     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3375
3376   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3377
3378   for (uint32_t i = 0; i < map.tu_count; ++i)
3379     {
3380       struct signatured_type *sig_type;
3381       ULONGEST signature;
3382       void **slot;
3383       cu_offset type_offset_in_tu;
3384
3385       sect_offset sect_off
3386         = (sect_offset) (extract_unsigned_integer
3387                          (map.tu_table_reordered + i * map.offset_size,
3388                           map.offset_size,
3389                           map.dwarf5_byte_order));
3390
3391       comp_unit_head cu_header;
3392       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3393                                      abbrev_section,
3394                                      section->buffer + to_underlying (sect_off),
3395                                      rcuh_kind::TYPE);
3396
3397       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3398                                  struct signatured_type);
3399       sig_type->signature = cu_header.signature;
3400       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3401       sig_type->per_cu.is_debug_types = 1;
3402       sig_type->per_cu.section = section;
3403       sig_type->per_cu.sect_off = sect_off;
3404       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3405       sig_type->per_cu.v.quick
3406         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3407                           struct dwarf2_per_cu_quick_data);
3408
3409       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3410       *slot = sig_type;
3411
3412       dwarf2_per_objfile->all_type_units[i] = sig_type;
3413     }
3414
3415   dwarf2_per_objfile->signatured_types = sig_types_hash;
3416 }
3417
3418 /* Read the address map data from the mapped index, and use it to
3419    populate the objfile's psymtabs_addrmap.  */
3420
3421 static void
3422 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3423                            struct mapped_index *index)
3424 {
3425   struct objfile *objfile = dwarf2_per_objfile->objfile;
3426   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3427   const gdb_byte *iter, *end;
3428   struct addrmap *mutable_map;
3429   CORE_ADDR baseaddr;
3430
3431   auto_obstack temp_obstack;
3432
3433   mutable_map = addrmap_create_mutable (&temp_obstack);
3434
3435   iter = index->address_table.data ();
3436   end = iter + index->address_table.size ();
3437
3438   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3439
3440   while (iter < end)
3441     {
3442       ULONGEST hi, lo, cu_index;
3443       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3444       iter += 8;
3445       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3446       iter += 8;
3447       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3448       iter += 4;
3449
3450       if (lo > hi)
3451         {
3452           complaint (&symfile_complaints,
3453                      _(".gdb_index address table has invalid range (%s - %s)"),
3454                      hex_string (lo), hex_string (hi));
3455           continue;
3456         }
3457
3458       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3459         {
3460           complaint (&symfile_complaints,
3461                      _(".gdb_index address table has invalid CU number %u"),
3462                      (unsigned) cu_index);
3463           continue;
3464         }
3465
3466       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3467       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3468       addrmap_set_empty (mutable_map, lo, hi - 1,
3469                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3470     }
3471
3472   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3473                                                     &objfile->objfile_obstack);
3474 }
3475
3476 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3477    populate the objfile's psymtabs_addrmap.  */
3478
3479 static void
3480 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3481                              struct dwarf2_section_info *section)
3482 {
3483   struct objfile *objfile = dwarf2_per_objfile->objfile;
3484   bfd *abfd = objfile->obfd;
3485   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3486   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3487                                        SECT_OFF_TEXT (objfile));
3488
3489   auto_obstack temp_obstack;
3490   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3491
3492   std::unordered_map<sect_offset,
3493                      dwarf2_per_cu_data *,
3494                      gdb::hash_enum<sect_offset>>
3495     debug_info_offset_to_per_cu;
3496   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3497     {
3498       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3499       const auto insertpair
3500         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3501       if (!insertpair.second)
3502         {
3503           warning (_("Section .debug_aranges in %s has duplicate "
3504                      "debug_info_offset %u, ignoring .debug_aranges."),
3505                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3506           return;
3507         }
3508     }
3509
3510   dwarf2_read_section (objfile, section);
3511
3512   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3513
3514   const gdb_byte *addr = section->buffer;
3515
3516   while (addr < section->buffer + section->size)
3517     {
3518       const gdb_byte *const entry_addr = addr;
3519       unsigned int bytes_read;
3520
3521       const LONGEST entry_length = read_initial_length (abfd, addr,
3522                                                         &bytes_read);
3523       addr += bytes_read;
3524
3525       const gdb_byte *const entry_end = addr + entry_length;
3526       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3527       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3528       if (addr + entry_length > section->buffer + section->size)
3529         {
3530           warning (_("Section .debug_aranges in %s entry at offset %zu "
3531                      "length %s exceeds section length %s, "
3532                      "ignoring .debug_aranges."),
3533                    objfile_name (objfile), entry_addr - section->buffer,
3534                    plongest (bytes_read + entry_length),
3535                    pulongest (section->size));
3536           return;
3537         }
3538
3539       /* The version number.  */
3540       const uint16_t version = read_2_bytes (abfd, addr);
3541       addr += 2;
3542       if (version != 2)
3543         {
3544           warning (_("Section .debug_aranges in %s entry at offset %zu "
3545                      "has unsupported version %d, ignoring .debug_aranges."),
3546                    objfile_name (objfile), entry_addr - section->buffer,
3547                    version);
3548           return;
3549         }
3550
3551       const uint64_t debug_info_offset
3552         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3553       addr += offset_size;
3554       const auto per_cu_it
3555         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3556       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3557         {
3558           warning (_("Section .debug_aranges in %s entry at offset %zu "
3559                      "debug_info_offset %s does not exists, "
3560                      "ignoring .debug_aranges."),
3561                    objfile_name (objfile), entry_addr - section->buffer,
3562                    pulongest (debug_info_offset));
3563           return;
3564         }
3565       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3566
3567       const uint8_t address_size = *addr++;
3568       if (address_size < 1 || address_size > 8)
3569         {
3570           warning (_("Section .debug_aranges in %s entry at offset %zu "
3571                      "address_size %u is invalid, ignoring .debug_aranges."),
3572                    objfile_name (objfile), entry_addr - section->buffer,
3573                    address_size);
3574           return;
3575         }
3576
3577       const uint8_t segment_selector_size = *addr++;
3578       if (segment_selector_size != 0)
3579         {
3580           warning (_("Section .debug_aranges in %s entry at offset %zu "
3581                      "segment_selector_size %u is not supported, "
3582                      "ignoring .debug_aranges."),
3583                    objfile_name (objfile), entry_addr - section->buffer,
3584                    segment_selector_size);
3585           return;
3586         }
3587
3588       /* Must pad to an alignment boundary that is twice the address
3589          size.  It is undocumented by the DWARF standard but GCC does
3590          use it.  */
3591       for (size_t padding = ((-(addr - section->buffer))
3592                              & (2 * address_size - 1));
3593            padding > 0; padding--)
3594         if (*addr++ != 0)
3595           {
3596             warning (_("Section .debug_aranges in %s entry at offset %zu "
3597                        "padding is not zero, ignoring .debug_aranges."),
3598                      objfile_name (objfile), entry_addr - section->buffer);
3599             return;
3600           }
3601
3602       for (;;)
3603         {
3604           if (addr + 2 * address_size > entry_end)
3605             {
3606               warning (_("Section .debug_aranges in %s entry at offset %zu "
3607                          "address list is not properly terminated, "
3608                          "ignoring .debug_aranges."),
3609                        objfile_name (objfile), entry_addr - section->buffer);
3610               return;
3611             }
3612           ULONGEST start = extract_unsigned_integer (addr, address_size,
3613                                                      dwarf5_byte_order);
3614           addr += address_size;
3615           ULONGEST length = extract_unsigned_integer (addr, address_size,
3616                                                       dwarf5_byte_order);
3617           addr += address_size;
3618           if (start == 0 && length == 0)
3619             break;
3620           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3621             {
3622               /* Symbol was eliminated due to a COMDAT group.  */
3623               continue;
3624             }
3625           ULONGEST end = start + length;
3626           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3627           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3628           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3629         }
3630     }
3631
3632   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3633                                                     &objfile->objfile_obstack);
3634 }
3635
3636 /* The hash function for strings in the mapped index.  This is the same as
3637    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3638    implementation.  This is necessary because the hash function is tied to the
3639    format of the mapped index file.  The hash values do not have to match with
3640    SYMBOL_HASH_NEXT.
3641    
3642    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3643
3644 static hashval_t
3645 mapped_index_string_hash (int index_version, const void *p)
3646 {
3647   const unsigned char *str = (const unsigned char *) p;
3648   hashval_t r = 0;
3649   unsigned char c;
3650
3651   while ((c = *str++) != 0)
3652     {
3653       if (index_version >= 5)
3654         c = tolower (c);
3655       r = r * 67 + c - 113;
3656     }
3657
3658   return r;
3659 }
3660
3661 /* Find a slot in the mapped index INDEX for the object named NAME.
3662    If NAME is found, set *VEC_OUT to point to the CU vector in the
3663    constant pool and return true.  If NAME cannot be found, return
3664    false.  */
3665
3666 static bool
3667 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3668                           offset_type **vec_out)
3669 {
3670   offset_type hash;
3671   offset_type slot, step;
3672   int (*cmp) (const char *, const char *);
3673
3674   gdb::unique_xmalloc_ptr<char> without_params;
3675   if (current_language->la_language == language_cplus
3676       || current_language->la_language == language_fortran
3677       || current_language->la_language == language_d)
3678     {
3679       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3680          not contain any.  */
3681
3682       if (strchr (name, '(') != NULL)
3683         {
3684           without_params = cp_remove_params (name);
3685
3686           if (without_params != NULL)
3687             name = without_params.get ();
3688         }
3689     }
3690
3691   /* Index version 4 did not support case insensitive searches.  But the
3692      indices for case insensitive languages are built in lowercase, therefore
3693      simulate our NAME being searched is also lowercased.  */
3694   hash = mapped_index_string_hash ((index->version == 4
3695                                     && case_sensitivity == case_sensitive_off
3696                                     ? 5 : index->version),
3697                                    name);
3698
3699   slot = hash & (index->symbol_table.size () - 1);
3700   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3701   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3702
3703   for (;;)
3704     {
3705       const char *str;
3706
3707       const auto &bucket = index->symbol_table[slot];
3708       if (bucket.name == 0 && bucket.vec == 0)
3709         return false;
3710
3711       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3712       if (!cmp (name, str))
3713         {
3714           *vec_out = (offset_type *) (index->constant_pool
3715                                       + MAYBE_SWAP (bucket.vec));
3716           return true;
3717         }
3718
3719       slot = (slot + step) & (index->symbol_table.size () - 1);
3720     }
3721 }
3722
3723 /* A helper function that reads the .gdb_index from SECTION and fills
3724    in MAP.  FILENAME is the name of the file containing the section;
3725    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3726    ok to use deprecated sections.
3727
3728    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3729    out parameters that are filled in with information about the CU and
3730    TU lists in the section.
3731
3732    Returns 1 if all went well, 0 otherwise.  */
3733
3734 static int
3735 read_index_from_section (struct objfile *objfile,
3736                          const char *filename,
3737                          int deprecated_ok,
3738                          struct dwarf2_section_info *section,
3739                          struct mapped_index *map,
3740                          const gdb_byte **cu_list,
3741                          offset_type *cu_list_elements,
3742                          const gdb_byte **types_list,
3743                          offset_type *types_list_elements)
3744 {
3745   const gdb_byte *addr;
3746   offset_type version;
3747   offset_type *metadata;
3748   int i;
3749
3750   if (dwarf2_section_empty_p (section))
3751     return 0;
3752
3753   /* Older elfutils strip versions could keep the section in the main
3754      executable while splitting it for the separate debug info file.  */
3755   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3756     return 0;
3757
3758   dwarf2_read_section (objfile, section);
3759
3760   addr = section->buffer;
3761   /* Version check.  */
3762   version = MAYBE_SWAP (*(offset_type *) addr);
3763   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3764      causes the index to behave very poorly for certain requests.  Version 3
3765      contained incomplete addrmap.  So, it seems better to just ignore such
3766      indices.  */
3767   if (version < 4)
3768     {
3769       static int warning_printed = 0;
3770       if (!warning_printed)
3771         {
3772           warning (_("Skipping obsolete .gdb_index section in %s."),
3773                    filename);
3774           warning_printed = 1;
3775         }
3776       return 0;
3777     }
3778   /* Index version 4 uses a different hash function than index version
3779      5 and later.
3780
3781      Versions earlier than 6 did not emit psymbols for inlined
3782      functions.  Using these files will cause GDB not to be able to
3783      set breakpoints on inlined functions by name, so we ignore these
3784      indices unless the user has done
3785      "set use-deprecated-index-sections on".  */
3786   if (version < 6 && !deprecated_ok)
3787     {
3788       static int warning_printed = 0;
3789       if (!warning_printed)
3790         {
3791           warning (_("\
3792 Skipping deprecated .gdb_index section in %s.\n\
3793 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3794 to use the section anyway."),
3795                    filename);
3796           warning_printed = 1;
3797         }
3798       return 0;
3799     }
3800   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3801      of the TU (for symbols coming from TUs),
3802      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3803      Plus gold-generated indices can have duplicate entries for global symbols,
3804      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3805      These are just performance bugs, and we can't distinguish gdb-generated
3806      indices from gold-generated ones, so issue no warning here.  */
3807
3808   /* Indexes with higher version than the one supported by GDB may be no
3809      longer backward compatible.  */
3810   if (version > 8)
3811     return 0;
3812
3813   map->version = version;
3814   map->total_size = section->size;
3815
3816   metadata = (offset_type *) (addr + sizeof (offset_type));
3817
3818   i = 0;
3819   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3820   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3821                        / 8);
3822   ++i;
3823
3824   *types_list = addr + MAYBE_SWAP (metadata[i]);
3825   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3826                            - MAYBE_SWAP (metadata[i]))
3827                           / 8);
3828   ++i;
3829
3830   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3831   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3832   map->address_table
3833     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3834   ++i;
3835
3836   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3837   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3838   map->symbol_table
3839     = gdb::array_view<mapped_index::symbol_table_slot>
3840        ((mapped_index::symbol_table_slot *) symbol_table,
3841         (mapped_index::symbol_table_slot *) symbol_table_end);
3842
3843   ++i;
3844   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3845
3846   return 1;
3847 }
3848
3849 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3850    elements of all the CUs and return 1.  Otherwise, return 0.  */
3851
3852 static int
3853 dwarf2_read_index (struct objfile *objfile)
3854 {
3855   struct mapped_index local_map, *map;
3856   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3857   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3858   struct dwz_file *dwz;
3859   struct dwarf2_per_objfile *dwarf2_per_objfile
3860     = get_dwarf2_per_objfile (objfile);
3861
3862   if (!read_index_from_section (objfile, objfile_name (objfile),
3863                                 use_deprecated_index_sections,
3864                                 &dwarf2_per_objfile->gdb_index, &local_map,
3865                                 &cu_list, &cu_list_elements,
3866                                 &types_list, &types_list_elements))
3867     return 0;
3868
3869   /* Don't use the index if it's empty.  */
3870   if (local_map.symbol_table.empty ())
3871     return 0;
3872
3873   /* If there is a .dwz file, read it so we can get its CU list as
3874      well.  */
3875   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3876   if (dwz != NULL)
3877     {
3878       struct mapped_index dwz_map;
3879       const gdb_byte *dwz_types_ignore;
3880       offset_type dwz_types_elements_ignore;
3881
3882       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3883                                     1,
3884                                     &dwz->gdb_index, &dwz_map,
3885                                     &dwz_list, &dwz_list_elements,
3886                                     &dwz_types_ignore,
3887                                     &dwz_types_elements_ignore))
3888         {
3889           warning (_("could not read '.gdb_index' section from %s; skipping"),
3890                    bfd_get_filename (dwz->dwz_bfd));
3891           return 0;
3892         }
3893     }
3894
3895   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3896                          dwz_list_elements);
3897
3898   if (types_list_elements)
3899     {
3900       struct dwarf2_section_info *section;
3901
3902       /* We can only handle a single .debug_types when we have an
3903          index.  */
3904       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3905         return 0;
3906
3907       section = VEC_index (dwarf2_section_info_def,
3908                            dwarf2_per_objfile->types, 0);
3909
3910       create_signatured_type_table_from_index (objfile, section, types_list,
3911                                                types_list_elements);
3912     }
3913
3914   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3915
3916   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3917   map = new (map) mapped_index ();
3918   *map = local_map;
3919
3920   dwarf2_per_objfile->index_table = map;
3921   dwarf2_per_objfile->using_index = 1;
3922   dwarf2_per_objfile->quick_file_names_table =
3923     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3924
3925   return 1;
3926 }
3927
3928 /* die_reader_func for dw2_get_file_names.  */
3929
3930 static void
3931 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3932                            const gdb_byte *info_ptr,
3933                            struct die_info *comp_unit_die,
3934                            int has_children,
3935                            void *data)
3936 {
3937   struct dwarf2_cu *cu = reader->cu;
3938   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3939   struct dwarf2_per_objfile *dwarf2_per_objfile
3940     = cu->per_cu->dwarf2_per_objfile;
3941   struct objfile *objfile = dwarf2_per_objfile->objfile;
3942   struct dwarf2_per_cu_data *lh_cu;
3943   struct attribute *attr;
3944   int i;
3945   void **slot;
3946   struct quick_file_names *qfn;
3947
3948   gdb_assert (! this_cu->is_debug_types);
3949
3950   /* Our callers never want to match partial units -- instead they
3951      will match the enclosing full CU.  */
3952   if (comp_unit_die->tag == DW_TAG_partial_unit)
3953     {
3954       this_cu->v.quick->no_file_data = 1;
3955       return;
3956     }
3957
3958   lh_cu = this_cu;
3959   slot = NULL;
3960
3961   line_header_up lh;
3962   sect_offset line_offset {};
3963
3964   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3965   if (attr)
3966     {
3967       struct quick_file_names find_entry;
3968
3969       line_offset = (sect_offset) DW_UNSND (attr);
3970
3971       /* We may have already read in this line header (TU line header sharing).
3972          If we have we're done.  */
3973       find_entry.hash.dwo_unit = cu->dwo_unit;
3974       find_entry.hash.line_sect_off = line_offset;
3975       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3976                              &find_entry, INSERT);
3977       if (*slot != NULL)
3978         {
3979           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3980           return;
3981         }
3982
3983       lh = dwarf_decode_line_header (line_offset, cu);
3984     }
3985   if (lh == NULL)
3986     {
3987       lh_cu->v.quick->no_file_data = 1;
3988       return;
3989     }
3990
3991   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3992   qfn->hash.dwo_unit = cu->dwo_unit;
3993   qfn->hash.line_sect_off = line_offset;
3994   gdb_assert (slot != NULL);
3995   *slot = qfn;
3996
3997   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3998
3999   qfn->num_file_names = lh->file_names.size ();
4000   qfn->file_names =
4001     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
4002   for (i = 0; i < lh->file_names.size (); ++i)
4003     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
4004   qfn->real_names = NULL;
4005
4006   lh_cu->v.quick->file_names = qfn;
4007 }
4008
4009 /* A helper for the "quick" functions which attempts to read the line
4010    table for THIS_CU.  */
4011
4012 static struct quick_file_names *
4013 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4014 {
4015   /* This should never be called for TUs.  */
4016   gdb_assert (! this_cu->is_debug_types);
4017   /* Nor type unit groups.  */
4018   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4019
4020   if (this_cu->v.quick->file_names != NULL)
4021     return this_cu->v.quick->file_names;
4022   /* If we know there is no line data, no point in looking again.  */
4023   if (this_cu->v.quick->no_file_data)
4024     return NULL;
4025
4026   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4027
4028   if (this_cu->v.quick->no_file_data)
4029     return NULL;
4030   return this_cu->v.quick->file_names;
4031 }
4032
4033 /* A helper for the "quick" functions which computes and caches the
4034    real path for a given file name from the line table.  */
4035
4036 static const char *
4037 dw2_get_real_path (struct objfile *objfile,
4038                    struct quick_file_names *qfn, int index)
4039 {
4040   if (qfn->real_names == NULL)
4041     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4042                                       qfn->num_file_names, const char *);
4043
4044   if (qfn->real_names[index] == NULL)
4045     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4046
4047   return qfn->real_names[index];
4048 }
4049
4050 static struct symtab *
4051 dw2_find_last_source_symtab (struct objfile *objfile)
4052 {
4053   struct dwarf2_per_objfile *dwarf2_per_objfile
4054     = get_dwarf2_per_objfile (objfile);
4055   int index = dwarf2_per_objfile->n_comp_units - 1;
4056   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4057   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4058
4059   if (cust == NULL)
4060     return NULL;
4061
4062   return compunit_primary_filetab (cust);
4063 }
4064
4065 /* Traversal function for dw2_forget_cached_source_info.  */
4066
4067 static int
4068 dw2_free_cached_file_names (void **slot, void *info)
4069 {
4070   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4071
4072   if (file_data->real_names)
4073     {
4074       int i;
4075
4076       for (i = 0; i < file_data->num_file_names; ++i)
4077         {
4078           xfree ((void*) file_data->real_names[i]);
4079           file_data->real_names[i] = NULL;
4080         }
4081     }
4082
4083   return 1;
4084 }
4085
4086 static void
4087 dw2_forget_cached_source_info (struct objfile *objfile)
4088 {
4089   struct dwarf2_per_objfile *dwarf2_per_objfile
4090     = get_dwarf2_per_objfile (objfile);
4091
4092   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4093                           dw2_free_cached_file_names, NULL);
4094 }
4095
4096 /* Helper function for dw2_map_symtabs_matching_filename that expands
4097    the symtabs and calls the iterator.  */
4098
4099 static int
4100 dw2_map_expand_apply (struct objfile *objfile,
4101                       struct dwarf2_per_cu_data *per_cu,
4102                       const char *name, const char *real_path,
4103                       gdb::function_view<bool (symtab *)> callback)
4104 {
4105   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4106
4107   /* Don't visit already-expanded CUs.  */
4108   if (per_cu->v.quick->compunit_symtab)
4109     return 0;
4110
4111   /* This may expand more than one symtab, and we want to iterate over
4112      all of them.  */
4113   dw2_instantiate_symtab (per_cu);
4114
4115   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4116                                     last_made, callback);
4117 }
4118
4119 /* Implementation of the map_symtabs_matching_filename method.  */
4120
4121 static bool
4122 dw2_map_symtabs_matching_filename
4123   (struct objfile *objfile, const char *name, const char *real_path,
4124    gdb::function_view<bool (symtab *)> callback)
4125 {
4126   int i;
4127   const char *name_basename = lbasename (name);
4128   struct dwarf2_per_objfile *dwarf2_per_objfile
4129     = get_dwarf2_per_objfile (objfile);
4130
4131   /* The rule is CUs specify all the files, including those used by
4132      any TU, so there's no need to scan TUs here.  */
4133
4134   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4135     {
4136       int j;
4137       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4138       struct quick_file_names *file_data;
4139
4140       /* We only need to look at symtabs not already expanded.  */
4141       if (per_cu->v.quick->compunit_symtab)
4142         continue;
4143
4144       file_data = dw2_get_file_names (per_cu);
4145       if (file_data == NULL)
4146         continue;
4147
4148       for (j = 0; j < file_data->num_file_names; ++j)
4149         {
4150           const char *this_name = file_data->file_names[j];
4151           const char *this_real_name;
4152
4153           if (compare_filenames_for_search (this_name, name))
4154             {
4155               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4156                                         callback))
4157                 return true;
4158               continue;
4159             }
4160
4161           /* Before we invoke realpath, which can get expensive when many
4162              files are involved, do a quick comparison of the basenames.  */
4163           if (! basenames_may_differ
4164               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4165             continue;
4166
4167           this_real_name = dw2_get_real_path (objfile, file_data, j);
4168           if (compare_filenames_for_search (this_real_name, name))
4169             {
4170               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4171                                         callback))
4172                 return true;
4173               continue;
4174             }
4175
4176           if (real_path != NULL)
4177             {
4178               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4179               gdb_assert (IS_ABSOLUTE_PATH (name));
4180               if (this_real_name != NULL
4181                   && FILENAME_CMP (real_path, this_real_name) == 0)
4182                 {
4183                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4184                                             callback))
4185                     return true;
4186                   continue;
4187                 }
4188             }
4189         }
4190     }
4191
4192   return false;
4193 }
4194
4195 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4196
4197 struct dw2_symtab_iterator
4198 {
4199   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4200   struct dwarf2_per_objfile *dwarf2_per_objfile;
4201   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4202   int want_specific_block;
4203   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4204      Unused if !WANT_SPECIFIC_BLOCK.  */
4205   int block_index;
4206   /* The kind of symbol we're looking for.  */
4207   domain_enum domain;
4208   /* The list of CUs from the index entry of the symbol,
4209      or NULL if not found.  */
4210   offset_type *vec;
4211   /* The next element in VEC to look at.  */
4212   int next;
4213   /* The number of elements in VEC, or zero if there is no match.  */
4214   int length;
4215   /* Have we seen a global version of the symbol?
4216      If so we can ignore all further global instances.
4217      This is to work around gold/15646, inefficient gold-generated
4218      indices.  */
4219   int global_seen;
4220 };
4221
4222 /* Initialize the index symtab iterator ITER.
4223    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4224    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4225
4226 static void
4227 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4228                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4229                       int want_specific_block,
4230                       int block_index,
4231                       domain_enum domain,
4232                       const char *name)
4233 {
4234   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4235   iter->want_specific_block = want_specific_block;
4236   iter->block_index = block_index;
4237   iter->domain = domain;
4238   iter->next = 0;
4239   iter->global_seen = 0;
4240
4241   mapped_index *index = dwarf2_per_objfile->index_table;
4242
4243   /* index is NULL if OBJF_READNOW.  */
4244   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4245     iter->length = MAYBE_SWAP (*iter->vec);
4246   else
4247     {
4248       iter->vec = NULL;
4249       iter->length = 0;
4250     }
4251 }
4252
4253 /* Return the next matching CU or NULL if there are no more.  */
4254
4255 static struct dwarf2_per_cu_data *
4256 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4257 {
4258   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4259
4260   for ( ; iter->next < iter->length; ++iter->next)
4261     {
4262       offset_type cu_index_and_attrs =
4263         MAYBE_SWAP (iter->vec[iter->next + 1]);
4264       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4265       struct dwarf2_per_cu_data *per_cu;
4266       int want_static = iter->block_index != GLOBAL_BLOCK;
4267       /* This value is only valid for index versions >= 7.  */
4268       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4269       gdb_index_symbol_kind symbol_kind =
4270         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4271       /* Only check the symbol attributes if they're present.
4272          Indices prior to version 7 don't record them,
4273          and indices >= 7 may elide them for certain symbols
4274          (gold does this).  */
4275       int attrs_valid =
4276         (dwarf2_per_objfile->index_table->version >= 7
4277          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4278
4279       /* Don't crash on bad data.  */
4280       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4281                        + dwarf2_per_objfile->n_type_units))
4282         {
4283           complaint (&symfile_complaints,
4284                      _(".gdb_index entry has bad CU index"
4285                        " [in module %s]"),
4286                      objfile_name (dwarf2_per_objfile->objfile));
4287           continue;
4288         }
4289
4290       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4291
4292       /* Skip if already read in.  */
4293       if (per_cu->v.quick->compunit_symtab)
4294         continue;
4295
4296       /* Check static vs global.  */
4297       if (attrs_valid)
4298         {
4299           if (iter->want_specific_block
4300               && want_static != is_static)
4301             continue;
4302           /* Work around gold/15646.  */
4303           if (!is_static && iter->global_seen)
4304             continue;
4305           if (!is_static)
4306             iter->global_seen = 1;
4307         }
4308
4309       /* Only check the symbol's kind if it has one.  */
4310       if (attrs_valid)
4311         {
4312           switch (iter->domain)
4313             {
4314             case VAR_DOMAIN:
4315               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4316                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4317                   /* Some types are also in VAR_DOMAIN.  */
4318                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4319                 continue;
4320               break;
4321             case STRUCT_DOMAIN:
4322               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4323                 continue;
4324               break;
4325             case LABEL_DOMAIN:
4326               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4327                 continue;
4328               break;
4329             default:
4330               break;
4331             }
4332         }
4333
4334       ++iter->next;
4335       return per_cu;
4336     }
4337
4338   return NULL;
4339 }
4340
4341 static struct compunit_symtab *
4342 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4343                    const char *name, domain_enum domain)
4344 {
4345   struct compunit_symtab *stab_best = NULL;
4346   struct dwarf2_per_objfile *dwarf2_per_objfile
4347     = get_dwarf2_per_objfile (objfile);
4348
4349   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4350
4351   struct dw2_symtab_iterator iter;
4352   struct dwarf2_per_cu_data *per_cu;
4353
4354   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4355
4356   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4357     {
4358       struct symbol *sym, *with_opaque = NULL;
4359       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4360       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4361       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4362
4363       sym = block_find_symbol (block, name, domain,
4364                                block_find_non_opaque_type_preferred,
4365                                &with_opaque);
4366
4367       /* Some caution must be observed with overloaded functions
4368          and methods, since the index will not contain any overload
4369          information (but NAME might contain it).  */
4370
4371       if (sym != NULL
4372           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4373         return stab;
4374       if (with_opaque != NULL
4375           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4376         stab_best = stab;
4377
4378       /* Keep looking through other CUs.  */
4379     }
4380
4381   return stab_best;
4382 }
4383
4384 static void
4385 dw2_print_stats (struct objfile *objfile)
4386 {
4387   struct dwarf2_per_objfile *dwarf2_per_objfile
4388     = get_dwarf2_per_objfile (objfile);
4389   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4390   int count = 0;
4391
4392   for (int i = 0; i < total; ++i)
4393     {
4394       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4395
4396       if (!per_cu->v.quick->compunit_symtab)
4397         ++count;
4398     }
4399   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4400   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4401 }
4402
4403 /* This dumps minimal information about the index.
4404    It is called via "mt print objfiles".
4405    One use is to verify .gdb_index has been loaded by the
4406    gdb.dwarf2/gdb-index.exp testcase.  */
4407
4408 static void
4409 dw2_dump (struct objfile *objfile)
4410 {
4411   struct dwarf2_per_objfile *dwarf2_per_objfile
4412     = get_dwarf2_per_objfile (objfile);
4413
4414   gdb_assert (dwarf2_per_objfile->using_index);
4415   printf_filtered (".gdb_index:");
4416   if (dwarf2_per_objfile->index_table != NULL)
4417     {
4418       printf_filtered (" version %d\n",
4419                        dwarf2_per_objfile->index_table->version);
4420     }
4421   else
4422     printf_filtered (" faked for \"readnow\"\n");
4423   printf_filtered ("\n");
4424 }
4425
4426 static void
4427 dw2_relocate (struct objfile *objfile,
4428               const struct section_offsets *new_offsets,
4429               const struct section_offsets *delta)
4430 {
4431   /* There's nothing to relocate here.  */
4432 }
4433
4434 static void
4435 dw2_expand_symtabs_for_function (struct objfile *objfile,
4436                                  const char *func_name)
4437 {
4438   struct dwarf2_per_objfile *dwarf2_per_objfile
4439     = get_dwarf2_per_objfile (objfile);
4440
4441   struct dw2_symtab_iterator iter;
4442   struct dwarf2_per_cu_data *per_cu;
4443
4444   /* Note: It doesn't matter what we pass for block_index here.  */
4445   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4446                         func_name);
4447
4448   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4449     dw2_instantiate_symtab (per_cu);
4450
4451 }
4452
4453 static void
4454 dw2_expand_all_symtabs (struct objfile *objfile)
4455 {
4456   struct dwarf2_per_objfile *dwarf2_per_objfile
4457     = get_dwarf2_per_objfile (objfile);
4458   int total_units = (dwarf2_per_objfile->n_comp_units
4459                      + dwarf2_per_objfile->n_type_units);
4460
4461   for (int i = 0; i < total_units; ++i)
4462     {
4463       struct dwarf2_per_cu_data *per_cu
4464         = dw2_get_cutu (dwarf2_per_objfile, i);
4465
4466       dw2_instantiate_symtab (per_cu);
4467     }
4468 }
4469
4470 static void
4471 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4472                                   const char *fullname)
4473 {
4474   struct dwarf2_per_objfile *dwarf2_per_objfile
4475     = get_dwarf2_per_objfile (objfile);
4476
4477   /* We don't need to consider type units here.
4478      This is only called for examining code, e.g. expand_line_sal.
4479      There can be an order of magnitude (or more) more type units
4480      than comp units, and we avoid them if we can.  */
4481
4482   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4483     {
4484       int j;
4485       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4486       struct quick_file_names *file_data;
4487
4488       /* We only need to look at symtabs not already expanded.  */
4489       if (per_cu->v.quick->compunit_symtab)
4490         continue;
4491
4492       file_data = dw2_get_file_names (per_cu);
4493       if (file_data == NULL)
4494         continue;
4495
4496       for (j = 0; j < file_data->num_file_names; ++j)
4497         {
4498           const char *this_fullname = file_data->file_names[j];
4499
4500           if (filename_cmp (this_fullname, fullname) == 0)
4501             {
4502               dw2_instantiate_symtab (per_cu);
4503               break;
4504             }
4505         }
4506     }
4507 }
4508
4509 static void
4510 dw2_map_matching_symbols (struct objfile *objfile,
4511                           const char * name, domain_enum domain,
4512                           int global,
4513                           int (*callback) (struct block *,
4514                                            struct symbol *, void *),
4515                           void *data, symbol_name_match_type match,
4516                           symbol_compare_ftype *ordered_compare)
4517 {
4518   /* Currently unimplemented; used for Ada.  The function can be called if the
4519      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4520      does not look for non-Ada symbols this function should just return.  */
4521 }
4522
4523 /* Symbol name matcher for .gdb_index names.
4524
4525    Symbol names in .gdb_index have a few particularities:
4526
4527    - There's no indication of which is the language of each symbol.
4528
4529      Since each language has its own symbol name matching algorithm,
4530      and we don't know which language is the right one, we must match
4531      each symbol against all languages.  This would be a potential
4532      performance problem if it were not mitigated by the
4533      mapped_index::name_components lookup table, which significantly
4534      reduces the number of times we need to call into this matcher,
4535      making it a non-issue.
4536
4537    - Symbol names in the index have no overload (parameter)
4538      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4539      appear as "foo" in the index, for example.
4540
4541      This means that the lookup names passed to the symbol name
4542      matcher functions must have no parameter information either
4543      because (e.g.) symbol search name "foo" does not match
4544      lookup-name "foo(int)" [while swapping search name for lookup
4545      name would match].
4546 */
4547 class gdb_index_symbol_name_matcher
4548 {
4549 public:
4550   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4551   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4552
4553   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4554      Returns true if any matcher matches.  */
4555   bool matches (const char *symbol_name);
4556
4557 private:
4558   /* A reference to the lookup name we're matching against.  */
4559   const lookup_name_info &m_lookup_name;
4560
4561   /* A vector holding all the different symbol name matchers, for all
4562      languages.  */
4563   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4564 };
4565
4566 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4567   (const lookup_name_info &lookup_name)
4568     : m_lookup_name (lookup_name)
4569 {
4570   /* Prepare the vector of comparison functions upfront, to avoid
4571      doing the same work for each symbol.  Care is taken to avoid
4572      matching with the same matcher more than once if/when multiple
4573      languages use the same matcher function.  */
4574   auto &matchers = m_symbol_name_matcher_funcs;
4575   matchers.reserve (nr_languages);
4576
4577   matchers.push_back (default_symbol_name_matcher);
4578
4579   for (int i = 0; i < nr_languages; i++)
4580     {
4581       const language_defn *lang = language_def ((enum language) i);
4582       symbol_name_matcher_ftype *name_matcher
4583         = get_symbol_name_matcher (lang, m_lookup_name);
4584
4585       /* Don't insert the same comparison routine more than once.
4586          Note that we do this linear walk instead of a seemingly
4587          cheaper sorted insert, or use a std::set or something like
4588          that, because relative order of function addresses is not
4589          stable.  This is not a problem in practice because the number
4590          of supported languages is low, and the cost here is tiny
4591          compared to the number of searches we'll do afterwards using
4592          this object.  */
4593       if (name_matcher != default_symbol_name_matcher
4594           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4595               == matchers.end ()))
4596         matchers.push_back (name_matcher);
4597     }
4598 }
4599
4600 bool
4601 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4602 {
4603   for (auto matches_name : m_symbol_name_matcher_funcs)
4604     if (matches_name (symbol_name, m_lookup_name, NULL))
4605       return true;
4606
4607   return false;
4608 }
4609
4610 /* Starting from a search name, return the string that finds the upper
4611    bound of all strings that start with SEARCH_NAME in a sorted name
4612    list.  Returns the empty string to indicate that the upper bound is
4613    the end of the list.  */
4614
4615 static std::string
4616 make_sort_after_prefix_name (const char *search_name)
4617 {
4618   /* When looking to complete "func", we find the upper bound of all
4619      symbols that start with "func" by looking for where we'd insert
4620      the closest string that would follow "func" in lexicographical
4621      order.  Usually, that's "func"-with-last-character-incremented,
4622      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4623      will be UTF-8 multi-byte sequences, but we can't be certain.
4624      Especially mind the 0xff character, which is a valid character in
4625      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4626      rule out compilers allowing it in identifiers.  Note that
4627      conveniently, strcmp/strcasecmp are specified to compare
4628      characters interpreted as unsigned char.  So what we do is treat
4629      the whole string as a base 256 number composed of a sequence of
4630      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4631      to 0, and carries 1 to the following more-significant position.
4632      If the very first character in SEARCH_NAME ends up incremented
4633      and carries/overflows, then the upper bound is the end of the
4634      list.  The string after the empty string is also the empty
4635      string.
4636
4637      Some examples of this operation:
4638
4639        SEARCH_NAME  => "+1" RESULT
4640
4641        "abc"              => "abd"
4642        "ab\xff"           => "ac"
4643        "\xff" "a" "\xff"  => "\xff" "b"
4644        "\xff"             => ""
4645        "\xff\xff"         => ""
4646        ""                 => ""
4647
4648      Then, with these symbols for example:
4649
4650       func
4651       func1
4652       fund
4653
4654      completing "func" looks for symbols between "func" and
4655      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4656      which finds "func" and "func1", but not "fund".
4657
4658      And with:
4659
4660       funcÿ     (Latin1 'ÿ' [0xff])
4661       funcÿ1
4662       fund
4663
4664      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4665      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4666
4667      And with:
4668
4669       ÿÿ        (Latin1 'ÿ' [0xff])
4670       ÿÿ1
4671
4672      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4673      the end of the list.
4674   */
4675   std::string after = search_name;
4676   while (!after.empty () && (unsigned char) after.back () == 0xff)
4677     after.pop_back ();
4678   if (!after.empty ())
4679     after.back () = (unsigned char) after.back () + 1;
4680   return after;
4681 }
4682
4683 /* See declaration.  */
4684
4685 std::pair<std::vector<name_component>::const_iterator,
4686           std::vector<name_component>::const_iterator>
4687 mapped_index_base::find_name_components_bounds
4688   (const lookup_name_info &lookup_name_without_params) const
4689 {
4690   auto *name_cmp
4691     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4692
4693   const char *cplus
4694     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4695
4696   /* Comparison function object for lower_bound that matches against a
4697      given symbol name.  */
4698   auto lookup_compare_lower = [&] (const name_component &elem,
4699                                    const char *name)
4700     {
4701       const char *elem_qualified = this->symbol_name_at (elem.idx);
4702       const char *elem_name = elem_qualified + elem.name_offset;
4703       return name_cmp (elem_name, name) < 0;
4704     };
4705
4706   /* Comparison function object for upper_bound that matches against a
4707      given symbol name.  */
4708   auto lookup_compare_upper = [&] (const char *name,
4709                                    const name_component &elem)
4710     {
4711       const char *elem_qualified = this->symbol_name_at (elem.idx);
4712       const char *elem_name = elem_qualified + elem.name_offset;
4713       return name_cmp (name, elem_name) < 0;
4714     };
4715
4716   auto begin = this->name_components.begin ();
4717   auto end = this->name_components.end ();
4718
4719   /* Find the lower bound.  */
4720   auto lower = [&] ()
4721     {
4722       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4723         return begin;
4724       else
4725         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4726     } ();
4727
4728   /* Find the upper bound.  */
4729   auto upper = [&] ()
4730     {
4731       if (lookup_name_without_params.completion_mode ())
4732         {
4733           /* In completion mode, we want UPPER to point past all
4734              symbols names that have the same prefix.  I.e., with
4735              these symbols, and completing "func":
4736
4737               function        << lower bound
4738               function1
4739               other_function  << upper bound
4740
4741              We find the upper bound by looking for the insertion
4742              point of "func"-with-last-character-incremented,
4743              i.e. "fund".  */
4744           std::string after = make_sort_after_prefix_name (cplus);
4745           if (after.empty ())
4746             return end;
4747           return std::lower_bound (lower, end, after.c_str (),
4748                                    lookup_compare_lower);
4749         }
4750       else
4751         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4752     } ();
4753
4754   return {lower, upper};
4755 }
4756
4757 /* See declaration.  */
4758
4759 void
4760 mapped_index_base::build_name_components ()
4761 {
4762   if (!this->name_components.empty ())
4763     return;
4764
4765   this->name_components_casing = case_sensitivity;
4766   auto *name_cmp
4767     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4768
4769   /* The code below only knows how to break apart components of C++
4770      symbol names (and other languages that use '::' as
4771      namespace/module separator).  If we add support for wild matching
4772      to some language that uses some other operator (E.g., Ada, Go and
4773      D use '.'), then we'll need to try splitting the symbol name
4774      according to that language too.  Note that Ada does support wild
4775      matching, but doesn't currently support .gdb_index.  */
4776   auto count = this->symbol_name_count ();
4777   for (offset_type idx = 0; idx < count; idx++)
4778     {
4779       if (this->symbol_name_slot_invalid (idx))
4780         continue;
4781
4782       const char *name = this->symbol_name_at (idx);
4783
4784       /* Add each name component to the name component table.  */
4785       unsigned int previous_len = 0;
4786       for (unsigned int current_len = cp_find_first_component (name);
4787            name[current_len] != '\0';
4788            current_len += cp_find_first_component (name + current_len))
4789         {
4790           gdb_assert (name[current_len] == ':');
4791           this->name_components.push_back ({previous_len, idx});
4792           /* Skip the '::'.  */
4793           current_len += 2;
4794           previous_len = current_len;
4795         }
4796       this->name_components.push_back ({previous_len, idx});
4797     }
4798
4799   /* Sort name_components elements by name.  */
4800   auto name_comp_compare = [&] (const name_component &left,
4801                                 const name_component &right)
4802     {
4803       const char *left_qualified = this->symbol_name_at (left.idx);
4804       const char *right_qualified = this->symbol_name_at (right.idx);
4805
4806       const char *left_name = left_qualified + left.name_offset;
4807       const char *right_name = right_qualified + right.name_offset;
4808
4809       return name_cmp (left_name, right_name) < 0;
4810     };
4811
4812   std::sort (this->name_components.begin (),
4813              this->name_components.end (),
4814              name_comp_compare);
4815 }
4816
4817 /* Helper for dw2_expand_symtabs_matching that works with a
4818    mapped_index_base instead of the containing objfile.  This is split
4819    to a separate function in order to be able to unit test the
4820    name_components matching using a mock mapped_index_base.  For each
4821    symbol name that matches, calls MATCH_CALLBACK, passing it the
4822    symbol's index in the mapped_index_base symbol table.  */
4823
4824 static void
4825 dw2_expand_symtabs_matching_symbol
4826   (mapped_index_base &index,
4827    const lookup_name_info &lookup_name_in,
4828    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4829    enum search_domain kind,
4830    gdb::function_view<void (offset_type)> match_callback)
4831 {
4832   lookup_name_info lookup_name_without_params
4833     = lookup_name_in.make_ignore_params ();
4834   gdb_index_symbol_name_matcher lookup_name_matcher
4835     (lookup_name_without_params);
4836
4837   /* Build the symbol name component sorted vector, if we haven't
4838      yet.  */
4839   index.build_name_components ();
4840
4841   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4842
4843   /* Now for each symbol name in range, check to see if we have a name
4844      match, and if so, call the MATCH_CALLBACK callback.  */
4845
4846   /* The same symbol may appear more than once in the range though.
4847      E.g., if we're looking for symbols that complete "w", and we have
4848      a symbol named "w1::w2", we'll find the two name components for
4849      that same symbol in the range.  To be sure we only call the
4850      callback once per symbol, we first collect the symbol name
4851      indexes that matched in a temporary vector and ignore
4852      duplicates.  */
4853   std::vector<offset_type> matches;
4854   matches.reserve (std::distance (bounds.first, bounds.second));
4855
4856   for (; bounds.first != bounds.second; ++bounds.first)
4857     {
4858       const char *qualified = index.symbol_name_at (bounds.first->idx);
4859
4860       if (!lookup_name_matcher.matches (qualified)
4861           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4862         continue;
4863
4864       matches.push_back (bounds.first->idx);
4865     }
4866
4867   std::sort (matches.begin (), matches.end ());
4868
4869   /* Finally call the callback, once per match.  */
4870   ULONGEST prev = -1;
4871   for (offset_type idx : matches)
4872     {
4873       if (prev != idx)
4874         {
4875           match_callback (idx);
4876           prev = idx;
4877         }
4878     }
4879
4880   /* Above we use a type wider than idx's for 'prev', since 0 and
4881      (offset_type)-1 are both possible values.  */
4882   static_assert (sizeof (prev) > sizeof (offset_type), "");
4883 }
4884
4885 #if GDB_SELF_TEST
4886
4887 namespace selftests { namespace dw2_expand_symtabs_matching {
4888
4889 /* A mock .gdb_index/.debug_names-like name index table, enough to
4890    exercise dw2_expand_symtabs_matching_symbol, which works with the
4891    mapped_index_base interface.  Builds an index from the symbol list
4892    passed as parameter to the constructor.  */
4893 class mock_mapped_index : public mapped_index_base
4894 {
4895 public:
4896   mock_mapped_index (gdb::array_view<const char *> symbols)
4897     : m_symbol_table (symbols)
4898   {}
4899
4900   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4901
4902   /* Return the number of names in the symbol table.  */
4903   virtual size_t symbol_name_count () const
4904   {
4905     return m_symbol_table.size ();
4906   }
4907
4908   /* Get the name of the symbol at IDX in the symbol table.  */
4909   virtual const char *symbol_name_at (offset_type idx) const
4910   {
4911     return m_symbol_table[idx];
4912   }
4913
4914 private:
4915   gdb::array_view<const char *> m_symbol_table;
4916 };
4917
4918 /* Convenience function that converts a NULL pointer to a "<null>"
4919    string, to pass to print routines.  */
4920
4921 static const char *
4922 string_or_null (const char *str)
4923 {
4924   return str != NULL ? str : "<null>";
4925 }
4926
4927 /* Check if a lookup_name_info built from
4928    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4929    index.  EXPECTED_LIST is the list of expected matches, in expected
4930    matching order.  If no match expected, then an empty list is
4931    specified.  Returns true on success.  On failure prints a warning
4932    indicating the file:line that failed, and returns false.  */
4933
4934 static bool
4935 check_match (const char *file, int line,
4936              mock_mapped_index &mock_index,
4937              const char *name, symbol_name_match_type match_type,
4938              bool completion_mode,
4939              std::initializer_list<const char *> expected_list)
4940 {
4941   lookup_name_info lookup_name (name, match_type, completion_mode);
4942
4943   bool matched = true;
4944
4945   auto mismatch = [&] (const char *expected_str,
4946                        const char *got)
4947   {
4948     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4949                "expected=\"%s\", got=\"%s\"\n"),
4950              file, line,
4951              (match_type == symbol_name_match_type::FULL
4952               ? "FULL" : "WILD"),
4953              name, string_or_null (expected_str), string_or_null (got));
4954     matched = false;
4955   };
4956
4957   auto expected_it = expected_list.begin ();
4958   auto expected_end = expected_list.end ();
4959
4960   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4961                                       NULL, ALL_DOMAIN,
4962                                       [&] (offset_type idx)
4963   {
4964     const char *matched_name = mock_index.symbol_name_at (idx);
4965     const char *expected_str
4966       = expected_it == expected_end ? NULL : *expected_it++;
4967
4968     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4969       mismatch (expected_str, matched_name);
4970   });
4971
4972   const char *expected_str
4973   = expected_it == expected_end ? NULL : *expected_it++;
4974   if (expected_str != NULL)
4975     mismatch (expected_str, NULL);
4976
4977   return matched;
4978 }
4979
4980 /* The symbols added to the mock mapped_index for testing (in
4981    canonical form).  */
4982 static const char *test_symbols[] = {
4983   "function",
4984   "std::bar",
4985   "std::zfunction",
4986   "std::zfunction2",
4987   "w1::w2",
4988   "ns::foo<char*>",
4989   "ns::foo<int>",
4990   "ns::foo<long>",
4991   "ns2::tmpl<int>::foo2",
4992   "(anonymous namespace)::A::B::C",
4993
4994   /* These are used to check that the increment-last-char in the
4995      matching algorithm for completion doesn't match "t1_fund" when
4996      completing "t1_func".  */
4997   "t1_func",
4998   "t1_func1",
4999   "t1_fund",
5000   "t1_fund1",
5001
5002   /* A UTF-8 name with multi-byte sequences to make sure that
5003      cp-name-parser understands this as a single identifier ("função"
5004      is "function" in PT).  */
5005   u8"u8função",
5006
5007   /* \377 (0xff) is Latin1 'ÿ'.  */
5008   "yfunc\377",
5009
5010   /* \377 (0xff) is Latin1 'ÿ'.  */
5011   "\377",
5012   "\377\377123",
5013
5014   /* A name with all sorts of complications.  Starts with "z" to make
5015      it easier for the completion tests below.  */
5016 #define Z_SYM_NAME \
5017   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5018     "::tuple<(anonymous namespace)::ui*, " \
5019     "std::default_delete<(anonymous namespace)::ui>, void>"
5020
5021   Z_SYM_NAME
5022 };
5023
5024 /* Returns true if the mapped_index_base::find_name_component_bounds
5025    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5026    in completion mode.  */
5027
5028 static bool
5029 check_find_bounds_finds (mapped_index_base &index,
5030                          const char *search_name,
5031                          gdb::array_view<const char *> expected_syms)
5032 {
5033   lookup_name_info lookup_name (search_name,
5034                                 symbol_name_match_type::FULL, true);
5035
5036   auto bounds = index.find_name_components_bounds (lookup_name);
5037
5038   size_t distance = std::distance (bounds.first, bounds.second);
5039   if (distance != expected_syms.size ())
5040     return false;
5041
5042   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5043     {
5044       auto nc_elem = bounds.first + exp_elem;
5045       const char *qualified = index.symbol_name_at (nc_elem->idx);
5046       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5047         return false;
5048     }
5049
5050   return true;
5051 }
5052
5053 /* Test the lower-level mapped_index::find_name_component_bounds
5054    method.  */
5055
5056 static void
5057 test_mapped_index_find_name_component_bounds ()
5058 {
5059   mock_mapped_index mock_index (test_symbols);
5060
5061   mock_index.build_name_components ();
5062
5063   /* Test the lower-level mapped_index::find_name_component_bounds
5064      method in completion mode.  */
5065   {
5066     static const char *expected_syms[] = {
5067       "t1_func",
5068       "t1_func1",
5069     };
5070
5071     SELF_CHECK (check_find_bounds_finds (mock_index,
5072                                          "t1_func", expected_syms));
5073   }
5074
5075   /* Check that the increment-last-char in the name matching algorithm
5076      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5077   {
5078     static const char *expected_syms1[] = {
5079       "\377",
5080       "\377\377123",
5081     };
5082     SELF_CHECK (check_find_bounds_finds (mock_index,
5083                                          "\377", expected_syms1));
5084
5085     static const char *expected_syms2[] = {
5086       "\377\377123",
5087     };
5088     SELF_CHECK (check_find_bounds_finds (mock_index,
5089                                          "\377\377", expected_syms2));
5090   }
5091 }
5092
5093 /* Test dw2_expand_symtabs_matching_symbol.  */
5094
5095 static void
5096 test_dw2_expand_symtabs_matching_symbol ()
5097 {
5098   mock_mapped_index mock_index (test_symbols);
5099
5100   /* We let all tests run until the end even if some fails, for debug
5101      convenience.  */
5102   bool any_mismatch = false;
5103
5104   /* Create the expected symbols list (an initializer_list).  Needed
5105      because lists have commas, and we need to pass them to CHECK,
5106      which is a macro.  */
5107 #define EXPECT(...) { __VA_ARGS__ }
5108
5109   /* Wrapper for check_match that passes down the current
5110      __FILE__/__LINE__.  */
5111 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5112   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5113                                 mock_index,                             \
5114                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5115                                 EXPECTED_LIST)
5116
5117   /* Identity checks.  */
5118   for (const char *sym : test_symbols)
5119     {
5120       /* Should be able to match all existing symbols.  */
5121       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5122                    EXPECT (sym));
5123
5124       /* Should be able to match all existing symbols with
5125          parameters.  */
5126       std::string with_params = std::string (sym) + "(int)";
5127       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5128                    EXPECT (sym));
5129
5130       /* Should be able to match all existing symbols with
5131          parameters and qualifiers.  */
5132       with_params = std::string (sym) + " ( int ) const";
5133       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5134                    EXPECT (sym));
5135
5136       /* This should really find sym, but cp-name-parser.y doesn't
5137          know about lvalue/rvalue qualifiers yet.  */
5138       with_params = std::string (sym) + " ( int ) &&";
5139       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5140                    {});
5141     }
5142
5143   /* Check that the name matching algorithm for completion doesn't get
5144      confused with Latin1 'ÿ' / 0xff.  */
5145   {
5146     static const char str[] = "\377";
5147     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5148                  EXPECT ("\377", "\377\377123"));
5149   }
5150
5151   /* Check that the increment-last-char in the matching algorithm for
5152      completion doesn't match "t1_fund" when completing "t1_func".  */
5153   {
5154     static const char str[] = "t1_func";
5155     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5156                  EXPECT ("t1_func", "t1_func1"));
5157   }
5158
5159   /* Check that completion mode works at each prefix of the expected
5160      symbol name.  */
5161   {
5162     static const char str[] = "function(int)";
5163     size_t len = strlen (str);
5164     std::string lookup;
5165
5166     for (size_t i = 1; i < len; i++)
5167       {
5168         lookup.assign (str, i);
5169         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5170                      EXPECT ("function"));
5171       }
5172   }
5173
5174   /* While "w" is a prefix of both components, the match function
5175      should still only be called once.  */
5176   {
5177     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5178                  EXPECT ("w1::w2"));
5179     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5180                  EXPECT ("w1::w2"));
5181   }
5182
5183   /* Same, with a "complicated" symbol.  */
5184   {
5185     static const char str[] = Z_SYM_NAME;
5186     size_t len = strlen (str);
5187     std::string lookup;
5188
5189     for (size_t i = 1; i < len; i++)
5190       {
5191         lookup.assign (str, i);
5192         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5193                      EXPECT (Z_SYM_NAME));
5194       }
5195   }
5196
5197   /* In FULL mode, an incomplete symbol doesn't match.  */
5198   {
5199     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5200                  {});
5201   }
5202
5203   /* A complete symbol with parameters matches any overload, since the
5204      index has no overload info.  */
5205   {
5206     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5207                  EXPECT ("std::zfunction", "std::zfunction2"));
5208     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5209                  EXPECT ("std::zfunction", "std::zfunction2"));
5210     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5211                  EXPECT ("std::zfunction", "std::zfunction2"));
5212   }
5213
5214   /* Check that whitespace is ignored appropriately.  A symbol with a
5215      template argument list. */
5216   {
5217     static const char expected[] = "ns::foo<int>";
5218     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5219                  EXPECT (expected));
5220     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5221                  EXPECT (expected));
5222   }
5223
5224   /* Check that whitespace is ignored appropriately.  A symbol with a
5225      template argument list that includes a pointer.  */
5226   {
5227     static const char expected[] = "ns::foo<char*>";
5228     /* Try both completion and non-completion modes.  */
5229     static const bool completion_mode[2] = {false, true};
5230     for (size_t i = 0; i < 2; i++)
5231       {
5232         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5233                      completion_mode[i], EXPECT (expected));
5234         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5235                      completion_mode[i], EXPECT (expected));
5236
5237         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5238                      completion_mode[i], EXPECT (expected));
5239         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5240                      completion_mode[i], EXPECT (expected));
5241       }
5242   }
5243
5244   {
5245     /* Check method qualifiers are ignored.  */
5246     static const char expected[] = "ns::foo<char*>";
5247     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5248                  symbol_name_match_type::FULL, true, EXPECT (expected));
5249     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5250                  symbol_name_match_type::FULL, true, EXPECT (expected));
5251     CHECK_MATCH ("foo < char * >  ( int ) const",
5252                  symbol_name_match_type::WILD, true, EXPECT (expected));
5253     CHECK_MATCH ("foo < char * >  ( int ) &&",
5254                  symbol_name_match_type::WILD, true, EXPECT (expected));
5255   }
5256
5257   /* Test lookup names that don't match anything.  */
5258   {
5259     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5260                  {});
5261
5262     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5263                  {});
5264   }
5265
5266   /* Some wild matching tests, exercising "(anonymous namespace)",
5267      which should not be confused with a parameter list.  */
5268   {
5269     static const char *syms[] = {
5270       "A::B::C",
5271       "B::C",
5272       "C",
5273       "A :: B :: C ( int )",
5274       "B :: C ( int )",
5275       "C ( int )",
5276     };
5277
5278     for (const char *s : syms)
5279       {
5280         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5281                      EXPECT ("(anonymous namespace)::A::B::C"));
5282       }
5283   }
5284
5285   {
5286     static const char expected[] = "ns2::tmpl<int>::foo2";
5287     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5288                  EXPECT (expected));
5289     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5290                  EXPECT (expected));
5291   }
5292
5293   SELF_CHECK (!any_mismatch);
5294
5295 #undef EXPECT
5296 #undef CHECK_MATCH
5297 }
5298
5299 static void
5300 run_test ()
5301 {
5302   test_mapped_index_find_name_component_bounds ();
5303   test_dw2_expand_symtabs_matching_symbol ();
5304 }
5305
5306 }} // namespace selftests::dw2_expand_symtabs_matching
5307
5308 #endif /* GDB_SELF_TEST */
5309
5310 /* If FILE_MATCHER is NULL or if PER_CU has
5311    dwarf2_per_cu_quick_data::MARK set (see
5312    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5313    EXPANSION_NOTIFY on it.  */
5314
5315 static void
5316 dw2_expand_symtabs_matching_one
5317   (struct dwarf2_per_cu_data *per_cu,
5318    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5319    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5320 {
5321   if (file_matcher == NULL || per_cu->v.quick->mark)
5322     {
5323       bool symtab_was_null
5324         = (per_cu->v.quick->compunit_symtab == NULL);
5325
5326       dw2_instantiate_symtab (per_cu);
5327
5328       if (expansion_notify != NULL
5329           && symtab_was_null
5330           && per_cu->v.quick->compunit_symtab != NULL)
5331         expansion_notify (per_cu->v.quick->compunit_symtab);
5332     }
5333 }
5334
5335 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5336    matched, to expand corresponding CUs that were marked.  IDX is the
5337    index of the symbol name that matched.  */
5338
5339 static void
5340 dw2_expand_marked_cus
5341   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5342    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5343    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5344    search_domain kind)
5345 {
5346   offset_type *vec, vec_len, vec_idx;
5347   bool global_seen = false;
5348   mapped_index &index = *dwarf2_per_objfile->index_table;
5349
5350   vec = (offset_type *) (index.constant_pool
5351                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5352   vec_len = MAYBE_SWAP (vec[0]);
5353   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5354     {
5355       struct dwarf2_per_cu_data *per_cu;
5356       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5357       /* This value is only valid for index versions >= 7.  */
5358       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5359       gdb_index_symbol_kind symbol_kind =
5360         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5361       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5362       /* Only check the symbol attributes if they're present.
5363          Indices prior to version 7 don't record them,
5364          and indices >= 7 may elide them for certain symbols
5365          (gold does this).  */
5366       int attrs_valid =
5367         (index.version >= 7
5368          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5369
5370       /* Work around gold/15646.  */
5371       if (attrs_valid)
5372         {
5373           if (!is_static && global_seen)
5374             continue;
5375           if (!is_static)
5376             global_seen = true;
5377         }
5378
5379       /* Only check the symbol's kind if it has one.  */
5380       if (attrs_valid)
5381         {
5382           switch (kind)
5383             {
5384             case VARIABLES_DOMAIN:
5385               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5386                 continue;
5387               break;
5388             case FUNCTIONS_DOMAIN:
5389               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5390                 continue;
5391               break;
5392             case TYPES_DOMAIN:
5393               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5394                 continue;
5395               break;
5396             default:
5397               break;
5398             }
5399         }
5400
5401       /* Don't crash on bad data.  */
5402       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5403                        + dwarf2_per_objfile->n_type_units))
5404         {
5405           complaint (&symfile_complaints,
5406                      _(".gdb_index entry has bad CU index"
5407                        " [in module %s]"),
5408                        objfile_name (dwarf2_per_objfile->objfile));
5409           continue;
5410         }
5411
5412       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5413       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5414                                        expansion_notify);
5415     }
5416 }
5417
5418 /* If FILE_MATCHER is non-NULL, set all the
5419    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5420    that match FILE_MATCHER.  */
5421
5422 static void
5423 dw_expand_symtabs_matching_file_matcher
5424   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5425    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5426 {
5427   if (file_matcher == NULL)
5428     return;
5429
5430   objfile *const objfile = dwarf2_per_objfile->objfile;
5431
5432   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5433                                             htab_eq_pointer,
5434                                             NULL, xcalloc, xfree));
5435   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5436                                                 htab_eq_pointer,
5437                                                 NULL, xcalloc, xfree));
5438
5439   /* The rule is CUs specify all the files, including those used by
5440      any TU, so there's no need to scan TUs here.  */
5441
5442   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5443     {
5444       int j;
5445       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5446       struct quick_file_names *file_data;
5447       void **slot;
5448
5449       QUIT;
5450
5451       per_cu->v.quick->mark = 0;
5452
5453       /* We only need to look at symtabs not already expanded.  */
5454       if (per_cu->v.quick->compunit_symtab)
5455         continue;
5456
5457       file_data = dw2_get_file_names (per_cu);
5458       if (file_data == NULL)
5459         continue;
5460
5461       if (htab_find (visited_not_found.get (), file_data) != NULL)
5462         continue;
5463       else if (htab_find (visited_found.get (), file_data) != NULL)
5464         {
5465           per_cu->v.quick->mark = 1;
5466           continue;
5467         }
5468
5469       for (j = 0; j < file_data->num_file_names; ++j)
5470         {
5471           const char *this_real_name;
5472
5473           if (file_matcher (file_data->file_names[j], false))
5474             {
5475               per_cu->v.quick->mark = 1;
5476               break;
5477             }
5478
5479           /* Before we invoke realpath, which can get expensive when many
5480              files are involved, do a quick comparison of the basenames.  */
5481           if (!basenames_may_differ
5482               && !file_matcher (lbasename (file_data->file_names[j]),
5483                                 true))
5484             continue;
5485
5486           this_real_name = dw2_get_real_path (objfile, file_data, j);
5487           if (file_matcher (this_real_name, false))
5488             {
5489               per_cu->v.quick->mark = 1;
5490               break;
5491             }
5492         }
5493
5494       slot = htab_find_slot (per_cu->v.quick->mark
5495                              ? visited_found.get ()
5496                              : visited_not_found.get (),
5497                              file_data, INSERT);
5498       *slot = file_data;
5499     }
5500 }
5501
5502 static void
5503 dw2_expand_symtabs_matching
5504   (struct objfile *objfile,
5505    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5506    const lookup_name_info &lookup_name,
5507    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5508    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5509    enum search_domain kind)
5510 {
5511   struct dwarf2_per_objfile *dwarf2_per_objfile
5512     = get_dwarf2_per_objfile (objfile);
5513
5514   /* index_table is NULL if OBJF_READNOW.  */
5515   if (!dwarf2_per_objfile->index_table)
5516     return;
5517
5518   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5519
5520   mapped_index &index = *dwarf2_per_objfile->index_table;
5521
5522   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5523                                       symbol_matcher,
5524                                       kind, [&] (offset_type idx)
5525     {
5526       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5527                              expansion_notify, kind);
5528     });
5529 }
5530
5531 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5532    symtab.  */
5533
5534 static struct compunit_symtab *
5535 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5536                                           CORE_ADDR pc)
5537 {
5538   int i;
5539
5540   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5541       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5542     return cust;
5543
5544   if (cust->includes == NULL)
5545     return NULL;
5546
5547   for (i = 0; cust->includes[i]; ++i)
5548     {
5549       struct compunit_symtab *s = cust->includes[i];
5550
5551       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5552       if (s != NULL)
5553         return s;
5554     }
5555
5556   return NULL;
5557 }
5558
5559 static struct compunit_symtab *
5560 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5561                                   struct bound_minimal_symbol msymbol,
5562                                   CORE_ADDR pc,
5563                                   struct obj_section *section,
5564                                   int warn_if_readin)
5565 {
5566   struct dwarf2_per_cu_data *data;
5567   struct compunit_symtab *result;
5568
5569   if (!objfile->psymtabs_addrmap)
5570     return NULL;
5571
5572   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5573                                                      pc);
5574   if (!data)
5575     return NULL;
5576
5577   if (warn_if_readin && data->v.quick->compunit_symtab)
5578     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5579              paddress (get_objfile_arch (objfile), pc));
5580
5581   result
5582     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5583                                                 pc);
5584   gdb_assert (result != NULL);
5585   return result;
5586 }
5587
5588 static void
5589 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5590                           void *data, int need_fullname)
5591 {
5592   struct dwarf2_per_objfile *dwarf2_per_objfile
5593     = get_dwarf2_per_objfile (objfile);
5594
5595   if (!dwarf2_per_objfile->filenames_cache)
5596     {
5597       dwarf2_per_objfile->filenames_cache.emplace ();
5598
5599       htab_up visited (htab_create_alloc (10,
5600                                           htab_hash_pointer, htab_eq_pointer,
5601                                           NULL, xcalloc, xfree));
5602
5603       /* The rule is CUs specify all the files, including those used
5604          by any TU, so there's no need to scan TUs here.  We can
5605          ignore file names coming from already-expanded CUs.  */
5606
5607       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5608         {
5609           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5610
5611           if (per_cu->v.quick->compunit_symtab)
5612             {
5613               void **slot = htab_find_slot (visited.get (),
5614                                             per_cu->v.quick->file_names,
5615                                             INSERT);
5616
5617               *slot = per_cu->v.quick->file_names;
5618             }
5619         }
5620
5621       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5622         {
5623           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5624           struct quick_file_names *file_data;
5625           void **slot;
5626
5627           /* We only need to look at symtabs not already expanded.  */
5628           if (per_cu->v.quick->compunit_symtab)
5629             continue;
5630
5631           file_data = dw2_get_file_names (per_cu);
5632           if (file_data == NULL)
5633             continue;
5634
5635           slot = htab_find_slot (visited.get (), file_data, INSERT);
5636           if (*slot)
5637             {
5638               /* Already visited.  */
5639               continue;
5640             }
5641           *slot = file_data;
5642
5643           for (int j = 0; j < file_data->num_file_names; ++j)
5644             {
5645               const char *filename = file_data->file_names[j];
5646               dwarf2_per_objfile->filenames_cache->seen (filename);
5647             }
5648         }
5649     }
5650
5651   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5652     {
5653       gdb::unique_xmalloc_ptr<char> this_real_name;
5654
5655       if (need_fullname)
5656         this_real_name = gdb_realpath (filename);
5657       (*fun) (filename, this_real_name.get (), data);
5658     });
5659 }
5660
5661 static int
5662 dw2_has_symbols (struct objfile *objfile)
5663 {
5664   return 1;
5665 }
5666
5667 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5668 {
5669   dw2_has_symbols,
5670   dw2_find_last_source_symtab,
5671   dw2_forget_cached_source_info,
5672   dw2_map_symtabs_matching_filename,
5673   dw2_lookup_symbol,
5674   dw2_print_stats,
5675   dw2_dump,
5676   dw2_relocate,
5677   dw2_expand_symtabs_for_function,
5678   dw2_expand_all_symtabs,
5679   dw2_expand_symtabs_with_fullname,
5680   dw2_map_matching_symbols,
5681   dw2_expand_symtabs_matching,
5682   dw2_find_pc_sect_compunit_symtab,
5683   NULL,
5684   dw2_map_symbol_filenames
5685 };
5686
5687 /* DWARF-5 debug_names reader.  */
5688
5689 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5690 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5691
5692 /* A helper function that reads the .debug_names section in SECTION
5693    and fills in MAP.  FILENAME is the name of the file containing the
5694    section; it is used for error reporting.
5695
5696    Returns true if all went well, false otherwise.  */
5697
5698 static bool
5699 read_debug_names_from_section (struct objfile *objfile,
5700                                const char *filename,
5701                                struct dwarf2_section_info *section,
5702                                mapped_debug_names &map)
5703 {
5704   if (dwarf2_section_empty_p (section))
5705     return false;
5706
5707   /* Older elfutils strip versions could keep the section in the main
5708      executable while splitting it for the separate debug info file.  */
5709   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5710     return false;
5711
5712   dwarf2_read_section (objfile, section);
5713
5714   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5715
5716   const gdb_byte *addr = section->buffer;
5717
5718   bfd *const abfd = get_section_bfd_owner (section);
5719
5720   unsigned int bytes_read;
5721   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5722   addr += bytes_read;
5723
5724   map.dwarf5_is_dwarf64 = bytes_read != 4;
5725   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5726   if (bytes_read + length != section->size)
5727     {
5728       /* There may be multiple per-CU indices.  */
5729       warning (_("Section .debug_names in %s length %s does not match "
5730                  "section length %s, ignoring .debug_names."),
5731                filename, plongest (bytes_read + length),
5732                pulongest (section->size));
5733       return false;
5734     }
5735
5736   /* The version number.  */
5737   uint16_t version = read_2_bytes (abfd, addr);
5738   addr += 2;
5739   if (version != 5)
5740     {
5741       warning (_("Section .debug_names in %s has unsupported version %d, "
5742                  "ignoring .debug_names."),
5743                filename, version);
5744       return false;
5745     }
5746
5747   /* Padding.  */
5748   uint16_t padding = read_2_bytes (abfd, addr);
5749   addr += 2;
5750   if (padding != 0)
5751     {
5752       warning (_("Section .debug_names in %s has unsupported padding %d, "
5753                  "ignoring .debug_names."),
5754                filename, padding);
5755       return false;
5756     }
5757
5758   /* comp_unit_count - The number of CUs in the CU list.  */
5759   map.cu_count = read_4_bytes (abfd, addr);
5760   addr += 4;
5761
5762   /* local_type_unit_count - The number of TUs in the local TU
5763      list.  */
5764   map.tu_count = read_4_bytes (abfd, addr);
5765   addr += 4;
5766
5767   /* foreign_type_unit_count - The number of TUs in the foreign TU
5768      list.  */
5769   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5770   addr += 4;
5771   if (foreign_tu_count != 0)
5772     {
5773       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5774                  "ignoring .debug_names."),
5775                filename, static_cast<unsigned long> (foreign_tu_count));
5776       return false;
5777     }
5778
5779   /* bucket_count - The number of hash buckets in the hash lookup
5780      table.  */
5781   map.bucket_count = read_4_bytes (abfd, addr);
5782   addr += 4;
5783
5784   /* name_count - The number of unique names in the index.  */
5785   map.name_count = read_4_bytes (abfd, addr);
5786   addr += 4;
5787
5788   /* abbrev_table_size - The size in bytes of the abbreviations
5789      table.  */
5790   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5791   addr += 4;
5792
5793   /* augmentation_string_size - The size in bytes of the augmentation
5794      string.  This value is rounded up to a multiple of 4.  */
5795   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5796   addr += 4;
5797   map.augmentation_is_gdb = ((augmentation_string_size
5798                               == sizeof (dwarf5_augmentation))
5799                              && memcmp (addr, dwarf5_augmentation,
5800                                         sizeof (dwarf5_augmentation)) == 0);
5801   augmentation_string_size += (-augmentation_string_size) & 3;
5802   addr += augmentation_string_size;
5803
5804   /* List of CUs */
5805   map.cu_table_reordered = addr;
5806   addr += map.cu_count * map.offset_size;
5807
5808   /* List of Local TUs */
5809   map.tu_table_reordered = addr;
5810   addr += map.tu_count * map.offset_size;
5811
5812   /* Hash Lookup Table */
5813   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5814   addr += map.bucket_count * 4;
5815   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5816   addr += map.name_count * 4;
5817
5818   /* Name Table */
5819   map.name_table_string_offs_reordered = addr;
5820   addr += map.name_count * map.offset_size;
5821   map.name_table_entry_offs_reordered = addr;
5822   addr += map.name_count * map.offset_size;
5823
5824   const gdb_byte *abbrev_table_start = addr;
5825   for (;;)
5826     {
5827       unsigned int bytes_read;
5828       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5829       addr += bytes_read;
5830       if (index_num == 0)
5831         break;
5832
5833       const auto insertpair
5834         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5835       if (!insertpair.second)
5836         {
5837           warning (_("Section .debug_names in %s has duplicate index %s, "
5838                      "ignoring .debug_names."),
5839                    filename, pulongest (index_num));
5840           return false;
5841         }
5842       mapped_debug_names::index_val &indexval = insertpair.first->second;
5843       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5844       addr += bytes_read;
5845
5846       for (;;)
5847         {
5848           mapped_debug_names::index_val::attr attr;
5849           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5850           addr += bytes_read;
5851           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5852           addr += bytes_read;
5853           if (attr.form == DW_FORM_implicit_const)
5854             {
5855               attr.implicit_const = read_signed_leb128 (abfd, addr,
5856                                                         &bytes_read);
5857               addr += bytes_read;
5858             }
5859           if (attr.dw_idx == 0 && attr.form == 0)
5860             break;
5861           indexval.attr_vec.push_back (std::move (attr));
5862         }
5863     }
5864   if (addr != abbrev_table_start + abbrev_table_size)
5865     {
5866       warning (_("Section .debug_names in %s has abbreviation_table "
5867                  "of size %zu vs. written as %u, ignoring .debug_names."),
5868                filename, addr - abbrev_table_start, abbrev_table_size);
5869       return false;
5870     }
5871   map.entry_pool = addr;
5872
5873   return true;
5874 }
5875
5876 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5877    list.  */
5878
5879 static void
5880 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5881                                   const mapped_debug_names &map,
5882                                   dwarf2_section_info &section,
5883                                   bool is_dwz, int base_offset)
5884 {
5885   sect_offset sect_off_prev;
5886   for (uint32_t i = 0; i <= map.cu_count; ++i)
5887     {
5888       sect_offset sect_off_next;
5889       if (i < map.cu_count)
5890         {
5891           sect_off_next
5892             = (sect_offset) (extract_unsigned_integer
5893                              (map.cu_table_reordered + i * map.offset_size,
5894                               map.offset_size,
5895                               map.dwarf5_byte_order));
5896         }
5897       else
5898         sect_off_next = (sect_offset) section.size;
5899       if (i >= 1)
5900         {
5901           const ULONGEST length = sect_off_next - sect_off_prev;
5902           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5903             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5904                                          sect_off_prev, length);
5905         }
5906       sect_off_prev = sect_off_next;
5907     }
5908 }
5909
5910 /* Read the CU list from the mapped index, and use it to create all
5911    the CU objects for this dwarf2_per_objfile.  */
5912
5913 static void
5914 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5915                              const mapped_debug_names &map,
5916                              const mapped_debug_names &dwz_map)
5917 {
5918   struct objfile *objfile = dwarf2_per_objfile->objfile;
5919
5920   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5921   dwarf2_per_objfile->all_comp_units
5922     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5923                  dwarf2_per_objfile->n_comp_units);
5924
5925   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5926                                     dwarf2_per_objfile->info,
5927                                     false /* is_dwz */,
5928                                     0 /* base_offset */);
5929
5930   if (dwz_map.cu_count == 0)
5931     return;
5932
5933   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5934   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5935                                     true /* is_dwz */,
5936                                     map.cu_count /* base_offset */);
5937 }
5938
5939 /* Read .debug_names.  If everything went ok, initialize the "quick"
5940    elements of all the CUs and return true.  Otherwise, return false.  */
5941
5942 static bool
5943 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5944 {
5945   mapped_debug_names local_map (dwarf2_per_objfile);
5946   mapped_debug_names dwz_map (dwarf2_per_objfile);
5947   struct objfile *objfile = dwarf2_per_objfile->objfile;
5948
5949   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5950                                       &dwarf2_per_objfile->debug_names,
5951                                       local_map))
5952     return false;
5953
5954   /* Don't use the index if it's empty.  */
5955   if (local_map.name_count == 0)
5956     return false;
5957
5958   /* If there is a .dwz file, read it so we can get its CU list as
5959      well.  */
5960   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5961   if (dwz != NULL)
5962     {
5963       if (!read_debug_names_from_section (objfile,
5964                                           bfd_get_filename (dwz->dwz_bfd),
5965                                           &dwz->debug_names, dwz_map))
5966         {
5967           warning (_("could not read '.debug_names' section from %s; skipping"),
5968                    bfd_get_filename (dwz->dwz_bfd));
5969           return false;
5970         }
5971     }
5972
5973   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5974
5975   if (local_map.tu_count != 0)
5976     {
5977       /* We can only handle a single .debug_types when we have an
5978          index.  */
5979       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5980         return false;
5981
5982       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5983                                                 dwarf2_per_objfile->types, 0);
5984
5985       create_signatured_type_table_from_debug_names
5986         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5987     }
5988
5989   create_addrmap_from_aranges (dwarf2_per_objfile,
5990                                &dwarf2_per_objfile->debug_aranges);
5991
5992   dwarf2_per_objfile->debug_names_table.reset
5993     (new mapped_debug_names (dwarf2_per_objfile));
5994   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5995   dwarf2_per_objfile->using_index = 1;
5996   dwarf2_per_objfile->quick_file_names_table =
5997     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5998
5999   return true;
6000 }
6001
6002 /* Symbol name hashing function as specified by DWARF-5.  */
6003
6004 static uint32_t
6005 dwarf5_djb_hash (const char *str_)
6006 {
6007   const unsigned char *str = (const unsigned char *) str_;
6008
6009   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6010      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6011
6012   uint32_t hash = 5381;
6013   while (int c = *str++)
6014     hash = hash * 33 + tolower (c);
6015   return hash;
6016 }
6017
6018 /* Type used to manage iterating over all CUs looking for a symbol for
6019    .debug_names.  */
6020
6021 class dw2_debug_names_iterator
6022 {
6023 public:
6024   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6025      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6026   dw2_debug_names_iterator (const mapped_debug_names &map,
6027                             bool want_specific_block,
6028                             block_enum block_index, domain_enum domain,
6029                             const char *name)
6030     : m_map (map), m_want_specific_block (want_specific_block),
6031       m_block_index (block_index), m_domain (domain),
6032       m_addr (find_vec_in_debug_names (map, name))
6033   {}
6034
6035   dw2_debug_names_iterator (const mapped_debug_names &map,
6036                             search_domain search, uint32_t namei)
6037     : m_map (map),
6038       m_search (search),
6039       m_addr (find_vec_in_debug_names (map, namei))
6040   {}
6041
6042   /* Return the next matching CU or NULL if there are no more.  */
6043   dwarf2_per_cu_data *next ();
6044
6045 private:
6046   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6047                                                   const char *name);
6048   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6049                                                   uint32_t namei);
6050
6051   /* The internalized form of .debug_names.  */
6052   const mapped_debug_names &m_map;
6053
6054   /* If true, only look for symbols that match BLOCK_INDEX.  */
6055   const bool m_want_specific_block = false;
6056
6057   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6058      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6059      value.  */
6060   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6061
6062   /* The kind of symbol we're looking for.  */
6063   const domain_enum m_domain = UNDEF_DOMAIN;
6064   const search_domain m_search = ALL_DOMAIN;
6065
6066   /* The list of CUs from the index entry of the symbol, or NULL if
6067      not found.  */
6068   const gdb_byte *m_addr;
6069 };
6070
6071 const char *
6072 mapped_debug_names::namei_to_name (uint32_t namei) const
6073 {
6074   const ULONGEST namei_string_offs
6075     = extract_unsigned_integer ((name_table_string_offs_reordered
6076                                  + namei * offset_size),
6077                                 offset_size,
6078                                 dwarf5_byte_order);
6079   return read_indirect_string_at_offset
6080     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6081 }
6082
6083 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6084    found, return pointer to its pool data.  If NAME cannot be found,
6085    return NULL.  */
6086
6087 const gdb_byte *
6088 dw2_debug_names_iterator::find_vec_in_debug_names
6089   (const mapped_debug_names &map, const char *name)
6090 {
6091   int (*cmp) (const char *, const char *);
6092
6093   if (current_language->la_language == language_cplus
6094       || current_language->la_language == language_fortran
6095       || current_language->la_language == language_d)
6096     {
6097       /* NAME is already canonical.  Drop any qualifiers as
6098          .debug_names does not contain any.  */
6099
6100       if (strchr (name, '(') != NULL)
6101         {
6102           gdb::unique_xmalloc_ptr<char> without_params
6103             = cp_remove_params (name);
6104
6105           if (without_params != NULL)
6106             {
6107               name = without_params.get();
6108             }
6109         }
6110     }
6111
6112   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6113
6114   const uint32_t full_hash = dwarf5_djb_hash (name);
6115   uint32_t namei
6116     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6117                                 (map.bucket_table_reordered
6118                                  + (full_hash % map.bucket_count)), 4,
6119                                 map.dwarf5_byte_order);
6120   if (namei == 0)
6121     return NULL;
6122   --namei;
6123   if (namei >= map.name_count)
6124     {
6125       complaint (&symfile_complaints,
6126                  _("Wrong .debug_names with name index %u but name_count=%u "
6127                    "[in module %s]"),
6128                  namei, map.name_count,
6129                  objfile_name (map.dwarf2_per_objfile->objfile));
6130       return NULL;
6131     }
6132
6133   for (;;)
6134     {
6135       const uint32_t namei_full_hash
6136         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6137                                     (map.hash_table_reordered + namei), 4,
6138                                     map.dwarf5_byte_order);
6139       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6140         return NULL;
6141
6142       if (full_hash == namei_full_hash)
6143         {
6144           const char *const namei_string = map.namei_to_name (namei);
6145
6146 #if 0 /* An expensive sanity check.  */
6147           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6148             {
6149               complaint (&symfile_complaints,
6150                          _("Wrong .debug_names hash for string at index %u "
6151                            "[in module %s]"),
6152                          namei, objfile_name (dwarf2_per_objfile->objfile));
6153               return NULL;
6154             }
6155 #endif
6156
6157           if (cmp (namei_string, name) == 0)
6158             {
6159               const ULONGEST namei_entry_offs
6160                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6161                                              + namei * map.offset_size),
6162                                             map.offset_size, map.dwarf5_byte_order);
6163               return map.entry_pool + namei_entry_offs;
6164             }
6165         }
6166
6167       ++namei;
6168       if (namei >= map.name_count)
6169         return NULL;
6170     }
6171 }
6172
6173 const gdb_byte *
6174 dw2_debug_names_iterator::find_vec_in_debug_names
6175   (const mapped_debug_names &map, uint32_t namei)
6176 {
6177   if (namei >= map.name_count)
6178     {
6179       complaint (&symfile_complaints,
6180                  _("Wrong .debug_names with name index %u but name_count=%u "
6181                    "[in module %s]"),
6182                  namei, map.name_count,
6183                  objfile_name (map.dwarf2_per_objfile->objfile));
6184       return NULL;
6185     }
6186
6187   const ULONGEST namei_entry_offs
6188     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6189                                  + namei * map.offset_size),
6190                                 map.offset_size, map.dwarf5_byte_order);
6191   return map.entry_pool + namei_entry_offs;
6192 }
6193
6194 /* See dw2_debug_names_iterator.  */
6195
6196 dwarf2_per_cu_data *
6197 dw2_debug_names_iterator::next ()
6198 {
6199   if (m_addr == NULL)
6200     return NULL;
6201
6202   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6203   struct objfile *objfile = dwarf2_per_objfile->objfile;
6204   bfd *const abfd = objfile->obfd;
6205
6206  again:
6207
6208   unsigned int bytes_read;
6209   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6210   m_addr += bytes_read;
6211   if (abbrev == 0)
6212     return NULL;
6213
6214   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6215   if (indexval_it == m_map.abbrev_map.cend ())
6216     {
6217       complaint (&symfile_complaints,
6218                  _("Wrong .debug_names undefined abbrev code %s "
6219                    "[in module %s]"),
6220                  pulongest (abbrev), objfile_name (objfile));
6221       return NULL;
6222     }
6223   const mapped_debug_names::index_val &indexval = indexval_it->second;
6224   bool have_is_static = false;
6225   bool is_static;
6226   dwarf2_per_cu_data *per_cu = NULL;
6227   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6228     {
6229       ULONGEST ull;
6230       switch (attr.form)
6231         {
6232         case DW_FORM_implicit_const:
6233           ull = attr.implicit_const;
6234           break;
6235         case DW_FORM_flag_present:
6236           ull = 1;
6237           break;
6238         case DW_FORM_udata:
6239           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6240           m_addr += bytes_read;
6241           break;
6242         default:
6243           complaint (&symfile_complaints,
6244                      _("Unsupported .debug_names form %s [in module %s]"),
6245                      dwarf_form_name (attr.form),
6246                      objfile_name (objfile));
6247           return NULL;
6248         }
6249       switch (attr.dw_idx)
6250         {
6251         case DW_IDX_compile_unit:
6252           /* Don't crash on bad data.  */
6253           if (ull >= dwarf2_per_objfile->n_comp_units)
6254             {
6255               complaint (&symfile_complaints,
6256                          _(".debug_names entry has bad CU index %s"
6257                            " [in module %s]"),
6258                          pulongest (ull),
6259                          objfile_name (dwarf2_per_objfile->objfile));
6260               continue;
6261             }
6262           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6263           break;
6264         case DW_IDX_type_unit:
6265           /* Don't crash on bad data.  */
6266           if (ull >= dwarf2_per_objfile->n_type_units)
6267             {
6268               complaint (&symfile_complaints,
6269                          _(".debug_names entry has bad TU index %s"
6270                            " [in module %s]"),
6271                          pulongest (ull),
6272                          objfile_name (dwarf2_per_objfile->objfile));
6273               continue;
6274             }
6275           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6276                                  dwarf2_per_objfile->n_comp_units + ull);
6277           break;
6278         case DW_IDX_GNU_internal:
6279           if (!m_map.augmentation_is_gdb)
6280             break;
6281           have_is_static = true;
6282           is_static = true;
6283           break;
6284         case DW_IDX_GNU_external:
6285           if (!m_map.augmentation_is_gdb)
6286             break;
6287           have_is_static = true;
6288           is_static = false;
6289           break;
6290         }
6291     }
6292
6293   /* Skip if already read in.  */
6294   if (per_cu->v.quick->compunit_symtab)
6295     goto again;
6296
6297   /* Check static vs global.  */
6298   if (have_is_static)
6299     {
6300       const bool want_static = m_block_index != GLOBAL_BLOCK;
6301       if (m_want_specific_block && want_static != is_static)
6302         goto again;
6303     }
6304
6305   /* Match dw2_symtab_iter_next, symbol_kind
6306      and debug_names::psymbol_tag.  */
6307   switch (m_domain)
6308     {
6309     case VAR_DOMAIN:
6310       switch (indexval.dwarf_tag)
6311         {
6312         case DW_TAG_variable:
6313         case DW_TAG_subprogram:
6314         /* Some types are also in VAR_DOMAIN.  */
6315         case DW_TAG_typedef:
6316         case DW_TAG_structure_type:
6317           break;
6318         default:
6319           goto again;
6320         }
6321       break;
6322     case STRUCT_DOMAIN:
6323       switch (indexval.dwarf_tag)
6324         {
6325         case DW_TAG_typedef:
6326         case DW_TAG_structure_type:
6327           break;
6328         default:
6329           goto again;
6330         }
6331       break;
6332     case LABEL_DOMAIN:
6333       switch (indexval.dwarf_tag)
6334         {
6335         case 0:
6336         case DW_TAG_variable:
6337           break;
6338         default:
6339           goto again;
6340         }
6341       break;
6342     default:
6343       break;
6344     }
6345
6346   /* Match dw2_expand_symtabs_matching, symbol_kind and
6347      debug_names::psymbol_tag.  */
6348   switch (m_search)
6349     {
6350     case VARIABLES_DOMAIN:
6351       switch (indexval.dwarf_tag)
6352         {
6353         case DW_TAG_variable:
6354           break;
6355         default:
6356           goto again;
6357         }
6358       break;
6359     case FUNCTIONS_DOMAIN:
6360       switch (indexval.dwarf_tag)
6361         {
6362         case DW_TAG_subprogram:
6363           break;
6364         default:
6365           goto again;
6366         }
6367       break;
6368     case TYPES_DOMAIN:
6369       switch (indexval.dwarf_tag)
6370         {
6371         case DW_TAG_typedef:
6372         case DW_TAG_structure_type:
6373           break;
6374         default:
6375           goto again;
6376         }
6377       break;
6378     default:
6379       break;
6380     }
6381
6382   return per_cu;
6383 }
6384
6385 static struct compunit_symtab *
6386 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6387                                const char *name, domain_enum domain)
6388 {
6389   const block_enum block_index = static_cast<block_enum> (block_index_int);
6390   struct dwarf2_per_objfile *dwarf2_per_objfile
6391     = get_dwarf2_per_objfile (objfile);
6392
6393   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6394   if (!mapp)
6395     {
6396       /* index is NULL if OBJF_READNOW.  */
6397       return NULL;
6398     }
6399   const auto &map = *mapp;
6400
6401   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6402                                  block_index, domain, name);
6403
6404   struct compunit_symtab *stab_best = NULL;
6405   struct dwarf2_per_cu_data *per_cu;
6406   while ((per_cu = iter.next ()) != NULL)
6407     {
6408       struct symbol *sym, *with_opaque = NULL;
6409       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6410       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6411       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6412
6413       sym = block_find_symbol (block, name, domain,
6414                                block_find_non_opaque_type_preferred,
6415                                &with_opaque);
6416
6417       /* Some caution must be observed with overloaded functions and
6418          methods, since the index will not contain any overload
6419          information (but NAME might contain it).  */
6420
6421       if (sym != NULL
6422           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6423         return stab;
6424       if (with_opaque != NULL
6425           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6426         stab_best = stab;
6427
6428       /* Keep looking through other CUs.  */
6429     }
6430
6431   return stab_best;
6432 }
6433
6434 /* This dumps minimal information about .debug_names.  It is called
6435    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6436    uses this to verify that .debug_names has been loaded.  */
6437
6438 static void
6439 dw2_debug_names_dump (struct objfile *objfile)
6440 {
6441   struct dwarf2_per_objfile *dwarf2_per_objfile
6442     = get_dwarf2_per_objfile (objfile);
6443
6444   gdb_assert (dwarf2_per_objfile->using_index);
6445   printf_filtered (".debug_names:");
6446   if (dwarf2_per_objfile->debug_names_table)
6447     printf_filtered (" exists\n");
6448   else
6449     printf_filtered (" faked for \"readnow\"\n");
6450   printf_filtered ("\n");
6451 }
6452
6453 static void
6454 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6455                                              const char *func_name)
6456 {
6457   struct dwarf2_per_objfile *dwarf2_per_objfile
6458     = get_dwarf2_per_objfile (objfile);
6459
6460   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6461   if (dwarf2_per_objfile->debug_names_table)
6462     {
6463       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6464
6465       /* Note: It doesn't matter what we pass for block_index here.  */
6466       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6467                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6468
6469       struct dwarf2_per_cu_data *per_cu;
6470       while ((per_cu = iter.next ()) != NULL)
6471         dw2_instantiate_symtab (per_cu);
6472     }
6473 }
6474
6475 static void
6476 dw2_debug_names_expand_symtabs_matching
6477   (struct objfile *objfile,
6478    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6479    const lookup_name_info &lookup_name,
6480    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6481    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6482    enum search_domain kind)
6483 {
6484   struct dwarf2_per_objfile *dwarf2_per_objfile
6485     = get_dwarf2_per_objfile (objfile);
6486
6487   /* debug_names_table is NULL if OBJF_READNOW.  */
6488   if (!dwarf2_per_objfile->debug_names_table)
6489     return;
6490
6491   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6492
6493   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6494
6495   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6496                                       symbol_matcher,
6497                                       kind, [&] (offset_type namei)
6498     {
6499       /* The name was matched, now expand corresponding CUs that were
6500          marked.  */
6501       dw2_debug_names_iterator iter (map, kind, namei);
6502
6503       struct dwarf2_per_cu_data *per_cu;
6504       while ((per_cu = iter.next ()) != NULL)
6505         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6506                                          expansion_notify);
6507     });
6508 }
6509
6510 const struct quick_symbol_functions dwarf2_debug_names_functions =
6511 {
6512   dw2_has_symbols,
6513   dw2_find_last_source_symtab,
6514   dw2_forget_cached_source_info,
6515   dw2_map_symtabs_matching_filename,
6516   dw2_debug_names_lookup_symbol,
6517   dw2_print_stats,
6518   dw2_debug_names_dump,
6519   dw2_relocate,
6520   dw2_debug_names_expand_symtabs_for_function,
6521   dw2_expand_all_symtabs,
6522   dw2_expand_symtabs_with_fullname,
6523   dw2_map_matching_symbols,
6524   dw2_debug_names_expand_symtabs_matching,
6525   dw2_find_pc_sect_compunit_symtab,
6526   NULL,
6527   dw2_map_symbol_filenames
6528 };
6529
6530 /* See symfile.h.  */
6531
6532 bool
6533 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6534 {
6535   struct dwarf2_per_objfile *dwarf2_per_objfile
6536     = get_dwarf2_per_objfile (objfile);
6537
6538   /* If we're about to read full symbols, don't bother with the
6539      indices.  In this case we also don't care if some other debug
6540      format is making psymtabs, because they are all about to be
6541      expanded anyway.  */
6542   if ((objfile->flags & OBJF_READNOW))
6543     {
6544       int i;
6545
6546       dwarf2_per_objfile->using_index = 1;
6547       create_all_comp_units (dwarf2_per_objfile);
6548       create_all_type_units (dwarf2_per_objfile);
6549       dwarf2_per_objfile->quick_file_names_table =
6550         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6551
6552       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6553                        + dwarf2_per_objfile->n_type_units); ++i)
6554         {
6555           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6556
6557           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6558                                             struct dwarf2_per_cu_quick_data);
6559         }
6560
6561       /* Return 1 so that gdb sees the "quick" functions.  However,
6562          these functions will be no-ops because we will have expanded
6563          all symtabs.  */
6564       *index_kind = dw_index_kind::GDB_INDEX;
6565       return true;
6566     }
6567
6568   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6569     {
6570       *index_kind = dw_index_kind::DEBUG_NAMES;
6571       return true;
6572     }
6573
6574   if (dwarf2_read_index (objfile))
6575     {
6576       *index_kind = dw_index_kind::GDB_INDEX;
6577       return true;
6578     }
6579
6580   return false;
6581 }
6582
6583 \f
6584
6585 /* Build a partial symbol table.  */
6586
6587 void
6588 dwarf2_build_psymtabs (struct objfile *objfile)
6589 {
6590   struct dwarf2_per_objfile *dwarf2_per_objfile
6591     = get_dwarf2_per_objfile (objfile);
6592
6593   if (objfile->global_psymbols.capacity () == 0
6594       && objfile->static_psymbols.capacity () == 0)
6595     init_psymbol_list (objfile, 1024);
6596
6597   TRY
6598     {
6599       /* This isn't really ideal: all the data we allocate on the
6600          objfile's obstack is still uselessly kept around.  However,
6601          freeing it seems unsafe.  */
6602       psymtab_discarder psymtabs (objfile);
6603       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6604       psymtabs.keep ();
6605     }
6606   CATCH (except, RETURN_MASK_ERROR)
6607     {
6608       exception_print (gdb_stderr, except);
6609     }
6610   END_CATCH
6611 }
6612
6613 /* Return the total length of the CU described by HEADER.  */
6614
6615 static unsigned int
6616 get_cu_length (const struct comp_unit_head *header)
6617 {
6618   return header->initial_length_size + header->length;
6619 }
6620
6621 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6622
6623 static inline bool
6624 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6625 {
6626   sect_offset bottom = cu_header->sect_off;
6627   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6628
6629   return sect_off >= bottom && sect_off < top;
6630 }
6631
6632 /* Find the base address of the compilation unit for range lists and
6633    location lists.  It will normally be specified by DW_AT_low_pc.
6634    In DWARF-3 draft 4, the base address could be overridden by
6635    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6636    compilation units with discontinuous ranges.  */
6637
6638 static void
6639 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6640 {
6641   struct attribute *attr;
6642
6643   cu->base_known = 0;
6644   cu->base_address = 0;
6645
6646   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6647   if (attr)
6648     {
6649       cu->base_address = attr_value_as_address (attr);
6650       cu->base_known = 1;
6651     }
6652   else
6653     {
6654       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6655       if (attr)
6656         {
6657           cu->base_address = attr_value_as_address (attr);
6658           cu->base_known = 1;
6659         }
6660     }
6661 }
6662
6663 /* Read in the comp unit header information from the debug_info at info_ptr.
6664    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6665    NOTE: This leaves members offset, first_die_offset to be filled in
6666    by the caller.  */
6667
6668 static const gdb_byte *
6669 read_comp_unit_head (struct comp_unit_head *cu_header,
6670                      const gdb_byte *info_ptr,
6671                      struct dwarf2_section_info *section,
6672                      rcuh_kind section_kind)
6673 {
6674   int signed_addr;
6675   unsigned int bytes_read;
6676   const char *filename = get_section_file_name (section);
6677   bfd *abfd = get_section_bfd_owner (section);
6678
6679   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6680   cu_header->initial_length_size = bytes_read;
6681   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6682   info_ptr += bytes_read;
6683   cu_header->version = read_2_bytes (abfd, info_ptr);
6684   info_ptr += 2;
6685   if (cu_header->version < 5)
6686     switch (section_kind)
6687       {
6688       case rcuh_kind::COMPILE:
6689         cu_header->unit_type = DW_UT_compile;
6690         break;
6691       case rcuh_kind::TYPE:
6692         cu_header->unit_type = DW_UT_type;
6693         break;
6694       default:
6695         internal_error (__FILE__, __LINE__,
6696                         _("read_comp_unit_head: invalid section_kind"));
6697       }
6698   else
6699     {
6700       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6701                                                  (read_1_byte (abfd, info_ptr));
6702       info_ptr += 1;
6703       switch (cu_header->unit_type)
6704         {
6705         case DW_UT_compile:
6706           if (section_kind != rcuh_kind::COMPILE)
6707             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6708                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6709                    filename);
6710           break;
6711         case DW_UT_type:
6712           section_kind = rcuh_kind::TYPE;
6713           break;
6714         default:
6715           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6716                  "(is %d, should be %d or %d) [in module %s]"),
6717                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6718         }
6719
6720       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6721       info_ptr += 1;
6722     }
6723   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6724                                                           cu_header,
6725                                                           &bytes_read);
6726   info_ptr += bytes_read;
6727   if (cu_header->version < 5)
6728     {
6729       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6730       info_ptr += 1;
6731     }
6732   signed_addr = bfd_get_sign_extend_vma (abfd);
6733   if (signed_addr < 0)
6734     internal_error (__FILE__, __LINE__,
6735                     _("read_comp_unit_head: dwarf from non elf file"));
6736   cu_header->signed_addr_p = signed_addr;
6737
6738   if (section_kind == rcuh_kind::TYPE)
6739     {
6740       LONGEST type_offset;
6741
6742       cu_header->signature = read_8_bytes (abfd, info_ptr);
6743       info_ptr += 8;
6744
6745       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6746       info_ptr += bytes_read;
6747       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6748       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6749         error (_("Dwarf Error: Too big type_offset in compilation unit "
6750                "header (is %s) [in module %s]"), plongest (type_offset),
6751                filename);
6752     }
6753
6754   return info_ptr;
6755 }
6756
6757 /* Helper function that returns the proper abbrev section for
6758    THIS_CU.  */
6759
6760 static struct dwarf2_section_info *
6761 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6762 {
6763   struct dwarf2_section_info *abbrev;
6764   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6765
6766   if (this_cu->is_dwz)
6767     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6768   else
6769     abbrev = &dwarf2_per_objfile->abbrev;
6770
6771   return abbrev;
6772 }
6773
6774 /* Subroutine of read_and_check_comp_unit_head and
6775    read_and_check_type_unit_head to simplify them.
6776    Perform various error checking on the header.  */
6777
6778 static void
6779 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6780                             struct comp_unit_head *header,
6781                             struct dwarf2_section_info *section,
6782                             struct dwarf2_section_info *abbrev_section)
6783 {
6784   const char *filename = get_section_file_name (section);
6785
6786   if (header->version < 2 || header->version > 5)
6787     error (_("Dwarf Error: wrong version in compilation unit header "
6788            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6789            filename);
6790
6791   if (to_underlying (header->abbrev_sect_off)
6792       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6793     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6794            "(offset 0x%x + 6) [in module %s]"),
6795            to_underlying (header->abbrev_sect_off),
6796            to_underlying (header->sect_off),
6797            filename);
6798
6799   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6800      avoid potential 32-bit overflow.  */
6801   if (((ULONGEST) header->sect_off + get_cu_length (header))
6802       > section->size)
6803     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6804            "(offset 0x%x + 0) [in module %s]"),
6805            header->length, to_underlying (header->sect_off),
6806            filename);
6807 }
6808
6809 /* Read in a CU/TU header and perform some basic error checking.
6810    The contents of the header are stored in HEADER.
6811    The result is a pointer to the start of the first DIE.  */
6812
6813 static const gdb_byte *
6814 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6815                                struct comp_unit_head *header,
6816                                struct dwarf2_section_info *section,
6817                                struct dwarf2_section_info *abbrev_section,
6818                                const gdb_byte *info_ptr,
6819                                rcuh_kind section_kind)
6820 {
6821   const gdb_byte *beg_of_comp_unit = info_ptr;
6822
6823   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6824
6825   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6826
6827   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6828
6829   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6830                               abbrev_section);
6831
6832   return info_ptr;
6833 }
6834
6835 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6836
6837 static sect_offset
6838 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6839                     struct dwarf2_section_info *section,
6840                     sect_offset sect_off)
6841 {
6842   bfd *abfd = get_section_bfd_owner (section);
6843   const gdb_byte *info_ptr;
6844   unsigned int initial_length_size, offset_size;
6845   uint16_t version;
6846
6847   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6848   info_ptr = section->buffer + to_underlying (sect_off);
6849   read_initial_length (abfd, info_ptr, &initial_length_size);
6850   offset_size = initial_length_size == 4 ? 4 : 8;
6851   info_ptr += initial_length_size;
6852
6853   version = read_2_bytes (abfd, info_ptr);
6854   info_ptr += 2;
6855   if (version >= 5)
6856     {
6857       /* Skip unit type and address size.  */
6858       info_ptr += 2;
6859     }
6860
6861   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6862 }
6863
6864 /* Allocate a new partial symtab for file named NAME and mark this new
6865    partial symtab as being an include of PST.  */
6866
6867 static void
6868 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6869                                struct objfile *objfile)
6870 {
6871   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6872
6873   if (!IS_ABSOLUTE_PATH (subpst->filename))
6874     {
6875       /* It shares objfile->objfile_obstack.  */
6876       subpst->dirname = pst->dirname;
6877     }
6878
6879   subpst->textlow = 0;
6880   subpst->texthigh = 0;
6881
6882   subpst->dependencies
6883     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6884   subpst->dependencies[0] = pst;
6885   subpst->number_of_dependencies = 1;
6886
6887   subpst->globals_offset = 0;
6888   subpst->n_global_syms = 0;
6889   subpst->statics_offset = 0;
6890   subpst->n_static_syms = 0;
6891   subpst->compunit_symtab = NULL;
6892   subpst->read_symtab = pst->read_symtab;
6893   subpst->readin = 0;
6894
6895   /* No private part is necessary for include psymtabs.  This property
6896      can be used to differentiate between such include psymtabs and
6897      the regular ones.  */
6898   subpst->read_symtab_private = NULL;
6899 }
6900
6901 /* Read the Line Number Program data and extract the list of files
6902    included by the source file represented by PST.  Build an include
6903    partial symtab for each of these included files.  */
6904
6905 static void
6906 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6907                                struct die_info *die,
6908                                struct partial_symtab *pst)
6909 {
6910   line_header_up lh;
6911   struct attribute *attr;
6912
6913   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6914   if (attr)
6915     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6916   if (lh == NULL)
6917     return;  /* No linetable, so no includes.  */
6918
6919   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6920   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6921 }
6922
6923 static hashval_t
6924 hash_signatured_type (const void *item)
6925 {
6926   const struct signatured_type *sig_type
6927     = (const struct signatured_type *) item;
6928
6929   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6930   return sig_type->signature;
6931 }
6932
6933 static int
6934 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6935 {
6936   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6937   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6938
6939   return lhs->signature == rhs->signature;
6940 }
6941
6942 /* Allocate a hash table for signatured types.  */
6943
6944 static htab_t
6945 allocate_signatured_type_table (struct objfile *objfile)
6946 {
6947   return htab_create_alloc_ex (41,
6948                                hash_signatured_type,
6949                                eq_signatured_type,
6950                                NULL,
6951                                &objfile->objfile_obstack,
6952                                hashtab_obstack_allocate,
6953                                dummy_obstack_deallocate);
6954 }
6955
6956 /* A helper function to add a signatured type CU to a table.  */
6957
6958 static int
6959 add_signatured_type_cu_to_table (void **slot, void *datum)
6960 {
6961   struct signatured_type *sigt = (struct signatured_type *) *slot;
6962   struct signatured_type ***datap = (struct signatured_type ***) datum;
6963
6964   **datap = sigt;
6965   ++*datap;
6966
6967   return 1;
6968 }
6969
6970 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6971    and fill them into TYPES_HTAB.  It will process only type units,
6972    therefore DW_UT_type.  */
6973
6974 static void
6975 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6976                               struct dwo_file *dwo_file,
6977                               dwarf2_section_info *section, htab_t &types_htab,
6978                               rcuh_kind section_kind)
6979 {
6980   struct objfile *objfile = dwarf2_per_objfile->objfile;
6981   struct dwarf2_section_info *abbrev_section;
6982   bfd *abfd;
6983   const gdb_byte *info_ptr, *end_ptr;
6984
6985   abbrev_section = (dwo_file != NULL
6986                     ? &dwo_file->sections.abbrev
6987                     : &dwarf2_per_objfile->abbrev);
6988
6989   if (dwarf_read_debug)
6990     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6991                         get_section_name (section),
6992                         get_section_file_name (abbrev_section));
6993
6994   dwarf2_read_section (objfile, section);
6995   info_ptr = section->buffer;
6996
6997   if (info_ptr == NULL)
6998     return;
6999
7000   /* We can't set abfd until now because the section may be empty or
7001      not present, in which case the bfd is unknown.  */
7002   abfd = get_section_bfd_owner (section);
7003
7004   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7005      because we don't need to read any dies: the signature is in the
7006      header.  */
7007
7008   end_ptr = info_ptr + section->size;
7009   while (info_ptr < end_ptr)
7010     {
7011       struct signatured_type *sig_type;
7012       struct dwo_unit *dwo_tu;
7013       void **slot;
7014       const gdb_byte *ptr = info_ptr;
7015       struct comp_unit_head header;
7016       unsigned int length;
7017
7018       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7019
7020       /* Initialize it due to a false compiler warning.  */
7021       header.signature = -1;
7022       header.type_cu_offset_in_tu = (cu_offset) -1;
7023
7024       /* We need to read the type's signature in order to build the hash
7025          table, but we don't need anything else just yet.  */
7026
7027       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7028                                            abbrev_section, ptr, section_kind);
7029
7030       length = get_cu_length (&header);
7031
7032       /* Skip dummy type units.  */
7033       if (ptr >= info_ptr + length
7034           || peek_abbrev_code (abfd, ptr) == 0
7035           || header.unit_type != DW_UT_type)
7036         {
7037           info_ptr += length;
7038           continue;
7039         }
7040
7041       if (types_htab == NULL)
7042         {
7043           if (dwo_file)
7044             types_htab = allocate_dwo_unit_table (objfile);
7045           else
7046             types_htab = allocate_signatured_type_table (objfile);
7047         }
7048
7049       if (dwo_file)
7050         {
7051           sig_type = NULL;
7052           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7053                                    struct dwo_unit);
7054           dwo_tu->dwo_file = dwo_file;
7055           dwo_tu->signature = header.signature;
7056           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7057           dwo_tu->section = section;
7058           dwo_tu->sect_off = sect_off;
7059           dwo_tu->length = length;
7060         }
7061       else
7062         {
7063           /* N.B.: type_offset is not usable if this type uses a DWO file.
7064              The real type_offset is in the DWO file.  */
7065           dwo_tu = NULL;
7066           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7067                                      struct signatured_type);
7068           sig_type->signature = header.signature;
7069           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7070           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7071           sig_type->per_cu.is_debug_types = 1;
7072           sig_type->per_cu.section = section;
7073           sig_type->per_cu.sect_off = sect_off;
7074           sig_type->per_cu.length = length;
7075         }
7076
7077       slot = htab_find_slot (types_htab,
7078                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7079                              INSERT);
7080       gdb_assert (slot != NULL);
7081       if (*slot != NULL)
7082         {
7083           sect_offset dup_sect_off;
7084
7085           if (dwo_file)
7086             {
7087               const struct dwo_unit *dup_tu
7088                 = (const struct dwo_unit *) *slot;
7089
7090               dup_sect_off = dup_tu->sect_off;
7091             }
7092           else
7093             {
7094               const struct signatured_type *dup_tu
7095                 = (const struct signatured_type *) *slot;
7096
7097               dup_sect_off = dup_tu->per_cu.sect_off;
7098             }
7099
7100           complaint (&symfile_complaints,
7101                      _("debug type entry at offset 0x%x is duplicate to"
7102                        " the entry at offset 0x%x, signature %s"),
7103                      to_underlying (sect_off), to_underlying (dup_sect_off),
7104                      hex_string (header.signature));
7105         }
7106       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7107
7108       if (dwarf_read_debug > 1)
7109         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7110                             to_underlying (sect_off),
7111                             hex_string (header.signature));
7112
7113       info_ptr += length;
7114     }
7115 }
7116
7117 /* Create the hash table of all entries in the .debug_types
7118    (or .debug_types.dwo) section(s).
7119    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7120    otherwise it is NULL.
7121
7122    The result is a pointer to the hash table or NULL if there are no types.
7123
7124    Note: This function processes DWO files only, not DWP files.  */
7125
7126 static void
7127 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7128                                struct dwo_file *dwo_file,
7129                                VEC (dwarf2_section_info_def) *types,
7130                                htab_t &types_htab)
7131 {
7132   int ix;
7133   struct dwarf2_section_info *section;
7134
7135   if (VEC_empty (dwarf2_section_info_def, types))
7136     return;
7137
7138   for (ix = 0;
7139        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7140        ++ix)
7141     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7142                                   types_htab, rcuh_kind::TYPE);
7143 }
7144
7145 /* Create the hash table of all entries in the .debug_types section,
7146    and initialize all_type_units.
7147    The result is zero if there is an error (e.g. missing .debug_types section),
7148    otherwise non-zero.  */
7149
7150 static int
7151 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7152 {
7153   htab_t types_htab = NULL;
7154   struct signatured_type **iter;
7155
7156   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7157                                 &dwarf2_per_objfile->info, types_htab,
7158                                 rcuh_kind::COMPILE);
7159   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7160                                  dwarf2_per_objfile->types, types_htab);
7161   if (types_htab == NULL)
7162     {
7163       dwarf2_per_objfile->signatured_types = NULL;
7164       return 0;
7165     }
7166
7167   dwarf2_per_objfile->signatured_types = types_htab;
7168
7169   dwarf2_per_objfile->n_type_units
7170     = dwarf2_per_objfile->n_allocated_type_units
7171     = htab_elements (types_htab);
7172   dwarf2_per_objfile->all_type_units =
7173     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7174   iter = &dwarf2_per_objfile->all_type_units[0];
7175   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7176   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7177               == dwarf2_per_objfile->n_type_units);
7178
7179   return 1;
7180 }
7181
7182 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7183    If SLOT is non-NULL, it is the entry to use in the hash table.
7184    Otherwise we find one.  */
7185
7186 static struct signatured_type *
7187 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7188                void **slot)
7189 {
7190   struct objfile *objfile = dwarf2_per_objfile->objfile;
7191   int n_type_units = dwarf2_per_objfile->n_type_units;
7192   struct signatured_type *sig_type;
7193
7194   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7195   ++n_type_units;
7196   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7197     {
7198       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7199         dwarf2_per_objfile->n_allocated_type_units = 1;
7200       dwarf2_per_objfile->n_allocated_type_units *= 2;
7201       dwarf2_per_objfile->all_type_units
7202         = XRESIZEVEC (struct signatured_type *,
7203                       dwarf2_per_objfile->all_type_units,
7204                       dwarf2_per_objfile->n_allocated_type_units);
7205       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7206     }
7207   dwarf2_per_objfile->n_type_units = n_type_units;
7208
7209   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7210                              struct signatured_type);
7211   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7212   sig_type->signature = sig;
7213   sig_type->per_cu.is_debug_types = 1;
7214   if (dwarf2_per_objfile->using_index)
7215     {
7216       sig_type->per_cu.v.quick =
7217         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7218                         struct dwarf2_per_cu_quick_data);
7219     }
7220
7221   if (slot == NULL)
7222     {
7223       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7224                              sig_type, INSERT);
7225     }
7226   gdb_assert (*slot == NULL);
7227   *slot = sig_type;
7228   /* The rest of sig_type must be filled in by the caller.  */
7229   return sig_type;
7230 }
7231
7232 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7233    Fill in SIG_ENTRY with DWO_ENTRY.  */
7234
7235 static void
7236 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7237                                   struct signatured_type *sig_entry,
7238                                   struct dwo_unit *dwo_entry)
7239 {
7240   /* Make sure we're not clobbering something we don't expect to.  */
7241   gdb_assert (! sig_entry->per_cu.queued);
7242   gdb_assert (sig_entry->per_cu.cu == NULL);
7243   if (dwarf2_per_objfile->using_index)
7244     {
7245       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7246       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7247     }
7248   else
7249       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7250   gdb_assert (sig_entry->signature == dwo_entry->signature);
7251   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7252   gdb_assert (sig_entry->type_unit_group == NULL);
7253   gdb_assert (sig_entry->dwo_unit == NULL);
7254
7255   sig_entry->per_cu.section = dwo_entry->section;
7256   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7257   sig_entry->per_cu.length = dwo_entry->length;
7258   sig_entry->per_cu.reading_dwo_directly = 1;
7259   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7260   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7261   sig_entry->dwo_unit = dwo_entry;
7262 }
7263
7264 /* Subroutine of lookup_signatured_type.
7265    If we haven't read the TU yet, create the signatured_type data structure
7266    for a TU to be read in directly from a DWO file, bypassing the stub.
7267    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7268    using .gdb_index, then when reading a CU we want to stay in the DWO file
7269    containing that CU.  Otherwise we could end up reading several other DWO
7270    files (due to comdat folding) to process the transitive closure of all the
7271    mentioned TUs, and that can be slow.  The current DWO file will have every
7272    type signature that it needs.
7273    We only do this for .gdb_index because in the psymtab case we already have
7274    to read all the DWOs to build the type unit groups.  */
7275
7276 static struct signatured_type *
7277 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7278 {
7279   struct dwarf2_per_objfile *dwarf2_per_objfile
7280     = cu->per_cu->dwarf2_per_objfile;
7281   struct objfile *objfile = dwarf2_per_objfile->objfile;
7282   struct dwo_file *dwo_file;
7283   struct dwo_unit find_dwo_entry, *dwo_entry;
7284   struct signatured_type find_sig_entry, *sig_entry;
7285   void **slot;
7286
7287   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7288
7289   /* If TU skeletons have been removed then we may not have read in any
7290      TUs yet.  */
7291   if (dwarf2_per_objfile->signatured_types == NULL)
7292     {
7293       dwarf2_per_objfile->signatured_types
7294         = allocate_signatured_type_table (objfile);
7295     }
7296
7297   /* We only ever need to read in one copy of a signatured type.
7298      Use the global signatured_types array to do our own comdat-folding
7299      of types.  If this is the first time we're reading this TU, and
7300      the TU has an entry in .gdb_index, replace the recorded data from
7301      .gdb_index with this TU.  */
7302
7303   find_sig_entry.signature = sig;
7304   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7305                          &find_sig_entry, INSERT);
7306   sig_entry = (struct signatured_type *) *slot;
7307
7308   /* We can get here with the TU already read, *or* in the process of being
7309      read.  Don't reassign the global entry to point to this DWO if that's
7310      the case.  Also note that if the TU is already being read, it may not
7311      have come from a DWO, the program may be a mix of Fission-compiled
7312      code and non-Fission-compiled code.  */
7313
7314   /* Have we already tried to read this TU?
7315      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7316      needn't exist in the global table yet).  */
7317   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7318     return sig_entry;
7319
7320   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7321      dwo_unit of the TU itself.  */
7322   dwo_file = cu->dwo_unit->dwo_file;
7323
7324   /* Ok, this is the first time we're reading this TU.  */
7325   if (dwo_file->tus == NULL)
7326     return NULL;
7327   find_dwo_entry.signature = sig;
7328   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7329   if (dwo_entry == NULL)
7330     return NULL;
7331
7332   /* If the global table doesn't have an entry for this TU, add one.  */
7333   if (sig_entry == NULL)
7334     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7335
7336   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7337   sig_entry->per_cu.tu_read = 1;
7338   return sig_entry;
7339 }
7340
7341 /* Subroutine of lookup_signatured_type.
7342    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7343    then try the DWP file.  If the TU stub (skeleton) has been removed then
7344    it won't be in .gdb_index.  */
7345
7346 static struct signatured_type *
7347 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7348 {
7349   struct dwarf2_per_objfile *dwarf2_per_objfile
7350     = cu->per_cu->dwarf2_per_objfile;
7351   struct objfile *objfile = dwarf2_per_objfile->objfile;
7352   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7353   struct dwo_unit *dwo_entry;
7354   struct signatured_type find_sig_entry, *sig_entry;
7355   void **slot;
7356
7357   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7358   gdb_assert (dwp_file != NULL);
7359
7360   /* If TU skeletons have been removed then we may not have read in any
7361      TUs yet.  */
7362   if (dwarf2_per_objfile->signatured_types == NULL)
7363     {
7364       dwarf2_per_objfile->signatured_types
7365         = allocate_signatured_type_table (objfile);
7366     }
7367
7368   find_sig_entry.signature = sig;
7369   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7370                          &find_sig_entry, INSERT);
7371   sig_entry = (struct signatured_type *) *slot;
7372
7373   /* Have we already tried to read this TU?
7374      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7375      needn't exist in the global table yet).  */
7376   if (sig_entry != NULL)
7377     return sig_entry;
7378
7379   if (dwp_file->tus == NULL)
7380     return NULL;
7381   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7382                                       sig, 1 /* is_debug_types */);
7383   if (dwo_entry == NULL)
7384     return NULL;
7385
7386   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7387   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7388
7389   return sig_entry;
7390 }
7391
7392 /* Lookup a signature based type for DW_FORM_ref_sig8.
7393    Returns NULL if signature SIG is not present in the table.
7394    It is up to the caller to complain about this.  */
7395
7396 static struct signatured_type *
7397 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7398 {
7399   struct dwarf2_per_objfile *dwarf2_per_objfile
7400     = cu->per_cu->dwarf2_per_objfile;
7401
7402   if (cu->dwo_unit
7403       && dwarf2_per_objfile->using_index)
7404     {
7405       /* We're in a DWO/DWP file, and we're using .gdb_index.
7406          These cases require special processing.  */
7407       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7408         return lookup_dwo_signatured_type (cu, sig);
7409       else
7410         return lookup_dwp_signatured_type (cu, sig);
7411     }
7412   else
7413     {
7414       struct signatured_type find_entry, *entry;
7415
7416       if (dwarf2_per_objfile->signatured_types == NULL)
7417         return NULL;
7418       find_entry.signature = sig;
7419       entry = ((struct signatured_type *)
7420                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7421       return entry;
7422     }
7423 }
7424 \f
7425 /* Low level DIE reading support.  */
7426
7427 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7428
7429 static void
7430 init_cu_die_reader (struct die_reader_specs *reader,
7431                     struct dwarf2_cu *cu,
7432                     struct dwarf2_section_info *section,
7433                     struct dwo_file *dwo_file,
7434                     struct abbrev_table *abbrev_table)
7435 {
7436   gdb_assert (section->readin && section->buffer != NULL);
7437   reader->abfd = get_section_bfd_owner (section);
7438   reader->cu = cu;
7439   reader->dwo_file = dwo_file;
7440   reader->die_section = section;
7441   reader->buffer = section->buffer;
7442   reader->buffer_end = section->buffer + section->size;
7443   reader->comp_dir = NULL;
7444   reader->abbrev_table = abbrev_table;
7445 }
7446
7447 /* Subroutine of init_cutu_and_read_dies to simplify it.
7448    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7449    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7450    already.
7451
7452    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7453    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7454    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7455    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7456    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7457    STUB_COMP_DIR may be non-NULL.
7458    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7459    are filled in with the info of the DIE from the DWO file.
7460    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7461    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7462    kept around for at least as long as *RESULT_READER.
7463
7464    The result is non-zero if a valid (non-dummy) DIE was found.  */
7465
7466 static int
7467 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7468                         struct dwo_unit *dwo_unit,
7469                         struct die_info *stub_comp_unit_die,
7470                         const char *stub_comp_dir,
7471                         struct die_reader_specs *result_reader,
7472                         const gdb_byte **result_info_ptr,
7473                         struct die_info **result_comp_unit_die,
7474                         int *result_has_children,
7475                         abbrev_table_up *result_dwo_abbrev_table)
7476 {
7477   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7478   struct objfile *objfile = dwarf2_per_objfile->objfile;
7479   struct dwarf2_cu *cu = this_cu->cu;
7480   bfd *abfd;
7481   const gdb_byte *begin_info_ptr, *info_ptr;
7482   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7483   int i,num_extra_attrs;
7484   struct dwarf2_section_info *dwo_abbrev_section;
7485   struct attribute *attr;
7486   struct die_info *comp_unit_die;
7487
7488   /* At most one of these may be provided.  */
7489   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7490
7491   /* These attributes aren't processed until later:
7492      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7493      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7494      referenced later.  However, these attributes are found in the stub
7495      which we won't have later.  In order to not impose this complication
7496      on the rest of the code, we read them here and copy them to the
7497      DWO CU/TU die.  */
7498
7499   stmt_list = NULL;
7500   low_pc = NULL;
7501   high_pc = NULL;
7502   ranges = NULL;
7503   comp_dir = NULL;
7504
7505   if (stub_comp_unit_die != NULL)
7506     {
7507       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7508          DWO file.  */
7509       if (! this_cu->is_debug_types)
7510         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7511       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7512       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7513       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7514       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7515
7516       /* There should be a DW_AT_addr_base attribute here (if needed).
7517          We need the value before we can process DW_FORM_GNU_addr_index.  */
7518       cu->addr_base = 0;
7519       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7520       if (attr)
7521         cu->addr_base = DW_UNSND (attr);
7522
7523       /* There should be a DW_AT_ranges_base attribute here (if needed).
7524          We need the value before we can process DW_AT_ranges.  */
7525       cu->ranges_base = 0;
7526       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7527       if (attr)
7528         cu->ranges_base = DW_UNSND (attr);
7529     }
7530   else if (stub_comp_dir != NULL)
7531     {
7532       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7533       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7534       comp_dir->name = DW_AT_comp_dir;
7535       comp_dir->form = DW_FORM_string;
7536       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7537       DW_STRING (comp_dir) = stub_comp_dir;
7538     }
7539
7540   /* Set up for reading the DWO CU/TU.  */
7541   cu->dwo_unit = dwo_unit;
7542   dwarf2_section_info *section = dwo_unit->section;
7543   dwarf2_read_section (objfile, section);
7544   abfd = get_section_bfd_owner (section);
7545   begin_info_ptr = info_ptr = (section->buffer
7546                                + to_underlying (dwo_unit->sect_off));
7547   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7548
7549   if (this_cu->is_debug_types)
7550     {
7551       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7552
7553       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7554                                                 &cu->header, section,
7555                                                 dwo_abbrev_section,
7556                                                 info_ptr, rcuh_kind::TYPE);
7557       /* This is not an assert because it can be caused by bad debug info.  */
7558       if (sig_type->signature != cu->header.signature)
7559         {
7560           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7561                    " TU at offset 0x%x [in module %s]"),
7562                  hex_string (sig_type->signature),
7563                  hex_string (cu->header.signature),
7564                  to_underlying (dwo_unit->sect_off),
7565                  bfd_get_filename (abfd));
7566         }
7567       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7568       /* For DWOs coming from DWP files, we don't know the CU length
7569          nor the type's offset in the TU until now.  */
7570       dwo_unit->length = get_cu_length (&cu->header);
7571       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7572
7573       /* Establish the type offset that can be used to lookup the type.
7574          For DWO files, we don't know it until now.  */
7575       sig_type->type_offset_in_section
7576         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7577     }
7578   else
7579     {
7580       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7581                                                 &cu->header, section,
7582                                                 dwo_abbrev_section,
7583                                                 info_ptr, rcuh_kind::COMPILE);
7584       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7585       /* For DWOs coming from DWP files, we don't know the CU length
7586          until now.  */
7587       dwo_unit->length = get_cu_length (&cu->header);
7588     }
7589
7590   *result_dwo_abbrev_table
7591     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7592                                cu->header.abbrev_sect_off);
7593   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7594                       result_dwo_abbrev_table->get ());
7595
7596   /* Read in the die, but leave space to copy over the attributes
7597      from the stub.  This has the benefit of simplifying the rest of
7598      the code - all the work to maintain the illusion of a single
7599      DW_TAG_{compile,type}_unit DIE is done here.  */
7600   num_extra_attrs = ((stmt_list != NULL)
7601                      + (low_pc != NULL)
7602                      + (high_pc != NULL)
7603                      + (ranges != NULL)
7604                      + (comp_dir != NULL));
7605   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7606                               result_has_children, num_extra_attrs);
7607
7608   /* Copy over the attributes from the stub to the DIE we just read in.  */
7609   comp_unit_die = *result_comp_unit_die;
7610   i = comp_unit_die->num_attrs;
7611   if (stmt_list != NULL)
7612     comp_unit_die->attrs[i++] = *stmt_list;
7613   if (low_pc != NULL)
7614     comp_unit_die->attrs[i++] = *low_pc;
7615   if (high_pc != NULL)
7616     comp_unit_die->attrs[i++] = *high_pc;
7617   if (ranges != NULL)
7618     comp_unit_die->attrs[i++] = *ranges;
7619   if (comp_dir != NULL)
7620     comp_unit_die->attrs[i++] = *comp_dir;
7621   comp_unit_die->num_attrs += num_extra_attrs;
7622
7623   if (dwarf_die_debug)
7624     {
7625       fprintf_unfiltered (gdb_stdlog,
7626                           "Read die from %s@0x%x of %s:\n",
7627                           get_section_name (section),
7628                           (unsigned) (begin_info_ptr - section->buffer),
7629                           bfd_get_filename (abfd));
7630       dump_die (comp_unit_die, dwarf_die_debug);
7631     }
7632
7633   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7634      TUs by skipping the stub and going directly to the entry in the DWO file.
7635      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7636      to get it via circuitous means.  Blech.  */
7637   if (comp_dir != NULL)
7638     result_reader->comp_dir = DW_STRING (comp_dir);
7639
7640   /* Skip dummy compilation units.  */
7641   if (info_ptr >= begin_info_ptr + dwo_unit->length
7642       || peek_abbrev_code (abfd, info_ptr) == 0)
7643     return 0;
7644
7645   *result_info_ptr = info_ptr;
7646   return 1;
7647 }
7648
7649 /* Subroutine of init_cutu_and_read_dies to simplify it.
7650    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7651    Returns NULL if the specified DWO unit cannot be found.  */
7652
7653 static struct dwo_unit *
7654 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7655                  struct die_info *comp_unit_die)
7656 {
7657   struct dwarf2_cu *cu = this_cu->cu;
7658   ULONGEST signature;
7659   struct dwo_unit *dwo_unit;
7660   const char *comp_dir, *dwo_name;
7661
7662   gdb_assert (cu != NULL);
7663
7664   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7665   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7666   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7667
7668   if (this_cu->is_debug_types)
7669     {
7670       struct signatured_type *sig_type;
7671
7672       /* Since this_cu is the first member of struct signatured_type,
7673          we can go from a pointer to one to a pointer to the other.  */
7674       sig_type = (struct signatured_type *) this_cu;
7675       signature = sig_type->signature;
7676       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7677     }
7678   else
7679     {
7680       struct attribute *attr;
7681
7682       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7683       if (! attr)
7684         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7685                  " [in module %s]"),
7686                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7687       signature = DW_UNSND (attr);
7688       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7689                                        signature);
7690     }
7691
7692   return dwo_unit;
7693 }
7694
7695 /* Subroutine of init_cutu_and_read_dies to simplify it.
7696    See it for a description of the parameters.
7697    Read a TU directly from a DWO file, bypassing the stub.
7698
7699    Note: This function could be a little bit simpler if we shared cleanups
7700    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7701    to do, so we keep this function self-contained.  Or we could move this
7702    into our caller, but it's complex enough already.  */
7703
7704 static void
7705 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7706                            int use_existing_cu, int keep,
7707                            die_reader_func_ftype *die_reader_func,
7708                            void *data)
7709 {
7710   struct dwarf2_cu *cu;
7711   struct signatured_type *sig_type;
7712   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7713   struct die_reader_specs reader;
7714   const gdb_byte *info_ptr;
7715   struct die_info *comp_unit_die;
7716   int has_children;
7717   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7718
7719   /* Verify we can do the following downcast, and that we have the
7720      data we need.  */
7721   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7722   sig_type = (struct signatured_type *) this_cu;
7723   gdb_assert (sig_type->dwo_unit != NULL);
7724
7725   cleanups = make_cleanup (null_cleanup, NULL);
7726
7727   if (use_existing_cu && this_cu->cu != NULL)
7728     {
7729       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7730       cu = this_cu->cu;
7731       /* There's no need to do the rereading_dwo_cu handling that
7732          init_cutu_and_read_dies does since we don't read the stub.  */
7733     }
7734   else
7735     {
7736       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7737       gdb_assert (this_cu->cu == NULL);
7738       cu = XNEW (struct dwarf2_cu);
7739       init_one_comp_unit (cu, this_cu);
7740       /* If an error occurs while loading, release our storage.  */
7741       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7742     }
7743
7744   /* A future optimization, if needed, would be to use an existing
7745      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7746      could share abbrev tables.  */
7747
7748   /* The abbreviation table used by READER, this must live at least as long as
7749      READER.  */
7750   abbrev_table_up dwo_abbrev_table;
7751
7752   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7753                               NULL /* stub_comp_unit_die */,
7754                               sig_type->dwo_unit->dwo_file->comp_dir,
7755                               &reader, &info_ptr,
7756                               &comp_unit_die, &has_children,
7757                               &dwo_abbrev_table) == 0)
7758     {
7759       /* Dummy die.  */
7760       do_cleanups (cleanups);
7761       return;
7762     }
7763
7764   /* All the "real" work is done here.  */
7765   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7766
7767   /* This duplicates the code in init_cutu_and_read_dies,
7768      but the alternative is making the latter more complex.
7769      This function is only for the special case of using DWO files directly:
7770      no point in overly complicating the general case just to handle this.  */
7771   if (free_cu_cleanup != NULL)
7772     {
7773       if (keep)
7774         {
7775           /* We've successfully allocated this compilation unit.  Let our
7776              caller clean it up when finished with it.  */
7777           discard_cleanups (free_cu_cleanup);
7778
7779           /* Link this CU into read_in_chain.  */
7780           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7781           dwarf2_per_objfile->read_in_chain = this_cu;
7782         }
7783       else
7784         do_cleanups (free_cu_cleanup);
7785     }
7786
7787   do_cleanups (cleanups);
7788 }
7789
7790 /* Initialize a CU (or TU) and read its DIEs.
7791    If the CU defers to a DWO file, read the DWO file as well.
7792
7793    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7794    Otherwise the table specified in the comp unit header is read in and used.
7795    This is an optimization for when we already have the abbrev table.
7796
7797    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7798    Otherwise, a new CU is allocated with xmalloc.
7799
7800    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7801    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7802
7803    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7804    linker) then DIE_READER_FUNC will not get called.  */
7805
7806 static void
7807 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7808                          struct abbrev_table *abbrev_table,
7809                          int use_existing_cu, int keep,
7810                          die_reader_func_ftype *die_reader_func,
7811                          void *data)
7812 {
7813   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7814   struct objfile *objfile = dwarf2_per_objfile->objfile;
7815   struct dwarf2_section_info *section = this_cu->section;
7816   bfd *abfd = get_section_bfd_owner (section);
7817   struct dwarf2_cu *cu;
7818   const gdb_byte *begin_info_ptr, *info_ptr;
7819   struct die_reader_specs reader;
7820   struct die_info *comp_unit_die;
7821   int has_children;
7822   struct attribute *attr;
7823   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7824   struct signatured_type *sig_type = NULL;
7825   struct dwarf2_section_info *abbrev_section;
7826   /* Non-zero if CU currently points to a DWO file and we need to
7827      reread it.  When this happens we need to reread the skeleton die
7828      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7829   int rereading_dwo_cu = 0;
7830
7831   if (dwarf_die_debug)
7832     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7833                         this_cu->is_debug_types ? "type" : "comp",
7834                         to_underlying (this_cu->sect_off));
7835
7836   if (use_existing_cu)
7837     gdb_assert (keep);
7838
7839   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7840      file (instead of going through the stub), short-circuit all of this.  */
7841   if (this_cu->reading_dwo_directly)
7842     {
7843       /* Narrow down the scope of possibilities to have to understand.  */
7844       gdb_assert (this_cu->is_debug_types);
7845       gdb_assert (abbrev_table == NULL);
7846       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7847                                  die_reader_func, data);
7848       return;
7849     }
7850
7851   cleanups = make_cleanup (null_cleanup, NULL);
7852
7853   /* This is cheap if the section is already read in.  */
7854   dwarf2_read_section (objfile, section);
7855
7856   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7857
7858   abbrev_section = get_abbrev_section_for_cu (this_cu);
7859
7860   if (use_existing_cu && this_cu->cu != NULL)
7861     {
7862       cu = this_cu->cu;
7863       /* If this CU is from a DWO file we need to start over, we need to
7864          refetch the attributes from the skeleton CU.
7865          This could be optimized by retrieving those attributes from when we
7866          were here the first time: the previous comp_unit_die was stored in
7867          comp_unit_obstack.  But there's no data yet that we need this
7868          optimization.  */
7869       if (cu->dwo_unit != NULL)
7870         rereading_dwo_cu = 1;
7871     }
7872   else
7873     {
7874       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7875       gdb_assert (this_cu->cu == NULL);
7876       cu = XNEW (struct dwarf2_cu);
7877       init_one_comp_unit (cu, this_cu);
7878       /* If an error occurs while loading, release our storage.  */
7879       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7880     }
7881
7882   /* Get the header.  */
7883   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7884     {
7885       /* We already have the header, there's no need to read it in again.  */
7886       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7887     }
7888   else
7889     {
7890       if (this_cu->is_debug_types)
7891         {
7892           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7893                                                     &cu->header, section,
7894                                                     abbrev_section, info_ptr,
7895                                                     rcuh_kind::TYPE);
7896
7897           /* Since per_cu is the first member of struct signatured_type,
7898              we can go from a pointer to one to a pointer to the other.  */
7899           sig_type = (struct signatured_type *) this_cu;
7900           gdb_assert (sig_type->signature == cu->header.signature);
7901           gdb_assert (sig_type->type_offset_in_tu
7902                       == cu->header.type_cu_offset_in_tu);
7903           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7904
7905           /* LENGTH has not been set yet for type units if we're
7906              using .gdb_index.  */
7907           this_cu->length = get_cu_length (&cu->header);
7908
7909           /* Establish the type offset that can be used to lookup the type.  */
7910           sig_type->type_offset_in_section =
7911             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7912
7913           this_cu->dwarf_version = cu->header.version;
7914         }
7915       else
7916         {
7917           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7918                                                     &cu->header, section,
7919                                                     abbrev_section,
7920                                                     info_ptr,
7921                                                     rcuh_kind::COMPILE);
7922
7923           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7924           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7925           this_cu->dwarf_version = cu->header.version;
7926         }
7927     }
7928
7929   /* Skip dummy compilation units.  */
7930   if (info_ptr >= begin_info_ptr + this_cu->length
7931       || peek_abbrev_code (abfd, info_ptr) == 0)
7932     {
7933       do_cleanups (cleanups);
7934       return;
7935     }
7936
7937   /* If we don't have them yet, read the abbrevs for this compilation unit.
7938      And if we need to read them now, make sure they're freed when we're
7939      done (own the table through ABBREV_TABLE_HOLDER).  */
7940   abbrev_table_up abbrev_table_holder;
7941   if (abbrev_table != NULL)
7942     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7943   else
7944     {
7945       abbrev_table_holder
7946         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7947                                    cu->header.abbrev_sect_off);
7948       abbrev_table = abbrev_table_holder.get ();
7949     }
7950
7951   /* Read the top level CU/TU die.  */
7952   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7953   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7954
7955   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7956      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7957      table from the DWO file and pass the ownership over to us.  It will be
7958      referenced from READER, so we must make sure to free it after we're done
7959      with READER.
7960
7961      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7962      DWO CU, that this test will fail (the attribute will not be present).  */
7963   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7964   abbrev_table_up dwo_abbrev_table;
7965   if (attr)
7966     {
7967       struct dwo_unit *dwo_unit;
7968       struct die_info *dwo_comp_unit_die;
7969
7970       if (has_children)
7971         {
7972           complaint (&symfile_complaints,
7973                      _("compilation unit with DW_AT_GNU_dwo_name"
7974                        " has children (offset 0x%x) [in module %s]"),
7975                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7976         }
7977       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7978       if (dwo_unit != NULL)
7979         {
7980           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7981                                       comp_unit_die, NULL,
7982                                       &reader, &info_ptr,
7983                                       &dwo_comp_unit_die, &has_children,
7984                                       &dwo_abbrev_table) == 0)
7985             {
7986               /* Dummy die.  */
7987               do_cleanups (cleanups);
7988               return;
7989             }
7990           comp_unit_die = dwo_comp_unit_die;
7991         }
7992       else
7993         {
7994           /* Yikes, we couldn't find the rest of the DIE, we only have
7995              the stub.  A complaint has already been logged.  There's
7996              not much more we can do except pass on the stub DIE to
7997              die_reader_func.  We don't want to throw an error on bad
7998              debug info.  */
7999         }
8000     }
8001
8002   /* All of the above is setup for this call.  Yikes.  */
8003   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8004
8005   /* Done, clean up.  */
8006   if (free_cu_cleanup != NULL)
8007     {
8008       if (keep)
8009         {
8010           /* We've successfully allocated this compilation unit.  Let our
8011              caller clean it up when finished with it.  */
8012           discard_cleanups (free_cu_cleanup);
8013
8014           /* Link this CU into read_in_chain.  */
8015           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8016           dwarf2_per_objfile->read_in_chain = this_cu;
8017         }
8018       else
8019         do_cleanups (free_cu_cleanup);
8020     }
8021
8022   do_cleanups (cleanups);
8023 }
8024
8025 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8026    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8027    to have already done the lookup to find the DWO file).
8028
8029    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8030    THIS_CU->is_debug_types, but nothing else.
8031
8032    We fill in THIS_CU->length.
8033
8034    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8035    linker) then DIE_READER_FUNC will not get called.
8036
8037    THIS_CU->cu is always freed when done.
8038    This is done in order to not leave THIS_CU->cu in a state where we have
8039    to care whether it refers to the "main" CU or the DWO CU.  */
8040
8041 static void
8042 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8043                                    struct dwo_file *dwo_file,
8044                                    die_reader_func_ftype *die_reader_func,
8045                                    void *data)
8046 {
8047   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8048   struct objfile *objfile = dwarf2_per_objfile->objfile;
8049   struct dwarf2_section_info *section = this_cu->section;
8050   bfd *abfd = get_section_bfd_owner (section);
8051   struct dwarf2_section_info *abbrev_section;
8052   struct dwarf2_cu cu;
8053   const gdb_byte *begin_info_ptr, *info_ptr;
8054   struct die_reader_specs reader;
8055   struct cleanup *cleanups;
8056   struct die_info *comp_unit_die;
8057   int has_children;
8058
8059   if (dwarf_die_debug)
8060     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
8061                         this_cu->is_debug_types ? "type" : "comp",
8062                         to_underlying (this_cu->sect_off));
8063
8064   gdb_assert (this_cu->cu == NULL);
8065
8066   abbrev_section = (dwo_file != NULL
8067                     ? &dwo_file->sections.abbrev
8068                     : get_abbrev_section_for_cu (this_cu));
8069
8070   /* This is cheap if the section is already read in.  */
8071   dwarf2_read_section (objfile, section);
8072
8073   init_one_comp_unit (&cu, this_cu);
8074
8075   cleanups = make_cleanup (free_stack_comp_unit, &cu);
8076
8077   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8078   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8079                                             &cu.header, section,
8080                                             abbrev_section, info_ptr,
8081                                             (this_cu->is_debug_types
8082                                              ? rcuh_kind::TYPE
8083                                              : rcuh_kind::COMPILE));
8084
8085   this_cu->length = get_cu_length (&cu.header);
8086
8087   /* Skip dummy compilation units.  */
8088   if (info_ptr >= begin_info_ptr + this_cu->length
8089       || peek_abbrev_code (abfd, info_ptr) == 0)
8090     {
8091       do_cleanups (cleanups);
8092       return;
8093     }
8094
8095   abbrev_table_up abbrev_table
8096     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
8097                                cu.header.abbrev_sect_off);
8098
8099   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
8100   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8101
8102   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8103
8104   do_cleanups (cleanups);
8105 }
8106
8107 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8108    does not lookup the specified DWO file.
8109    This cannot be used to read DWO files.
8110
8111    THIS_CU->cu is always freed when done.
8112    This is done in order to not leave THIS_CU->cu in a state where we have
8113    to care whether it refers to the "main" CU or the DWO CU.
8114    We can revisit this if the data shows there's a performance issue.  */
8115
8116 static void
8117 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8118                                 die_reader_func_ftype *die_reader_func,
8119                                 void *data)
8120 {
8121   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8122 }
8123 \f
8124 /* Type Unit Groups.
8125
8126    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8127    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8128    so that all types coming from the same compilation (.o file) are grouped
8129    together.  A future step could be to put the types in the same symtab as
8130    the CU the types ultimately came from.  */
8131
8132 static hashval_t
8133 hash_type_unit_group (const void *item)
8134 {
8135   const struct type_unit_group *tu_group
8136     = (const struct type_unit_group *) item;
8137
8138   return hash_stmt_list_entry (&tu_group->hash);
8139 }
8140
8141 static int
8142 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8143 {
8144   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8145   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8146
8147   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8148 }
8149
8150 /* Allocate a hash table for type unit groups.  */
8151
8152 static htab_t
8153 allocate_type_unit_groups_table (struct objfile *objfile)
8154 {
8155   return htab_create_alloc_ex (3,
8156                                hash_type_unit_group,
8157                                eq_type_unit_group,
8158                                NULL,
8159                                &objfile->objfile_obstack,
8160                                hashtab_obstack_allocate,
8161                                dummy_obstack_deallocate);
8162 }
8163
8164 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8165    partial symtabs.  We combine several TUs per psymtab to not let the size
8166    of any one psymtab grow too big.  */
8167 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8168 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8169
8170 /* Helper routine for get_type_unit_group.
8171    Create the type_unit_group object used to hold one or more TUs.  */
8172
8173 static struct type_unit_group *
8174 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8175 {
8176   struct dwarf2_per_objfile *dwarf2_per_objfile
8177     = cu->per_cu->dwarf2_per_objfile;
8178   struct objfile *objfile = dwarf2_per_objfile->objfile;
8179   struct dwarf2_per_cu_data *per_cu;
8180   struct type_unit_group *tu_group;
8181
8182   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8183                              struct type_unit_group);
8184   per_cu = &tu_group->per_cu;
8185   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8186
8187   if (dwarf2_per_objfile->using_index)
8188     {
8189       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8190                                         struct dwarf2_per_cu_quick_data);
8191     }
8192   else
8193     {
8194       unsigned int line_offset = to_underlying (line_offset_struct);
8195       struct partial_symtab *pst;
8196       char *name;
8197
8198       /* Give the symtab a useful name for debug purposes.  */
8199       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8200         name = xstrprintf ("<type_units_%d>",
8201                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8202       else
8203         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8204
8205       pst = create_partial_symtab (per_cu, name);
8206       pst->anonymous = 1;
8207
8208       xfree (name);
8209     }
8210
8211   tu_group->hash.dwo_unit = cu->dwo_unit;
8212   tu_group->hash.line_sect_off = line_offset_struct;
8213
8214   return tu_group;
8215 }
8216
8217 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8218    STMT_LIST is a DW_AT_stmt_list attribute.  */
8219
8220 static struct type_unit_group *
8221 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8222 {
8223   struct dwarf2_per_objfile *dwarf2_per_objfile
8224     = cu->per_cu->dwarf2_per_objfile;
8225   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8226   struct type_unit_group *tu_group;
8227   void **slot;
8228   unsigned int line_offset;
8229   struct type_unit_group type_unit_group_for_lookup;
8230
8231   if (dwarf2_per_objfile->type_unit_groups == NULL)
8232     {
8233       dwarf2_per_objfile->type_unit_groups =
8234         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8235     }
8236
8237   /* Do we need to create a new group, or can we use an existing one?  */
8238
8239   if (stmt_list)
8240     {
8241       line_offset = DW_UNSND (stmt_list);
8242       ++tu_stats->nr_symtab_sharers;
8243     }
8244   else
8245     {
8246       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8247          We can do various things here like create one group per TU or
8248          spread them over multiple groups to split up the expansion work.
8249          To avoid worst case scenarios (too many groups or too large groups)
8250          we, umm, group them in bunches.  */
8251       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8252                      | (tu_stats->nr_stmt_less_type_units
8253                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8254       ++tu_stats->nr_stmt_less_type_units;
8255     }
8256
8257   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8258   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8259   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8260                          &type_unit_group_for_lookup, INSERT);
8261   if (*slot != NULL)
8262     {
8263       tu_group = (struct type_unit_group *) *slot;
8264       gdb_assert (tu_group != NULL);
8265     }
8266   else
8267     {
8268       sect_offset line_offset_struct = (sect_offset) line_offset;
8269       tu_group = create_type_unit_group (cu, line_offset_struct);
8270       *slot = tu_group;
8271       ++tu_stats->nr_symtabs;
8272     }
8273
8274   return tu_group;
8275 }
8276 \f
8277 /* Partial symbol tables.  */
8278
8279 /* Create a psymtab named NAME and assign it to PER_CU.
8280
8281    The caller must fill in the following details:
8282    dirname, textlow, texthigh.  */
8283
8284 static struct partial_symtab *
8285 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8286 {
8287   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8288   struct partial_symtab *pst;
8289
8290   pst = start_psymtab_common (objfile, name, 0,
8291                               objfile->global_psymbols,
8292                               objfile->static_psymbols);
8293
8294   pst->psymtabs_addrmap_supported = 1;
8295
8296   /* This is the glue that links PST into GDB's symbol API.  */
8297   pst->read_symtab_private = per_cu;
8298   pst->read_symtab = dwarf2_read_symtab;
8299   per_cu->v.psymtab = pst;
8300
8301   return pst;
8302 }
8303
8304 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8305    type.  */
8306
8307 struct process_psymtab_comp_unit_data
8308 {
8309   /* True if we are reading a DW_TAG_partial_unit.  */
8310
8311   int want_partial_unit;
8312
8313   /* The "pretend" language that is used if the CU doesn't declare a
8314      language.  */
8315
8316   enum language pretend_language;
8317 };
8318
8319 /* die_reader_func for process_psymtab_comp_unit.  */
8320
8321 static void
8322 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8323                                   const gdb_byte *info_ptr,
8324                                   struct die_info *comp_unit_die,
8325                                   int has_children,
8326                                   void *data)
8327 {
8328   struct dwarf2_cu *cu = reader->cu;
8329   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8330   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8331   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8332   CORE_ADDR baseaddr;
8333   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8334   struct partial_symtab *pst;
8335   enum pc_bounds_kind cu_bounds_kind;
8336   const char *filename;
8337   struct process_psymtab_comp_unit_data *info
8338     = (struct process_psymtab_comp_unit_data *) data;
8339
8340   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8341     return;
8342
8343   gdb_assert (! per_cu->is_debug_types);
8344
8345   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8346
8347   cu->list_in_scope = &file_symbols;
8348
8349   /* Allocate a new partial symbol table structure.  */
8350   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8351   if (filename == NULL)
8352     filename = "";
8353
8354   pst = create_partial_symtab (per_cu, filename);
8355
8356   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8357   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8358
8359   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8360
8361   dwarf2_find_base_address (comp_unit_die, cu);
8362
8363   /* Possibly set the default values of LOWPC and HIGHPC from
8364      `DW_AT_ranges'.  */
8365   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8366                                          &best_highpc, cu, pst);
8367   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8368     /* Store the contiguous range if it is not empty; it can be empty for
8369        CUs with no code.  */
8370     addrmap_set_empty (objfile->psymtabs_addrmap,
8371                        gdbarch_adjust_dwarf2_addr (gdbarch,
8372                                                    best_lowpc + baseaddr),
8373                        gdbarch_adjust_dwarf2_addr (gdbarch,
8374                                                    best_highpc + baseaddr) - 1,
8375                        pst);
8376
8377   /* Check if comp unit has_children.
8378      If so, read the rest of the partial symbols from this comp unit.
8379      If not, there's no more debug_info for this comp unit.  */
8380   if (has_children)
8381     {
8382       struct partial_die_info *first_die;
8383       CORE_ADDR lowpc, highpc;
8384
8385       lowpc = ((CORE_ADDR) -1);
8386       highpc = ((CORE_ADDR) 0);
8387
8388       first_die = load_partial_dies (reader, info_ptr, 1);
8389
8390       scan_partial_symbols (first_die, &lowpc, &highpc,
8391                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8392
8393       /* If we didn't find a lowpc, set it to highpc to avoid
8394          complaints from `maint check'.  */
8395       if (lowpc == ((CORE_ADDR) -1))
8396         lowpc = highpc;
8397
8398       /* If the compilation unit didn't have an explicit address range,
8399          then use the information extracted from its child dies.  */
8400       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8401         {
8402           best_lowpc = lowpc;
8403           best_highpc = highpc;
8404         }
8405     }
8406   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8407   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8408
8409   end_psymtab_common (objfile, pst);
8410
8411   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8412     {
8413       int i;
8414       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8415       struct dwarf2_per_cu_data *iter;
8416
8417       /* Fill in 'dependencies' here; we fill in 'users' in a
8418          post-pass.  */
8419       pst->number_of_dependencies = len;
8420       pst->dependencies =
8421         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8422       for (i = 0;
8423            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8424                         i, iter);
8425            ++i)
8426         pst->dependencies[i] = iter->v.psymtab;
8427
8428       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8429     }
8430
8431   /* Get the list of files included in the current compilation unit,
8432      and build a psymtab for each of them.  */
8433   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8434
8435   if (dwarf_read_debug)
8436     {
8437       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8438
8439       fprintf_unfiltered (gdb_stdlog,
8440                           "Psymtab for %s unit @0x%x: %s - %s"
8441                           ", %d global, %d static syms\n",
8442                           per_cu->is_debug_types ? "type" : "comp",
8443                           to_underlying (per_cu->sect_off),
8444                           paddress (gdbarch, pst->textlow),
8445                           paddress (gdbarch, pst->texthigh),
8446                           pst->n_global_syms, pst->n_static_syms);
8447     }
8448 }
8449
8450 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8451    Process compilation unit THIS_CU for a psymtab.  */
8452
8453 static void
8454 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8455                            int want_partial_unit,
8456                            enum language pretend_language)
8457 {
8458   /* If this compilation unit was already read in, free the
8459      cached copy in order to read it in again.  This is
8460      necessary because we skipped some symbols when we first
8461      read in the compilation unit (see load_partial_dies).
8462      This problem could be avoided, but the benefit is unclear.  */
8463   if (this_cu->cu != NULL)
8464     free_one_cached_comp_unit (this_cu);
8465
8466   if (this_cu->is_debug_types)
8467     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8468                              NULL);
8469   else
8470     {
8471       process_psymtab_comp_unit_data info;
8472       info.want_partial_unit = want_partial_unit;
8473       info.pretend_language = pretend_language;
8474       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8475                                process_psymtab_comp_unit_reader, &info);
8476     }
8477
8478   /* Age out any secondary CUs.  */
8479   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8480 }
8481
8482 /* Reader function for build_type_psymtabs.  */
8483
8484 static void
8485 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8486                             const gdb_byte *info_ptr,
8487                             struct die_info *type_unit_die,
8488                             int has_children,
8489                             void *data)
8490 {
8491   struct dwarf2_per_objfile *dwarf2_per_objfile
8492     = reader->cu->per_cu->dwarf2_per_objfile;
8493   struct objfile *objfile = dwarf2_per_objfile->objfile;
8494   struct dwarf2_cu *cu = reader->cu;
8495   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8496   struct signatured_type *sig_type;
8497   struct type_unit_group *tu_group;
8498   struct attribute *attr;
8499   struct partial_die_info *first_die;
8500   CORE_ADDR lowpc, highpc;
8501   struct partial_symtab *pst;
8502
8503   gdb_assert (data == NULL);
8504   gdb_assert (per_cu->is_debug_types);
8505   sig_type = (struct signatured_type *) per_cu;
8506
8507   if (! has_children)
8508     return;
8509
8510   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8511   tu_group = get_type_unit_group (cu, attr);
8512
8513   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8514
8515   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8516   cu->list_in_scope = &file_symbols;
8517   pst = create_partial_symtab (per_cu, "");
8518   pst->anonymous = 1;
8519
8520   first_die = load_partial_dies (reader, info_ptr, 1);
8521
8522   lowpc = (CORE_ADDR) -1;
8523   highpc = (CORE_ADDR) 0;
8524   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8525
8526   end_psymtab_common (objfile, pst);
8527 }
8528
8529 /* Struct used to sort TUs by their abbreviation table offset.  */
8530
8531 struct tu_abbrev_offset
8532 {
8533   struct signatured_type *sig_type;
8534   sect_offset abbrev_offset;
8535 };
8536
8537 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8538
8539 static int
8540 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8541 {
8542   const struct tu_abbrev_offset * const *a
8543     = (const struct tu_abbrev_offset * const*) ap;
8544   const struct tu_abbrev_offset * const *b
8545     = (const struct tu_abbrev_offset * const*) bp;
8546   sect_offset aoff = (*a)->abbrev_offset;
8547   sect_offset boff = (*b)->abbrev_offset;
8548
8549   return (aoff > boff) - (aoff < boff);
8550 }
8551
8552 /* Efficiently read all the type units.
8553    This does the bulk of the work for build_type_psymtabs.
8554
8555    The efficiency is because we sort TUs by the abbrev table they use and
8556    only read each abbrev table once.  In one program there are 200K TUs
8557    sharing 8K abbrev tables.
8558
8559    The main purpose of this function is to support building the
8560    dwarf2_per_objfile->type_unit_groups table.
8561    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8562    can collapse the search space by grouping them by stmt_list.
8563    The savings can be significant, in the same program from above the 200K TUs
8564    share 8K stmt_list tables.
8565
8566    FUNC is expected to call get_type_unit_group, which will create the
8567    struct type_unit_group if necessary and add it to
8568    dwarf2_per_objfile->type_unit_groups.  */
8569
8570 static void
8571 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8572 {
8573   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8574   struct cleanup *cleanups;
8575   abbrev_table_up abbrev_table;
8576   sect_offset abbrev_offset;
8577   struct tu_abbrev_offset *sorted_by_abbrev;
8578   int i;
8579
8580   /* It's up to the caller to not call us multiple times.  */
8581   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8582
8583   if (dwarf2_per_objfile->n_type_units == 0)
8584     return;
8585
8586   /* TUs typically share abbrev tables, and there can be way more TUs than
8587      abbrev tables.  Sort by abbrev table to reduce the number of times we
8588      read each abbrev table in.
8589      Alternatives are to punt or to maintain a cache of abbrev tables.
8590      This is simpler and efficient enough for now.
8591
8592      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8593      symtab to use).  Typically TUs with the same abbrev offset have the same
8594      stmt_list value too so in practice this should work well.
8595
8596      The basic algorithm here is:
8597
8598       sort TUs by abbrev table
8599       for each TU with same abbrev table:
8600         read abbrev table if first user
8601         read TU top level DIE
8602           [IWBN if DWO skeletons had DW_AT_stmt_list]
8603         call FUNC  */
8604
8605   if (dwarf_read_debug)
8606     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8607
8608   /* Sort in a separate table to maintain the order of all_type_units
8609      for .gdb_index: TU indices directly index all_type_units.  */
8610   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8611                               dwarf2_per_objfile->n_type_units);
8612   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8613     {
8614       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8615
8616       sorted_by_abbrev[i].sig_type = sig_type;
8617       sorted_by_abbrev[i].abbrev_offset =
8618         read_abbrev_offset (dwarf2_per_objfile,
8619                             sig_type->per_cu.section,
8620                             sig_type->per_cu.sect_off);
8621     }
8622   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8623   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8624          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8625
8626   abbrev_offset = (sect_offset) ~(unsigned) 0;
8627
8628   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8629     {
8630       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8631
8632       /* Switch to the next abbrev table if necessary.  */
8633       if (abbrev_table == NULL
8634           || tu->abbrev_offset != abbrev_offset)
8635         {
8636           abbrev_offset = tu->abbrev_offset;
8637           abbrev_table =
8638             abbrev_table_read_table (dwarf2_per_objfile,
8639                                      &dwarf2_per_objfile->abbrev,
8640                                      abbrev_offset);
8641           ++tu_stats->nr_uniq_abbrev_tables;
8642         }
8643
8644       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8645                                0, 0, build_type_psymtabs_reader, NULL);
8646     }
8647
8648   do_cleanups (cleanups);
8649 }
8650
8651 /* Print collected type unit statistics.  */
8652
8653 static void
8654 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8655 {
8656   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8657
8658   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8659   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8660                       dwarf2_per_objfile->n_type_units);
8661   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8662                       tu_stats->nr_uniq_abbrev_tables);
8663   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8664                       tu_stats->nr_symtabs);
8665   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8666                       tu_stats->nr_symtab_sharers);
8667   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8668                       tu_stats->nr_stmt_less_type_units);
8669   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8670                       tu_stats->nr_all_type_units_reallocs);
8671 }
8672
8673 /* Traversal function for build_type_psymtabs.  */
8674
8675 static int
8676 build_type_psymtab_dependencies (void **slot, void *info)
8677 {
8678   struct dwarf2_per_objfile *dwarf2_per_objfile
8679     = (struct dwarf2_per_objfile *) info;
8680   struct objfile *objfile = dwarf2_per_objfile->objfile;
8681   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8682   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8683   struct partial_symtab *pst = per_cu->v.psymtab;
8684   int len = VEC_length (sig_type_ptr, tu_group->tus);
8685   struct signatured_type *iter;
8686   int i;
8687
8688   gdb_assert (len > 0);
8689   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8690
8691   pst->number_of_dependencies = len;
8692   pst->dependencies =
8693     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8694   for (i = 0;
8695        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8696        ++i)
8697     {
8698       gdb_assert (iter->per_cu.is_debug_types);
8699       pst->dependencies[i] = iter->per_cu.v.psymtab;
8700       iter->type_unit_group = tu_group;
8701     }
8702
8703   VEC_free (sig_type_ptr, tu_group->tus);
8704
8705   return 1;
8706 }
8707
8708 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8709    Build partial symbol tables for the .debug_types comp-units.  */
8710
8711 static void
8712 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8713 {
8714   if (! create_all_type_units (dwarf2_per_objfile))
8715     return;
8716
8717   build_type_psymtabs_1 (dwarf2_per_objfile);
8718 }
8719
8720 /* Traversal function for process_skeletonless_type_unit.
8721    Read a TU in a DWO file and build partial symbols for it.  */
8722
8723 static int
8724 process_skeletonless_type_unit (void **slot, void *info)
8725 {
8726   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8727   struct dwarf2_per_objfile *dwarf2_per_objfile
8728     = (struct dwarf2_per_objfile *) info;
8729   struct signatured_type find_entry, *entry;
8730
8731   /* If this TU doesn't exist in the global table, add it and read it in.  */
8732
8733   if (dwarf2_per_objfile->signatured_types == NULL)
8734     {
8735       dwarf2_per_objfile->signatured_types
8736         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8737     }
8738
8739   find_entry.signature = dwo_unit->signature;
8740   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8741                          INSERT);
8742   /* If we've already seen this type there's nothing to do.  What's happening
8743      is we're doing our own version of comdat-folding here.  */
8744   if (*slot != NULL)
8745     return 1;
8746
8747   /* This does the job that create_all_type_units would have done for
8748      this TU.  */
8749   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8750   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8751   *slot = entry;
8752
8753   /* This does the job that build_type_psymtabs_1 would have done.  */
8754   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8755                            build_type_psymtabs_reader, NULL);
8756
8757   return 1;
8758 }
8759
8760 /* Traversal function for process_skeletonless_type_units.  */
8761
8762 static int
8763 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8764 {
8765   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8766
8767   if (dwo_file->tus != NULL)
8768     {
8769       htab_traverse_noresize (dwo_file->tus,
8770                               process_skeletonless_type_unit, info);
8771     }
8772
8773   return 1;
8774 }
8775
8776 /* Scan all TUs of DWO files, verifying we've processed them.
8777    This is needed in case a TU was emitted without its skeleton.
8778    Note: This can't be done until we know what all the DWO files are.  */
8779
8780 static void
8781 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8782 {
8783   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8784   if (get_dwp_file (dwarf2_per_objfile) == NULL
8785       && dwarf2_per_objfile->dwo_files != NULL)
8786     {
8787       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8788                               process_dwo_file_for_skeletonless_type_units,
8789                               dwarf2_per_objfile);
8790     }
8791 }
8792
8793 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8794
8795 static void
8796 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8797 {
8798   int i;
8799
8800   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8801     {
8802       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8803       struct partial_symtab *pst = per_cu->v.psymtab;
8804       int j;
8805
8806       if (pst == NULL)
8807         continue;
8808
8809       for (j = 0; j < pst->number_of_dependencies; ++j)
8810         {
8811           /* Set the 'user' field only if it is not already set.  */
8812           if (pst->dependencies[j]->user == NULL)
8813             pst->dependencies[j]->user = pst;
8814         }
8815     }
8816 }
8817
8818 /* Build the partial symbol table by doing a quick pass through the
8819    .debug_info and .debug_abbrev sections.  */
8820
8821 static void
8822 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8823 {
8824   struct cleanup *back_to;
8825   int i;
8826   struct objfile *objfile = dwarf2_per_objfile->objfile;
8827
8828   if (dwarf_read_debug)
8829     {
8830       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8831                           objfile_name (objfile));
8832     }
8833
8834   dwarf2_per_objfile->reading_partial_symbols = 1;
8835
8836   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8837
8838   /* Any cached compilation units will be linked by the per-objfile
8839      read_in_chain.  Make sure to free them when we're done.  */
8840   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8841
8842   build_type_psymtabs (dwarf2_per_objfile);
8843
8844   create_all_comp_units (dwarf2_per_objfile);
8845
8846   /* Create a temporary address map on a temporary obstack.  We later
8847      copy this to the final obstack.  */
8848   auto_obstack temp_obstack;
8849
8850   scoped_restore save_psymtabs_addrmap
8851     = make_scoped_restore (&objfile->psymtabs_addrmap,
8852                            addrmap_create_mutable (&temp_obstack));
8853
8854   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8855     {
8856       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8857
8858       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8859     }
8860
8861   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8862   process_skeletonless_type_units (dwarf2_per_objfile);
8863
8864   /* Now that all TUs have been processed we can fill in the dependencies.  */
8865   if (dwarf2_per_objfile->type_unit_groups != NULL)
8866     {
8867       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8868                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8869     }
8870
8871   if (dwarf_read_debug)
8872     print_tu_stats (dwarf2_per_objfile);
8873
8874   set_partial_user (dwarf2_per_objfile);
8875
8876   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8877                                                     &objfile->objfile_obstack);
8878   /* At this point we want to keep the address map.  */
8879   save_psymtabs_addrmap.release ();
8880
8881   do_cleanups (back_to);
8882
8883   if (dwarf_read_debug)
8884     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8885                         objfile_name (objfile));
8886 }
8887
8888 /* die_reader_func for load_partial_comp_unit.  */
8889
8890 static void
8891 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8892                                const gdb_byte *info_ptr,
8893                                struct die_info *comp_unit_die,
8894                                int has_children,
8895                                void *data)
8896 {
8897   struct dwarf2_cu *cu = reader->cu;
8898
8899   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8900
8901   /* Check if comp unit has_children.
8902      If so, read the rest of the partial symbols from this comp unit.
8903      If not, there's no more debug_info for this comp unit.  */
8904   if (has_children)
8905     load_partial_dies (reader, info_ptr, 0);
8906 }
8907
8908 /* Load the partial DIEs for a secondary CU into memory.
8909    This is also used when rereading a primary CU with load_all_dies.  */
8910
8911 static void
8912 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8913 {
8914   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8915                            load_partial_comp_unit_reader, NULL);
8916 }
8917
8918 static void
8919 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8920                               struct dwarf2_section_info *section,
8921                               struct dwarf2_section_info *abbrev_section,
8922                               unsigned int is_dwz,
8923                               int *n_allocated,
8924                               int *n_comp_units,
8925                               struct dwarf2_per_cu_data ***all_comp_units)
8926 {
8927   const gdb_byte *info_ptr;
8928   struct objfile *objfile = dwarf2_per_objfile->objfile;
8929
8930   if (dwarf_read_debug)
8931     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8932                         get_section_name (section),
8933                         get_section_file_name (section));
8934
8935   dwarf2_read_section (objfile, section);
8936
8937   info_ptr = section->buffer;
8938
8939   while (info_ptr < section->buffer + section->size)
8940     {
8941       struct dwarf2_per_cu_data *this_cu;
8942
8943       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8944
8945       comp_unit_head cu_header;
8946       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8947                                      abbrev_section, info_ptr,
8948                                      rcuh_kind::COMPILE);
8949
8950       /* Save the compilation unit for later lookup.  */
8951       if (cu_header.unit_type != DW_UT_type)
8952         {
8953           this_cu = XOBNEW (&objfile->objfile_obstack,
8954                             struct dwarf2_per_cu_data);
8955           memset (this_cu, 0, sizeof (*this_cu));
8956         }
8957       else
8958         {
8959           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8960                                   struct signatured_type);
8961           memset (sig_type, 0, sizeof (*sig_type));
8962           sig_type->signature = cu_header.signature;
8963           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8964           this_cu = &sig_type->per_cu;
8965         }
8966       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8967       this_cu->sect_off = sect_off;
8968       this_cu->length = cu_header.length + cu_header.initial_length_size;
8969       this_cu->is_dwz = is_dwz;
8970       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8971       this_cu->section = section;
8972
8973       if (*n_comp_units == *n_allocated)
8974         {
8975           *n_allocated *= 2;
8976           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8977                                         *all_comp_units, *n_allocated);
8978         }
8979       (*all_comp_units)[*n_comp_units] = this_cu;
8980       ++*n_comp_units;
8981
8982       info_ptr = info_ptr + this_cu->length;
8983     }
8984 }
8985
8986 /* Create a list of all compilation units in OBJFILE.
8987    This is only done for -readnow and building partial symtabs.  */
8988
8989 static void
8990 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8991 {
8992   int n_allocated;
8993   int n_comp_units;
8994   struct dwarf2_per_cu_data **all_comp_units;
8995   struct dwz_file *dwz;
8996   struct objfile *objfile = dwarf2_per_objfile->objfile;
8997
8998   n_comp_units = 0;
8999   n_allocated = 10;
9000   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9001
9002   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9003                                 &dwarf2_per_objfile->abbrev, 0,
9004                                 &n_allocated, &n_comp_units, &all_comp_units);
9005
9006   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9007   if (dwz != NULL)
9008     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9009                                   1, &n_allocated, &n_comp_units,
9010                                   &all_comp_units);
9011
9012   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9013                                                   struct dwarf2_per_cu_data *,
9014                                                   n_comp_units);
9015   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9016           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9017   xfree (all_comp_units);
9018   dwarf2_per_objfile->n_comp_units = n_comp_units;
9019 }
9020
9021 /* Process all loaded DIEs for compilation unit CU, starting at
9022    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9023    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9024    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9025    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9026
9027 static void
9028 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9029                       CORE_ADDR *highpc, int set_addrmap,
9030                       struct dwarf2_cu *cu)
9031 {
9032   struct partial_die_info *pdi;
9033
9034   /* Now, march along the PDI's, descending into ones which have
9035      interesting children but skipping the children of the other ones,
9036      until we reach the end of the compilation unit.  */
9037
9038   pdi = first_die;
9039
9040   while (pdi != NULL)
9041     {
9042       fixup_partial_die (pdi, cu);
9043
9044       /* Anonymous namespaces or modules have no name but have interesting
9045          children, so we need to look at them.  Ditto for anonymous
9046          enums.  */
9047
9048       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9049           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9050           || pdi->tag == DW_TAG_imported_unit
9051           || pdi->tag == DW_TAG_inlined_subroutine)
9052         {
9053           switch (pdi->tag)
9054             {
9055             case DW_TAG_subprogram:
9056             case DW_TAG_inlined_subroutine:
9057               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9058               break;
9059             case DW_TAG_constant:
9060             case DW_TAG_variable:
9061             case DW_TAG_typedef:
9062             case DW_TAG_union_type:
9063               if (!pdi->is_declaration)
9064                 {
9065                   add_partial_symbol (pdi, cu);
9066                 }
9067               break;
9068             case DW_TAG_class_type:
9069             case DW_TAG_interface_type:
9070             case DW_TAG_structure_type:
9071               if (!pdi->is_declaration)
9072                 {
9073                   add_partial_symbol (pdi, cu);
9074                 }
9075               if (cu->language == language_rust && pdi->has_children)
9076                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9077                                       set_addrmap, cu);
9078               break;
9079             case DW_TAG_enumeration_type:
9080               if (!pdi->is_declaration)
9081                 add_partial_enumeration (pdi, cu);
9082               break;
9083             case DW_TAG_base_type:
9084             case DW_TAG_subrange_type:
9085               /* File scope base type definitions are added to the partial
9086                  symbol table.  */
9087               add_partial_symbol (pdi, cu);
9088               break;
9089             case DW_TAG_namespace:
9090               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9091               break;
9092             case DW_TAG_module:
9093               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9094               break;
9095             case DW_TAG_imported_unit:
9096               {
9097                 struct dwarf2_per_cu_data *per_cu;
9098
9099                 /* For now we don't handle imported units in type units.  */
9100                 if (cu->per_cu->is_debug_types)
9101                   {
9102                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9103                              " supported in type units [in module %s]"),
9104                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
9105                   }
9106
9107                 per_cu = dwarf2_find_containing_comp_unit
9108                            (pdi->d.sect_off, pdi->is_dwz,
9109                             cu->per_cu->dwarf2_per_objfile);
9110
9111                 /* Go read the partial unit, if needed.  */
9112                 if (per_cu->v.psymtab == NULL)
9113                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9114
9115                 VEC_safe_push (dwarf2_per_cu_ptr,
9116                                cu->per_cu->imported_symtabs, per_cu);
9117               }
9118               break;
9119             case DW_TAG_imported_declaration:
9120               add_partial_symbol (pdi, cu);
9121               break;
9122             default:
9123               break;
9124             }
9125         }
9126
9127       /* If the die has a sibling, skip to the sibling.  */
9128
9129       pdi = pdi->die_sibling;
9130     }
9131 }
9132
9133 /* Functions used to compute the fully scoped name of a partial DIE.
9134
9135    Normally, this is simple.  For C++, the parent DIE's fully scoped
9136    name is concatenated with "::" and the partial DIE's name.
9137    Enumerators are an exception; they use the scope of their parent
9138    enumeration type, i.e. the name of the enumeration type is not
9139    prepended to the enumerator.
9140
9141    There are two complexities.  One is DW_AT_specification; in this
9142    case "parent" means the parent of the target of the specification,
9143    instead of the direct parent of the DIE.  The other is compilers
9144    which do not emit DW_TAG_namespace; in this case we try to guess
9145    the fully qualified name of structure types from their members'
9146    linkage names.  This must be done using the DIE's children rather
9147    than the children of any DW_AT_specification target.  We only need
9148    to do this for structures at the top level, i.e. if the target of
9149    any DW_AT_specification (if any; otherwise the DIE itself) does not
9150    have a parent.  */
9151
9152 /* Compute the scope prefix associated with PDI's parent, in
9153    compilation unit CU.  The result will be allocated on CU's
9154    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9155    field.  NULL is returned if no prefix is necessary.  */
9156 static const char *
9157 partial_die_parent_scope (struct partial_die_info *pdi,
9158                           struct dwarf2_cu *cu)
9159 {
9160   const char *grandparent_scope;
9161   struct partial_die_info *parent, *real_pdi;
9162
9163   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9164      then this means the parent of the specification DIE.  */
9165
9166   real_pdi = pdi;
9167   while (real_pdi->has_specification)
9168     real_pdi = find_partial_die (real_pdi->spec_offset,
9169                                  real_pdi->spec_is_dwz, cu);
9170
9171   parent = real_pdi->die_parent;
9172   if (parent == NULL)
9173     return NULL;
9174
9175   if (parent->scope_set)
9176     return parent->scope;
9177
9178   fixup_partial_die (parent, cu);
9179
9180   grandparent_scope = partial_die_parent_scope (parent, cu);
9181
9182   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9183      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9184      Work around this problem here.  */
9185   if (cu->language == language_cplus
9186       && parent->tag == DW_TAG_namespace
9187       && strcmp (parent->name, "::") == 0
9188       && grandparent_scope == NULL)
9189     {
9190       parent->scope = NULL;
9191       parent->scope_set = 1;
9192       return NULL;
9193     }
9194
9195   if (pdi->tag == DW_TAG_enumerator)
9196     /* Enumerators should not get the name of the enumeration as a prefix.  */
9197     parent->scope = grandparent_scope;
9198   else if (parent->tag == DW_TAG_namespace
9199       || parent->tag == DW_TAG_module
9200       || parent->tag == DW_TAG_structure_type
9201       || parent->tag == DW_TAG_class_type
9202       || parent->tag == DW_TAG_interface_type
9203       || parent->tag == DW_TAG_union_type
9204       || parent->tag == DW_TAG_enumeration_type)
9205     {
9206       if (grandparent_scope == NULL)
9207         parent->scope = parent->name;
9208       else
9209         parent->scope = typename_concat (&cu->comp_unit_obstack,
9210                                          grandparent_scope,
9211                                          parent->name, 0, cu);
9212     }
9213   else
9214     {
9215       /* FIXME drow/2004-04-01: What should we be doing with
9216          function-local names?  For partial symbols, we should probably be
9217          ignoring them.  */
9218       complaint (&symfile_complaints,
9219                  _("unhandled containing DIE tag %d for DIE at %d"),
9220                  parent->tag, to_underlying (pdi->sect_off));
9221       parent->scope = grandparent_scope;
9222     }
9223
9224   parent->scope_set = 1;
9225   return parent->scope;
9226 }
9227
9228 /* Return the fully scoped name associated with PDI, from compilation unit
9229    CU.  The result will be allocated with malloc.  */
9230
9231 static char *
9232 partial_die_full_name (struct partial_die_info *pdi,
9233                        struct dwarf2_cu *cu)
9234 {
9235   const char *parent_scope;
9236
9237   /* If this is a template instantiation, we can not work out the
9238      template arguments from partial DIEs.  So, unfortunately, we have
9239      to go through the full DIEs.  At least any work we do building
9240      types here will be reused if full symbols are loaded later.  */
9241   if (pdi->has_template_arguments)
9242     {
9243       fixup_partial_die (pdi, cu);
9244
9245       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9246         {
9247           struct die_info *die;
9248           struct attribute attr;
9249           struct dwarf2_cu *ref_cu = cu;
9250
9251           /* DW_FORM_ref_addr is using section offset.  */
9252           attr.name = (enum dwarf_attribute) 0;
9253           attr.form = DW_FORM_ref_addr;
9254           attr.u.unsnd = to_underlying (pdi->sect_off);
9255           die = follow_die_ref (NULL, &attr, &ref_cu);
9256
9257           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9258         }
9259     }
9260
9261   parent_scope = partial_die_parent_scope (pdi, cu);
9262   if (parent_scope == NULL)
9263     return NULL;
9264   else
9265     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9266 }
9267
9268 static void
9269 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9270 {
9271   struct dwarf2_per_objfile *dwarf2_per_objfile
9272     = cu->per_cu->dwarf2_per_objfile;
9273   struct objfile *objfile = dwarf2_per_objfile->objfile;
9274   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9275   CORE_ADDR addr = 0;
9276   const char *actual_name = NULL;
9277   CORE_ADDR baseaddr;
9278   char *built_actual_name;
9279
9280   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9281
9282   built_actual_name = partial_die_full_name (pdi, cu);
9283   if (built_actual_name != NULL)
9284     actual_name = built_actual_name;
9285
9286   if (actual_name == NULL)
9287     actual_name = pdi->name;
9288
9289   switch (pdi->tag)
9290     {
9291     case DW_TAG_inlined_subroutine:
9292     case DW_TAG_subprogram:
9293       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9294       if (pdi->is_external || cu->language == language_ada)
9295         {
9296           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9297              of the global scope.  But in Ada, we want to be able to access
9298              nested procedures globally.  So all Ada subprograms are stored
9299              in the global scope.  */
9300           add_psymbol_to_list (actual_name, strlen (actual_name),
9301                                built_actual_name != NULL,
9302                                VAR_DOMAIN, LOC_BLOCK,
9303                                &objfile->global_psymbols,
9304                                addr, cu->language, objfile);
9305         }
9306       else
9307         {
9308           add_psymbol_to_list (actual_name, strlen (actual_name),
9309                                built_actual_name != NULL,
9310                                VAR_DOMAIN, LOC_BLOCK,
9311                                &objfile->static_psymbols,
9312                                addr, cu->language, objfile);
9313         }
9314
9315       if (pdi->main_subprogram && actual_name != NULL)
9316         set_objfile_main_name (objfile, actual_name, cu->language);
9317       break;
9318     case DW_TAG_constant:
9319       {
9320         std::vector<partial_symbol *> *list;
9321
9322         if (pdi->is_external)
9323           list = &objfile->global_psymbols;
9324         else
9325           list = &objfile->static_psymbols;
9326         add_psymbol_to_list (actual_name, strlen (actual_name),
9327                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9328                              list, 0, cu->language, objfile);
9329       }
9330       break;
9331     case DW_TAG_variable:
9332       if (pdi->d.locdesc)
9333         addr = decode_locdesc (pdi->d.locdesc, cu);
9334
9335       if (pdi->d.locdesc
9336           && addr == 0
9337           && !dwarf2_per_objfile->has_section_at_zero)
9338         {
9339           /* A global or static variable may also have been stripped
9340              out by the linker if unused, in which case its address
9341              will be nullified; do not add such variables into partial
9342              symbol table then.  */
9343         }
9344       else if (pdi->is_external)
9345         {
9346           /* Global Variable.
9347              Don't enter into the minimal symbol tables as there is
9348              a minimal symbol table entry from the ELF symbols already.
9349              Enter into partial symbol table if it has a location
9350              descriptor or a type.
9351              If the location descriptor is missing, new_symbol will create
9352              a LOC_UNRESOLVED symbol, the address of the variable will then
9353              be determined from the minimal symbol table whenever the variable
9354              is referenced.
9355              The address for the partial symbol table entry is not
9356              used by GDB, but it comes in handy for debugging partial symbol
9357              table building.  */
9358
9359           if (pdi->d.locdesc || pdi->has_type)
9360             add_psymbol_to_list (actual_name, strlen (actual_name),
9361                                  built_actual_name != NULL,
9362                                  VAR_DOMAIN, LOC_STATIC,
9363                                  &objfile->global_psymbols,
9364                                  addr + baseaddr,
9365                                  cu->language, objfile);
9366         }
9367       else
9368         {
9369           int has_loc = pdi->d.locdesc != NULL;
9370
9371           /* Static Variable.  Skip symbols whose value we cannot know (those
9372              without location descriptors or constant values).  */
9373           if (!has_loc && !pdi->has_const_value)
9374             {
9375               xfree (built_actual_name);
9376               return;
9377             }
9378
9379           add_psymbol_to_list (actual_name, strlen (actual_name),
9380                                built_actual_name != NULL,
9381                                VAR_DOMAIN, LOC_STATIC,
9382                                &objfile->static_psymbols,
9383                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9384                                cu->language, objfile);
9385         }
9386       break;
9387     case DW_TAG_typedef:
9388     case DW_TAG_base_type:
9389     case DW_TAG_subrange_type:
9390       add_psymbol_to_list (actual_name, strlen (actual_name),
9391                            built_actual_name != NULL,
9392                            VAR_DOMAIN, LOC_TYPEDEF,
9393                            &objfile->static_psymbols,
9394                            0, cu->language, objfile);
9395       break;
9396     case DW_TAG_imported_declaration:
9397     case DW_TAG_namespace:
9398       add_psymbol_to_list (actual_name, strlen (actual_name),
9399                            built_actual_name != NULL,
9400                            VAR_DOMAIN, LOC_TYPEDEF,
9401                            &objfile->global_psymbols,
9402                            0, cu->language, objfile);
9403       break;
9404     case DW_TAG_module:
9405       add_psymbol_to_list (actual_name, strlen (actual_name),
9406                            built_actual_name != NULL,
9407                            MODULE_DOMAIN, LOC_TYPEDEF,
9408                            &objfile->global_psymbols,
9409                            0, cu->language, objfile);
9410       break;
9411     case DW_TAG_class_type:
9412     case DW_TAG_interface_type:
9413     case DW_TAG_structure_type:
9414     case DW_TAG_union_type:
9415     case DW_TAG_enumeration_type:
9416       /* Skip external references.  The DWARF standard says in the section
9417          about "Structure, Union, and Class Type Entries": "An incomplete
9418          structure, union or class type is represented by a structure,
9419          union or class entry that does not have a byte size attribute
9420          and that has a DW_AT_declaration attribute."  */
9421       if (!pdi->has_byte_size && pdi->is_declaration)
9422         {
9423           xfree (built_actual_name);
9424           return;
9425         }
9426
9427       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9428          static vs. global.  */
9429       add_psymbol_to_list (actual_name, strlen (actual_name),
9430                            built_actual_name != NULL,
9431                            STRUCT_DOMAIN, LOC_TYPEDEF,
9432                            cu->language == language_cplus
9433                            ? &objfile->global_psymbols
9434                            : &objfile->static_psymbols,
9435                            0, cu->language, objfile);
9436
9437       break;
9438     case DW_TAG_enumerator:
9439       add_psymbol_to_list (actual_name, strlen (actual_name),
9440                            built_actual_name != NULL,
9441                            VAR_DOMAIN, LOC_CONST,
9442                            cu->language == language_cplus
9443                            ? &objfile->global_psymbols
9444                            : &objfile->static_psymbols,
9445                            0, cu->language, objfile);
9446       break;
9447     default:
9448       break;
9449     }
9450
9451   xfree (built_actual_name);
9452 }
9453
9454 /* Read a partial die corresponding to a namespace; also, add a symbol
9455    corresponding to that namespace to the symbol table.  NAMESPACE is
9456    the name of the enclosing namespace.  */
9457
9458 static void
9459 add_partial_namespace (struct partial_die_info *pdi,
9460                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9461                        int set_addrmap, struct dwarf2_cu *cu)
9462 {
9463   /* Add a symbol for the namespace.  */
9464
9465   add_partial_symbol (pdi, cu);
9466
9467   /* Now scan partial symbols in that namespace.  */
9468
9469   if (pdi->has_children)
9470     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9471 }
9472
9473 /* Read a partial die corresponding to a Fortran module.  */
9474
9475 static void
9476 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9477                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9478 {
9479   /* Add a symbol for the namespace.  */
9480
9481   add_partial_symbol (pdi, cu);
9482
9483   /* Now scan partial symbols in that module.  */
9484
9485   if (pdi->has_children)
9486     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9487 }
9488
9489 /* Read a partial die corresponding to a subprogram or an inlined
9490    subprogram and create a partial symbol for that subprogram.
9491    When the CU language allows it, this routine also defines a partial
9492    symbol for each nested subprogram that this subprogram contains.
9493    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9494    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9495
9496    PDI may also be a lexical block, in which case we simply search
9497    recursively for subprograms defined inside that lexical block.
9498    Again, this is only performed when the CU language allows this
9499    type of definitions.  */
9500
9501 static void
9502 add_partial_subprogram (struct partial_die_info *pdi,
9503                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9504                         int set_addrmap, struct dwarf2_cu *cu)
9505 {
9506   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9507     {
9508       if (pdi->has_pc_info)
9509         {
9510           if (pdi->lowpc < *lowpc)
9511             *lowpc = pdi->lowpc;
9512           if (pdi->highpc > *highpc)
9513             *highpc = pdi->highpc;
9514           if (set_addrmap)
9515             {
9516               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9517               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9518               CORE_ADDR baseaddr;
9519               CORE_ADDR highpc;
9520               CORE_ADDR lowpc;
9521
9522               baseaddr = ANOFFSET (objfile->section_offsets,
9523                                    SECT_OFF_TEXT (objfile));
9524               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9525                                                   pdi->lowpc + baseaddr);
9526               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9527                                                    pdi->highpc + baseaddr);
9528               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9529                                  cu->per_cu->v.psymtab);
9530             }
9531         }
9532
9533       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9534         {
9535           if (!pdi->is_declaration)
9536             /* Ignore subprogram DIEs that do not have a name, they are
9537                illegal.  Do not emit a complaint at this point, we will
9538                do so when we convert this psymtab into a symtab.  */
9539             if (pdi->name)
9540               add_partial_symbol (pdi, cu);
9541         }
9542     }
9543
9544   if (! pdi->has_children)
9545     return;
9546
9547   if (cu->language == language_ada)
9548     {
9549       pdi = pdi->die_child;
9550       while (pdi != NULL)
9551         {
9552           fixup_partial_die (pdi, cu);
9553           if (pdi->tag == DW_TAG_subprogram
9554               || pdi->tag == DW_TAG_inlined_subroutine
9555               || pdi->tag == DW_TAG_lexical_block)
9556             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9557           pdi = pdi->die_sibling;
9558         }
9559     }
9560 }
9561
9562 /* Read a partial die corresponding to an enumeration type.  */
9563
9564 static void
9565 add_partial_enumeration (struct partial_die_info *enum_pdi,
9566                          struct dwarf2_cu *cu)
9567 {
9568   struct partial_die_info *pdi;
9569
9570   if (enum_pdi->name != NULL)
9571     add_partial_symbol (enum_pdi, cu);
9572
9573   pdi = enum_pdi->die_child;
9574   while (pdi)
9575     {
9576       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9577         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9578       else
9579         add_partial_symbol (pdi, cu);
9580       pdi = pdi->die_sibling;
9581     }
9582 }
9583
9584 /* Return the initial uleb128 in the die at INFO_PTR.  */
9585
9586 static unsigned int
9587 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9588 {
9589   unsigned int bytes_read;
9590
9591   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9592 }
9593
9594 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9595    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9596
9597    Return the corresponding abbrev, or NULL if the number is zero (indicating
9598    an empty DIE).  In either case *BYTES_READ will be set to the length of
9599    the initial number.  */
9600
9601 static struct abbrev_info *
9602 peek_die_abbrev (const die_reader_specs &reader,
9603                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9604 {
9605   dwarf2_cu *cu = reader.cu;
9606   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9607   unsigned int abbrev_number
9608     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9609
9610   if (abbrev_number == 0)
9611     return NULL;
9612
9613   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9614   if (!abbrev)
9615     {
9616       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9617                " at offset 0x%x [in module %s]"),
9618              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9619              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9620     }
9621
9622   return abbrev;
9623 }
9624
9625 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9626    Returns a pointer to the end of a series of DIEs, terminated by an empty
9627    DIE.  Any children of the skipped DIEs will also be skipped.  */
9628
9629 static const gdb_byte *
9630 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9631 {
9632   while (1)
9633     {
9634       unsigned int bytes_read;
9635       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9636
9637       if (abbrev == NULL)
9638         return info_ptr + bytes_read;
9639       else
9640         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9641     }
9642 }
9643
9644 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9645    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9646    abbrev corresponding to that skipped uleb128 should be passed in
9647    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9648    children.  */
9649
9650 static const gdb_byte *
9651 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9652               struct abbrev_info *abbrev)
9653 {
9654   unsigned int bytes_read;
9655   struct attribute attr;
9656   bfd *abfd = reader->abfd;
9657   struct dwarf2_cu *cu = reader->cu;
9658   const gdb_byte *buffer = reader->buffer;
9659   const gdb_byte *buffer_end = reader->buffer_end;
9660   unsigned int form, i;
9661
9662   for (i = 0; i < abbrev->num_attrs; i++)
9663     {
9664       /* The only abbrev we care about is DW_AT_sibling.  */
9665       if (abbrev->attrs[i].name == DW_AT_sibling)
9666         {
9667           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9668           if (attr.form == DW_FORM_ref_addr)
9669             complaint (&symfile_complaints,
9670                        _("ignoring absolute DW_AT_sibling"));
9671           else
9672             {
9673               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9674               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9675
9676               if (sibling_ptr < info_ptr)
9677                 complaint (&symfile_complaints,
9678                            _("DW_AT_sibling points backwards"));
9679               else if (sibling_ptr > reader->buffer_end)
9680                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9681               else
9682                 return sibling_ptr;
9683             }
9684         }
9685
9686       /* If it isn't DW_AT_sibling, skip this attribute.  */
9687       form = abbrev->attrs[i].form;
9688     skip_attribute:
9689       switch (form)
9690         {
9691         case DW_FORM_ref_addr:
9692           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9693              and later it is offset sized.  */
9694           if (cu->header.version == 2)
9695             info_ptr += cu->header.addr_size;
9696           else
9697             info_ptr += cu->header.offset_size;
9698           break;
9699         case DW_FORM_GNU_ref_alt:
9700           info_ptr += cu->header.offset_size;
9701           break;
9702         case DW_FORM_addr:
9703           info_ptr += cu->header.addr_size;
9704           break;
9705         case DW_FORM_data1:
9706         case DW_FORM_ref1:
9707         case DW_FORM_flag:
9708           info_ptr += 1;
9709           break;
9710         case DW_FORM_flag_present:
9711         case DW_FORM_implicit_const:
9712           break;
9713         case DW_FORM_data2:
9714         case DW_FORM_ref2:
9715           info_ptr += 2;
9716           break;
9717         case DW_FORM_data4:
9718         case DW_FORM_ref4:
9719           info_ptr += 4;
9720           break;
9721         case DW_FORM_data8:
9722         case DW_FORM_ref8:
9723         case DW_FORM_ref_sig8:
9724           info_ptr += 8;
9725           break;
9726         case DW_FORM_data16:
9727           info_ptr += 16;
9728           break;
9729         case DW_FORM_string:
9730           read_direct_string (abfd, info_ptr, &bytes_read);
9731           info_ptr += bytes_read;
9732           break;
9733         case DW_FORM_sec_offset:
9734         case DW_FORM_strp:
9735         case DW_FORM_GNU_strp_alt:
9736           info_ptr += cu->header.offset_size;
9737           break;
9738         case DW_FORM_exprloc:
9739         case DW_FORM_block:
9740           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9741           info_ptr += bytes_read;
9742           break;
9743         case DW_FORM_block1:
9744           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9745           break;
9746         case DW_FORM_block2:
9747           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9748           break;
9749         case DW_FORM_block4:
9750           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9751           break;
9752         case DW_FORM_sdata:
9753         case DW_FORM_udata:
9754         case DW_FORM_ref_udata:
9755         case DW_FORM_GNU_addr_index:
9756         case DW_FORM_GNU_str_index:
9757           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9758           break;
9759         case DW_FORM_indirect:
9760           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9761           info_ptr += bytes_read;
9762           /* We need to continue parsing from here, so just go back to
9763              the top.  */
9764           goto skip_attribute;
9765
9766         default:
9767           error (_("Dwarf Error: Cannot handle %s "
9768                    "in DWARF reader [in module %s]"),
9769                  dwarf_form_name (form),
9770                  bfd_get_filename (abfd));
9771         }
9772     }
9773
9774   if (abbrev->has_children)
9775     return skip_children (reader, info_ptr);
9776   else
9777     return info_ptr;
9778 }
9779
9780 /* Locate ORIG_PDI's sibling.
9781    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9782
9783 static const gdb_byte *
9784 locate_pdi_sibling (const struct die_reader_specs *reader,
9785                     struct partial_die_info *orig_pdi,
9786                     const gdb_byte *info_ptr)
9787 {
9788   /* Do we know the sibling already?  */
9789
9790   if (orig_pdi->sibling)
9791     return orig_pdi->sibling;
9792
9793   /* Are there any children to deal with?  */
9794
9795   if (!orig_pdi->has_children)
9796     return info_ptr;
9797
9798   /* Skip the children the long way.  */
9799
9800   return skip_children (reader, info_ptr);
9801 }
9802
9803 /* Expand this partial symbol table into a full symbol table.  SELF is
9804    not NULL.  */
9805
9806 static void
9807 dwarf2_read_symtab (struct partial_symtab *self,
9808                     struct objfile *objfile)
9809 {
9810   struct dwarf2_per_objfile *dwarf2_per_objfile
9811     = get_dwarf2_per_objfile (objfile);
9812
9813   if (self->readin)
9814     {
9815       warning (_("bug: psymtab for %s is already read in."),
9816                self->filename);
9817     }
9818   else
9819     {
9820       if (info_verbose)
9821         {
9822           printf_filtered (_("Reading in symbols for %s..."),
9823                            self->filename);
9824           gdb_flush (gdb_stdout);
9825         }
9826
9827       /* If this psymtab is constructed from a debug-only objfile, the
9828          has_section_at_zero flag will not necessarily be correct.  We
9829          can get the correct value for this flag by looking at the data
9830          associated with the (presumably stripped) associated objfile.  */
9831       if (objfile->separate_debug_objfile_backlink)
9832         {
9833           struct dwarf2_per_objfile *dpo_backlink
9834             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9835
9836           dwarf2_per_objfile->has_section_at_zero
9837             = dpo_backlink->has_section_at_zero;
9838         }
9839
9840       dwarf2_per_objfile->reading_partial_symbols = 0;
9841
9842       psymtab_to_symtab_1 (self);
9843
9844       /* Finish up the debug error message.  */
9845       if (info_verbose)
9846         printf_filtered (_("done.\n"));
9847     }
9848
9849   process_cu_includes (dwarf2_per_objfile);
9850 }
9851 \f
9852 /* Reading in full CUs.  */
9853
9854 /* Add PER_CU to the queue.  */
9855
9856 static void
9857 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9858                  enum language pretend_language)
9859 {
9860   struct dwarf2_queue_item *item;
9861
9862   per_cu->queued = 1;
9863   item = XNEW (struct dwarf2_queue_item);
9864   item->per_cu = per_cu;
9865   item->pretend_language = pretend_language;
9866   item->next = NULL;
9867
9868   if (dwarf2_queue == NULL)
9869     dwarf2_queue = item;
9870   else
9871     dwarf2_queue_tail->next = item;
9872
9873   dwarf2_queue_tail = item;
9874 }
9875
9876 /* If PER_CU is not yet queued, add it to the queue.
9877    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9878    dependency.
9879    The result is non-zero if PER_CU was queued, otherwise the result is zero
9880    meaning either PER_CU is already queued or it is already loaded.
9881
9882    N.B. There is an invariant here that if a CU is queued then it is loaded.
9883    The caller is required to load PER_CU if we return non-zero.  */
9884
9885 static int
9886 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9887                        struct dwarf2_per_cu_data *per_cu,
9888                        enum language pretend_language)
9889 {
9890   /* We may arrive here during partial symbol reading, if we need full
9891      DIEs to process an unusual case (e.g. template arguments).  Do
9892      not queue PER_CU, just tell our caller to load its DIEs.  */
9893   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9894     {
9895       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9896         return 1;
9897       return 0;
9898     }
9899
9900   /* Mark the dependence relation so that we don't flush PER_CU
9901      too early.  */
9902   if (dependent_cu != NULL)
9903     dwarf2_add_dependence (dependent_cu, per_cu);
9904
9905   /* If it's already on the queue, we have nothing to do.  */
9906   if (per_cu->queued)
9907     return 0;
9908
9909   /* If the compilation unit is already loaded, just mark it as
9910      used.  */
9911   if (per_cu->cu != NULL)
9912     {
9913       per_cu->cu->last_used = 0;
9914       return 0;
9915     }
9916
9917   /* Add it to the queue.  */
9918   queue_comp_unit (per_cu, pretend_language);
9919
9920   return 1;
9921 }
9922
9923 /* Process the queue.  */
9924
9925 static void
9926 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9927 {
9928   struct dwarf2_queue_item *item, *next_item;
9929
9930   if (dwarf_read_debug)
9931     {
9932       fprintf_unfiltered (gdb_stdlog,
9933                           "Expanding one or more symtabs of objfile %s ...\n",
9934                           objfile_name (dwarf2_per_objfile->objfile));
9935     }
9936
9937   /* The queue starts out with one item, but following a DIE reference
9938      may load a new CU, adding it to the end of the queue.  */
9939   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9940     {
9941       if ((dwarf2_per_objfile->using_index
9942            ? !item->per_cu->v.quick->compunit_symtab
9943            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9944           /* Skip dummy CUs.  */
9945           && item->per_cu->cu != NULL)
9946         {
9947           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9948           unsigned int debug_print_threshold;
9949           char buf[100];
9950
9951           if (per_cu->is_debug_types)
9952             {
9953               struct signatured_type *sig_type =
9954                 (struct signatured_type *) per_cu;
9955
9956               sprintf (buf, "TU %s at offset 0x%x",
9957                        hex_string (sig_type->signature),
9958                        to_underlying (per_cu->sect_off));
9959               /* There can be 100s of TUs.
9960                  Only print them in verbose mode.  */
9961               debug_print_threshold = 2;
9962             }
9963           else
9964             {
9965               sprintf (buf, "CU at offset 0x%x",
9966                        to_underlying (per_cu->sect_off));
9967               debug_print_threshold = 1;
9968             }
9969
9970           if (dwarf_read_debug >= debug_print_threshold)
9971             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9972
9973           if (per_cu->is_debug_types)
9974             process_full_type_unit (per_cu, item->pretend_language);
9975           else
9976             process_full_comp_unit (per_cu, item->pretend_language);
9977
9978           if (dwarf_read_debug >= debug_print_threshold)
9979             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9980         }
9981
9982       item->per_cu->queued = 0;
9983       next_item = item->next;
9984       xfree (item);
9985     }
9986
9987   dwarf2_queue_tail = NULL;
9988
9989   if (dwarf_read_debug)
9990     {
9991       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9992                           objfile_name (dwarf2_per_objfile->objfile));
9993     }
9994 }
9995
9996 /* Free all allocated queue entries.  This function only releases anything if
9997    an error was thrown; if the queue was processed then it would have been
9998    freed as we went along.  */
9999
10000 static void
10001 dwarf2_release_queue (void *dummy)
10002 {
10003   struct dwarf2_queue_item *item, *last;
10004
10005   item = dwarf2_queue;
10006   while (item)
10007     {
10008       /* Anything still marked queued is likely to be in an
10009          inconsistent state, so discard it.  */
10010       if (item->per_cu->queued)
10011         {
10012           if (item->per_cu->cu != NULL)
10013             free_one_cached_comp_unit (item->per_cu);
10014           item->per_cu->queued = 0;
10015         }
10016
10017       last = item;
10018       item = item->next;
10019       xfree (last);
10020     }
10021
10022   dwarf2_queue = dwarf2_queue_tail = NULL;
10023 }
10024
10025 /* Read in full symbols for PST, and anything it depends on.  */
10026
10027 static void
10028 psymtab_to_symtab_1 (struct partial_symtab *pst)
10029 {
10030   struct dwarf2_per_cu_data *per_cu;
10031   int i;
10032
10033   if (pst->readin)
10034     return;
10035
10036   for (i = 0; i < pst->number_of_dependencies; i++)
10037     if (!pst->dependencies[i]->readin
10038         && pst->dependencies[i]->user == NULL)
10039       {
10040         /* Inform about additional files that need to be read in.  */
10041         if (info_verbose)
10042           {
10043             /* FIXME: i18n: Need to make this a single string.  */
10044             fputs_filtered (" ", gdb_stdout);
10045             wrap_here ("");
10046             fputs_filtered ("and ", gdb_stdout);
10047             wrap_here ("");
10048             printf_filtered ("%s...", pst->dependencies[i]->filename);
10049             wrap_here ("");     /* Flush output.  */
10050             gdb_flush (gdb_stdout);
10051           }
10052         psymtab_to_symtab_1 (pst->dependencies[i]);
10053       }
10054
10055   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10056
10057   if (per_cu == NULL)
10058     {
10059       /* It's an include file, no symbols to read for it.
10060          Everything is in the parent symtab.  */
10061       pst->readin = 1;
10062       return;
10063     }
10064
10065   dw2_do_instantiate_symtab (per_cu);
10066 }
10067
10068 /* Trivial hash function for die_info: the hash value of a DIE
10069    is its offset in .debug_info for this objfile.  */
10070
10071 static hashval_t
10072 die_hash (const void *item)
10073 {
10074   const struct die_info *die = (const struct die_info *) item;
10075
10076   return to_underlying (die->sect_off);
10077 }
10078
10079 /* Trivial comparison function for die_info structures: two DIEs
10080    are equal if they have the same offset.  */
10081
10082 static int
10083 die_eq (const void *item_lhs, const void *item_rhs)
10084 {
10085   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10086   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10087
10088   return die_lhs->sect_off == die_rhs->sect_off;
10089 }
10090
10091 /* die_reader_func for load_full_comp_unit.
10092    This is identical to read_signatured_type_reader,
10093    but is kept separate for now.  */
10094
10095 static void
10096 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10097                             const gdb_byte *info_ptr,
10098                             struct die_info *comp_unit_die,
10099                             int has_children,
10100                             void *data)
10101 {
10102   struct dwarf2_cu *cu = reader->cu;
10103   enum language *language_ptr = (enum language *) data;
10104
10105   gdb_assert (cu->die_hash == NULL);
10106   cu->die_hash =
10107     htab_create_alloc_ex (cu->header.length / 12,
10108                           die_hash,
10109                           die_eq,
10110                           NULL,
10111                           &cu->comp_unit_obstack,
10112                           hashtab_obstack_allocate,
10113                           dummy_obstack_deallocate);
10114
10115   if (has_children)
10116     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10117                                                   &info_ptr, comp_unit_die);
10118   cu->dies = comp_unit_die;
10119   /* comp_unit_die is not stored in die_hash, no need.  */
10120
10121   /* We try not to read any attributes in this function, because not
10122      all CUs needed for references have been loaded yet, and symbol
10123      table processing isn't initialized.  But we have to set the CU language,
10124      or we won't be able to build types correctly.
10125      Similarly, if we do not read the producer, we can not apply
10126      producer-specific interpretation.  */
10127   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10128 }
10129
10130 /* Load the DIEs associated with PER_CU into memory.  */
10131
10132 static void
10133 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10134                      enum language pretend_language)
10135 {
10136   gdb_assert (! this_cu->is_debug_types);
10137
10138   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10139                            load_full_comp_unit_reader, &pretend_language);
10140 }
10141
10142 /* Add a DIE to the delayed physname list.  */
10143
10144 static void
10145 add_to_method_list (struct type *type, int fnfield_index, int index,
10146                     const char *name, struct die_info *die,
10147                     struct dwarf2_cu *cu)
10148 {
10149   struct delayed_method_info mi;
10150   mi.type = type;
10151   mi.fnfield_index = fnfield_index;
10152   mi.index = index;
10153   mi.name = name;
10154   mi.die = die;
10155   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10156 }
10157
10158 /* A cleanup for freeing the delayed method list.  */
10159
10160 static void
10161 free_delayed_list (void *ptr)
10162 {
10163   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10164   if (cu->method_list != NULL)
10165     {
10166       VEC_free (delayed_method_info, cu->method_list);
10167       cu->method_list = NULL;
10168     }
10169 }
10170
10171 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10172    "const" / "volatile".  If so, decrements LEN by the length of the
10173    modifier and return true.  Otherwise return false.  */
10174
10175 template<size_t N>
10176 static bool
10177 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10178 {
10179   size_t mod_len = sizeof (mod) - 1;
10180   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10181     {
10182       len -= mod_len;
10183       return true;
10184     }
10185   return false;
10186 }
10187
10188 /* Compute the physnames of any methods on the CU's method list.
10189
10190    The computation of method physnames is delayed in order to avoid the
10191    (bad) condition that one of the method's formal parameters is of an as yet
10192    incomplete type.  */
10193
10194 static void
10195 compute_delayed_physnames (struct dwarf2_cu *cu)
10196 {
10197   int i;
10198   struct delayed_method_info *mi;
10199
10200   /* Only C++ delays computing physnames.  */
10201   if (VEC_empty (delayed_method_info, cu->method_list))
10202     return;
10203   gdb_assert (cu->language == language_cplus);
10204
10205   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10206     {
10207       const char *physname;
10208       struct fn_fieldlist *fn_flp
10209         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10210       physname = dwarf2_physname (mi->name, mi->die, cu);
10211       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10212         = physname ? physname : "";
10213
10214       /* Since there's no tag to indicate whether a method is a
10215          const/volatile overload, extract that information out of the
10216          demangled name.  */
10217       if (physname != NULL)
10218         {
10219           size_t len = strlen (physname);
10220
10221           while (1)
10222             {
10223               if (physname[len] == ')') /* shortcut */
10224                 break;
10225               else if (check_modifier (physname, len, " const"))
10226                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10227               else if (check_modifier (physname, len, " volatile"))
10228                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10229               else
10230                 break;
10231             }
10232         }
10233     }
10234 }
10235
10236 /* Go objects should be embedded in a DW_TAG_module DIE,
10237    and it's not clear if/how imported objects will appear.
10238    To keep Go support simple until that's worked out,
10239    go back through what we've read and create something usable.
10240    We could do this while processing each DIE, and feels kinda cleaner,
10241    but that way is more invasive.
10242    This is to, for example, allow the user to type "p var" or "b main"
10243    without having to specify the package name, and allow lookups
10244    of module.object to work in contexts that use the expression
10245    parser.  */
10246
10247 static void
10248 fixup_go_packaging (struct dwarf2_cu *cu)
10249 {
10250   char *package_name = NULL;
10251   struct pending *list;
10252   int i;
10253
10254   for (list = global_symbols; list != NULL; list = list->next)
10255     {
10256       for (i = 0; i < list->nsyms; ++i)
10257         {
10258           struct symbol *sym = list->symbol[i];
10259
10260           if (SYMBOL_LANGUAGE (sym) == language_go
10261               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10262             {
10263               char *this_package_name = go_symbol_package_name (sym);
10264
10265               if (this_package_name == NULL)
10266                 continue;
10267               if (package_name == NULL)
10268                 package_name = this_package_name;
10269               else
10270                 {
10271                   struct objfile *objfile
10272                     = cu->per_cu->dwarf2_per_objfile->objfile;
10273                   if (strcmp (package_name, this_package_name) != 0)
10274                     complaint (&symfile_complaints,
10275                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10276                                (symbol_symtab (sym) != NULL
10277                                 ? symtab_to_filename_for_display
10278                                     (symbol_symtab (sym))
10279                                 : objfile_name (objfile)),
10280                                this_package_name, package_name);
10281                   xfree (this_package_name);
10282                 }
10283             }
10284         }
10285     }
10286
10287   if (package_name != NULL)
10288     {
10289       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10290       const char *saved_package_name
10291         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10292                                         package_name,
10293                                         strlen (package_name));
10294       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10295                                      saved_package_name);
10296       struct symbol *sym;
10297
10298       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10299
10300       sym = allocate_symbol (objfile);
10301       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10302       SYMBOL_SET_NAMES (sym, saved_package_name,
10303                         strlen (saved_package_name), 0, objfile);
10304       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10305          e.g., "main" finds the "main" module and not C's main().  */
10306       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10307       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10308       SYMBOL_TYPE (sym) = type;
10309
10310       add_symbol_to_list (sym, &global_symbols);
10311
10312       xfree (package_name);
10313     }
10314 }
10315
10316 /* Return the symtab for PER_CU.  This works properly regardless of
10317    whether we're using the index or psymtabs.  */
10318
10319 static struct compunit_symtab *
10320 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10321 {
10322   return (per_cu->dwarf2_per_objfile->using_index
10323           ? per_cu->v.quick->compunit_symtab
10324           : per_cu->v.psymtab->compunit_symtab);
10325 }
10326
10327 /* A helper function for computing the list of all symbol tables
10328    included by PER_CU.  */
10329
10330 static void
10331 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10332                                 htab_t all_children, htab_t all_type_symtabs,
10333                                 struct dwarf2_per_cu_data *per_cu,
10334                                 struct compunit_symtab *immediate_parent)
10335 {
10336   void **slot;
10337   int ix;
10338   struct compunit_symtab *cust;
10339   struct dwarf2_per_cu_data *iter;
10340
10341   slot = htab_find_slot (all_children, per_cu, INSERT);
10342   if (*slot != NULL)
10343     {
10344       /* This inclusion and its children have been processed.  */
10345       return;
10346     }
10347
10348   *slot = per_cu;
10349   /* Only add a CU if it has a symbol table.  */
10350   cust = get_compunit_symtab (per_cu);
10351   if (cust != NULL)
10352     {
10353       /* If this is a type unit only add its symbol table if we haven't
10354          seen it yet (type unit per_cu's can share symtabs).  */
10355       if (per_cu->is_debug_types)
10356         {
10357           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10358           if (*slot == NULL)
10359             {
10360               *slot = cust;
10361               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10362               if (cust->user == NULL)
10363                 cust->user = immediate_parent;
10364             }
10365         }
10366       else
10367         {
10368           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10369           if (cust->user == NULL)
10370             cust->user = immediate_parent;
10371         }
10372     }
10373
10374   for (ix = 0;
10375        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10376        ++ix)
10377     {
10378       recursively_compute_inclusions (result, all_children,
10379                                       all_type_symtabs, iter, cust);
10380     }
10381 }
10382
10383 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10384    PER_CU.  */
10385
10386 static void
10387 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10388 {
10389   gdb_assert (! per_cu->is_debug_types);
10390
10391   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10392     {
10393       int ix, len;
10394       struct dwarf2_per_cu_data *per_cu_iter;
10395       struct compunit_symtab *compunit_symtab_iter;
10396       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10397       htab_t all_children, all_type_symtabs;
10398       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10399
10400       /* If we don't have a symtab, we can just skip this case.  */
10401       if (cust == NULL)
10402         return;
10403
10404       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10405                                         NULL, xcalloc, xfree);
10406       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10407                                             NULL, xcalloc, xfree);
10408
10409       for (ix = 0;
10410            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10411                         ix, per_cu_iter);
10412            ++ix)
10413         {
10414           recursively_compute_inclusions (&result_symtabs, all_children,
10415                                           all_type_symtabs, per_cu_iter,
10416                                           cust);
10417         }
10418
10419       /* Now we have a transitive closure of all the included symtabs.  */
10420       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10421       cust->includes
10422         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10423                      struct compunit_symtab *, len + 1);
10424       for (ix = 0;
10425            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10426                         compunit_symtab_iter);
10427            ++ix)
10428         cust->includes[ix] = compunit_symtab_iter;
10429       cust->includes[len] = NULL;
10430
10431       VEC_free (compunit_symtab_ptr, result_symtabs);
10432       htab_delete (all_children);
10433       htab_delete (all_type_symtabs);
10434     }
10435 }
10436
10437 /* Compute the 'includes' field for the symtabs of all the CUs we just
10438    read.  */
10439
10440 static void
10441 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10442 {
10443   int ix;
10444   struct dwarf2_per_cu_data *iter;
10445
10446   for (ix = 0;
10447        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10448                     ix, iter);
10449        ++ix)
10450     {
10451       if (! iter->is_debug_types)
10452         compute_compunit_symtab_includes (iter);
10453     }
10454
10455   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10456 }
10457
10458 /* Generate full symbol information for PER_CU, whose DIEs have
10459    already been loaded into memory.  */
10460
10461 static void
10462 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10463                         enum language pretend_language)
10464 {
10465   struct dwarf2_cu *cu = per_cu->cu;
10466   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10467   struct objfile *objfile = dwarf2_per_objfile->objfile;
10468   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10469   CORE_ADDR lowpc, highpc;
10470   struct compunit_symtab *cust;
10471   struct cleanup *delayed_list_cleanup;
10472   CORE_ADDR baseaddr;
10473   struct block *static_block;
10474   CORE_ADDR addr;
10475
10476   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10477
10478   buildsym_init ();
10479   scoped_free_pendings free_pending;
10480   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10481
10482   cu->list_in_scope = &file_symbols;
10483
10484   cu->language = pretend_language;
10485   cu->language_defn = language_def (cu->language);
10486
10487   /* Do line number decoding in read_file_scope () */
10488   process_die (cu->dies, cu);
10489
10490   /* For now fudge the Go package.  */
10491   if (cu->language == language_go)
10492     fixup_go_packaging (cu);
10493
10494   /* Now that we have processed all the DIEs in the CU, all the types 
10495      should be complete, and it should now be safe to compute all of the
10496      physnames.  */
10497   compute_delayed_physnames (cu);
10498   do_cleanups (delayed_list_cleanup);
10499
10500   /* Some compilers don't define a DW_AT_high_pc attribute for the
10501      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10502      it, by scanning the DIE's below the compilation unit.  */
10503   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10504
10505   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10506   static_block = end_symtab_get_static_block (addr, 0, 1);
10507
10508   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10509      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10510      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10511      addrmap to help ensure it has an accurate map of pc values belonging to
10512      this comp unit.  */
10513   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10514
10515   cust = end_symtab_from_static_block (static_block,
10516                                        SECT_OFF_TEXT (objfile), 0);
10517
10518   if (cust != NULL)
10519     {
10520       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10521
10522       /* Set symtab language to language from DW_AT_language.  If the
10523          compilation is from a C file generated by language preprocessors, do
10524          not set the language if it was already deduced by start_subfile.  */
10525       if (!(cu->language == language_c
10526             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10527         COMPUNIT_FILETABS (cust)->language = cu->language;
10528
10529       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10530          produce DW_AT_location with location lists but it can be possibly
10531          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10532          there were bugs in prologue debug info, fixed later in GCC-4.5
10533          by "unwind info for epilogues" patch (which is not directly related).
10534
10535          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10536          needed, it would be wrong due to missing DW_AT_producer there.
10537
10538          Still one can confuse GDB by using non-standard GCC compilation
10539          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10540          */ 
10541       if (cu->has_loclist && gcc_4_minor >= 5)
10542         cust->locations_valid = 1;
10543
10544       if (gcc_4_minor >= 5)
10545         cust->epilogue_unwind_valid = 1;
10546
10547       cust->call_site_htab = cu->call_site_htab;
10548     }
10549
10550   if (dwarf2_per_objfile->using_index)
10551     per_cu->v.quick->compunit_symtab = cust;
10552   else
10553     {
10554       struct partial_symtab *pst = per_cu->v.psymtab;
10555       pst->compunit_symtab = cust;
10556       pst->readin = 1;
10557     }
10558
10559   /* Push it for inclusion processing later.  */
10560   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10561 }
10562
10563 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10564    already been loaded into memory.  */
10565
10566 static void
10567 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10568                         enum language pretend_language)
10569 {
10570   struct dwarf2_cu *cu = per_cu->cu;
10571   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10572   struct objfile *objfile = dwarf2_per_objfile->objfile;
10573   struct compunit_symtab *cust;
10574   struct cleanup *delayed_list_cleanup;
10575   struct signatured_type *sig_type;
10576
10577   gdb_assert (per_cu->is_debug_types);
10578   sig_type = (struct signatured_type *) per_cu;
10579
10580   buildsym_init ();
10581   scoped_free_pendings free_pending;
10582   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10583
10584   cu->list_in_scope = &file_symbols;
10585
10586   cu->language = pretend_language;
10587   cu->language_defn = language_def (cu->language);
10588
10589   /* The symbol tables are set up in read_type_unit_scope.  */
10590   process_die (cu->dies, cu);
10591
10592   /* For now fudge the Go package.  */
10593   if (cu->language == language_go)
10594     fixup_go_packaging (cu);
10595
10596   /* Now that we have processed all the DIEs in the CU, all the types 
10597      should be complete, and it should now be safe to compute all of the
10598      physnames.  */
10599   compute_delayed_physnames (cu);
10600   do_cleanups (delayed_list_cleanup);
10601
10602   /* TUs share symbol tables.
10603      If this is the first TU to use this symtab, complete the construction
10604      of it with end_expandable_symtab.  Otherwise, complete the addition of
10605      this TU's symbols to the existing symtab.  */
10606   if (sig_type->type_unit_group->compunit_symtab == NULL)
10607     {
10608       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10609       sig_type->type_unit_group->compunit_symtab = cust;
10610
10611       if (cust != NULL)
10612         {
10613           /* Set symtab language to language from DW_AT_language.  If the
10614              compilation is from a C file generated by language preprocessors,
10615              do not set the language if it was already deduced by
10616              start_subfile.  */
10617           if (!(cu->language == language_c
10618                 && COMPUNIT_FILETABS (cust)->language != language_c))
10619             COMPUNIT_FILETABS (cust)->language = cu->language;
10620         }
10621     }
10622   else
10623     {
10624       augment_type_symtab ();
10625       cust = sig_type->type_unit_group->compunit_symtab;
10626     }
10627
10628   if (dwarf2_per_objfile->using_index)
10629     per_cu->v.quick->compunit_symtab = cust;
10630   else
10631     {
10632       struct partial_symtab *pst = per_cu->v.psymtab;
10633       pst->compunit_symtab = cust;
10634       pst->readin = 1;
10635     }
10636 }
10637
10638 /* Process an imported unit DIE.  */
10639
10640 static void
10641 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10642 {
10643   struct attribute *attr;
10644
10645   /* For now we don't handle imported units in type units.  */
10646   if (cu->per_cu->is_debug_types)
10647     {
10648       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10649                " supported in type units [in module %s]"),
10650              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10651     }
10652
10653   attr = dwarf2_attr (die, DW_AT_import, cu);
10654   if (attr != NULL)
10655     {
10656       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10657       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10658       dwarf2_per_cu_data *per_cu
10659         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10660                                             cu->per_cu->dwarf2_per_objfile);
10661
10662       /* If necessary, add it to the queue and load its DIEs.  */
10663       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10664         load_full_comp_unit (per_cu, cu->language);
10665
10666       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10667                      per_cu);
10668     }
10669 }
10670
10671 /* RAII object that represents a process_die scope: i.e.,
10672    starts/finishes processing a DIE.  */
10673 class process_die_scope
10674 {
10675 public:
10676   process_die_scope (die_info *die, dwarf2_cu *cu)
10677     : m_die (die), m_cu (cu)
10678   {
10679     /* We should only be processing DIEs not already in process.  */
10680     gdb_assert (!m_die->in_process);
10681     m_die->in_process = true;
10682   }
10683
10684   ~process_die_scope ()
10685   {
10686     m_die->in_process = false;
10687
10688     /* If we're done processing the DIE for the CU that owns the line
10689        header, we don't need the line header anymore.  */
10690     if (m_cu->line_header_die_owner == m_die)
10691       {
10692         delete m_cu->line_header;
10693         m_cu->line_header = NULL;
10694         m_cu->line_header_die_owner = NULL;
10695       }
10696   }
10697
10698 private:
10699   die_info *m_die;
10700   dwarf2_cu *m_cu;
10701 };
10702
10703 /* Process a die and its children.  */
10704
10705 static void
10706 process_die (struct die_info *die, struct dwarf2_cu *cu)
10707 {
10708   process_die_scope scope (die, cu);
10709
10710   switch (die->tag)
10711     {
10712     case DW_TAG_padding:
10713       break;
10714     case DW_TAG_compile_unit:
10715     case DW_TAG_partial_unit:
10716       read_file_scope (die, cu);
10717       break;
10718     case DW_TAG_type_unit:
10719       read_type_unit_scope (die, cu);
10720       break;
10721     case DW_TAG_subprogram:
10722     case DW_TAG_inlined_subroutine:
10723       read_func_scope (die, cu);
10724       break;
10725     case DW_TAG_lexical_block:
10726     case DW_TAG_try_block:
10727     case DW_TAG_catch_block:
10728       read_lexical_block_scope (die, cu);
10729       break;
10730     case DW_TAG_call_site:
10731     case DW_TAG_GNU_call_site:
10732       read_call_site_scope (die, cu);
10733       break;
10734     case DW_TAG_class_type:
10735     case DW_TAG_interface_type:
10736     case DW_TAG_structure_type:
10737     case DW_TAG_union_type:
10738       process_structure_scope (die, cu);
10739       break;
10740     case DW_TAG_enumeration_type:
10741       process_enumeration_scope (die, cu);
10742       break;
10743
10744     /* These dies have a type, but processing them does not create
10745        a symbol or recurse to process the children.  Therefore we can
10746        read them on-demand through read_type_die.  */
10747     case DW_TAG_subroutine_type:
10748     case DW_TAG_set_type:
10749     case DW_TAG_array_type:
10750     case DW_TAG_pointer_type:
10751     case DW_TAG_ptr_to_member_type:
10752     case DW_TAG_reference_type:
10753     case DW_TAG_rvalue_reference_type:
10754     case DW_TAG_string_type:
10755       break;
10756
10757     case DW_TAG_base_type:
10758     case DW_TAG_subrange_type:
10759     case DW_TAG_typedef:
10760       /* Add a typedef symbol for the type definition, if it has a
10761          DW_AT_name.  */
10762       new_symbol (die, read_type_die (die, cu), cu);
10763       break;
10764     case DW_TAG_common_block:
10765       read_common_block (die, cu);
10766       break;
10767     case DW_TAG_common_inclusion:
10768       break;
10769     case DW_TAG_namespace:
10770       cu->processing_has_namespace_info = 1;
10771       read_namespace (die, cu);
10772       break;
10773     case DW_TAG_module:
10774       cu->processing_has_namespace_info = 1;
10775       read_module (die, cu);
10776       break;
10777     case DW_TAG_imported_declaration:
10778       cu->processing_has_namespace_info = 1;
10779       if (read_namespace_alias (die, cu))
10780         break;
10781       /* The declaration is not a global namespace alias: fall through.  */
10782     case DW_TAG_imported_module:
10783       cu->processing_has_namespace_info = 1;
10784       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10785                                  || cu->language != language_fortran))
10786         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10787                    dwarf_tag_name (die->tag));
10788       read_import_statement (die, cu);
10789       break;
10790
10791     case DW_TAG_imported_unit:
10792       process_imported_unit_die (die, cu);
10793       break;
10794
10795     case DW_TAG_variable:
10796       read_variable (die, cu);
10797       break;
10798
10799     default:
10800       new_symbol (die, NULL, cu);
10801       break;
10802     }
10803 }
10804 \f
10805 /* DWARF name computation.  */
10806
10807 /* A helper function for dwarf2_compute_name which determines whether DIE
10808    needs to have the name of the scope prepended to the name listed in the
10809    die.  */
10810
10811 static int
10812 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10813 {
10814   struct attribute *attr;
10815
10816   switch (die->tag)
10817     {
10818     case DW_TAG_namespace:
10819     case DW_TAG_typedef:
10820     case DW_TAG_class_type:
10821     case DW_TAG_interface_type:
10822     case DW_TAG_structure_type:
10823     case DW_TAG_union_type:
10824     case DW_TAG_enumeration_type:
10825     case DW_TAG_enumerator:
10826     case DW_TAG_subprogram:
10827     case DW_TAG_inlined_subroutine:
10828     case DW_TAG_member:
10829     case DW_TAG_imported_declaration:
10830       return 1;
10831
10832     case DW_TAG_variable:
10833     case DW_TAG_constant:
10834       /* We only need to prefix "globally" visible variables.  These include
10835          any variable marked with DW_AT_external or any variable that
10836          lives in a namespace.  [Variables in anonymous namespaces
10837          require prefixing, but they are not DW_AT_external.]  */
10838
10839       if (dwarf2_attr (die, DW_AT_specification, cu))
10840         {
10841           struct dwarf2_cu *spec_cu = cu;
10842
10843           return die_needs_namespace (die_specification (die, &spec_cu),
10844                                       spec_cu);
10845         }
10846
10847       attr = dwarf2_attr (die, DW_AT_external, cu);
10848       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10849           && die->parent->tag != DW_TAG_module)
10850         return 0;
10851       /* A variable in a lexical block of some kind does not need a
10852          namespace, even though in C++ such variables may be external
10853          and have a mangled name.  */
10854       if (die->parent->tag ==  DW_TAG_lexical_block
10855           || die->parent->tag ==  DW_TAG_try_block
10856           || die->parent->tag ==  DW_TAG_catch_block
10857           || die->parent->tag == DW_TAG_subprogram)
10858         return 0;
10859       return 1;
10860
10861     default:
10862       return 0;
10863     }
10864 }
10865
10866 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10867    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10868    defined for the given DIE.  */
10869
10870 static struct attribute *
10871 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10872 {
10873   struct attribute *attr;
10874
10875   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10876   if (attr == NULL)
10877     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10878
10879   return attr;
10880 }
10881
10882 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10883    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10884    defined for the given DIE.  */
10885
10886 static const char *
10887 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10888 {
10889   const char *linkage_name;
10890
10891   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10892   if (linkage_name == NULL)
10893     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10894
10895   return linkage_name;
10896 }
10897
10898 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10899    compute the physname for the object, which include a method's:
10900    - formal parameters (C++),
10901    - receiver type (Go),
10902
10903    The term "physname" is a bit confusing.
10904    For C++, for example, it is the demangled name.
10905    For Go, for example, it's the mangled name.
10906
10907    For Ada, return the DIE's linkage name rather than the fully qualified
10908    name.  PHYSNAME is ignored..
10909
10910    The result is allocated on the objfile_obstack and canonicalized.  */
10911
10912 static const char *
10913 dwarf2_compute_name (const char *name,
10914                      struct die_info *die, struct dwarf2_cu *cu,
10915                      int physname)
10916 {
10917   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10918
10919   if (name == NULL)
10920     name = dwarf2_name (die, cu);
10921
10922   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10923      but otherwise compute it by typename_concat inside GDB.
10924      FIXME: Actually this is not really true, or at least not always true.
10925      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10926      Fortran names because there is no mangling standard.  So new_symbol
10927      will set the demangled name to the result of dwarf2_full_name, and it is
10928      the demangled name that GDB uses if it exists.  */
10929   if (cu->language == language_ada
10930       || (cu->language == language_fortran && physname))
10931     {
10932       /* For Ada unit, we prefer the linkage name over the name, as
10933          the former contains the exported name, which the user expects
10934          to be able to reference.  Ideally, we want the user to be able
10935          to reference this entity using either natural or linkage name,
10936          but we haven't started looking at this enhancement yet.  */
10937       const char *linkage_name = dw2_linkage_name (die, cu);
10938
10939       if (linkage_name != NULL)
10940         return linkage_name;
10941     }
10942
10943   /* These are the only languages we know how to qualify names in.  */
10944   if (name != NULL
10945       && (cu->language == language_cplus
10946           || cu->language == language_fortran || cu->language == language_d
10947           || cu->language == language_rust))
10948     {
10949       if (die_needs_namespace (die, cu))
10950         {
10951           const char *prefix;
10952           const char *canonical_name = NULL;
10953
10954           string_file buf;
10955
10956           prefix = determine_prefix (die, cu);
10957           if (*prefix != '\0')
10958             {
10959               char *prefixed_name = typename_concat (NULL, prefix, name,
10960                                                      physname, cu);
10961
10962               buf.puts (prefixed_name);
10963               xfree (prefixed_name);
10964             }
10965           else
10966             buf.puts (name);
10967
10968           /* Template parameters may be specified in the DIE's DW_AT_name, or
10969              as children with DW_TAG_template_type_param or
10970              DW_TAG_value_type_param.  If the latter, add them to the name
10971              here.  If the name already has template parameters, then
10972              skip this step; some versions of GCC emit both, and
10973              it is more efficient to use the pre-computed name.
10974
10975              Something to keep in mind about this process: it is very
10976              unlikely, or in some cases downright impossible, to produce
10977              something that will match the mangled name of a function.
10978              If the definition of the function has the same debug info,
10979              we should be able to match up with it anyway.  But fallbacks
10980              using the minimal symbol, for instance to find a method
10981              implemented in a stripped copy of libstdc++, will not work.
10982              If we do not have debug info for the definition, we will have to
10983              match them up some other way.
10984
10985              When we do name matching there is a related problem with function
10986              templates; two instantiated function templates are allowed to
10987              differ only by their return types, which we do not add here.  */
10988
10989           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10990             {
10991               struct attribute *attr;
10992               struct die_info *child;
10993               int first = 1;
10994
10995               die->building_fullname = 1;
10996
10997               for (child = die->child; child != NULL; child = child->sibling)
10998                 {
10999                   struct type *type;
11000                   LONGEST value;
11001                   const gdb_byte *bytes;
11002                   struct dwarf2_locexpr_baton *baton;
11003                   struct value *v;
11004
11005                   if (child->tag != DW_TAG_template_type_param
11006                       && child->tag != DW_TAG_template_value_param)
11007                     continue;
11008
11009                   if (first)
11010                     {
11011                       buf.puts ("<");
11012                       first = 0;
11013                     }
11014                   else
11015                     buf.puts (", ");
11016
11017                   attr = dwarf2_attr (child, DW_AT_type, cu);
11018                   if (attr == NULL)
11019                     {
11020                       complaint (&symfile_complaints,
11021                                  _("template parameter missing DW_AT_type"));
11022                       buf.puts ("UNKNOWN_TYPE");
11023                       continue;
11024                     }
11025                   type = die_type (child, cu);
11026
11027                   if (child->tag == DW_TAG_template_type_param)
11028                     {
11029                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11030                       continue;
11031                     }
11032
11033                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11034                   if (attr == NULL)
11035                     {
11036                       complaint (&symfile_complaints,
11037                                  _("template parameter missing "
11038                                    "DW_AT_const_value"));
11039                       buf.puts ("UNKNOWN_VALUE");
11040                       continue;
11041                     }
11042
11043                   dwarf2_const_value_attr (attr, type, name,
11044                                            &cu->comp_unit_obstack, cu,
11045                                            &value, &bytes, &baton);
11046
11047                   if (TYPE_NOSIGN (type))
11048                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11049                        changed, this can use value_print instead.  */
11050                     c_printchar (value, type, &buf);
11051                   else
11052                     {
11053                       struct value_print_options opts;
11054
11055                       if (baton != NULL)
11056                         v = dwarf2_evaluate_loc_desc (type, NULL,
11057                                                       baton->data,
11058                                                       baton->size,
11059                                                       baton->per_cu);
11060                       else if (bytes != NULL)
11061                         {
11062                           v = allocate_value (type);
11063                           memcpy (value_contents_writeable (v), bytes,
11064                                   TYPE_LENGTH (type));
11065                         }
11066                       else
11067                         v = value_from_longest (type, value);
11068
11069                       /* Specify decimal so that we do not depend on
11070                          the radix.  */
11071                       get_formatted_print_options (&opts, 'd');
11072                       opts.raw = 1;
11073                       value_print (v, &buf, &opts);
11074                       release_value (v);
11075                       value_free (v);
11076                     }
11077                 }
11078
11079               die->building_fullname = 0;
11080
11081               if (!first)
11082                 {
11083                   /* Close the argument list, with a space if necessary
11084                      (nested templates).  */
11085                   if (!buf.empty () && buf.string ().back () == '>')
11086                     buf.puts (" >");
11087                   else
11088                     buf.puts (">");
11089                 }
11090             }
11091
11092           /* For C++ methods, append formal parameter type
11093              information, if PHYSNAME.  */
11094
11095           if (physname && die->tag == DW_TAG_subprogram
11096               && cu->language == language_cplus)
11097             {
11098               struct type *type = read_type_die (die, cu);
11099
11100               c_type_print_args (type, &buf, 1, cu->language,
11101                                  &type_print_raw_options);
11102
11103               if (cu->language == language_cplus)
11104                 {
11105                   /* Assume that an artificial first parameter is
11106                      "this", but do not crash if it is not.  RealView
11107                      marks unnamed (and thus unused) parameters as
11108                      artificial; there is no way to differentiate
11109                      the two cases.  */
11110                   if (TYPE_NFIELDS (type) > 0
11111                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11112                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11113                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11114                                                                         0))))
11115                     buf.puts (" const");
11116                 }
11117             }
11118
11119           const std::string &intermediate_name = buf.string ();
11120
11121           if (cu->language == language_cplus)
11122             canonical_name
11123               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11124                                           &objfile->per_bfd->storage_obstack);
11125
11126           /* If we only computed INTERMEDIATE_NAME, or if
11127              INTERMEDIATE_NAME is already canonical, then we need to
11128              copy it to the appropriate obstack.  */
11129           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11130             name = ((const char *)
11131                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11132                                    intermediate_name.c_str (),
11133                                    intermediate_name.length ()));
11134           else
11135             name = canonical_name;
11136         }
11137     }
11138
11139   return name;
11140 }
11141
11142 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11143    If scope qualifiers are appropriate they will be added.  The result
11144    will be allocated on the storage_obstack, or NULL if the DIE does
11145    not have a name.  NAME may either be from a previous call to
11146    dwarf2_name or NULL.
11147
11148    The output string will be canonicalized (if C++).  */
11149
11150 static const char *
11151 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11152 {
11153   return dwarf2_compute_name (name, die, cu, 0);
11154 }
11155
11156 /* Construct a physname for the given DIE in CU.  NAME may either be
11157    from a previous call to dwarf2_name or NULL.  The result will be
11158    allocated on the objfile_objstack or NULL if the DIE does not have a
11159    name.
11160
11161    The output string will be canonicalized (if C++).  */
11162
11163 static const char *
11164 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11165 {
11166   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11167   const char *retval, *mangled = NULL, *canon = NULL;
11168   int need_copy = 1;
11169
11170   /* In this case dwarf2_compute_name is just a shortcut not building anything
11171      on its own.  */
11172   if (!die_needs_namespace (die, cu))
11173     return dwarf2_compute_name (name, die, cu, 1);
11174
11175   mangled = dw2_linkage_name (die, cu);
11176
11177   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11178      See https://github.com/rust-lang/rust/issues/32925.  */
11179   if (cu->language == language_rust && mangled != NULL
11180       && strchr (mangled, '{') != NULL)
11181     mangled = NULL;
11182
11183   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11184      has computed.  */
11185   gdb::unique_xmalloc_ptr<char> demangled;
11186   if (mangled != NULL)
11187     {
11188       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11189          type.  It is easier for GDB users to search for such functions as
11190          `name(params)' than `long name(params)'.  In such case the minimal
11191          symbol names do not match the full symbol names but for template
11192          functions there is never a need to look up their definition from their
11193          declaration so the only disadvantage remains the minimal symbol
11194          variant `long name(params)' does not have the proper inferior type.
11195          */
11196
11197       if (cu->language == language_go)
11198         {
11199           /* This is a lie, but we already lie to the caller new_symbol.
11200              new_symbol assumes we return the mangled name.
11201              This just undoes that lie until things are cleaned up.  */
11202         }
11203       else
11204         {
11205           demangled.reset (gdb_demangle (mangled,
11206                                          (DMGL_PARAMS | DMGL_ANSI
11207                                           | DMGL_RET_DROP)));
11208         }
11209       if (demangled)
11210         canon = demangled.get ();
11211       else
11212         {
11213           canon = mangled;
11214           need_copy = 0;
11215         }
11216     }
11217
11218   if (canon == NULL || check_physname)
11219     {
11220       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11221
11222       if (canon != NULL && strcmp (physname, canon) != 0)
11223         {
11224           /* It may not mean a bug in GDB.  The compiler could also
11225              compute DW_AT_linkage_name incorrectly.  But in such case
11226              GDB would need to be bug-to-bug compatible.  */
11227
11228           complaint (&symfile_complaints,
11229                      _("Computed physname <%s> does not match demangled <%s> "
11230                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11231                      physname, canon, mangled, to_underlying (die->sect_off),
11232                      objfile_name (objfile));
11233
11234           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11235              is available here - over computed PHYSNAME.  It is safer
11236              against both buggy GDB and buggy compilers.  */
11237
11238           retval = canon;
11239         }
11240       else
11241         {
11242           retval = physname;
11243           need_copy = 0;
11244         }
11245     }
11246   else
11247     retval = canon;
11248
11249   if (need_copy)
11250     retval = ((const char *)
11251               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11252                              retval, strlen (retval)));
11253
11254   return retval;
11255 }
11256
11257 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11258    a new symbol for it.
11259
11260    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11261
11262 static int
11263 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11264 {
11265   struct attribute *attr;
11266
11267   /* If the die does not have a name, this is not a namespace
11268      alias.  */
11269   attr = dwarf2_attr (die, DW_AT_name, cu);
11270   if (attr != NULL)
11271     {
11272       int num;
11273       struct die_info *d = die;
11274       struct dwarf2_cu *imported_cu = cu;
11275
11276       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11277          keep inspecting DIEs until we hit the underlying import.  */
11278 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11279       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11280         {
11281           attr = dwarf2_attr (d, DW_AT_import, cu);
11282           if (attr == NULL)
11283             break;
11284
11285           d = follow_die_ref (d, attr, &imported_cu);
11286           if (d->tag != DW_TAG_imported_declaration)
11287             break;
11288         }
11289
11290       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11291         {
11292           complaint (&symfile_complaints,
11293                      _("DIE at 0x%x has too many recursively imported "
11294                        "declarations"), to_underlying (d->sect_off));
11295           return 0;
11296         }
11297
11298       if (attr != NULL)
11299         {
11300           struct type *type;
11301           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11302
11303           type = get_die_type_at_offset (sect_off, cu->per_cu);
11304           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11305             {
11306               /* This declaration is a global namespace alias.  Add
11307                  a symbol for it whose type is the aliased namespace.  */
11308               new_symbol (die, type, cu);
11309               return 1;
11310             }
11311         }
11312     }
11313
11314   return 0;
11315 }
11316
11317 /* Return the using directives repository (global or local?) to use in the
11318    current context for LANGUAGE.
11319
11320    For Ada, imported declarations can materialize renamings, which *may* be
11321    global.  However it is impossible (for now?) in DWARF to distinguish
11322    "external" imported declarations and "static" ones.  As all imported
11323    declarations seem to be static in all other languages, make them all CU-wide
11324    global only in Ada.  */
11325
11326 static struct using_direct **
11327 using_directives (enum language language)
11328 {
11329   if (language == language_ada && context_stack_depth == 0)
11330     return &global_using_directives;
11331   else
11332     return &local_using_directives;
11333 }
11334
11335 /* Read the import statement specified by the given die and record it.  */
11336
11337 static void
11338 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11339 {
11340   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11341   struct attribute *import_attr;
11342   struct die_info *imported_die, *child_die;
11343   struct dwarf2_cu *imported_cu;
11344   const char *imported_name;
11345   const char *imported_name_prefix;
11346   const char *canonical_name;
11347   const char *import_alias;
11348   const char *imported_declaration = NULL;
11349   const char *import_prefix;
11350   std::vector<const char *> excludes;
11351
11352   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11353   if (import_attr == NULL)
11354     {
11355       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11356                  dwarf_tag_name (die->tag));
11357       return;
11358     }
11359
11360   imported_cu = cu;
11361   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11362   imported_name = dwarf2_name (imported_die, imported_cu);
11363   if (imported_name == NULL)
11364     {
11365       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11366
11367         The import in the following code:
11368         namespace A
11369           {
11370             typedef int B;
11371           }
11372
11373         int main ()
11374           {
11375             using A::B;
11376             B b;
11377             return b;
11378           }
11379
11380         ...
11381          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11382             <52>   DW_AT_decl_file   : 1
11383             <53>   DW_AT_decl_line   : 6
11384             <54>   DW_AT_import      : <0x75>
11385          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11386             <59>   DW_AT_name        : B
11387             <5b>   DW_AT_decl_file   : 1
11388             <5c>   DW_AT_decl_line   : 2
11389             <5d>   DW_AT_type        : <0x6e>
11390         ...
11391          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11392             <76>   DW_AT_byte_size   : 4
11393             <77>   DW_AT_encoding    : 5        (signed)
11394
11395         imports the wrong die ( 0x75 instead of 0x58 ).
11396         This case will be ignored until the gcc bug is fixed.  */
11397       return;
11398     }
11399
11400   /* Figure out the local name after import.  */
11401   import_alias = dwarf2_name (die, cu);
11402
11403   /* Figure out where the statement is being imported to.  */
11404   import_prefix = determine_prefix (die, cu);
11405
11406   /* Figure out what the scope of the imported die is and prepend it
11407      to the name of the imported die.  */
11408   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11409
11410   if (imported_die->tag != DW_TAG_namespace
11411       && imported_die->tag != DW_TAG_module)
11412     {
11413       imported_declaration = imported_name;
11414       canonical_name = imported_name_prefix;
11415     }
11416   else if (strlen (imported_name_prefix) > 0)
11417     canonical_name = obconcat (&objfile->objfile_obstack,
11418                                imported_name_prefix,
11419                                (cu->language == language_d ? "." : "::"),
11420                                imported_name, (char *) NULL);
11421   else
11422     canonical_name = imported_name;
11423
11424   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11425     for (child_die = die->child; child_die && child_die->tag;
11426          child_die = sibling_die (child_die))
11427       {
11428         /* DWARF-4: A Fortran use statement with a “rename list” may be
11429            represented by an imported module entry with an import attribute
11430            referring to the module and owned entries corresponding to those
11431            entities that are renamed as part of being imported.  */
11432
11433         if (child_die->tag != DW_TAG_imported_declaration)
11434           {
11435             complaint (&symfile_complaints,
11436                        _("child DW_TAG_imported_declaration expected "
11437                          "- DIE at 0x%x [in module %s]"),
11438                        to_underlying (child_die->sect_off), objfile_name (objfile));
11439             continue;
11440           }
11441
11442         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11443         if (import_attr == NULL)
11444           {
11445             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11446                        dwarf_tag_name (child_die->tag));
11447             continue;
11448           }
11449
11450         imported_cu = cu;
11451         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11452                                               &imported_cu);
11453         imported_name = dwarf2_name (imported_die, imported_cu);
11454         if (imported_name == NULL)
11455           {
11456             complaint (&symfile_complaints,
11457                        _("child DW_TAG_imported_declaration has unknown "
11458                          "imported name - DIE at 0x%x [in module %s]"),
11459                        to_underlying (child_die->sect_off), objfile_name (objfile));
11460             continue;
11461           }
11462
11463         excludes.push_back (imported_name);
11464
11465         process_die (child_die, cu);
11466       }
11467
11468   add_using_directive (using_directives (cu->language),
11469                        import_prefix,
11470                        canonical_name,
11471                        import_alias,
11472                        imported_declaration,
11473                        excludes,
11474                        0,
11475                        &objfile->objfile_obstack);
11476 }
11477
11478 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11479    types, but gives them a size of zero.  Starting with version 14,
11480    ICC is compatible with GCC.  */
11481
11482 static int
11483 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11484 {
11485   if (!cu->checked_producer)
11486     check_producer (cu);
11487
11488   return cu->producer_is_icc_lt_14;
11489 }
11490
11491 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11492    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11493    this, it was first present in GCC release 4.3.0.  */
11494
11495 static int
11496 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11497 {
11498   if (!cu->checked_producer)
11499     check_producer (cu);
11500
11501   return cu->producer_is_gcc_lt_4_3;
11502 }
11503
11504 static file_and_directory
11505 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11506 {
11507   file_and_directory res;
11508
11509   /* Find the filename.  Do not use dwarf2_name here, since the filename
11510      is not a source language identifier.  */
11511   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11512   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11513
11514   if (res.comp_dir == NULL
11515       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11516       && IS_ABSOLUTE_PATH (res.name))
11517     {
11518       res.comp_dir_storage = ldirname (res.name);
11519       if (!res.comp_dir_storage.empty ())
11520         res.comp_dir = res.comp_dir_storage.c_str ();
11521     }
11522   if (res.comp_dir != NULL)
11523     {
11524       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11525          directory, get rid of it.  */
11526       const char *cp = strchr (res.comp_dir, ':');
11527
11528       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11529         res.comp_dir = cp + 1;
11530     }
11531
11532   if (res.name == NULL)
11533     res.name = "<unknown>";
11534
11535   return res;
11536 }
11537
11538 /* Handle DW_AT_stmt_list for a compilation unit.
11539    DIE is the DW_TAG_compile_unit die for CU.
11540    COMP_DIR is the compilation directory.  LOWPC is passed to
11541    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11542
11543 static void
11544 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11545                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11546 {
11547   struct dwarf2_per_objfile *dwarf2_per_objfile
11548     = cu->per_cu->dwarf2_per_objfile;
11549   struct objfile *objfile = dwarf2_per_objfile->objfile;
11550   struct attribute *attr;
11551   struct line_header line_header_local;
11552   hashval_t line_header_local_hash;
11553   void **slot;
11554   int decode_mapping;
11555
11556   gdb_assert (! cu->per_cu->is_debug_types);
11557
11558   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11559   if (attr == NULL)
11560     return;
11561
11562   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11563
11564   /* The line header hash table is only created if needed (it exists to
11565      prevent redundant reading of the line table for partial_units).
11566      If we're given a partial_unit, we'll need it.  If we're given a
11567      compile_unit, then use the line header hash table if it's already
11568      created, but don't create one just yet.  */
11569
11570   if (dwarf2_per_objfile->line_header_hash == NULL
11571       && die->tag == DW_TAG_partial_unit)
11572     {
11573       dwarf2_per_objfile->line_header_hash
11574         = htab_create_alloc_ex (127, line_header_hash_voidp,
11575                                 line_header_eq_voidp,
11576                                 free_line_header_voidp,
11577                                 &objfile->objfile_obstack,
11578                                 hashtab_obstack_allocate,
11579                                 dummy_obstack_deallocate);
11580     }
11581
11582   line_header_local.sect_off = line_offset;
11583   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11584   line_header_local_hash = line_header_hash (&line_header_local);
11585   if (dwarf2_per_objfile->line_header_hash != NULL)
11586     {
11587       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11588                                        &line_header_local,
11589                                        line_header_local_hash, NO_INSERT);
11590
11591       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11592          is not present in *SLOT (since if there is something in *SLOT then
11593          it will be for a partial_unit).  */
11594       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11595         {
11596           gdb_assert (*slot != NULL);
11597           cu->line_header = (struct line_header *) *slot;
11598           return;
11599         }
11600     }
11601
11602   /* dwarf_decode_line_header does not yet provide sufficient information.
11603      We always have to call also dwarf_decode_lines for it.  */
11604   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11605   if (lh == NULL)
11606     return;
11607
11608   cu->line_header = lh.release ();
11609   cu->line_header_die_owner = die;
11610
11611   if (dwarf2_per_objfile->line_header_hash == NULL)
11612     slot = NULL;
11613   else
11614     {
11615       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11616                                        &line_header_local,
11617                                        line_header_local_hash, INSERT);
11618       gdb_assert (slot != NULL);
11619     }
11620   if (slot != NULL && *slot == NULL)
11621     {
11622       /* This newly decoded line number information unit will be owned
11623          by line_header_hash hash table.  */
11624       *slot = cu->line_header;
11625       cu->line_header_die_owner = NULL;
11626     }
11627   else
11628     {
11629       /* We cannot free any current entry in (*slot) as that struct line_header
11630          may be already used by multiple CUs.  Create only temporary decoded
11631          line_header for this CU - it may happen at most once for each line
11632          number information unit.  And if we're not using line_header_hash
11633          then this is what we want as well.  */
11634       gdb_assert (die->tag != DW_TAG_partial_unit);
11635     }
11636   decode_mapping = (die->tag != DW_TAG_partial_unit);
11637   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11638                       decode_mapping);
11639
11640 }
11641
11642 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11643
11644 static void
11645 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11646 {
11647   struct dwarf2_per_objfile *dwarf2_per_objfile
11648     = cu->per_cu->dwarf2_per_objfile;
11649   struct objfile *objfile = dwarf2_per_objfile->objfile;
11650   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11651   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11652   CORE_ADDR highpc = ((CORE_ADDR) 0);
11653   struct attribute *attr;
11654   struct die_info *child_die;
11655   CORE_ADDR baseaddr;
11656
11657   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11658
11659   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11660
11661   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11662      from finish_block.  */
11663   if (lowpc == ((CORE_ADDR) -1))
11664     lowpc = highpc;
11665   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11666
11667   file_and_directory fnd = find_file_and_directory (die, cu);
11668
11669   prepare_one_comp_unit (cu, die, cu->language);
11670
11671   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11672      standardised yet.  As a workaround for the language detection we fall
11673      back to the DW_AT_producer string.  */
11674   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11675     cu->language = language_opencl;
11676
11677   /* Similar hack for Go.  */
11678   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11679     set_cu_language (DW_LANG_Go, cu);
11680
11681   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11682
11683   /* Decode line number information if present.  We do this before
11684      processing child DIEs, so that the line header table is available
11685      for DW_AT_decl_file.  */
11686   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11687
11688   /* Process all dies in compilation unit.  */
11689   if (die->child != NULL)
11690     {
11691       child_die = die->child;
11692       while (child_die && child_die->tag)
11693         {
11694           process_die (child_die, cu);
11695           child_die = sibling_die (child_die);
11696         }
11697     }
11698
11699   /* Decode macro information, if present.  Dwarf 2 macro information
11700      refers to information in the line number info statement program
11701      header, so we can only read it if we've read the header
11702      successfully.  */
11703   attr = dwarf2_attr (die, DW_AT_macros, cu);
11704   if (attr == NULL)
11705     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11706   if (attr && cu->line_header)
11707     {
11708       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11709         complaint (&symfile_complaints,
11710                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11711
11712       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11713     }
11714   else
11715     {
11716       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11717       if (attr && cu->line_header)
11718         {
11719           unsigned int macro_offset = DW_UNSND (attr);
11720
11721           dwarf_decode_macros (cu, macro_offset, 0);
11722         }
11723     }
11724 }
11725
11726 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11727    Create the set of symtabs used by this TU, or if this TU is sharing
11728    symtabs with another TU and the symtabs have already been created
11729    then restore those symtabs in the line header.
11730    We don't need the pc/line-number mapping for type units.  */
11731
11732 static void
11733 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11734 {
11735   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11736   struct type_unit_group *tu_group;
11737   int first_time;
11738   struct attribute *attr;
11739   unsigned int i;
11740   struct signatured_type *sig_type;
11741
11742   gdb_assert (per_cu->is_debug_types);
11743   sig_type = (struct signatured_type *) per_cu;
11744
11745   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11746
11747   /* If we're using .gdb_index (includes -readnow) then
11748      per_cu->type_unit_group may not have been set up yet.  */
11749   if (sig_type->type_unit_group == NULL)
11750     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11751   tu_group = sig_type->type_unit_group;
11752
11753   /* If we've already processed this stmt_list there's no real need to
11754      do it again, we could fake it and just recreate the part we need
11755      (file name,index -> symtab mapping).  If data shows this optimization
11756      is useful we can do it then.  */
11757   first_time = tu_group->compunit_symtab == NULL;
11758
11759   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11760      debug info.  */
11761   line_header_up lh;
11762   if (attr != NULL)
11763     {
11764       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11765       lh = dwarf_decode_line_header (line_offset, cu);
11766     }
11767   if (lh == NULL)
11768     {
11769       if (first_time)
11770         dwarf2_start_symtab (cu, "", NULL, 0);
11771       else
11772         {
11773           gdb_assert (tu_group->symtabs == NULL);
11774           restart_symtab (tu_group->compunit_symtab, "", 0);
11775         }
11776       return;
11777     }
11778
11779   cu->line_header = lh.release ();
11780   cu->line_header_die_owner = die;
11781
11782   if (first_time)
11783     {
11784       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11785
11786       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11787          still initializing it, and our caller (a few levels up)
11788          process_full_type_unit still needs to know if this is the first
11789          time.  */
11790
11791       tu_group->num_symtabs = cu->line_header->file_names.size ();
11792       tu_group->symtabs = XNEWVEC (struct symtab *,
11793                                    cu->line_header->file_names.size ());
11794
11795       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11796         {
11797           file_entry &fe = cu->line_header->file_names[i];
11798
11799           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11800
11801           if (current_subfile->symtab == NULL)
11802             {
11803               /* NOTE: start_subfile will recognize when it's been
11804                  passed a file it has already seen.  So we can't
11805                  assume there's a simple mapping from
11806                  cu->line_header->file_names to subfiles, plus
11807                  cu->line_header->file_names may contain dups.  */
11808               current_subfile->symtab
11809                 = allocate_symtab (cust, current_subfile->name);
11810             }
11811
11812           fe.symtab = current_subfile->symtab;
11813           tu_group->symtabs[i] = fe.symtab;
11814         }
11815     }
11816   else
11817     {
11818       restart_symtab (tu_group->compunit_symtab, "", 0);
11819
11820       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11821         {
11822           file_entry &fe = cu->line_header->file_names[i];
11823
11824           fe.symtab = tu_group->symtabs[i];
11825         }
11826     }
11827
11828   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11829      so they don't have a "real" (so to speak) symtab anyway.
11830      There is later code that will assign the main symtab to all symbols
11831      that don't have one.  We need to handle the case of a symbol with a
11832      missing symtab (DW_AT_decl_file) anyway.  */
11833 }
11834
11835 /* Process DW_TAG_type_unit.
11836    For TUs we want to skip the first top level sibling if it's not the
11837    actual type being defined by this TU.  In this case the first top
11838    level sibling is there to provide context only.  */
11839
11840 static void
11841 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11842 {
11843   struct die_info *child_die;
11844
11845   prepare_one_comp_unit (cu, die, language_minimal);
11846
11847   /* Initialize (or reinitialize) the machinery for building symtabs.
11848      We do this before processing child DIEs, so that the line header table
11849      is available for DW_AT_decl_file.  */
11850   setup_type_unit_groups (die, cu);
11851
11852   if (die->child != NULL)
11853     {
11854       child_die = die->child;
11855       while (child_die && child_die->tag)
11856         {
11857           process_die (child_die, cu);
11858           child_die = sibling_die (child_die);
11859         }
11860     }
11861 }
11862 \f
11863 /* DWO/DWP files.
11864
11865    http://gcc.gnu.org/wiki/DebugFission
11866    http://gcc.gnu.org/wiki/DebugFissionDWP
11867
11868    To simplify handling of both DWO files ("object" files with the DWARF info)
11869    and DWP files (a file with the DWOs packaged up into one file), we treat
11870    DWP files as having a collection of virtual DWO files.  */
11871
11872 static hashval_t
11873 hash_dwo_file (const void *item)
11874 {
11875   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11876   hashval_t hash;
11877
11878   hash = htab_hash_string (dwo_file->dwo_name);
11879   if (dwo_file->comp_dir != NULL)
11880     hash += htab_hash_string (dwo_file->comp_dir);
11881   return hash;
11882 }
11883
11884 static int
11885 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11886 {
11887   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11888   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11889
11890   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11891     return 0;
11892   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11893     return lhs->comp_dir == rhs->comp_dir;
11894   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11895 }
11896
11897 /* Allocate a hash table for DWO files.  */
11898
11899 static htab_t
11900 allocate_dwo_file_hash_table (struct objfile *objfile)
11901 {
11902   return htab_create_alloc_ex (41,
11903                                hash_dwo_file,
11904                                eq_dwo_file,
11905                                NULL,
11906                                &objfile->objfile_obstack,
11907                                hashtab_obstack_allocate,
11908                                dummy_obstack_deallocate);
11909 }
11910
11911 /* Lookup DWO file DWO_NAME.  */
11912
11913 static void **
11914 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11915                       const char *dwo_name,
11916                       const char *comp_dir)
11917 {
11918   struct dwo_file find_entry;
11919   void **slot;
11920
11921   if (dwarf2_per_objfile->dwo_files == NULL)
11922     dwarf2_per_objfile->dwo_files
11923       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11924
11925   memset (&find_entry, 0, sizeof (find_entry));
11926   find_entry.dwo_name = dwo_name;
11927   find_entry.comp_dir = comp_dir;
11928   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11929
11930   return slot;
11931 }
11932
11933 static hashval_t
11934 hash_dwo_unit (const void *item)
11935 {
11936   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11937
11938   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11939   return dwo_unit->signature;
11940 }
11941
11942 static int
11943 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11944 {
11945   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11946   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11947
11948   /* The signature is assumed to be unique within the DWO file.
11949      So while object file CU dwo_id's always have the value zero,
11950      that's OK, assuming each object file DWO file has only one CU,
11951      and that's the rule for now.  */
11952   return lhs->signature == rhs->signature;
11953 }
11954
11955 /* Allocate a hash table for DWO CUs,TUs.
11956    There is one of these tables for each of CUs,TUs for each DWO file.  */
11957
11958 static htab_t
11959 allocate_dwo_unit_table (struct objfile *objfile)
11960 {
11961   /* Start out with a pretty small number.
11962      Generally DWO files contain only one CU and maybe some TUs.  */
11963   return htab_create_alloc_ex (3,
11964                                hash_dwo_unit,
11965                                eq_dwo_unit,
11966                                NULL,
11967                                &objfile->objfile_obstack,
11968                                hashtab_obstack_allocate,
11969                                dummy_obstack_deallocate);
11970 }
11971
11972 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11973
11974 struct create_dwo_cu_data
11975 {
11976   struct dwo_file *dwo_file;
11977   struct dwo_unit dwo_unit;
11978 };
11979
11980 /* die_reader_func for create_dwo_cu.  */
11981
11982 static void
11983 create_dwo_cu_reader (const struct die_reader_specs *reader,
11984                       const gdb_byte *info_ptr,
11985                       struct die_info *comp_unit_die,
11986                       int has_children,
11987                       void *datap)
11988 {
11989   struct dwarf2_cu *cu = reader->cu;
11990   sect_offset sect_off = cu->per_cu->sect_off;
11991   struct dwarf2_section_info *section = cu->per_cu->section;
11992   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11993   struct dwo_file *dwo_file = data->dwo_file;
11994   struct dwo_unit *dwo_unit = &data->dwo_unit;
11995   struct attribute *attr;
11996
11997   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11998   if (attr == NULL)
11999     {
12000       complaint (&symfile_complaints,
12001                  _("Dwarf Error: debug entry at offset 0x%x is missing"
12002                    " its dwo_id [in module %s]"),
12003                  to_underlying (sect_off), dwo_file->dwo_name);
12004       return;
12005     }
12006
12007   dwo_unit->dwo_file = dwo_file;
12008   dwo_unit->signature = DW_UNSND (attr);
12009   dwo_unit->section = section;
12010   dwo_unit->sect_off = sect_off;
12011   dwo_unit->length = cu->per_cu->length;
12012
12013   if (dwarf_read_debug)
12014     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
12015                         to_underlying (sect_off),
12016                         hex_string (dwo_unit->signature));
12017 }
12018
12019 /* Create the dwo_units for the CUs in a DWO_FILE.
12020    Note: This function processes DWO files only, not DWP files.  */
12021
12022 static void
12023 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12024                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12025                        htab_t &cus_htab)
12026 {
12027   struct objfile *objfile = dwarf2_per_objfile->objfile;
12028   const gdb_byte *info_ptr, *end_ptr;
12029
12030   dwarf2_read_section (objfile, &section);
12031   info_ptr = section.buffer;
12032
12033   if (info_ptr == NULL)
12034     return;
12035
12036   if (dwarf_read_debug)
12037     {
12038       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12039                           get_section_name (&section),
12040                           get_section_file_name (&section));
12041     }
12042
12043   end_ptr = info_ptr + section.size;
12044   while (info_ptr < end_ptr)
12045     {
12046       struct dwarf2_per_cu_data per_cu;
12047       struct create_dwo_cu_data create_dwo_cu_data;
12048       struct dwo_unit *dwo_unit;
12049       void **slot;
12050       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12051
12052       memset (&create_dwo_cu_data.dwo_unit, 0,
12053               sizeof (create_dwo_cu_data.dwo_unit));
12054       memset (&per_cu, 0, sizeof (per_cu));
12055       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12056       per_cu.is_debug_types = 0;
12057       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12058       per_cu.section = &section;
12059       create_dwo_cu_data.dwo_file = &dwo_file;
12060
12061       init_cutu_and_read_dies_no_follow (
12062           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12063       info_ptr += per_cu.length;
12064
12065       // If the unit could not be parsed, skip it.
12066       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12067         continue;
12068
12069       if (cus_htab == NULL)
12070         cus_htab = allocate_dwo_unit_table (objfile);
12071
12072       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12073       *dwo_unit = create_dwo_cu_data.dwo_unit;
12074       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12075       gdb_assert (slot != NULL);
12076       if (*slot != NULL)
12077         {
12078           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12079           sect_offset dup_sect_off = dup_cu->sect_off;
12080
12081           complaint (&symfile_complaints,
12082                      _("debug cu entry at offset 0x%x is duplicate to"
12083                        " the entry at offset 0x%x, signature %s"),
12084                      to_underlying (sect_off), to_underlying (dup_sect_off),
12085                      hex_string (dwo_unit->signature));
12086         }
12087       *slot = (void *)dwo_unit;
12088     }
12089 }
12090
12091 /* DWP file .debug_{cu,tu}_index section format:
12092    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12093
12094    DWP Version 1:
12095
12096    Both index sections have the same format, and serve to map a 64-bit
12097    signature to a set of section numbers.  Each section begins with a header,
12098    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12099    indexes, and a pool of 32-bit section numbers.  The index sections will be
12100    aligned at 8-byte boundaries in the file.
12101
12102    The index section header consists of:
12103
12104     V, 32 bit version number
12105     -, 32 bits unused
12106     N, 32 bit number of compilation units or type units in the index
12107     M, 32 bit number of slots in the hash table
12108
12109    Numbers are recorded using the byte order of the application binary.
12110
12111    The hash table begins at offset 16 in the section, and consists of an array
12112    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12113    order of the application binary).  Unused slots in the hash table are 0.
12114    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12115
12116    The parallel table begins immediately after the hash table
12117    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12118    array of 32-bit indexes (using the byte order of the application binary),
12119    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12120    table contains a 32-bit index into the pool of section numbers.  For unused
12121    hash table slots, the corresponding entry in the parallel table will be 0.
12122
12123    The pool of section numbers begins immediately following the hash table
12124    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12125    section numbers consists of an array of 32-bit words (using the byte order
12126    of the application binary).  Each item in the array is indexed starting
12127    from 0.  The hash table entry provides the index of the first section
12128    number in the set.  Additional section numbers in the set follow, and the
12129    set is terminated by a 0 entry (section number 0 is not used in ELF).
12130
12131    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12132    section must be the first entry in the set, and the .debug_abbrev.dwo must
12133    be the second entry. Other members of the set may follow in any order.
12134
12135    ---
12136
12137    DWP Version 2:
12138
12139    DWP Version 2 combines all the .debug_info, etc. sections into one,
12140    and the entries in the index tables are now offsets into these sections.
12141    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12142    section.
12143
12144    Index Section Contents:
12145     Header
12146     Hash Table of Signatures   dwp_hash_table.hash_table
12147     Parallel Table of Indices  dwp_hash_table.unit_table
12148     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12149     Table of Section Sizes     dwp_hash_table.v2.sizes
12150
12151    The index section header consists of:
12152
12153     V, 32 bit version number
12154     L, 32 bit number of columns in the table of section offsets
12155     N, 32 bit number of compilation units or type units in the index
12156     M, 32 bit number of slots in the hash table
12157
12158    Numbers are recorded using the byte order of the application binary.
12159
12160    The hash table has the same format as version 1.
12161    The parallel table of indices has the same format as version 1,
12162    except that the entries are origin-1 indices into the table of sections
12163    offsets and the table of section sizes.
12164
12165    The table of offsets begins immediately following the parallel table
12166    (at offset 16 + 12 * M from the beginning of the section).  The table is
12167    a two-dimensional array of 32-bit words (using the byte order of the
12168    application binary), with L columns and N+1 rows, in row-major order.
12169    Each row in the array is indexed starting from 0.  The first row provides
12170    a key to the remaining rows: each column in this row provides an identifier
12171    for a debug section, and the offsets in the same column of subsequent rows
12172    refer to that section.  The section identifiers are:
12173
12174     DW_SECT_INFO         1  .debug_info.dwo
12175     DW_SECT_TYPES        2  .debug_types.dwo
12176     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12177     DW_SECT_LINE         4  .debug_line.dwo
12178     DW_SECT_LOC          5  .debug_loc.dwo
12179     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12180     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12181     DW_SECT_MACRO        8  .debug_macro.dwo
12182
12183    The offsets provided by the CU and TU index sections are the base offsets
12184    for the contributions made by each CU or TU to the corresponding section
12185    in the package file.  Each CU and TU header contains an abbrev_offset
12186    field, used to find the abbreviations table for that CU or TU within the
12187    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12188    be interpreted as relative to the base offset given in the index section.
12189    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12190    should be interpreted as relative to the base offset for .debug_line.dwo,
12191    and offsets into other debug sections obtained from DWARF attributes should
12192    also be interpreted as relative to the corresponding base offset.
12193
12194    The table of sizes begins immediately following the table of offsets.
12195    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12196    with L columns and N rows, in row-major order.  Each row in the array is
12197    indexed starting from 1 (row 0 is shared by the two tables).
12198
12199    ---
12200
12201    Hash table lookup is handled the same in version 1 and 2:
12202
12203    We assume that N and M will not exceed 2^32 - 1.
12204    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12205
12206    Given a 64-bit compilation unit signature or a type signature S, an entry
12207    in the hash table is located as follows:
12208
12209    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12210       the low-order k bits all set to 1.
12211
12212    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12213
12214    3) If the hash table entry at index H matches the signature, use that
12215       entry.  If the hash table entry at index H is unused (all zeroes),
12216       terminate the search: the signature is not present in the table.
12217
12218    4) Let H = (H + H') modulo M. Repeat at Step 3.
12219
12220    Because M > N and H' and M are relatively prime, the search is guaranteed
12221    to stop at an unused slot or find the match.  */
12222
12223 /* Create a hash table to map DWO IDs to their CU/TU entry in
12224    .debug_{info,types}.dwo in DWP_FILE.
12225    Returns NULL if there isn't one.
12226    Note: This function processes DWP files only, not DWO files.  */
12227
12228 static struct dwp_hash_table *
12229 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12230                        struct dwp_file *dwp_file, int is_debug_types)
12231 {
12232   struct objfile *objfile = dwarf2_per_objfile->objfile;
12233   bfd *dbfd = dwp_file->dbfd;
12234   const gdb_byte *index_ptr, *index_end;
12235   struct dwarf2_section_info *index;
12236   uint32_t version, nr_columns, nr_units, nr_slots;
12237   struct dwp_hash_table *htab;
12238
12239   if (is_debug_types)
12240     index = &dwp_file->sections.tu_index;
12241   else
12242     index = &dwp_file->sections.cu_index;
12243
12244   if (dwarf2_section_empty_p (index))
12245     return NULL;
12246   dwarf2_read_section (objfile, index);
12247
12248   index_ptr = index->buffer;
12249   index_end = index_ptr + index->size;
12250
12251   version = read_4_bytes (dbfd, index_ptr);
12252   index_ptr += 4;
12253   if (version == 2)
12254     nr_columns = read_4_bytes (dbfd, index_ptr);
12255   else
12256     nr_columns = 0;
12257   index_ptr += 4;
12258   nr_units = read_4_bytes (dbfd, index_ptr);
12259   index_ptr += 4;
12260   nr_slots = read_4_bytes (dbfd, index_ptr);
12261   index_ptr += 4;
12262
12263   if (version != 1 && version != 2)
12264     {
12265       error (_("Dwarf Error: unsupported DWP file version (%s)"
12266                " [in module %s]"),
12267              pulongest (version), dwp_file->name);
12268     }
12269   if (nr_slots != (nr_slots & -nr_slots))
12270     {
12271       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12272                " is not power of 2 [in module %s]"),
12273              pulongest (nr_slots), dwp_file->name);
12274     }
12275
12276   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12277   htab->version = version;
12278   htab->nr_columns = nr_columns;
12279   htab->nr_units = nr_units;
12280   htab->nr_slots = nr_slots;
12281   htab->hash_table = index_ptr;
12282   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12283
12284   /* Exit early if the table is empty.  */
12285   if (nr_slots == 0 || nr_units == 0
12286       || (version == 2 && nr_columns == 0))
12287     {
12288       /* All must be zero.  */
12289       if (nr_slots != 0 || nr_units != 0
12290           || (version == 2 && nr_columns != 0))
12291         {
12292           complaint (&symfile_complaints,
12293                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12294                        " all zero [in modules %s]"),
12295                      dwp_file->name);
12296         }
12297       return htab;
12298     }
12299
12300   if (version == 1)
12301     {
12302       htab->section_pool.v1.indices =
12303         htab->unit_table + sizeof (uint32_t) * nr_slots;
12304       /* It's harder to decide whether the section is too small in v1.
12305          V1 is deprecated anyway so we punt.  */
12306     }
12307   else
12308     {
12309       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12310       int *ids = htab->section_pool.v2.section_ids;
12311       /* Reverse map for error checking.  */
12312       int ids_seen[DW_SECT_MAX + 1];
12313       int i;
12314
12315       if (nr_columns < 2)
12316         {
12317           error (_("Dwarf Error: bad DWP hash table, too few columns"
12318                    " in section table [in module %s]"),
12319                  dwp_file->name);
12320         }
12321       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12322         {
12323           error (_("Dwarf Error: bad DWP hash table, too many columns"
12324                    " in section table [in module %s]"),
12325                  dwp_file->name);
12326         }
12327       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12328       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12329       for (i = 0; i < nr_columns; ++i)
12330         {
12331           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12332
12333           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12334             {
12335               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12336                        " in section table [in module %s]"),
12337                      id, dwp_file->name);
12338             }
12339           if (ids_seen[id] != -1)
12340             {
12341               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12342                        " id %d in section table [in module %s]"),
12343                      id, dwp_file->name);
12344             }
12345           ids_seen[id] = i;
12346           ids[i] = id;
12347         }
12348       /* Must have exactly one info or types section.  */
12349       if (((ids_seen[DW_SECT_INFO] != -1)
12350            + (ids_seen[DW_SECT_TYPES] != -1))
12351           != 1)
12352         {
12353           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12354                    " DWO info/types section [in module %s]"),
12355                  dwp_file->name);
12356         }
12357       /* Must have an abbrev section.  */
12358       if (ids_seen[DW_SECT_ABBREV] == -1)
12359         {
12360           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12361                    " section [in module %s]"),
12362                  dwp_file->name);
12363         }
12364       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12365       htab->section_pool.v2.sizes =
12366         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12367                                          * nr_units * nr_columns);
12368       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12369                                           * nr_units * nr_columns))
12370           > index_end)
12371         {
12372           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12373                    " [in module %s]"),
12374                  dwp_file->name);
12375         }
12376     }
12377
12378   return htab;
12379 }
12380
12381 /* Update SECTIONS with the data from SECTP.
12382
12383    This function is like the other "locate" section routines that are
12384    passed to bfd_map_over_sections, but in this context the sections to
12385    read comes from the DWP V1 hash table, not the full ELF section table.
12386
12387    The result is non-zero for success, or zero if an error was found.  */
12388
12389 static int
12390 locate_v1_virtual_dwo_sections (asection *sectp,
12391                                 struct virtual_v1_dwo_sections *sections)
12392 {
12393   const struct dwop_section_names *names = &dwop_section_names;
12394
12395   if (section_is_p (sectp->name, &names->abbrev_dwo))
12396     {
12397       /* There can be only one.  */
12398       if (sections->abbrev.s.section != NULL)
12399         return 0;
12400       sections->abbrev.s.section = sectp;
12401       sections->abbrev.size = bfd_get_section_size (sectp);
12402     }
12403   else if (section_is_p (sectp->name, &names->info_dwo)
12404            || section_is_p (sectp->name, &names->types_dwo))
12405     {
12406       /* There can be only one.  */
12407       if (sections->info_or_types.s.section != NULL)
12408         return 0;
12409       sections->info_or_types.s.section = sectp;
12410       sections->info_or_types.size = bfd_get_section_size (sectp);
12411     }
12412   else if (section_is_p (sectp->name, &names->line_dwo))
12413     {
12414       /* There can be only one.  */
12415       if (sections->line.s.section != NULL)
12416         return 0;
12417       sections->line.s.section = sectp;
12418       sections->line.size = bfd_get_section_size (sectp);
12419     }
12420   else if (section_is_p (sectp->name, &names->loc_dwo))
12421     {
12422       /* There can be only one.  */
12423       if (sections->loc.s.section != NULL)
12424         return 0;
12425       sections->loc.s.section = sectp;
12426       sections->loc.size = bfd_get_section_size (sectp);
12427     }
12428   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12429     {
12430       /* There can be only one.  */
12431       if (sections->macinfo.s.section != NULL)
12432         return 0;
12433       sections->macinfo.s.section = sectp;
12434       sections->macinfo.size = bfd_get_section_size (sectp);
12435     }
12436   else if (section_is_p (sectp->name, &names->macro_dwo))
12437     {
12438       /* There can be only one.  */
12439       if (sections->macro.s.section != NULL)
12440         return 0;
12441       sections->macro.s.section = sectp;
12442       sections->macro.size = bfd_get_section_size (sectp);
12443     }
12444   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12445     {
12446       /* There can be only one.  */
12447       if (sections->str_offsets.s.section != NULL)
12448         return 0;
12449       sections->str_offsets.s.section = sectp;
12450       sections->str_offsets.size = bfd_get_section_size (sectp);
12451     }
12452   else
12453     {
12454       /* No other kind of section is valid.  */
12455       return 0;
12456     }
12457
12458   return 1;
12459 }
12460
12461 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12462    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12463    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12464    This is for DWP version 1 files.  */
12465
12466 static struct dwo_unit *
12467 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12468                            struct dwp_file *dwp_file,
12469                            uint32_t unit_index,
12470                            const char *comp_dir,
12471                            ULONGEST signature, int is_debug_types)
12472 {
12473   struct objfile *objfile = dwarf2_per_objfile->objfile;
12474   const struct dwp_hash_table *dwp_htab =
12475     is_debug_types ? dwp_file->tus : dwp_file->cus;
12476   bfd *dbfd = dwp_file->dbfd;
12477   const char *kind = is_debug_types ? "TU" : "CU";
12478   struct dwo_file *dwo_file;
12479   struct dwo_unit *dwo_unit;
12480   struct virtual_v1_dwo_sections sections;
12481   void **dwo_file_slot;
12482   int i;
12483
12484   gdb_assert (dwp_file->version == 1);
12485
12486   if (dwarf_read_debug)
12487     {
12488       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12489                           kind,
12490                           pulongest (unit_index), hex_string (signature),
12491                           dwp_file->name);
12492     }
12493
12494   /* Fetch the sections of this DWO unit.
12495      Put a limit on the number of sections we look for so that bad data
12496      doesn't cause us to loop forever.  */
12497
12498 #define MAX_NR_V1_DWO_SECTIONS \
12499   (1 /* .debug_info or .debug_types */ \
12500    + 1 /* .debug_abbrev */ \
12501    + 1 /* .debug_line */ \
12502    + 1 /* .debug_loc */ \
12503    + 1 /* .debug_str_offsets */ \
12504    + 1 /* .debug_macro or .debug_macinfo */ \
12505    + 1 /* trailing zero */)
12506
12507   memset (&sections, 0, sizeof (sections));
12508
12509   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12510     {
12511       asection *sectp;
12512       uint32_t section_nr =
12513         read_4_bytes (dbfd,
12514                       dwp_htab->section_pool.v1.indices
12515                       + (unit_index + i) * sizeof (uint32_t));
12516
12517       if (section_nr == 0)
12518         break;
12519       if (section_nr >= dwp_file->num_sections)
12520         {
12521           error (_("Dwarf Error: bad DWP hash table, section number too large"
12522                    " [in module %s]"),
12523                  dwp_file->name);
12524         }
12525
12526       sectp = dwp_file->elf_sections[section_nr];
12527       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12528         {
12529           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12530                    " [in module %s]"),
12531                  dwp_file->name);
12532         }
12533     }
12534
12535   if (i < 2
12536       || dwarf2_section_empty_p (&sections.info_or_types)
12537       || dwarf2_section_empty_p (&sections.abbrev))
12538     {
12539       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12540                " [in module %s]"),
12541              dwp_file->name);
12542     }
12543   if (i == MAX_NR_V1_DWO_SECTIONS)
12544     {
12545       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12546                " [in module %s]"),
12547              dwp_file->name);
12548     }
12549
12550   /* It's easier for the rest of the code if we fake a struct dwo_file and
12551      have dwo_unit "live" in that.  At least for now.
12552
12553      The DWP file can be made up of a random collection of CUs and TUs.
12554      However, for each CU + set of TUs that came from the same original DWO
12555      file, we can combine them back into a virtual DWO file to save space
12556      (fewer struct dwo_file objects to allocate).  Remember that for really
12557      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12558
12559   std::string virtual_dwo_name =
12560     string_printf ("virtual-dwo/%d-%d-%d-%d",
12561                    get_section_id (&sections.abbrev),
12562                    get_section_id (&sections.line),
12563                    get_section_id (&sections.loc),
12564                    get_section_id (&sections.str_offsets));
12565   /* Can we use an existing virtual DWO file?  */
12566   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12567                                         virtual_dwo_name.c_str (),
12568                                         comp_dir);
12569   /* Create one if necessary.  */
12570   if (*dwo_file_slot == NULL)
12571     {
12572       if (dwarf_read_debug)
12573         {
12574           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12575                               virtual_dwo_name.c_str ());
12576         }
12577       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12578       dwo_file->dwo_name
12579         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12580                                         virtual_dwo_name.c_str (),
12581                                         virtual_dwo_name.size ());
12582       dwo_file->comp_dir = comp_dir;
12583       dwo_file->sections.abbrev = sections.abbrev;
12584       dwo_file->sections.line = sections.line;
12585       dwo_file->sections.loc = sections.loc;
12586       dwo_file->sections.macinfo = sections.macinfo;
12587       dwo_file->sections.macro = sections.macro;
12588       dwo_file->sections.str_offsets = sections.str_offsets;
12589       /* The "str" section is global to the entire DWP file.  */
12590       dwo_file->sections.str = dwp_file->sections.str;
12591       /* The info or types section is assigned below to dwo_unit,
12592          there's no need to record it in dwo_file.
12593          Also, we can't simply record type sections in dwo_file because
12594          we record a pointer into the vector in dwo_unit.  As we collect more
12595          types we'll grow the vector and eventually have to reallocate space
12596          for it, invalidating all copies of pointers into the previous
12597          contents.  */
12598       *dwo_file_slot = dwo_file;
12599     }
12600   else
12601     {
12602       if (dwarf_read_debug)
12603         {
12604           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12605                               virtual_dwo_name.c_str ());
12606         }
12607       dwo_file = (struct dwo_file *) *dwo_file_slot;
12608     }
12609
12610   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12611   dwo_unit->dwo_file = dwo_file;
12612   dwo_unit->signature = signature;
12613   dwo_unit->section =
12614     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12615   *dwo_unit->section = sections.info_or_types;
12616   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12617
12618   return dwo_unit;
12619 }
12620
12621 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12622    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12623    piece within that section used by a TU/CU, return a virtual section
12624    of just that piece.  */
12625
12626 static struct dwarf2_section_info
12627 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12628                        struct dwarf2_section_info *section,
12629                        bfd_size_type offset, bfd_size_type size)
12630 {
12631   struct dwarf2_section_info result;
12632   asection *sectp;
12633
12634   gdb_assert (section != NULL);
12635   gdb_assert (!section->is_virtual);
12636
12637   memset (&result, 0, sizeof (result));
12638   result.s.containing_section = section;
12639   result.is_virtual = 1;
12640
12641   if (size == 0)
12642     return result;
12643
12644   sectp = get_section_bfd_section (section);
12645
12646   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12647      bounds of the real section.  This is a pretty-rare event, so just
12648      flag an error (easier) instead of a warning and trying to cope.  */
12649   if (sectp == NULL
12650       || offset + size > bfd_get_section_size (sectp))
12651     {
12652       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12653                " in section %s [in module %s]"),
12654              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12655              objfile_name (dwarf2_per_objfile->objfile));
12656     }
12657
12658   result.virtual_offset = offset;
12659   result.size = size;
12660   return result;
12661 }
12662
12663 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12664    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12665    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12666    This is for DWP version 2 files.  */
12667
12668 static struct dwo_unit *
12669 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12670                            struct dwp_file *dwp_file,
12671                            uint32_t unit_index,
12672                            const char *comp_dir,
12673                            ULONGEST signature, int is_debug_types)
12674 {
12675   struct objfile *objfile = dwarf2_per_objfile->objfile;
12676   const struct dwp_hash_table *dwp_htab =
12677     is_debug_types ? dwp_file->tus : dwp_file->cus;
12678   bfd *dbfd = dwp_file->dbfd;
12679   const char *kind = is_debug_types ? "TU" : "CU";
12680   struct dwo_file *dwo_file;
12681   struct dwo_unit *dwo_unit;
12682   struct virtual_v2_dwo_sections sections;
12683   void **dwo_file_slot;
12684   int i;
12685
12686   gdb_assert (dwp_file->version == 2);
12687
12688   if (dwarf_read_debug)
12689     {
12690       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12691                           kind,
12692                           pulongest (unit_index), hex_string (signature),
12693                           dwp_file->name);
12694     }
12695
12696   /* Fetch the section offsets of this DWO unit.  */
12697
12698   memset (&sections, 0, sizeof (sections));
12699
12700   for (i = 0; i < dwp_htab->nr_columns; ++i)
12701     {
12702       uint32_t offset = read_4_bytes (dbfd,
12703                                       dwp_htab->section_pool.v2.offsets
12704                                       + (((unit_index - 1) * dwp_htab->nr_columns
12705                                           + i)
12706                                          * sizeof (uint32_t)));
12707       uint32_t size = read_4_bytes (dbfd,
12708                                     dwp_htab->section_pool.v2.sizes
12709                                     + (((unit_index - 1) * dwp_htab->nr_columns
12710                                         + i)
12711                                        * sizeof (uint32_t)));
12712
12713       switch (dwp_htab->section_pool.v2.section_ids[i])
12714         {
12715         case DW_SECT_INFO:
12716         case DW_SECT_TYPES:
12717           sections.info_or_types_offset = offset;
12718           sections.info_or_types_size = size;
12719           break;
12720         case DW_SECT_ABBREV:
12721           sections.abbrev_offset = offset;
12722           sections.abbrev_size = size;
12723           break;
12724         case DW_SECT_LINE:
12725           sections.line_offset = offset;
12726           sections.line_size = size;
12727           break;
12728         case DW_SECT_LOC:
12729           sections.loc_offset = offset;
12730           sections.loc_size = size;
12731           break;
12732         case DW_SECT_STR_OFFSETS:
12733           sections.str_offsets_offset = offset;
12734           sections.str_offsets_size = size;
12735           break;
12736         case DW_SECT_MACINFO:
12737           sections.macinfo_offset = offset;
12738           sections.macinfo_size = size;
12739           break;
12740         case DW_SECT_MACRO:
12741           sections.macro_offset = offset;
12742           sections.macro_size = size;
12743           break;
12744         }
12745     }
12746
12747   /* It's easier for the rest of the code if we fake a struct dwo_file and
12748      have dwo_unit "live" in that.  At least for now.
12749
12750      The DWP file can be made up of a random collection of CUs and TUs.
12751      However, for each CU + set of TUs that came from the same original DWO
12752      file, we can combine them back into a virtual DWO file to save space
12753      (fewer struct dwo_file objects to allocate).  Remember that for really
12754      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12755
12756   std::string virtual_dwo_name =
12757     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12758                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12759                    (long) (sections.line_size ? sections.line_offset : 0),
12760                    (long) (sections.loc_size ? sections.loc_offset : 0),
12761                    (long) (sections.str_offsets_size
12762                            ? sections.str_offsets_offset : 0));
12763   /* Can we use an existing virtual DWO file?  */
12764   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12765                                         virtual_dwo_name.c_str (),
12766                                         comp_dir);
12767   /* Create one if necessary.  */
12768   if (*dwo_file_slot == NULL)
12769     {
12770       if (dwarf_read_debug)
12771         {
12772           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12773                               virtual_dwo_name.c_str ());
12774         }
12775       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12776       dwo_file->dwo_name
12777         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12778                                         virtual_dwo_name.c_str (),
12779                                         virtual_dwo_name.size ());
12780       dwo_file->comp_dir = comp_dir;
12781       dwo_file->sections.abbrev =
12782         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12783                                sections.abbrev_offset, sections.abbrev_size);
12784       dwo_file->sections.line =
12785         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12786                                sections.line_offset, sections.line_size);
12787       dwo_file->sections.loc =
12788         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12789                                sections.loc_offset, sections.loc_size);
12790       dwo_file->sections.macinfo =
12791         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12792                                sections.macinfo_offset, sections.macinfo_size);
12793       dwo_file->sections.macro =
12794         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12795                                sections.macro_offset, sections.macro_size);
12796       dwo_file->sections.str_offsets =
12797         create_dwp_v2_section (dwarf2_per_objfile,
12798                                &dwp_file->sections.str_offsets,
12799                                sections.str_offsets_offset,
12800                                sections.str_offsets_size);
12801       /* The "str" section is global to the entire DWP file.  */
12802       dwo_file->sections.str = dwp_file->sections.str;
12803       /* The info or types section is assigned below to dwo_unit,
12804          there's no need to record it in dwo_file.
12805          Also, we can't simply record type sections in dwo_file because
12806          we record a pointer into the vector in dwo_unit.  As we collect more
12807          types we'll grow the vector and eventually have to reallocate space
12808          for it, invalidating all copies of pointers into the previous
12809          contents.  */
12810       *dwo_file_slot = dwo_file;
12811     }
12812   else
12813     {
12814       if (dwarf_read_debug)
12815         {
12816           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12817                               virtual_dwo_name.c_str ());
12818         }
12819       dwo_file = (struct dwo_file *) *dwo_file_slot;
12820     }
12821
12822   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12823   dwo_unit->dwo_file = dwo_file;
12824   dwo_unit->signature = signature;
12825   dwo_unit->section =
12826     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12827   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12828                                               is_debug_types
12829                                               ? &dwp_file->sections.types
12830                                               : &dwp_file->sections.info,
12831                                               sections.info_or_types_offset,
12832                                               sections.info_or_types_size);
12833   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12834
12835   return dwo_unit;
12836 }
12837
12838 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12839    Returns NULL if the signature isn't found.  */
12840
12841 static struct dwo_unit *
12842 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12843                         struct dwp_file *dwp_file, const char *comp_dir,
12844                         ULONGEST signature, int is_debug_types)
12845 {
12846   const struct dwp_hash_table *dwp_htab =
12847     is_debug_types ? dwp_file->tus : dwp_file->cus;
12848   bfd *dbfd = dwp_file->dbfd;
12849   uint32_t mask = dwp_htab->nr_slots - 1;
12850   uint32_t hash = signature & mask;
12851   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12852   unsigned int i;
12853   void **slot;
12854   struct dwo_unit find_dwo_cu;
12855
12856   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12857   find_dwo_cu.signature = signature;
12858   slot = htab_find_slot (is_debug_types
12859                          ? dwp_file->loaded_tus
12860                          : dwp_file->loaded_cus,
12861                          &find_dwo_cu, INSERT);
12862
12863   if (*slot != NULL)
12864     return (struct dwo_unit *) *slot;
12865
12866   /* Use a for loop so that we don't loop forever on bad debug info.  */
12867   for (i = 0; i < dwp_htab->nr_slots; ++i)
12868     {
12869       ULONGEST signature_in_table;
12870
12871       signature_in_table =
12872         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12873       if (signature_in_table == signature)
12874         {
12875           uint32_t unit_index =
12876             read_4_bytes (dbfd,
12877                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12878
12879           if (dwp_file->version == 1)
12880             {
12881               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12882                                                  dwp_file, unit_index,
12883                                                  comp_dir, signature,
12884                                                  is_debug_types);
12885             }
12886           else
12887             {
12888               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12889                                                  dwp_file, unit_index,
12890                                                  comp_dir, signature,
12891                                                  is_debug_types);
12892             }
12893           return (struct dwo_unit *) *slot;
12894         }
12895       if (signature_in_table == 0)
12896         return NULL;
12897       hash = (hash + hash2) & mask;
12898     }
12899
12900   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12901            " [in module %s]"),
12902          dwp_file->name);
12903 }
12904
12905 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12906    Open the file specified by FILE_NAME and hand it off to BFD for
12907    preliminary analysis.  Return a newly initialized bfd *, which
12908    includes a canonicalized copy of FILE_NAME.
12909    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12910    SEARCH_CWD is true if the current directory is to be searched.
12911    It will be searched before debug-file-directory.
12912    If successful, the file is added to the bfd include table of the
12913    objfile's bfd (see gdb_bfd_record_inclusion).
12914    If unable to find/open the file, return NULL.
12915    NOTE: This function is derived from symfile_bfd_open.  */
12916
12917 static gdb_bfd_ref_ptr
12918 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12919                     const char *file_name, int is_dwp, int search_cwd)
12920 {
12921   int desc, flags;
12922   char *absolute_name;
12923   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12924      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12925      to debug_file_directory.  */
12926   char *search_path;
12927   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12928
12929   if (search_cwd)
12930     {
12931       if (*debug_file_directory != '\0')
12932         search_path = concat (".", dirname_separator_string,
12933                               debug_file_directory, (char *) NULL);
12934       else
12935         search_path = xstrdup (".");
12936     }
12937   else
12938     search_path = xstrdup (debug_file_directory);
12939
12940   flags = OPF_RETURN_REALPATH;
12941   if (is_dwp)
12942     flags |= OPF_SEARCH_IN_PATH;
12943   desc = openp (search_path, flags, file_name,
12944                 O_RDONLY | O_BINARY, &absolute_name);
12945   xfree (search_path);
12946   if (desc < 0)
12947     return NULL;
12948
12949   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12950   xfree (absolute_name);
12951   if (sym_bfd == NULL)
12952     return NULL;
12953   bfd_set_cacheable (sym_bfd.get (), 1);
12954
12955   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12956     return NULL;
12957
12958   /* Success.  Record the bfd as having been included by the objfile's bfd.
12959      This is important because things like demangled_names_hash lives in the
12960      objfile's per_bfd space and may have references to things like symbol
12961      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12962   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12963
12964   return sym_bfd;
12965 }
12966
12967 /* Try to open DWO file FILE_NAME.
12968    COMP_DIR is the DW_AT_comp_dir attribute.
12969    The result is the bfd handle of the file.
12970    If there is a problem finding or opening the file, return NULL.
12971    Upon success, the canonicalized path of the file is stored in the bfd,
12972    same as symfile_bfd_open.  */
12973
12974 static gdb_bfd_ref_ptr
12975 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12976                const char *file_name, const char *comp_dir)
12977 {
12978   if (IS_ABSOLUTE_PATH (file_name))
12979     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12980                                0 /*is_dwp*/, 0 /*search_cwd*/);
12981
12982   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12983
12984   if (comp_dir != NULL)
12985     {
12986       char *path_to_try = concat (comp_dir, SLASH_STRING,
12987                                   file_name, (char *) NULL);
12988
12989       /* NOTE: If comp_dir is a relative path, this will also try the
12990          search path, which seems useful.  */
12991       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12992                                                 path_to_try,
12993                                                 0 /*is_dwp*/,
12994                                                 1 /*search_cwd*/));
12995       xfree (path_to_try);
12996       if (abfd != NULL)
12997         return abfd;
12998     }
12999
13000   /* That didn't work, try debug-file-directory, which, despite its name,
13001      is a list of paths.  */
13002
13003   if (*debug_file_directory == '\0')
13004     return NULL;
13005
13006   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13007                              0 /*is_dwp*/, 1 /*search_cwd*/);
13008 }
13009
13010 /* This function is mapped across the sections and remembers the offset and
13011    size of each of the DWO debugging sections we are interested in.  */
13012
13013 static void
13014 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13015 {
13016   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13017   const struct dwop_section_names *names = &dwop_section_names;
13018
13019   if (section_is_p (sectp->name, &names->abbrev_dwo))
13020     {
13021       dwo_sections->abbrev.s.section = sectp;
13022       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13023     }
13024   else if (section_is_p (sectp->name, &names->info_dwo))
13025     {
13026       dwo_sections->info.s.section = sectp;
13027       dwo_sections->info.size = bfd_get_section_size (sectp);
13028     }
13029   else if (section_is_p (sectp->name, &names->line_dwo))
13030     {
13031       dwo_sections->line.s.section = sectp;
13032       dwo_sections->line.size = bfd_get_section_size (sectp);
13033     }
13034   else if (section_is_p (sectp->name, &names->loc_dwo))
13035     {
13036       dwo_sections->loc.s.section = sectp;
13037       dwo_sections->loc.size = bfd_get_section_size (sectp);
13038     }
13039   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13040     {
13041       dwo_sections->macinfo.s.section = sectp;
13042       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13043     }
13044   else if (section_is_p (sectp->name, &names->macro_dwo))
13045     {
13046       dwo_sections->macro.s.section = sectp;
13047       dwo_sections->macro.size = bfd_get_section_size (sectp);
13048     }
13049   else if (section_is_p (sectp->name, &names->str_dwo))
13050     {
13051       dwo_sections->str.s.section = sectp;
13052       dwo_sections->str.size = bfd_get_section_size (sectp);
13053     }
13054   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13055     {
13056       dwo_sections->str_offsets.s.section = sectp;
13057       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13058     }
13059   else if (section_is_p (sectp->name, &names->types_dwo))
13060     {
13061       struct dwarf2_section_info type_section;
13062
13063       memset (&type_section, 0, sizeof (type_section));
13064       type_section.s.section = sectp;
13065       type_section.size = bfd_get_section_size (sectp);
13066       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13067                      &type_section);
13068     }
13069 }
13070
13071 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13072    by PER_CU.  This is for the non-DWP case.
13073    The result is NULL if DWO_NAME can't be found.  */
13074
13075 static struct dwo_file *
13076 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13077                         const char *dwo_name, const char *comp_dir)
13078 {
13079   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13080   struct objfile *objfile = dwarf2_per_objfile->objfile;
13081   struct dwo_file *dwo_file;
13082   struct cleanup *cleanups;
13083
13084   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13085   if (dbfd == NULL)
13086     {
13087       if (dwarf_read_debug)
13088         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13089       return NULL;
13090     }
13091   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13092   dwo_file->dwo_name = dwo_name;
13093   dwo_file->comp_dir = comp_dir;
13094   dwo_file->dbfd = dbfd.release ();
13095
13096   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13097   cleanup_data->dwo_file = dwo_file;
13098   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13099
13100   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13101
13102   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13103                          &dwo_file->sections);
13104
13105   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13106                          dwo_file->cus);
13107
13108   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13109                                  dwo_file->sections.types, dwo_file->tus);
13110
13111   discard_cleanups (cleanups);
13112
13113   if (dwarf_read_debug)
13114     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13115
13116   return dwo_file;
13117 }
13118
13119 /* This function is mapped across the sections and remembers the offset and
13120    size of each of the DWP debugging sections common to version 1 and 2 that
13121    we are interested in.  */
13122
13123 static void
13124 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13125                                    void *dwp_file_ptr)
13126 {
13127   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13128   const struct dwop_section_names *names = &dwop_section_names;
13129   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13130
13131   /* Record the ELF section number for later lookup: this is what the
13132      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13133   gdb_assert (elf_section_nr < dwp_file->num_sections);
13134   dwp_file->elf_sections[elf_section_nr] = sectp;
13135
13136   /* Look for specific sections that we need.  */
13137   if (section_is_p (sectp->name, &names->str_dwo))
13138     {
13139       dwp_file->sections.str.s.section = sectp;
13140       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13141     }
13142   else if (section_is_p (sectp->name, &names->cu_index))
13143     {
13144       dwp_file->sections.cu_index.s.section = sectp;
13145       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13146     }
13147   else if (section_is_p (sectp->name, &names->tu_index))
13148     {
13149       dwp_file->sections.tu_index.s.section = sectp;
13150       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13151     }
13152 }
13153
13154 /* This function is mapped across the sections and remembers the offset and
13155    size of each of the DWP version 2 debugging sections that we are interested
13156    in.  This is split into a separate function because we don't know if we
13157    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13158
13159 static void
13160 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13161 {
13162   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13163   const struct dwop_section_names *names = &dwop_section_names;
13164   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13165
13166   /* Record the ELF section number for later lookup: this is what the
13167      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13168   gdb_assert (elf_section_nr < dwp_file->num_sections);
13169   dwp_file->elf_sections[elf_section_nr] = sectp;
13170
13171   /* Look for specific sections that we need.  */
13172   if (section_is_p (sectp->name, &names->abbrev_dwo))
13173     {
13174       dwp_file->sections.abbrev.s.section = sectp;
13175       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13176     }
13177   else if (section_is_p (sectp->name, &names->info_dwo))
13178     {
13179       dwp_file->sections.info.s.section = sectp;
13180       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13181     }
13182   else if (section_is_p (sectp->name, &names->line_dwo))
13183     {
13184       dwp_file->sections.line.s.section = sectp;
13185       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13186     }
13187   else if (section_is_p (sectp->name, &names->loc_dwo))
13188     {
13189       dwp_file->sections.loc.s.section = sectp;
13190       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13191     }
13192   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13193     {
13194       dwp_file->sections.macinfo.s.section = sectp;
13195       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13196     }
13197   else if (section_is_p (sectp->name, &names->macro_dwo))
13198     {
13199       dwp_file->sections.macro.s.section = sectp;
13200       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13201     }
13202   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13203     {
13204       dwp_file->sections.str_offsets.s.section = sectp;
13205       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13206     }
13207   else if (section_is_p (sectp->name, &names->types_dwo))
13208     {
13209       dwp_file->sections.types.s.section = sectp;
13210       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13211     }
13212 }
13213
13214 /* Hash function for dwp_file loaded CUs/TUs.  */
13215
13216 static hashval_t
13217 hash_dwp_loaded_cutus (const void *item)
13218 {
13219   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13220
13221   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13222   return dwo_unit->signature;
13223 }
13224
13225 /* Equality function for dwp_file loaded CUs/TUs.  */
13226
13227 static int
13228 eq_dwp_loaded_cutus (const void *a, const void *b)
13229 {
13230   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13231   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13232
13233   return dua->signature == dub->signature;
13234 }
13235
13236 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13237
13238 static htab_t
13239 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13240 {
13241   return htab_create_alloc_ex (3,
13242                                hash_dwp_loaded_cutus,
13243                                eq_dwp_loaded_cutus,
13244                                NULL,
13245                                &objfile->objfile_obstack,
13246                                hashtab_obstack_allocate,
13247                                dummy_obstack_deallocate);
13248 }
13249
13250 /* Try to open DWP file FILE_NAME.
13251    The result is the bfd handle of the file.
13252    If there is a problem finding or opening the file, return NULL.
13253    Upon success, the canonicalized path of the file is stored in the bfd,
13254    same as symfile_bfd_open.  */
13255
13256 static gdb_bfd_ref_ptr
13257 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13258                const char *file_name)
13259 {
13260   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13261                                             1 /*is_dwp*/,
13262                                             1 /*search_cwd*/));
13263   if (abfd != NULL)
13264     return abfd;
13265
13266   /* Work around upstream bug 15652.
13267      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13268      [Whether that's a "bug" is debatable, but it is getting in our way.]
13269      We have no real idea where the dwp file is, because gdb's realpath-ing
13270      of the executable's path may have discarded the needed info.
13271      [IWBN if the dwp file name was recorded in the executable, akin to
13272      .gnu_debuglink, but that doesn't exist yet.]
13273      Strip the directory from FILE_NAME and search again.  */
13274   if (*debug_file_directory != '\0')
13275     {
13276       /* Don't implicitly search the current directory here.
13277          If the user wants to search "." to handle this case,
13278          it must be added to debug-file-directory.  */
13279       return try_open_dwop_file (dwarf2_per_objfile,
13280                                  lbasename (file_name), 1 /*is_dwp*/,
13281                                  0 /*search_cwd*/);
13282     }
13283
13284   return NULL;
13285 }
13286
13287 /* Initialize the use of the DWP file for the current objfile.
13288    By convention the name of the DWP file is ${objfile}.dwp.
13289    The result is NULL if it can't be found.  */
13290
13291 static struct dwp_file *
13292 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13293 {
13294   struct objfile *objfile = dwarf2_per_objfile->objfile;
13295   struct dwp_file *dwp_file;
13296
13297   /* Try to find first .dwp for the binary file before any symbolic links
13298      resolving.  */
13299
13300   /* If the objfile is a debug file, find the name of the real binary
13301      file and get the name of dwp file from there.  */
13302   std::string dwp_name;
13303   if (objfile->separate_debug_objfile_backlink != NULL)
13304     {
13305       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13306       const char *backlink_basename = lbasename (backlink->original_name);
13307
13308       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13309     }
13310   else
13311     dwp_name = objfile->original_name;
13312
13313   dwp_name += ".dwp";
13314
13315   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13316   if (dbfd == NULL
13317       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13318     {
13319       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13320       dwp_name = objfile_name (objfile);
13321       dwp_name += ".dwp";
13322       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13323     }
13324
13325   if (dbfd == NULL)
13326     {
13327       if (dwarf_read_debug)
13328         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13329       return NULL;
13330     }
13331   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13332   dwp_file->name = bfd_get_filename (dbfd.get ());
13333   dwp_file->dbfd = dbfd.release ();
13334
13335   /* +1: section 0 is unused */
13336   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13337   dwp_file->elf_sections =
13338     OBSTACK_CALLOC (&objfile->objfile_obstack,
13339                     dwp_file->num_sections, asection *);
13340
13341   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13342                          dwp_file);
13343
13344   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13345
13346   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13347
13348   /* The DWP file version is stored in the hash table.  Oh well.  */
13349   if (dwp_file->cus && dwp_file->tus
13350       && dwp_file->cus->version != dwp_file->tus->version)
13351     {
13352       /* Technically speaking, we should try to limp along, but this is
13353          pretty bizarre.  We use pulongest here because that's the established
13354          portability solution (e.g, we cannot use %u for uint32_t).  */
13355       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13356                " TU version %s [in DWP file %s]"),
13357              pulongest (dwp_file->cus->version),
13358              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13359     }
13360
13361   if (dwp_file->cus)
13362     dwp_file->version = dwp_file->cus->version;
13363   else if (dwp_file->tus)
13364     dwp_file->version = dwp_file->tus->version;
13365   else
13366     dwp_file->version = 2;
13367
13368   if (dwp_file->version == 2)
13369     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13370                            dwp_file);
13371
13372   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13373   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13374
13375   if (dwarf_read_debug)
13376     {
13377       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13378       fprintf_unfiltered (gdb_stdlog,
13379                           "    %s CUs, %s TUs\n",
13380                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13381                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13382     }
13383
13384   return dwp_file;
13385 }
13386
13387 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13388
13389 static struct dwp_file *
13390 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13391 {
13392   if (! dwarf2_per_objfile->dwp_checked)
13393     {
13394       dwarf2_per_objfile->dwp_file
13395         = open_and_init_dwp_file (dwarf2_per_objfile);
13396       dwarf2_per_objfile->dwp_checked = 1;
13397     }
13398   return dwarf2_per_objfile->dwp_file;
13399 }
13400
13401 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13402    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13403    or in the DWP file for the objfile, referenced by THIS_UNIT.
13404    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13405    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13406
13407    This is called, for example, when wanting to read a variable with a
13408    complex location.  Therefore we don't want to do file i/o for every call.
13409    Therefore we don't want to look for a DWO file on every call.
13410    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13411    then we check if we've already seen DWO_NAME, and only THEN do we check
13412    for a DWO file.
13413
13414    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13415    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13416
13417 static struct dwo_unit *
13418 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13419                  const char *dwo_name, const char *comp_dir,
13420                  ULONGEST signature, int is_debug_types)
13421 {
13422   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13423   struct objfile *objfile = dwarf2_per_objfile->objfile;
13424   const char *kind = is_debug_types ? "TU" : "CU";
13425   void **dwo_file_slot;
13426   struct dwo_file *dwo_file;
13427   struct dwp_file *dwp_file;
13428
13429   /* First see if there's a DWP file.
13430      If we have a DWP file but didn't find the DWO inside it, don't
13431      look for the original DWO file.  It makes gdb behave differently
13432      depending on whether one is debugging in the build tree.  */
13433
13434   dwp_file = get_dwp_file (dwarf2_per_objfile);
13435   if (dwp_file != NULL)
13436     {
13437       const struct dwp_hash_table *dwp_htab =
13438         is_debug_types ? dwp_file->tus : dwp_file->cus;
13439
13440       if (dwp_htab != NULL)
13441         {
13442           struct dwo_unit *dwo_cutu =
13443             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13444                                     signature, is_debug_types);
13445
13446           if (dwo_cutu != NULL)
13447             {
13448               if (dwarf_read_debug)
13449                 {
13450                   fprintf_unfiltered (gdb_stdlog,
13451                                       "Virtual DWO %s %s found: @%s\n",
13452                                       kind, hex_string (signature),
13453                                       host_address_to_string (dwo_cutu));
13454                 }
13455               return dwo_cutu;
13456             }
13457         }
13458     }
13459   else
13460     {
13461       /* No DWP file, look for the DWO file.  */
13462
13463       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13464                                             dwo_name, comp_dir);
13465       if (*dwo_file_slot == NULL)
13466         {
13467           /* Read in the file and build a table of the CUs/TUs it contains.  */
13468           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13469         }
13470       /* NOTE: This will be NULL if unable to open the file.  */
13471       dwo_file = (struct dwo_file *) *dwo_file_slot;
13472
13473       if (dwo_file != NULL)
13474         {
13475           struct dwo_unit *dwo_cutu = NULL;
13476
13477           if (is_debug_types && dwo_file->tus)
13478             {
13479               struct dwo_unit find_dwo_cutu;
13480
13481               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13482               find_dwo_cutu.signature = signature;
13483               dwo_cutu
13484                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13485             }
13486           else if (!is_debug_types && dwo_file->cus)
13487             {
13488               struct dwo_unit find_dwo_cutu;
13489
13490               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13491               find_dwo_cutu.signature = signature;
13492               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13493                                                        &find_dwo_cutu);
13494             }
13495
13496           if (dwo_cutu != NULL)
13497             {
13498               if (dwarf_read_debug)
13499                 {
13500                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13501                                       kind, dwo_name, hex_string (signature),
13502                                       host_address_to_string (dwo_cutu));
13503                 }
13504               return dwo_cutu;
13505             }
13506         }
13507     }
13508
13509   /* We didn't find it.  This could mean a dwo_id mismatch, or
13510      someone deleted the DWO/DWP file, or the search path isn't set up
13511      correctly to find the file.  */
13512
13513   if (dwarf_read_debug)
13514     {
13515       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13516                           kind, dwo_name, hex_string (signature));
13517     }
13518
13519   /* This is a warning and not a complaint because it can be caused by
13520      pilot error (e.g., user accidentally deleting the DWO).  */
13521   {
13522     /* Print the name of the DWP file if we looked there, helps the user
13523        better diagnose the problem.  */
13524     std::string dwp_text;
13525
13526     if (dwp_file != NULL)
13527       dwp_text = string_printf (" [in DWP file %s]",
13528                                 lbasename (dwp_file->name));
13529
13530     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13531                " [in module %s]"),
13532              kind, dwo_name, hex_string (signature),
13533              dwp_text.c_str (),
13534              this_unit->is_debug_types ? "TU" : "CU",
13535              to_underlying (this_unit->sect_off), objfile_name (objfile));
13536   }
13537   return NULL;
13538 }
13539
13540 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13541    See lookup_dwo_cutu_unit for details.  */
13542
13543 static struct dwo_unit *
13544 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13545                       const char *dwo_name, const char *comp_dir,
13546                       ULONGEST signature)
13547 {
13548   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13549 }
13550
13551 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13552    See lookup_dwo_cutu_unit for details.  */
13553
13554 static struct dwo_unit *
13555 lookup_dwo_type_unit (struct signatured_type *this_tu,
13556                       const char *dwo_name, const char *comp_dir)
13557 {
13558   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13559 }
13560
13561 /* Traversal function for queue_and_load_all_dwo_tus.  */
13562
13563 static int
13564 queue_and_load_dwo_tu (void **slot, void *info)
13565 {
13566   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13567   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13568   ULONGEST signature = dwo_unit->signature;
13569   struct signatured_type *sig_type =
13570     lookup_dwo_signatured_type (per_cu->cu, signature);
13571
13572   if (sig_type != NULL)
13573     {
13574       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13575
13576       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13577          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13578          while processing PER_CU.  */
13579       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13580         load_full_type_unit (sig_cu);
13581       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13582     }
13583
13584   return 1;
13585 }
13586
13587 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13588    The DWO may have the only definition of the type, though it may not be
13589    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13590    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13591
13592 static void
13593 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13594 {
13595   struct dwo_unit *dwo_unit;
13596   struct dwo_file *dwo_file;
13597
13598   gdb_assert (!per_cu->is_debug_types);
13599   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13600   gdb_assert (per_cu->cu != NULL);
13601
13602   dwo_unit = per_cu->cu->dwo_unit;
13603   gdb_assert (dwo_unit != NULL);
13604
13605   dwo_file = dwo_unit->dwo_file;
13606   if (dwo_file->tus != NULL)
13607     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13608 }
13609
13610 /* Free all resources associated with DWO_FILE.
13611    Close the DWO file and munmap the sections.
13612    All memory should be on the objfile obstack.  */
13613
13614 static void
13615 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13616 {
13617
13618   /* Note: dbfd is NULL for virtual DWO files.  */
13619   gdb_bfd_unref (dwo_file->dbfd);
13620
13621   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13622 }
13623
13624 /* Wrapper for free_dwo_file for use in cleanups.  */
13625
13626 static void
13627 free_dwo_file_cleanup (void *arg)
13628 {
13629   struct free_dwo_file_cleanup_data *data
13630     = (struct free_dwo_file_cleanup_data *) arg;
13631   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13632
13633   free_dwo_file (data->dwo_file, objfile);
13634
13635   xfree (data);
13636 }
13637
13638 /* Traversal function for free_dwo_files.  */
13639
13640 static int
13641 free_dwo_file_from_slot (void **slot, void *info)
13642 {
13643   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13644   struct objfile *objfile = (struct objfile *) info;
13645
13646   free_dwo_file (dwo_file, objfile);
13647
13648   return 1;
13649 }
13650
13651 /* Free all resources associated with DWO_FILES.  */
13652
13653 static void
13654 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13655 {
13656   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13657 }
13658 \f
13659 /* Read in various DIEs.  */
13660
13661 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13662    Inherit only the children of the DW_AT_abstract_origin DIE not being
13663    already referenced by DW_AT_abstract_origin from the children of the
13664    current DIE.  */
13665
13666 static void
13667 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13668 {
13669   struct die_info *child_die;
13670   sect_offset *offsetp;
13671   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13672   struct die_info *origin_die;
13673   /* Iterator of the ORIGIN_DIE children.  */
13674   struct die_info *origin_child_die;
13675   struct attribute *attr;
13676   struct dwarf2_cu *origin_cu;
13677   struct pending **origin_previous_list_in_scope;
13678
13679   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13680   if (!attr)
13681     return;
13682
13683   /* Note that following die references may follow to a die in a
13684      different cu.  */
13685
13686   origin_cu = cu;
13687   origin_die = follow_die_ref (die, attr, &origin_cu);
13688
13689   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13690      symbols in.  */
13691   origin_previous_list_in_scope = origin_cu->list_in_scope;
13692   origin_cu->list_in_scope = cu->list_in_scope;
13693
13694   if (die->tag != origin_die->tag
13695       && !(die->tag == DW_TAG_inlined_subroutine
13696            && origin_die->tag == DW_TAG_subprogram))
13697     complaint (&symfile_complaints,
13698                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13699                to_underlying (die->sect_off),
13700                to_underlying (origin_die->sect_off));
13701
13702   std::vector<sect_offset> offsets;
13703
13704   for (child_die = die->child;
13705        child_die && child_die->tag;
13706        child_die = sibling_die (child_die))
13707     {
13708       struct die_info *child_origin_die;
13709       struct dwarf2_cu *child_origin_cu;
13710
13711       /* We are trying to process concrete instance entries:
13712          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13713          it's not relevant to our analysis here. i.e. detecting DIEs that are
13714          present in the abstract instance but not referenced in the concrete
13715          one.  */
13716       if (child_die->tag == DW_TAG_call_site
13717           || child_die->tag == DW_TAG_GNU_call_site)
13718         continue;
13719
13720       /* For each CHILD_DIE, find the corresponding child of
13721          ORIGIN_DIE.  If there is more than one layer of
13722          DW_AT_abstract_origin, follow them all; there shouldn't be,
13723          but GCC versions at least through 4.4 generate this (GCC PR
13724          40573).  */
13725       child_origin_die = child_die;
13726       child_origin_cu = cu;
13727       while (1)
13728         {
13729           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13730                               child_origin_cu);
13731           if (attr == NULL)
13732             break;
13733           child_origin_die = follow_die_ref (child_origin_die, attr,
13734                                              &child_origin_cu);
13735         }
13736
13737       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13738          counterpart may exist.  */
13739       if (child_origin_die != child_die)
13740         {
13741           if (child_die->tag != child_origin_die->tag
13742               && !(child_die->tag == DW_TAG_inlined_subroutine
13743                    && child_origin_die->tag == DW_TAG_subprogram))
13744             complaint (&symfile_complaints,
13745                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13746                          "different tags"),
13747                        to_underlying (child_die->sect_off),
13748                        to_underlying (child_origin_die->sect_off));
13749           if (child_origin_die->parent != origin_die)
13750             complaint (&symfile_complaints,
13751                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13752                          "different parents"),
13753                        to_underlying (child_die->sect_off),
13754                        to_underlying (child_origin_die->sect_off));
13755           else
13756             offsets.push_back (child_origin_die->sect_off);
13757         }
13758     }
13759   std::sort (offsets.begin (), offsets.end ());
13760   sect_offset *offsets_end = offsets.data () + offsets.size ();
13761   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13762     if (offsetp[-1] == *offsetp)
13763       complaint (&symfile_complaints,
13764                  _("Multiple children of DIE 0x%x refer "
13765                    "to DIE 0x%x as their abstract origin"),
13766                  to_underlying (die->sect_off), to_underlying (*offsetp));
13767
13768   offsetp = offsets.data ();
13769   origin_child_die = origin_die->child;
13770   while (origin_child_die && origin_child_die->tag)
13771     {
13772       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13773       while (offsetp < offsets_end
13774              && *offsetp < origin_child_die->sect_off)
13775         offsetp++;
13776       if (offsetp >= offsets_end
13777           || *offsetp > origin_child_die->sect_off)
13778         {
13779           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13780              Check whether we're already processing ORIGIN_CHILD_DIE.
13781              This can happen with mutually referenced abstract_origins.
13782              PR 16581.  */
13783           if (!origin_child_die->in_process)
13784             process_die (origin_child_die, origin_cu);
13785         }
13786       origin_child_die = sibling_die (origin_child_die);
13787     }
13788   origin_cu->list_in_scope = origin_previous_list_in_scope;
13789 }
13790
13791 static void
13792 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13793 {
13794   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13795   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13796   struct context_stack *newobj;
13797   CORE_ADDR lowpc;
13798   CORE_ADDR highpc;
13799   struct die_info *child_die;
13800   struct attribute *attr, *call_line, *call_file;
13801   const char *name;
13802   CORE_ADDR baseaddr;
13803   struct block *block;
13804   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13805   std::vector<struct symbol *> template_args;
13806   struct template_symbol *templ_func = NULL;
13807
13808   if (inlined_func)
13809     {
13810       /* If we do not have call site information, we can't show the
13811          caller of this inlined function.  That's too confusing, so
13812          only use the scope for local variables.  */
13813       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13814       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13815       if (call_line == NULL || call_file == NULL)
13816         {
13817           read_lexical_block_scope (die, cu);
13818           return;
13819         }
13820     }
13821
13822   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13823
13824   name = dwarf2_name (die, cu);
13825
13826   /* Ignore functions with missing or empty names.  These are actually
13827      illegal according to the DWARF standard.  */
13828   if (name == NULL)
13829     {
13830       complaint (&symfile_complaints,
13831                  _("missing name for subprogram DIE at %d"),
13832                  to_underlying (die->sect_off));
13833       return;
13834     }
13835
13836   /* Ignore functions with missing or invalid low and high pc attributes.  */
13837   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13838       <= PC_BOUNDS_INVALID)
13839     {
13840       attr = dwarf2_attr (die, DW_AT_external, cu);
13841       if (!attr || !DW_UNSND (attr))
13842         complaint (&symfile_complaints,
13843                    _("cannot get low and high bounds "
13844                      "for subprogram DIE at %d"),
13845                    to_underlying (die->sect_off));
13846       return;
13847     }
13848
13849   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13850   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13851
13852   /* If we have any template arguments, then we must allocate a
13853      different sort of symbol.  */
13854   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13855     {
13856       if (child_die->tag == DW_TAG_template_type_param
13857           || child_die->tag == DW_TAG_template_value_param)
13858         {
13859           templ_func = allocate_template_symbol (objfile);
13860           templ_func->subclass = SYMBOL_TEMPLATE;
13861           break;
13862         }
13863     }
13864
13865   newobj = push_context (0, lowpc);
13866   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13867                              (struct symbol *) templ_func);
13868
13869   /* If there is a location expression for DW_AT_frame_base, record
13870      it.  */
13871   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13872   if (attr)
13873     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13874
13875   /* If there is a location for the static link, record it.  */
13876   newobj->static_link = NULL;
13877   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13878   if (attr)
13879     {
13880       newobj->static_link
13881         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13882       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13883     }
13884
13885   cu->list_in_scope = &local_symbols;
13886
13887   if (die->child != NULL)
13888     {
13889       child_die = die->child;
13890       while (child_die && child_die->tag)
13891         {
13892           if (child_die->tag == DW_TAG_template_type_param
13893               || child_die->tag == DW_TAG_template_value_param)
13894             {
13895               struct symbol *arg = new_symbol (child_die, NULL, cu);
13896
13897               if (arg != NULL)
13898                 template_args.push_back (arg);
13899             }
13900           else
13901             process_die (child_die, cu);
13902           child_die = sibling_die (child_die);
13903         }
13904     }
13905
13906   inherit_abstract_dies (die, cu);
13907
13908   /* If we have a DW_AT_specification, we might need to import using
13909      directives from the context of the specification DIE.  See the
13910      comment in determine_prefix.  */
13911   if (cu->language == language_cplus
13912       && dwarf2_attr (die, DW_AT_specification, cu))
13913     {
13914       struct dwarf2_cu *spec_cu = cu;
13915       struct die_info *spec_die = die_specification (die, &spec_cu);
13916
13917       while (spec_die)
13918         {
13919           child_die = spec_die->child;
13920           while (child_die && child_die->tag)
13921             {
13922               if (child_die->tag == DW_TAG_imported_module)
13923                 process_die (child_die, spec_cu);
13924               child_die = sibling_die (child_die);
13925             }
13926
13927           /* In some cases, GCC generates specification DIEs that
13928              themselves contain DW_AT_specification attributes.  */
13929           spec_die = die_specification (spec_die, &spec_cu);
13930         }
13931     }
13932
13933   newobj = pop_context ();
13934   /* Make a block for the local symbols within.  */
13935   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13936                         newobj->static_link, lowpc, highpc);
13937
13938   /* For C++, set the block's scope.  */
13939   if ((cu->language == language_cplus
13940        || cu->language == language_fortran
13941        || cu->language == language_d
13942        || cu->language == language_rust)
13943       && cu->processing_has_namespace_info)
13944     block_set_scope (block, determine_prefix (die, cu),
13945                      &objfile->objfile_obstack);
13946
13947   /* If we have address ranges, record them.  */
13948   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13949
13950   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13951
13952   /* Attach template arguments to function.  */
13953   if (!template_args.empty ())
13954     {
13955       gdb_assert (templ_func != NULL);
13956
13957       templ_func->n_template_arguments = template_args.size ();
13958       templ_func->template_arguments
13959         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13960                      templ_func->n_template_arguments);
13961       memcpy (templ_func->template_arguments,
13962               template_args.data (),
13963               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13964     }
13965
13966   /* In C++, we can have functions nested inside functions (e.g., when
13967      a function declares a class that has methods).  This means that
13968      when we finish processing a function scope, we may need to go
13969      back to building a containing block's symbol lists.  */
13970   local_symbols = newobj->locals;
13971   local_using_directives = newobj->local_using_directives;
13972
13973   /* If we've finished processing a top-level function, subsequent
13974      symbols go in the file symbol list.  */
13975   if (outermost_context_p ())
13976     cu->list_in_scope = &file_symbols;
13977 }
13978
13979 /* Process all the DIES contained within a lexical block scope.  Start
13980    a new scope, process the dies, and then close the scope.  */
13981
13982 static void
13983 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13984 {
13985   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13986   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13987   struct context_stack *newobj;
13988   CORE_ADDR lowpc, highpc;
13989   struct die_info *child_die;
13990   CORE_ADDR baseaddr;
13991
13992   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13993
13994   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13995   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13996      as multiple lexical blocks?  Handling children in a sane way would
13997      be nasty.  Might be easier to properly extend generic blocks to
13998      describe ranges.  */
13999   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14000     {
14001     case PC_BOUNDS_NOT_PRESENT:
14002       /* DW_TAG_lexical_block has no attributes, process its children as if
14003          there was no wrapping by that DW_TAG_lexical_block.
14004          GCC does no longer produces such DWARF since GCC r224161.  */
14005       for (child_die = die->child;
14006            child_die != NULL && child_die->tag;
14007            child_die = sibling_die (child_die))
14008         process_die (child_die, cu);
14009       return;
14010     case PC_BOUNDS_INVALID:
14011       return;
14012     }
14013   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14014   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14015
14016   push_context (0, lowpc);
14017   if (die->child != NULL)
14018     {
14019       child_die = die->child;
14020       while (child_die && child_die->tag)
14021         {
14022           process_die (child_die, cu);
14023           child_die = sibling_die (child_die);
14024         }
14025     }
14026   inherit_abstract_dies (die, cu);
14027   newobj = pop_context ();
14028
14029   if (local_symbols != NULL || local_using_directives != NULL)
14030     {
14031       struct block *block
14032         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14033                         newobj->start_addr, highpc);
14034
14035       /* Note that recording ranges after traversing children, as we
14036          do here, means that recording a parent's ranges entails
14037          walking across all its children's ranges as they appear in
14038          the address map, which is quadratic behavior.
14039
14040          It would be nicer to record the parent's ranges before
14041          traversing its children, simply overriding whatever you find
14042          there.  But since we don't even decide whether to create a
14043          block until after we've traversed its children, that's hard
14044          to do.  */
14045       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14046     }
14047   local_symbols = newobj->locals;
14048   local_using_directives = newobj->local_using_directives;
14049 }
14050
14051 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14052
14053 static void
14054 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14055 {
14056   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14057   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14058   CORE_ADDR pc, baseaddr;
14059   struct attribute *attr;
14060   struct call_site *call_site, call_site_local;
14061   void **slot;
14062   int nparams;
14063   struct die_info *child_die;
14064
14065   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14066
14067   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14068   if (attr == NULL)
14069     {
14070       /* This was a pre-DWARF-5 GNU extension alias
14071          for DW_AT_call_return_pc.  */
14072       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14073     }
14074   if (!attr)
14075     {
14076       complaint (&symfile_complaints,
14077                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14078                    "DIE 0x%x [in module %s]"),
14079                  to_underlying (die->sect_off), objfile_name (objfile));
14080       return;
14081     }
14082   pc = attr_value_as_address (attr) + baseaddr;
14083   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14084
14085   if (cu->call_site_htab == NULL)
14086     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14087                                                NULL, &objfile->objfile_obstack,
14088                                                hashtab_obstack_allocate, NULL);
14089   call_site_local.pc = pc;
14090   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14091   if (*slot != NULL)
14092     {
14093       complaint (&symfile_complaints,
14094                  _("Duplicate PC %s for DW_TAG_call_site "
14095                    "DIE 0x%x [in module %s]"),
14096                  paddress (gdbarch, pc), to_underlying (die->sect_off),
14097                  objfile_name (objfile));
14098       return;
14099     }
14100
14101   /* Count parameters at the caller.  */
14102
14103   nparams = 0;
14104   for (child_die = die->child; child_die && child_die->tag;
14105        child_die = sibling_die (child_die))
14106     {
14107       if (child_die->tag != DW_TAG_call_site_parameter
14108           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14109         {
14110           complaint (&symfile_complaints,
14111                      _("Tag %d is not DW_TAG_call_site_parameter in "
14112                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14113                      child_die->tag, to_underlying (child_die->sect_off),
14114                      objfile_name (objfile));
14115           continue;
14116         }
14117
14118       nparams++;
14119     }
14120
14121   call_site
14122     = ((struct call_site *)
14123        obstack_alloc (&objfile->objfile_obstack,
14124                       sizeof (*call_site)
14125                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14126   *slot = call_site;
14127   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14128   call_site->pc = pc;
14129
14130   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14131       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14132     {
14133       struct die_info *func_die;
14134
14135       /* Skip also over DW_TAG_inlined_subroutine.  */
14136       for (func_die = die->parent;
14137            func_die && func_die->tag != DW_TAG_subprogram
14138            && func_die->tag != DW_TAG_subroutine_type;
14139            func_die = func_die->parent);
14140
14141       /* DW_AT_call_all_calls is a superset
14142          of DW_AT_call_all_tail_calls.  */
14143       if (func_die
14144           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14145           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14146           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14147           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14148         {
14149           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14150              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14151              both the initial caller containing the real return address PC and
14152              the final callee containing the current PC of a chain of tail
14153              calls do not need to have the tail call list complete.  But any
14154              function candidate for a virtual tail call frame searched via
14155              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14156              determined unambiguously.  */
14157         }
14158       else
14159         {
14160           struct type *func_type = NULL;
14161
14162           if (func_die)
14163             func_type = get_die_type (func_die, cu);
14164           if (func_type != NULL)
14165             {
14166               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14167
14168               /* Enlist this call site to the function.  */
14169               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14170               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14171             }
14172           else
14173             complaint (&symfile_complaints,
14174                        _("Cannot find function owning DW_TAG_call_site "
14175                          "DIE 0x%x [in module %s]"),
14176                        to_underlying (die->sect_off), objfile_name (objfile));
14177         }
14178     }
14179
14180   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14181   if (attr == NULL)
14182     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14183   if (attr == NULL)
14184     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14185   if (attr == NULL)
14186     {
14187       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14188       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14189     }
14190   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14191   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14192     /* Keep NULL DWARF_BLOCK.  */;
14193   else if (attr_form_is_block (attr))
14194     {
14195       struct dwarf2_locexpr_baton *dlbaton;
14196
14197       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14198       dlbaton->data = DW_BLOCK (attr)->data;
14199       dlbaton->size = DW_BLOCK (attr)->size;
14200       dlbaton->per_cu = cu->per_cu;
14201
14202       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14203     }
14204   else if (attr_form_is_ref (attr))
14205     {
14206       struct dwarf2_cu *target_cu = cu;
14207       struct die_info *target_die;
14208
14209       target_die = follow_die_ref (die, attr, &target_cu);
14210       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14211       if (die_is_declaration (target_die, target_cu))
14212         {
14213           const char *target_physname;
14214
14215           /* Prefer the mangled name; otherwise compute the demangled one.  */
14216           target_physname = dw2_linkage_name (target_die, target_cu);
14217           if (target_physname == NULL)
14218             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14219           if (target_physname == NULL)
14220             complaint (&symfile_complaints,
14221                        _("DW_AT_call_target target DIE has invalid "
14222                          "physname, for referencing DIE 0x%x [in module %s]"),
14223                        to_underlying (die->sect_off), objfile_name (objfile));
14224           else
14225             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14226         }
14227       else
14228         {
14229           CORE_ADDR lowpc;
14230
14231           /* DW_AT_entry_pc should be preferred.  */
14232           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14233               <= PC_BOUNDS_INVALID)
14234             complaint (&symfile_complaints,
14235                        _("DW_AT_call_target target DIE has invalid "
14236                          "low pc, for referencing DIE 0x%x [in module %s]"),
14237                        to_underlying (die->sect_off), objfile_name (objfile));
14238           else
14239             {
14240               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14241               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14242             }
14243         }
14244     }
14245   else
14246     complaint (&symfile_complaints,
14247                _("DW_TAG_call_site DW_AT_call_target is neither "
14248                  "block nor reference, for DIE 0x%x [in module %s]"),
14249                to_underlying (die->sect_off), objfile_name (objfile));
14250
14251   call_site->per_cu = cu->per_cu;
14252
14253   for (child_die = die->child;
14254        child_die && child_die->tag;
14255        child_die = sibling_die (child_die))
14256     {
14257       struct call_site_parameter *parameter;
14258       struct attribute *loc, *origin;
14259
14260       if (child_die->tag != DW_TAG_call_site_parameter
14261           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14262         {
14263           /* Already printed the complaint above.  */
14264           continue;
14265         }
14266
14267       gdb_assert (call_site->parameter_count < nparams);
14268       parameter = &call_site->parameter[call_site->parameter_count];
14269
14270       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14271          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14272          register is contained in DW_AT_call_value.  */
14273
14274       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14275       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14276       if (origin == NULL)
14277         {
14278           /* This was a pre-DWARF-5 GNU extension alias
14279              for DW_AT_call_parameter.  */
14280           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14281         }
14282       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14283         {
14284           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14285
14286           sect_offset sect_off
14287             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14288           if (!offset_in_cu_p (&cu->header, sect_off))
14289             {
14290               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14291                  binding can be done only inside one CU.  Such referenced DIE
14292                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14293               complaint (&symfile_complaints,
14294                          _("DW_AT_call_parameter offset is not in CU for "
14295                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14296                          to_underlying (child_die->sect_off),
14297                          objfile_name (objfile));
14298               continue;
14299             }
14300           parameter->u.param_cu_off
14301             = (cu_offset) (sect_off - cu->header.sect_off);
14302         }
14303       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14304         {
14305           complaint (&symfile_complaints,
14306                      _("No DW_FORM_block* DW_AT_location for "
14307                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14308                      to_underlying (child_die->sect_off), objfile_name (objfile));
14309           continue;
14310         }
14311       else
14312         {
14313           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14314             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14315           if (parameter->u.dwarf_reg != -1)
14316             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14317           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14318                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14319                                              &parameter->u.fb_offset))
14320             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14321           else
14322             {
14323               complaint (&symfile_complaints,
14324                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14325                            "for DW_FORM_block* DW_AT_location is supported for "
14326                            "DW_TAG_call_site child DIE 0x%x "
14327                            "[in module %s]"),
14328                          to_underlying (child_die->sect_off),
14329                          objfile_name (objfile));
14330               continue;
14331             }
14332         }
14333
14334       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14335       if (attr == NULL)
14336         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14337       if (!attr_form_is_block (attr))
14338         {
14339           complaint (&symfile_complaints,
14340                      _("No DW_FORM_block* DW_AT_call_value for "
14341                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14342                      to_underlying (child_die->sect_off),
14343                      objfile_name (objfile));
14344           continue;
14345         }
14346       parameter->value = DW_BLOCK (attr)->data;
14347       parameter->value_size = DW_BLOCK (attr)->size;
14348
14349       /* Parameters are not pre-cleared by memset above.  */
14350       parameter->data_value = NULL;
14351       parameter->data_value_size = 0;
14352       call_site->parameter_count++;
14353
14354       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14355       if (attr == NULL)
14356         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14357       if (attr)
14358         {
14359           if (!attr_form_is_block (attr))
14360             complaint (&symfile_complaints,
14361                        _("No DW_FORM_block* DW_AT_call_data_value for "
14362                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14363                        to_underlying (child_die->sect_off),
14364                        objfile_name (objfile));
14365           else
14366             {
14367               parameter->data_value = DW_BLOCK (attr)->data;
14368               parameter->data_value_size = DW_BLOCK (attr)->size;
14369             }
14370         }
14371     }
14372 }
14373
14374 /* Helper function for read_variable.  If DIE represents a virtual
14375    table, then return the type of the concrete object that is
14376    associated with the virtual table.  Otherwise, return NULL.  */
14377
14378 static struct type *
14379 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14380 {
14381   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14382   if (attr == NULL)
14383     return NULL;
14384
14385   /* Find the type DIE.  */
14386   struct die_info *type_die = NULL;
14387   struct dwarf2_cu *type_cu = cu;
14388
14389   if (attr_form_is_ref (attr))
14390     type_die = follow_die_ref (die, attr, &type_cu);
14391   if (type_die == NULL)
14392     return NULL;
14393
14394   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14395     return NULL;
14396   return die_containing_type (type_die, type_cu);
14397 }
14398
14399 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14400
14401 static void
14402 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14403 {
14404   struct rust_vtable_symbol *storage = NULL;
14405
14406   if (cu->language == language_rust)
14407     {
14408       struct type *containing_type = rust_containing_type (die, cu);
14409
14410       if (containing_type != NULL)
14411         {
14412           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14413
14414           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14415                                     struct rust_vtable_symbol);
14416           initialize_objfile_symbol (storage);
14417           storage->concrete_type = containing_type;
14418           storage->subclass = SYMBOL_RUST_VTABLE;
14419         }
14420     }
14421
14422   new_symbol (die, NULL, cu, storage);
14423 }
14424
14425 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14426    reading .debug_rnglists.
14427    Callback's type should be:
14428     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14429    Return true if the attributes are present and valid, otherwise,
14430    return false.  */
14431
14432 template <typename Callback>
14433 static bool
14434 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14435                          Callback &&callback)
14436 {
14437   struct dwarf2_per_objfile *dwarf2_per_objfile
14438     = cu->per_cu->dwarf2_per_objfile;
14439   struct objfile *objfile = dwarf2_per_objfile->objfile;
14440   bfd *obfd = objfile->obfd;
14441   /* Base address selection entry.  */
14442   CORE_ADDR base;
14443   int found_base;
14444   const gdb_byte *buffer;
14445   CORE_ADDR baseaddr;
14446   bool overflow = false;
14447
14448   found_base = cu->base_known;
14449   base = cu->base_address;
14450
14451   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14452   if (offset >= dwarf2_per_objfile->rnglists.size)
14453     {
14454       complaint (&symfile_complaints,
14455                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14456                  offset);
14457       return false;
14458     }
14459   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14460
14461   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14462
14463   while (1)
14464     {
14465       /* Initialize it due to a false compiler warning.  */
14466       CORE_ADDR range_beginning = 0, range_end = 0;
14467       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14468                                  + dwarf2_per_objfile->rnglists.size);
14469       unsigned int bytes_read;
14470
14471       if (buffer == buf_end)
14472         {
14473           overflow = true;
14474           break;
14475         }
14476       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14477       switch (rlet)
14478         {
14479         case DW_RLE_end_of_list:
14480           break;
14481         case DW_RLE_base_address:
14482           if (buffer + cu->header.addr_size > buf_end)
14483             {
14484               overflow = true;
14485               break;
14486             }
14487           base = read_address (obfd, buffer, cu, &bytes_read);
14488           found_base = 1;
14489           buffer += bytes_read;
14490           break;
14491         case DW_RLE_start_length:
14492           if (buffer + cu->header.addr_size > buf_end)
14493             {
14494               overflow = true;
14495               break;
14496             }
14497           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14498           buffer += bytes_read;
14499           range_end = (range_beginning
14500                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14501           buffer += bytes_read;
14502           if (buffer > buf_end)
14503             {
14504               overflow = true;
14505               break;
14506             }
14507           break;
14508         case DW_RLE_offset_pair:
14509           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14510           buffer += bytes_read;
14511           if (buffer > buf_end)
14512             {
14513               overflow = true;
14514               break;
14515             }
14516           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14517           buffer += bytes_read;
14518           if (buffer > buf_end)
14519             {
14520               overflow = true;
14521               break;
14522             }
14523           break;
14524         case DW_RLE_start_end:
14525           if (buffer + 2 * cu->header.addr_size > buf_end)
14526             {
14527               overflow = true;
14528               break;
14529             }
14530           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14531           buffer += bytes_read;
14532           range_end = read_address (obfd, buffer, cu, &bytes_read);
14533           buffer += bytes_read;
14534           break;
14535         default:
14536           complaint (&symfile_complaints,
14537                      _("Invalid .debug_rnglists data (no base address)"));
14538           return false;
14539         }
14540       if (rlet == DW_RLE_end_of_list || overflow)
14541         break;
14542       if (rlet == DW_RLE_base_address)
14543         continue;
14544
14545       if (!found_base)
14546         {
14547           /* We have no valid base address for the ranges
14548              data.  */
14549           complaint (&symfile_complaints,
14550                      _("Invalid .debug_rnglists data (no base address)"));
14551           return false;
14552         }
14553
14554       if (range_beginning > range_end)
14555         {
14556           /* Inverted range entries are invalid.  */
14557           complaint (&symfile_complaints,
14558                      _("Invalid .debug_rnglists data (inverted range)"));
14559           return false;
14560         }
14561
14562       /* Empty range entries have no effect.  */
14563       if (range_beginning == range_end)
14564         continue;
14565
14566       range_beginning += base;
14567       range_end += base;
14568
14569       /* A not-uncommon case of bad debug info.
14570          Don't pollute the addrmap with bad data.  */
14571       if (range_beginning + baseaddr == 0
14572           && !dwarf2_per_objfile->has_section_at_zero)
14573         {
14574           complaint (&symfile_complaints,
14575                      _(".debug_rnglists entry has start address of zero"
14576                        " [in module %s]"), objfile_name (objfile));
14577           continue;
14578         }
14579
14580       callback (range_beginning, range_end);
14581     }
14582
14583   if (overflow)
14584     {
14585       complaint (&symfile_complaints,
14586                  _("Offset %d is not terminated "
14587                    "for DW_AT_ranges attribute"),
14588                  offset);
14589       return false;
14590     }
14591
14592   return true;
14593 }
14594
14595 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14596    Callback's type should be:
14597     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14598    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14599
14600 template <typename Callback>
14601 static int
14602 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14603                        Callback &&callback)
14604 {
14605   struct dwarf2_per_objfile *dwarf2_per_objfile
14606       = cu->per_cu->dwarf2_per_objfile;
14607   struct objfile *objfile = dwarf2_per_objfile->objfile;
14608   struct comp_unit_head *cu_header = &cu->header;
14609   bfd *obfd = objfile->obfd;
14610   unsigned int addr_size = cu_header->addr_size;
14611   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14612   /* Base address selection entry.  */
14613   CORE_ADDR base;
14614   int found_base;
14615   unsigned int dummy;
14616   const gdb_byte *buffer;
14617   CORE_ADDR baseaddr;
14618
14619   if (cu_header->version >= 5)
14620     return dwarf2_rnglists_process (offset, cu, callback);
14621
14622   found_base = cu->base_known;
14623   base = cu->base_address;
14624
14625   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14626   if (offset >= dwarf2_per_objfile->ranges.size)
14627     {
14628       complaint (&symfile_complaints,
14629                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14630                  offset);
14631       return 0;
14632     }
14633   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14634
14635   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14636
14637   while (1)
14638     {
14639       CORE_ADDR range_beginning, range_end;
14640
14641       range_beginning = read_address (obfd, buffer, cu, &dummy);
14642       buffer += addr_size;
14643       range_end = read_address (obfd, buffer, cu, &dummy);
14644       buffer += addr_size;
14645       offset += 2 * addr_size;
14646
14647       /* An end of list marker is a pair of zero addresses.  */
14648       if (range_beginning == 0 && range_end == 0)
14649         /* Found the end of list entry.  */
14650         break;
14651
14652       /* Each base address selection entry is a pair of 2 values.
14653          The first is the largest possible address, the second is
14654          the base address.  Check for a base address here.  */
14655       if ((range_beginning & mask) == mask)
14656         {
14657           /* If we found the largest possible address, then we already
14658              have the base address in range_end.  */
14659           base = range_end;
14660           found_base = 1;
14661           continue;
14662         }
14663
14664       if (!found_base)
14665         {
14666           /* We have no valid base address for the ranges
14667              data.  */
14668           complaint (&symfile_complaints,
14669                      _("Invalid .debug_ranges data (no base address)"));
14670           return 0;
14671         }
14672
14673       if (range_beginning > range_end)
14674         {
14675           /* Inverted range entries are invalid.  */
14676           complaint (&symfile_complaints,
14677                      _("Invalid .debug_ranges data (inverted range)"));
14678           return 0;
14679         }
14680
14681       /* Empty range entries have no effect.  */
14682       if (range_beginning == range_end)
14683         continue;
14684
14685       range_beginning += base;
14686       range_end += base;
14687
14688       /* A not-uncommon case of bad debug info.
14689          Don't pollute the addrmap with bad data.  */
14690       if (range_beginning + baseaddr == 0
14691           && !dwarf2_per_objfile->has_section_at_zero)
14692         {
14693           complaint (&symfile_complaints,
14694                      _(".debug_ranges entry has start address of zero"
14695                        " [in module %s]"), objfile_name (objfile));
14696           continue;
14697         }
14698
14699       callback (range_beginning, range_end);
14700     }
14701
14702   return 1;
14703 }
14704
14705 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14706    Return 1 if the attributes are present and valid, otherwise, return 0.
14707    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14708
14709 static int
14710 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14711                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14712                     struct partial_symtab *ranges_pst)
14713 {
14714   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14715   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14716   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14717                                        SECT_OFF_TEXT (objfile));
14718   int low_set = 0;
14719   CORE_ADDR low = 0;
14720   CORE_ADDR high = 0;
14721   int retval;
14722
14723   retval = dwarf2_ranges_process (offset, cu,
14724     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14725     {
14726       if (ranges_pst != NULL)
14727         {
14728           CORE_ADDR lowpc;
14729           CORE_ADDR highpc;
14730
14731           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14732                                               range_beginning + baseaddr);
14733           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14734                                                range_end + baseaddr);
14735           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14736                              ranges_pst);
14737         }
14738
14739       /* FIXME: This is recording everything as a low-high
14740          segment of consecutive addresses.  We should have a
14741          data structure for discontiguous block ranges
14742          instead.  */
14743       if (! low_set)
14744         {
14745           low = range_beginning;
14746           high = range_end;
14747           low_set = 1;
14748         }
14749       else
14750         {
14751           if (range_beginning < low)
14752             low = range_beginning;
14753           if (range_end > high)
14754             high = range_end;
14755         }
14756     });
14757   if (!retval)
14758     return 0;
14759
14760   if (! low_set)
14761     /* If the first entry is an end-of-list marker, the range
14762        describes an empty scope, i.e. no instructions.  */
14763     return 0;
14764
14765   if (low_return)
14766     *low_return = low;
14767   if (high_return)
14768     *high_return = high;
14769   return 1;
14770 }
14771
14772 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14773    definition for the return value.  *LOWPC and *HIGHPC are set iff
14774    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14775
14776 static enum pc_bounds_kind
14777 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14778                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14779                       struct partial_symtab *pst)
14780 {
14781   struct dwarf2_per_objfile *dwarf2_per_objfile
14782     = cu->per_cu->dwarf2_per_objfile;
14783   struct attribute *attr;
14784   struct attribute *attr_high;
14785   CORE_ADDR low = 0;
14786   CORE_ADDR high = 0;
14787   enum pc_bounds_kind ret;
14788
14789   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14790   if (attr_high)
14791     {
14792       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14793       if (attr)
14794         {
14795           low = attr_value_as_address (attr);
14796           high = attr_value_as_address (attr_high);
14797           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14798             high += low;
14799         }
14800       else
14801         /* Found high w/o low attribute.  */
14802         return PC_BOUNDS_INVALID;
14803
14804       /* Found consecutive range of addresses.  */
14805       ret = PC_BOUNDS_HIGH_LOW;
14806     }
14807   else
14808     {
14809       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14810       if (attr != NULL)
14811         {
14812           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14813              We take advantage of the fact that DW_AT_ranges does not appear
14814              in DW_TAG_compile_unit of DWO files.  */
14815           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14816           unsigned int ranges_offset = (DW_UNSND (attr)
14817                                         + (need_ranges_base
14818                                            ? cu->ranges_base
14819                                            : 0));
14820
14821           /* Value of the DW_AT_ranges attribute is the offset in the
14822              .debug_ranges section.  */
14823           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14824             return PC_BOUNDS_INVALID;
14825           /* Found discontinuous range of addresses.  */
14826           ret = PC_BOUNDS_RANGES;
14827         }
14828       else
14829         return PC_BOUNDS_NOT_PRESENT;
14830     }
14831
14832   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14833   if (high <= low)
14834     return PC_BOUNDS_INVALID;
14835
14836   /* When using the GNU linker, .gnu.linkonce. sections are used to
14837      eliminate duplicate copies of functions and vtables and such.
14838      The linker will arbitrarily choose one and discard the others.
14839      The AT_*_pc values for such functions refer to local labels in
14840      these sections.  If the section from that file was discarded, the
14841      labels are not in the output, so the relocs get a value of 0.
14842      If this is a discarded function, mark the pc bounds as invalid,
14843      so that GDB will ignore it.  */
14844   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14845     return PC_BOUNDS_INVALID;
14846
14847   *lowpc = low;
14848   if (highpc)
14849     *highpc = high;
14850   return ret;
14851 }
14852
14853 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14854    its low and high PC addresses.  Do nothing if these addresses could not
14855    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14856    and HIGHPC to the high address if greater than HIGHPC.  */
14857
14858 static void
14859 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14860                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14861                                  struct dwarf2_cu *cu)
14862 {
14863   CORE_ADDR low, high;
14864   struct die_info *child = die->child;
14865
14866   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14867     {
14868       *lowpc = std::min (*lowpc, low);
14869       *highpc = std::max (*highpc, high);
14870     }
14871
14872   /* If the language does not allow nested subprograms (either inside
14873      subprograms or lexical blocks), we're done.  */
14874   if (cu->language != language_ada)
14875     return;
14876
14877   /* Check all the children of the given DIE.  If it contains nested
14878      subprograms, then check their pc bounds.  Likewise, we need to
14879      check lexical blocks as well, as they may also contain subprogram
14880      definitions.  */
14881   while (child && child->tag)
14882     {
14883       if (child->tag == DW_TAG_subprogram
14884           || child->tag == DW_TAG_lexical_block)
14885         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14886       child = sibling_die (child);
14887     }
14888 }
14889
14890 /* Get the low and high pc's represented by the scope DIE, and store
14891    them in *LOWPC and *HIGHPC.  If the correct values can't be
14892    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14893
14894 static void
14895 get_scope_pc_bounds (struct die_info *die,
14896                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14897                      struct dwarf2_cu *cu)
14898 {
14899   CORE_ADDR best_low = (CORE_ADDR) -1;
14900   CORE_ADDR best_high = (CORE_ADDR) 0;
14901   CORE_ADDR current_low, current_high;
14902
14903   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14904       >= PC_BOUNDS_RANGES)
14905     {
14906       best_low = current_low;
14907       best_high = current_high;
14908     }
14909   else
14910     {
14911       struct die_info *child = die->child;
14912
14913       while (child && child->tag)
14914         {
14915           switch (child->tag) {
14916           case DW_TAG_subprogram:
14917             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14918             break;
14919           case DW_TAG_namespace:
14920           case DW_TAG_module:
14921             /* FIXME: carlton/2004-01-16: Should we do this for
14922                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14923                that current GCC's always emit the DIEs corresponding
14924                to definitions of methods of classes as children of a
14925                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14926                the DIEs giving the declarations, which could be
14927                anywhere).  But I don't see any reason why the
14928                standards says that they have to be there.  */
14929             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14930
14931             if (current_low != ((CORE_ADDR) -1))
14932               {
14933                 best_low = std::min (best_low, current_low);
14934                 best_high = std::max (best_high, current_high);
14935               }
14936             break;
14937           default:
14938             /* Ignore.  */
14939             break;
14940           }
14941
14942           child = sibling_die (child);
14943         }
14944     }
14945
14946   *lowpc = best_low;
14947   *highpc = best_high;
14948 }
14949
14950 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14951    in DIE.  */
14952
14953 static void
14954 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14955                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14956 {
14957   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14958   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14959   struct attribute *attr;
14960   struct attribute *attr_high;
14961
14962   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14963   if (attr_high)
14964     {
14965       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14966       if (attr)
14967         {
14968           CORE_ADDR low = attr_value_as_address (attr);
14969           CORE_ADDR high = attr_value_as_address (attr_high);
14970
14971           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14972             high += low;
14973
14974           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14975           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14976           record_block_range (block, low, high - 1);
14977         }
14978     }
14979
14980   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14981   if (attr)
14982     {
14983       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14984          We take advantage of the fact that DW_AT_ranges does not appear
14985          in DW_TAG_compile_unit of DWO files.  */
14986       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14987
14988       /* The value of the DW_AT_ranges attribute is the offset of the
14989          address range list in the .debug_ranges section.  */
14990       unsigned long offset = (DW_UNSND (attr)
14991                               + (need_ranges_base ? cu->ranges_base : 0));
14992       const gdb_byte *buffer;
14993
14994       /* For some target architectures, but not others, the
14995          read_address function sign-extends the addresses it returns.
14996          To recognize base address selection entries, we need a
14997          mask.  */
14998       unsigned int addr_size = cu->header.addr_size;
14999       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15000
15001       /* The base address, to which the next pair is relative.  Note
15002          that this 'base' is a DWARF concept: most entries in a range
15003          list are relative, to reduce the number of relocs against the
15004          debugging information.  This is separate from this function's
15005          'baseaddr' argument, which GDB uses to relocate debugging
15006          information from a shared library based on the address at
15007          which the library was loaded.  */
15008       CORE_ADDR base = cu->base_address;
15009       int base_known = cu->base_known;
15010
15011       dwarf2_ranges_process (offset, cu,
15012         [&] (CORE_ADDR start, CORE_ADDR end)
15013         {
15014           start += baseaddr;
15015           end += baseaddr;
15016           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15017           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15018           record_block_range (block, start, end - 1);
15019         });
15020     }
15021 }
15022
15023 /* Check whether the producer field indicates either of GCC < 4.6, or the
15024    Intel C/C++ compiler, and cache the result in CU.  */
15025
15026 static void
15027 check_producer (struct dwarf2_cu *cu)
15028 {
15029   int major, minor;
15030
15031   if (cu->producer == NULL)
15032     {
15033       /* For unknown compilers expect their behavior is DWARF version
15034          compliant.
15035
15036          GCC started to support .debug_types sections by -gdwarf-4 since
15037          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15038          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15039          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15040          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15041     }
15042   else if (producer_is_gcc (cu->producer, &major, &minor))
15043     {
15044       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15045       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15046     }
15047   else if (producer_is_icc (cu->producer, &major, &minor))
15048     cu->producer_is_icc_lt_14 = major < 14;
15049   else
15050     {
15051       /* For other non-GCC compilers, expect their behavior is DWARF version
15052          compliant.  */
15053     }
15054
15055   cu->checked_producer = 1;
15056 }
15057
15058 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15059    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15060    during 4.6.0 experimental.  */
15061
15062 static int
15063 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15064 {
15065   if (!cu->checked_producer)
15066     check_producer (cu);
15067
15068   return cu->producer_is_gxx_lt_4_6;
15069 }
15070
15071 /* Return the default accessibility type if it is not overriden by
15072    DW_AT_accessibility.  */
15073
15074 static enum dwarf_access_attribute
15075 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15076 {
15077   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15078     {
15079       /* The default DWARF 2 accessibility for members is public, the default
15080          accessibility for inheritance is private.  */
15081
15082       if (die->tag != DW_TAG_inheritance)
15083         return DW_ACCESS_public;
15084       else
15085         return DW_ACCESS_private;
15086     }
15087   else
15088     {
15089       /* DWARF 3+ defines the default accessibility a different way.  The same
15090          rules apply now for DW_TAG_inheritance as for the members and it only
15091          depends on the container kind.  */
15092
15093       if (die->parent->tag == DW_TAG_class_type)
15094         return DW_ACCESS_private;
15095       else
15096         return DW_ACCESS_public;
15097     }
15098 }
15099
15100 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15101    offset.  If the attribute was not found return 0, otherwise return
15102    1.  If it was found but could not properly be handled, set *OFFSET
15103    to 0.  */
15104
15105 static int
15106 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15107                              LONGEST *offset)
15108 {
15109   struct attribute *attr;
15110
15111   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15112   if (attr != NULL)
15113     {
15114       *offset = 0;
15115
15116       /* Note that we do not check for a section offset first here.
15117          This is because DW_AT_data_member_location is new in DWARF 4,
15118          so if we see it, we can assume that a constant form is really
15119          a constant and not a section offset.  */
15120       if (attr_form_is_constant (attr))
15121         *offset = dwarf2_get_attr_constant_value (attr, 0);
15122       else if (attr_form_is_section_offset (attr))
15123         dwarf2_complex_location_expr_complaint ();
15124       else if (attr_form_is_block (attr))
15125         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15126       else
15127         dwarf2_complex_location_expr_complaint ();
15128
15129       return 1;
15130     }
15131
15132   return 0;
15133 }
15134
15135 /* Add an aggregate field to the field list.  */
15136
15137 static void
15138 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15139                   struct dwarf2_cu *cu)
15140 {
15141   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15142   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15143   struct nextfield *new_field;
15144   struct attribute *attr;
15145   struct field *fp;
15146   const char *fieldname = "";
15147
15148   /* Allocate a new field list entry and link it in.  */
15149   new_field = XNEW (struct nextfield);
15150   make_cleanup (xfree, new_field);
15151   memset (new_field, 0, sizeof (struct nextfield));
15152
15153   if (die->tag == DW_TAG_inheritance)
15154     {
15155       new_field->next = fip->baseclasses;
15156       fip->baseclasses = new_field;
15157     }
15158   else
15159     {
15160       new_field->next = fip->fields;
15161       fip->fields = new_field;
15162     }
15163   fip->nfields++;
15164
15165   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15166   if (attr)
15167     new_field->accessibility = DW_UNSND (attr);
15168   else
15169     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15170   if (new_field->accessibility != DW_ACCESS_public)
15171     fip->non_public_fields = 1;
15172
15173   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15174   if (attr)
15175     new_field->virtuality = DW_UNSND (attr);
15176   else
15177     new_field->virtuality = DW_VIRTUALITY_none;
15178
15179   fp = &new_field->field;
15180
15181   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15182     {
15183       LONGEST offset;
15184
15185       /* Data member other than a C++ static data member.  */
15186
15187       /* Get type of field.  */
15188       fp->type = die_type (die, cu);
15189
15190       SET_FIELD_BITPOS (*fp, 0);
15191
15192       /* Get bit size of field (zero if none).  */
15193       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15194       if (attr)
15195         {
15196           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15197         }
15198       else
15199         {
15200           FIELD_BITSIZE (*fp) = 0;
15201         }
15202
15203       /* Get bit offset of field.  */
15204       if (handle_data_member_location (die, cu, &offset))
15205         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15206       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15207       if (attr)
15208         {
15209           if (gdbarch_bits_big_endian (gdbarch))
15210             {
15211               /* For big endian bits, the DW_AT_bit_offset gives the
15212                  additional bit offset from the MSB of the containing
15213                  anonymous object to the MSB of the field.  We don't
15214                  have to do anything special since we don't need to
15215                  know the size of the anonymous object.  */
15216               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15217             }
15218           else
15219             {
15220               /* For little endian bits, compute the bit offset to the
15221                  MSB of the anonymous object, subtract off the number of
15222                  bits from the MSB of the field to the MSB of the
15223                  object, and then subtract off the number of bits of
15224                  the field itself.  The result is the bit offset of
15225                  the LSB of the field.  */
15226               int anonymous_size;
15227               int bit_offset = DW_UNSND (attr);
15228
15229               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15230               if (attr)
15231                 {
15232                   /* The size of the anonymous object containing
15233                      the bit field is explicit, so use the
15234                      indicated size (in bytes).  */
15235                   anonymous_size = DW_UNSND (attr);
15236                 }
15237               else
15238                 {
15239                   /* The size of the anonymous object containing
15240                      the bit field must be inferred from the type
15241                      attribute of the data member containing the
15242                      bit field.  */
15243                   anonymous_size = TYPE_LENGTH (fp->type);
15244                 }
15245               SET_FIELD_BITPOS (*fp,
15246                                 (FIELD_BITPOS (*fp)
15247                                  + anonymous_size * bits_per_byte
15248                                  - bit_offset - FIELD_BITSIZE (*fp)));
15249             }
15250         }
15251       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15252       if (attr != NULL)
15253         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15254                                 + dwarf2_get_attr_constant_value (attr, 0)));
15255
15256       /* Get name of field.  */
15257       fieldname = dwarf2_name (die, cu);
15258       if (fieldname == NULL)
15259         fieldname = "";
15260
15261       /* The name is already allocated along with this objfile, so we don't
15262          need to duplicate it for the type.  */
15263       fp->name = fieldname;
15264
15265       /* Change accessibility for artificial fields (e.g. virtual table
15266          pointer or virtual base class pointer) to private.  */
15267       if (dwarf2_attr (die, DW_AT_artificial, cu))
15268         {
15269           FIELD_ARTIFICIAL (*fp) = 1;
15270           new_field->accessibility = DW_ACCESS_private;
15271           fip->non_public_fields = 1;
15272         }
15273     }
15274   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15275     {
15276       /* C++ static member.  */
15277
15278       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15279          is a declaration, but all versions of G++ as of this writing
15280          (so through at least 3.2.1) incorrectly generate
15281          DW_TAG_variable tags.  */
15282
15283       const char *physname;
15284
15285       /* Get name of field.  */
15286       fieldname = dwarf2_name (die, cu);
15287       if (fieldname == NULL)
15288         return;
15289
15290       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15291       if (attr
15292           /* Only create a symbol if this is an external value.
15293              new_symbol checks this and puts the value in the global symbol
15294              table, which we want.  If it is not external, new_symbol
15295              will try to put the value in cu->list_in_scope which is wrong.  */
15296           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15297         {
15298           /* A static const member, not much different than an enum as far as
15299              we're concerned, except that we can support more types.  */
15300           new_symbol (die, NULL, cu);
15301         }
15302
15303       /* Get physical name.  */
15304       physname = dwarf2_physname (fieldname, die, cu);
15305
15306       /* The name is already allocated along with this objfile, so we don't
15307          need to duplicate it for the type.  */
15308       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15309       FIELD_TYPE (*fp) = die_type (die, cu);
15310       FIELD_NAME (*fp) = fieldname;
15311     }
15312   else if (die->tag == DW_TAG_inheritance)
15313     {
15314       LONGEST offset;
15315
15316       /* C++ base class field.  */
15317       if (handle_data_member_location (die, cu, &offset))
15318         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15319       FIELD_BITSIZE (*fp) = 0;
15320       FIELD_TYPE (*fp) = die_type (die, cu);
15321       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15322       fip->nbaseclasses++;
15323     }
15324 }
15325
15326 /* Can the type given by DIE define another type?  */
15327
15328 static bool
15329 type_can_define_types (const struct die_info *die)
15330 {
15331   switch (die->tag)
15332     {
15333     case DW_TAG_typedef:
15334     case DW_TAG_class_type:
15335     case DW_TAG_structure_type:
15336     case DW_TAG_union_type:
15337     case DW_TAG_enumeration_type:
15338       return true;
15339
15340     default:
15341       return false;
15342     }
15343 }
15344
15345 /* Add a type definition defined in the scope of the FIP's class.  */
15346
15347 static void
15348 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15349                       struct dwarf2_cu *cu)
15350 {
15351   struct decl_field_list *new_field;
15352   struct decl_field *fp;
15353
15354   /* Allocate a new field list entry and link it in.  */
15355   new_field = XCNEW (struct decl_field_list);
15356   make_cleanup (xfree, new_field);
15357
15358   gdb_assert (type_can_define_types (die));
15359
15360   fp = &new_field->field;
15361
15362   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15363   fp->name = dwarf2_name (die, cu);
15364   fp->type = read_type_die (die, cu);
15365
15366   /* Save accessibility.  */
15367   enum dwarf_access_attribute accessibility;
15368   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15369   if (attr != NULL)
15370     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15371   else
15372     accessibility = dwarf2_default_access_attribute (die, cu);
15373   switch (accessibility)
15374     {
15375     case DW_ACCESS_public:
15376       /* The assumed value if neither private nor protected.  */
15377       break;
15378     case DW_ACCESS_private:
15379       fp->is_private = 1;
15380       break;
15381     case DW_ACCESS_protected:
15382       fp->is_protected = 1;
15383       break;
15384     default:
15385       complaint (&symfile_complaints,
15386                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15387     }
15388
15389   if (die->tag == DW_TAG_typedef)
15390     {
15391       new_field->next = fip->typedef_field_list;
15392       fip->typedef_field_list = new_field;
15393       fip->typedef_field_list_count++;
15394     }
15395   else
15396     {
15397       new_field->next = fip->nested_types_list;
15398       fip->nested_types_list = new_field;
15399       fip->nested_types_list_count++;
15400     }
15401 }
15402
15403 /* Create the vector of fields, and attach it to the type.  */
15404
15405 static void
15406 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15407                               struct dwarf2_cu *cu)
15408 {
15409   int nfields = fip->nfields;
15410
15411   /* Record the field count, allocate space for the array of fields,
15412      and create blank accessibility bitfields if necessary.  */
15413   TYPE_NFIELDS (type) = nfields;
15414   TYPE_FIELDS (type) = (struct field *)
15415     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15416   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15417
15418   if (fip->non_public_fields && cu->language != language_ada)
15419     {
15420       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15421
15422       TYPE_FIELD_PRIVATE_BITS (type) =
15423         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15424       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15425
15426       TYPE_FIELD_PROTECTED_BITS (type) =
15427         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15428       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15429
15430       TYPE_FIELD_IGNORE_BITS (type) =
15431         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15432       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15433     }
15434
15435   /* If the type has baseclasses, allocate and clear a bit vector for
15436      TYPE_FIELD_VIRTUAL_BITS.  */
15437   if (fip->nbaseclasses && cu->language != language_ada)
15438     {
15439       int num_bytes = B_BYTES (fip->nbaseclasses);
15440       unsigned char *pointer;
15441
15442       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15443       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15444       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15445       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15446       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15447     }
15448
15449   /* Copy the saved-up fields into the field vector.  Start from the head of
15450      the list, adding to the tail of the field array, so that they end up in
15451      the same order in the array in which they were added to the list.  */
15452   while (nfields-- > 0)
15453     {
15454       struct nextfield *fieldp;
15455
15456       if (fip->fields)
15457         {
15458           fieldp = fip->fields;
15459           fip->fields = fieldp->next;
15460         }
15461       else
15462         {
15463           fieldp = fip->baseclasses;
15464           fip->baseclasses = fieldp->next;
15465         }
15466
15467       TYPE_FIELD (type, nfields) = fieldp->field;
15468       switch (fieldp->accessibility)
15469         {
15470         case DW_ACCESS_private:
15471           if (cu->language != language_ada)
15472             SET_TYPE_FIELD_PRIVATE (type, nfields);
15473           break;
15474
15475         case DW_ACCESS_protected:
15476           if (cu->language != language_ada)
15477             SET_TYPE_FIELD_PROTECTED (type, nfields);
15478           break;
15479
15480         case DW_ACCESS_public:
15481           break;
15482
15483         default:
15484           /* Unknown accessibility.  Complain and treat it as public.  */
15485           {
15486             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15487                        fieldp->accessibility);
15488           }
15489           break;
15490         }
15491       if (nfields < fip->nbaseclasses)
15492         {
15493           switch (fieldp->virtuality)
15494             {
15495             case DW_VIRTUALITY_virtual:
15496             case DW_VIRTUALITY_pure_virtual:
15497               if (cu->language == language_ada)
15498                 error (_("unexpected virtuality in component of Ada type"));
15499               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15500               break;
15501             }
15502         }
15503     }
15504 }
15505
15506 /* Return true if this member function is a constructor, false
15507    otherwise.  */
15508
15509 static int
15510 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15511 {
15512   const char *fieldname;
15513   const char *type_name;
15514   int len;
15515
15516   if (die->parent == NULL)
15517     return 0;
15518
15519   if (die->parent->tag != DW_TAG_structure_type
15520       && die->parent->tag != DW_TAG_union_type
15521       && die->parent->tag != DW_TAG_class_type)
15522     return 0;
15523
15524   fieldname = dwarf2_name (die, cu);
15525   type_name = dwarf2_name (die->parent, cu);
15526   if (fieldname == NULL || type_name == NULL)
15527     return 0;
15528
15529   len = strlen (fieldname);
15530   return (strncmp (fieldname, type_name, len) == 0
15531           && (type_name[len] == '\0' || type_name[len] == '<'));
15532 }
15533
15534 /* Add a member function to the proper fieldlist.  */
15535
15536 static void
15537 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15538                       struct type *type, struct dwarf2_cu *cu)
15539 {
15540   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15541   struct attribute *attr;
15542   struct fnfieldlist *flp;
15543   int i;
15544   struct fn_field *fnp;
15545   const char *fieldname;
15546   struct nextfnfield *new_fnfield;
15547   struct type *this_type;
15548   enum dwarf_access_attribute accessibility;
15549
15550   if (cu->language == language_ada)
15551     error (_("unexpected member function in Ada type"));
15552
15553   /* Get name of member function.  */
15554   fieldname = dwarf2_name (die, cu);
15555   if (fieldname == NULL)
15556     return;
15557
15558   /* Look up member function name in fieldlist.  */
15559   for (i = 0; i < fip->nfnfields; i++)
15560     {
15561       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15562         break;
15563     }
15564
15565   /* Create new list element if necessary.  */
15566   if (i < fip->nfnfields)
15567     flp = &fip->fnfieldlists[i];
15568   else
15569     {
15570       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15571         {
15572           fip->fnfieldlists = (struct fnfieldlist *)
15573             xrealloc (fip->fnfieldlists,
15574                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15575                       * sizeof (struct fnfieldlist));
15576           if (fip->nfnfields == 0)
15577             make_cleanup (free_current_contents, &fip->fnfieldlists);
15578         }
15579       flp = &fip->fnfieldlists[fip->nfnfields];
15580       flp->name = fieldname;
15581       flp->length = 0;
15582       flp->head = NULL;
15583       i = fip->nfnfields++;
15584     }
15585
15586   /* Create a new member function field and chain it to the field list
15587      entry.  */
15588   new_fnfield = XNEW (struct nextfnfield);
15589   make_cleanup (xfree, new_fnfield);
15590   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15591   new_fnfield->next = flp->head;
15592   flp->head = new_fnfield;
15593   flp->length++;
15594
15595   /* Fill in the member function field info.  */
15596   fnp = &new_fnfield->fnfield;
15597
15598   /* Delay processing of the physname until later.  */
15599   if (cu->language == language_cplus)
15600     {
15601       add_to_method_list (type, i, flp->length - 1, fieldname,
15602                           die, cu);
15603     }
15604   else
15605     {
15606       const char *physname = dwarf2_physname (fieldname, die, cu);
15607       fnp->physname = physname ? physname : "";
15608     }
15609
15610   fnp->type = alloc_type (objfile);
15611   this_type = read_type_die (die, cu);
15612   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15613     {
15614       int nparams = TYPE_NFIELDS (this_type);
15615
15616       /* TYPE is the domain of this method, and THIS_TYPE is the type
15617            of the method itself (TYPE_CODE_METHOD).  */
15618       smash_to_method_type (fnp->type, type,
15619                             TYPE_TARGET_TYPE (this_type),
15620                             TYPE_FIELDS (this_type),
15621                             TYPE_NFIELDS (this_type),
15622                             TYPE_VARARGS (this_type));
15623
15624       /* Handle static member functions.
15625          Dwarf2 has no clean way to discern C++ static and non-static
15626          member functions.  G++ helps GDB by marking the first
15627          parameter for non-static member functions (which is the this
15628          pointer) as artificial.  We obtain this information from
15629          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15630       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15631         fnp->voffset = VOFFSET_STATIC;
15632     }
15633   else
15634     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15635                dwarf2_full_name (fieldname, die, cu));
15636
15637   /* Get fcontext from DW_AT_containing_type if present.  */
15638   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15639     fnp->fcontext = die_containing_type (die, cu);
15640
15641   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15642      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15643
15644   /* Get accessibility.  */
15645   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15646   if (attr)
15647     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15648   else
15649     accessibility = dwarf2_default_access_attribute (die, cu);
15650   switch (accessibility)
15651     {
15652     case DW_ACCESS_private:
15653       fnp->is_private = 1;
15654       break;
15655     case DW_ACCESS_protected:
15656       fnp->is_protected = 1;
15657       break;
15658     }
15659
15660   /* Check for artificial methods.  */
15661   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15662   if (attr && DW_UNSND (attr) != 0)
15663     fnp->is_artificial = 1;
15664
15665   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15666
15667   /* Get index in virtual function table if it is a virtual member
15668      function.  For older versions of GCC, this is an offset in the
15669      appropriate virtual table, as specified by DW_AT_containing_type.
15670      For everyone else, it is an expression to be evaluated relative
15671      to the object address.  */
15672
15673   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15674   if (attr)
15675     {
15676       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15677         {
15678           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15679             {
15680               /* Old-style GCC.  */
15681               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15682             }
15683           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15684                    || (DW_BLOCK (attr)->size > 1
15685                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15686                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15687             {
15688               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15689               if ((fnp->voffset % cu->header.addr_size) != 0)
15690                 dwarf2_complex_location_expr_complaint ();
15691               else
15692                 fnp->voffset /= cu->header.addr_size;
15693               fnp->voffset += 2;
15694             }
15695           else
15696             dwarf2_complex_location_expr_complaint ();
15697
15698           if (!fnp->fcontext)
15699             {
15700               /* If there is no `this' field and no DW_AT_containing_type,
15701                  we cannot actually find a base class context for the
15702                  vtable!  */
15703               if (TYPE_NFIELDS (this_type) == 0
15704                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15705                 {
15706                   complaint (&symfile_complaints,
15707                              _("cannot determine context for virtual member "
15708                                "function \"%s\" (offset %d)"),
15709                              fieldname, to_underlying (die->sect_off));
15710                 }
15711               else
15712                 {
15713                   fnp->fcontext
15714                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15715                 }
15716             }
15717         }
15718       else if (attr_form_is_section_offset (attr))
15719         {
15720           dwarf2_complex_location_expr_complaint ();
15721         }
15722       else
15723         {
15724           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15725                                                  fieldname);
15726         }
15727     }
15728   else
15729     {
15730       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15731       if (attr && DW_UNSND (attr))
15732         {
15733           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15734           complaint (&symfile_complaints,
15735                      _("Member function \"%s\" (offset %d) is virtual "
15736                        "but the vtable offset is not specified"),
15737                      fieldname, to_underlying (die->sect_off));
15738           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15739           TYPE_CPLUS_DYNAMIC (type) = 1;
15740         }
15741     }
15742 }
15743
15744 /* Create the vector of member function fields, and attach it to the type.  */
15745
15746 static void
15747 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15748                                  struct dwarf2_cu *cu)
15749 {
15750   struct fnfieldlist *flp;
15751   int i;
15752
15753   if (cu->language == language_ada)
15754     error (_("unexpected member functions in Ada type"));
15755
15756   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15757   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15758     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15759
15760   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15761     {
15762       struct nextfnfield *nfp = flp->head;
15763       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15764       int k;
15765
15766       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15767       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15768       fn_flp->fn_fields = (struct fn_field *)
15769         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15770       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15771         fn_flp->fn_fields[k] = nfp->fnfield;
15772     }
15773
15774   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15775 }
15776
15777 /* Returns non-zero if NAME is the name of a vtable member in CU's
15778    language, zero otherwise.  */
15779 static int
15780 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15781 {
15782   static const char vptr[] = "_vptr";
15783
15784   /* Look for the C++ form of the vtable.  */
15785   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15786     return 1;
15787
15788   return 0;
15789 }
15790
15791 /* GCC outputs unnamed structures that are really pointers to member
15792    functions, with the ABI-specified layout.  If TYPE describes
15793    such a structure, smash it into a member function type.
15794
15795    GCC shouldn't do this; it should just output pointer to member DIEs.
15796    This is GCC PR debug/28767.  */
15797
15798 static void
15799 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15800 {
15801   struct type *pfn_type, *self_type, *new_type;
15802
15803   /* Check for a structure with no name and two children.  */
15804   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15805     return;
15806
15807   /* Check for __pfn and __delta members.  */
15808   if (TYPE_FIELD_NAME (type, 0) == NULL
15809       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15810       || TYPE_FIELD_NAME (type, 1) == NULL
15811       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15812     return;
15813
15814   /* Find the type of the method.  */
15815   pfn_type = TYPE_FIELD_TYPE (type, 0);
15816   if (pfn_type == NULL
15817       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15818       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15819     return;
15820
15821   /* Look for the "this" argument.  */
15822   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15823   if (TYPE_NFIELDS (pfn_type) == 0
15824       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15825       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15826     return;
15827
15828   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15829   new_type = alloc_type (objfile);
15830   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15831                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15832                         TYPE_VARARGS (pfn_type));
15833   smash_to_methodptr_type (type, new_type);
15834 }
15835
15836
15837 /* Called when we find the DIE that starts a structure or union scope
15838    (definition) to create a type for the structure or union.  Fill in
15839    the type's name and general properties; the members will not be
15840    processed until process_structure_scope.  A symbol table entry for
15841    the type will also not be done until process_structure_scope (assuming
15842    the type has a name).
15843
15844    NOTE: we need to call these functions regardless of whether or not the
15845    DIE has a DW_AT_name attribute, since it might be an anonymous
15846    structure or union.  This gets the type entered into our set of
15847    user defined types.  */
15848
15849 static struct type *
15850 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15851 {
15852   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15853   struct type *type;
15854   struct attribute *attr;
15855   const char *name;
15856
15857   /* If the definition of this type lives in .debug_types, read that type.
15858      Don't follow DW_AT_specification though, that will take us back up
15859      the chain and we want to go down.  */
15860   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15861   if (attr)
15862     {
15863       type = get_DW_AT_signature_type (die, attr, cu);
15864
15865       /* The type's CU may not be the same as CU.
15866          Ensure TYPE is recorded with CU in die_type_hash.  */
15867       return set_die_type (die, type, cu);
15868     }
15869
15870   type = alloc_type (objfile);
15871   INIT_CPLUS_SPECIFIC (type);
15872
15873   name = dwarf2_name (die, cu);
15874   if (name != NULL)
15875     {
15876       if (cu->language == language_cplus
15877           || cu->language == language_d
15878           || cu->language == language_rust)
15879         {
15880           const char *full_name = dwarf2_full_name (name, die, cu);
15881
15882           /* dwarf2_full_name might have already finished building the DIE's
15883              type.  If so, there is no need to continue.  */
15884           if (get_die_type (die, cu) != NULL)
15885             return get_die_type (die, cu);
15886
15887           TYPE_TAG_NAME (type) = full_name;
15888           if (die->tag == DW_TAG_structure_type
15889               || die->tag == DW_TAG_class_type)
15890             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15891         }
15892       else
15893         {
15894           /* The name is already allocated along with this objfile, so
15895              we don't need to duplicate it for the type.  */
15896           TYPE_TAG_NAME (type) = name;
15897           if (die->tag == DW_TAG_class_type)
15898             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15899         }
15900     }
15901
15902   if (die->tag == DW_TAG_structure_type)
15903     {
15904       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15905     }
15906   else if (die->tag == DW_TAG_union_type)
15907     {
15908       TYPE_CODE (type) = TYPE_CODE_UNION;
15909     }
15910   else
15911     {
15912       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15913     }
15914
15915   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15916     TYPE_DECLARED_CLASS (type) = 1;
15917
15918   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15919   if (attr)
15920     {
15921       if (attr_form_is_constant (attr))
15922         TYPE_LENGTH (type) = DW_UNSND (attr);
15923       else
15924         {
15925           /* For the moment, dynamic type sizes are not supported
15926              by GDB's struct type.  The actual size is determined
15927              on-demand when resolving the type of a given object,
15928              so set the type's length to zero for now.  Otherwise,
15929              we record an expression as the length, and that expression
15930              could lead to a very large value, which could eventually
15931              lead to us trying to allocate that much memory when creating
15932              a value of that type.  */
15933           TYPE_LENGTH (type) = 0;
15934         }
15935     }
15936   else
15937     {
15938       TYPE_LENGTH (type) = 0;
15939     }
15940
15941   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15942     {
15943       /* ICC<14 does not output the required DW_AT_declaration on
15944          incomplete types, but gives them a size of zero.  */
15945       TYPE_STUB (type) = 1;
15946     }
15947   else
15948     TYPE_STUB_SUPPORTED (type) = 1;
15949
15950   if (die_is_declaration (die, cu))
15951     TYPE_STUB (type) = 1;
15952   else if (attr == NULL && die->child == NULL
15953            && producer_is_realview (cu->producer))
15954     /* RealView does not output the required DW_AT_declaration
15955        on incomplete types.  */
15956     TYPE_STUB (type) = 1;
15957
15958   /* We need to add the type field to the die immediately so we don't
15959      infinitely recurse when dealing with pointers to the structure
15960      type within the structure itself.  */
15961   set_die_type (die, type, cu);
15962
15963   /* set_die_type should be already done.  */
15964   set_descriptive_type (type, die, cu);
15965
15966   return type;
15967 }
15968
15969 /* Finish creating a structure or union type, including filling in
15970    its members and creating a symbol for it.  */
15971
15972 static void
15973 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15974 {
15975   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15976   struct die_info *child_die;
15977   struct type *type;
15978
15979   type = get_die_type (die, cu);
15980   if (type == NULL)
15981     type = read_structure_type (die, cu);
15982
15983   if (die->child != NULL && ! die_is_declaration (die, cu))
15984     {
15985       struct field_info fi;
15986       std::vector<struct symbol *> template_args;
15987       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15988
15989       memset (&fi, 0, sizeof (struct field_info));
15990
15991       child_die = die->child;
15992
15993       while (child_die && child_die->tag)
15994         {
15995           if (child_die->tag == DW_TAG_member
15996               || child_die->tag == DW_TAG_variable)
15997             {
15998               /* NOTE: carlton/2002-11-05: A C++ static data member
15999                  should be a DW_TAG_member that is a declaration, but
16000                  all versions of G++ as of this writing (so through at
16001                  least 3.2.1) incorrectly generate DW_TAG_variable
16002                  tags for them instead.  */
16003               dwarf2_add_field (&fi, child_die, cu);
16004             }
16005           else if (child_die->tag == DW_TAG_subprogram)
16006             {
16007               /* Rust doesn't have member functions in the C++ sense.
16008                  However, it does emit ordinary functions as children
16009                  of a struct DIE.  */
16010               if (cu->language == language_rust)
16011                 read_func_scope (child_die, cu);
16012               else
16013                 {
16014                   /* C++ member function.  */
16015                   dwarf2_add_member_fn (&fi, child_die, type, cu);
16016                 }
16017             }
16018           else if (child_die->tag == DW_TAG_inheritance)
16019             {
16020               /* C++ base class field.  */
16021               dwarf2_add_field (&fi, child_die, cu);
16022             }
16023           else if (type_can_define_types (child_die))
16024             dwarf2_add_type_defn (&fi, child_die, cu);
16025           else if (child_die->tag == DW_TAG_template_type_param
16026                    || child_die->tag == DW_TAG_template_value_param)
16027             {
16028               struct symbol *arg = new_symbol (child_die, NULL, cu);
16029
16030               if (arg != NULL)
16031                 template_args.push_back (arg);
16032             }
16033
16034           child_die = sibling_die (child_die);
16035         }
16036
16037       /* Attach template arguments to type.  */
16038       if (!template_args.empty ())
16039         {
16040           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16041           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16042           TYPE_TEMPLATE_ARGUMENTS (type)
16043             = XOBNEWVEC (&objfile->objfile_obstack,
16044                          struct symbol *,
16045                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16046           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16047                   template_args.data (),
16048                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16049                    * sizeof (struct symbol *)));
16050         }
16051
16052       /* Attach fields and member functions to the type.  */
16053       if (fi.nfields)
16054         dwarf2_attach_fields_to_type (&fi, type, cu);
16055       if (fi.nfnfields)
16056         {
16057           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16058
16059           /* Get the type which refers to the base class (possibly this
16060              class itself) which contains the vtable pointer for the current
16061              class from the DW_AT_containing_type attribute.  This use of
16062              DW_AT_containing_type is a GNU extension.  */
16063
16064           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16065             {
16066               struct type *t = die_containing_type (die, cu);
16067
16068               set_type_vptr_basetype (type, t);
16069               if (type == t)
16070                 {
16071                   int i;
16072
16073                   /* Our own class provides vtbl ptr.  */
16074                   for (i = TYPE_NFIELDS (t) - 1;
16075                        i >= TYPE_N_BASECLASSES (t);
16076                        --i)
16077                     {
16078                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16079
16080                       if (is_vtable_name (fieldname, cu))
16081                         {
16082                           set_type_vptr_fieldno (type, i);
16083                           break;
16084                         }
16085                     }
16086
16087                   /* Complain if virtual function table field not found.  */
16088                   if (i < TYPE_N_BASECLASSES (t))
16089                     complaint (&symfile_complaints,
16090                                _("virtual function table pointer "
16091                                  "not found when defining class '%s'"),
16092                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16093                                "");
16094                 }
16095               else
16096                 {
16097                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16098                 }
16099             }
16100           else if (cu->producer
16101                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16102             {
16103               /* The IBM XLC compiler does not provide direct indication
16104                  of the containing type, but the vtable pointer is
16105                  always named __vfp.  */
16106
16107               int i;
16108
16109               for (i = TYPE_NFIELDS (type) - 1;
16110                    i >= TYPE_N_BASECLASSES (type);
16111                    --i)
16112                 {
16113                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16114                     {
16115                       set_type_vptr_fieldno (type, i);
16116                       set_type_vptr_basetype (type, type);
16117                       break;
16118                     }
16119                 }
16120             }
16121         }
16122
16123       /* Copy fi.typedef_field_list linked list elements content into the
16124          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16125       if (fi.typedef_field_list)
16126         {
16127           int i = fi.typedef_field_list_count;
16128
16129           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16130           TYPE_TYPEDEF_FIELD_ARRAY (type)
16131             = ((struct decl_field *)
16132                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16133           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16134
16135           /* Reverse the list order to keep the debug info elements order.  */
16136           while (--i >= 0)
16137             {
16138               struct decl_field *dest, *src;
16139
16140               dest = &TYPE_TYPEDEF_FIELD (type, i);
16141               src = &fi.typedef_field_list->field;
16142               fi.typedef_field_list = fi.typedef_field_list->next;
16143               *dest = *src;
16144             }
16145         }
16146
16147       /* Copy fi.nested_types_list linked list elements content into the
16148          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16149       if (fi.nested_types_list != NULL && cu->language != language_ada)
16150         {
16151           int i = fi.nested_types_list_count;
16152
16153           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16154           TYPE_NESTED_TYPES_ARRAY (type)
16155             = ((struct decl_field *)
16156                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16157           TYPE_NESTED_TYPES_COUNT (type) = i;
16158
16159           /* Reverse the list order to keep the debug info elements order.  */
16160           while (--i >= 0)
16161             {
16162               struct decl_field *dest, *src;
16163
16164               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16165               src = &fi.nested_types_list->field;
16166               fi.nested_types_list = fi.nested_types_list->next;
16167               *dest = *src;
16168             }
16169         }
16170
16171       do_cleanups (back_to);
16172     }
16173
16174   quirk_gcc_member_function_pointer (type, objfile);
16175
16176   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16177      snapshots) has been known to create a die giving a declaration
16178      for a class that has, as a child, a die giving a definition for a
16179      nested class.  So we have to process our children even if the
16180      current die is a declaration.  Normally, of course, a declaration
16181      won't have any children at all.  */
16182
16183   child_die = die->child;
16184
16185   while (child_die != NULL && child_die->tag)
16186     {
16187       if (child_die->tag == DW_TAG_member
16188           || child_die->tag == DW_TAG_variable
16189           || child_die->tag == DW_TAG_inheritance
16190           || child_die->tag == DW_TAG_template_value_param
16191           || child_die->tag == DW_TAG_template_type_param)
16192         {
16193           /* Do nothing.  */
16194         }
16195       else
16196         process_die (child_die, cu);
16197
16198       child_die = sibling_die (child_die);
16199     }
16200
16201   /* Do not consider external references.  According to the DWARF standard,
16202      these DIEs are identified by the fact that they have no byte_size
16203      attribute, and a declaration attribute.  */
16204   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16205       || !die_is_declaration (die, cu))
16206     new_symbol (die, type, cu);
16207 }
16208
16209 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16210    update TYPE using some information only available in DIE's children.  */
16211
16212 static void
16213 update_enumeration_type_from_children (struct die_info *die,
16214                                        struct type *type,
16215                                        struct dwarf2_cu *cu)
16216 {
16217   struct die_info *child_die;
16218   int unsigned_enum = 1;
16219   int flag_enum = 1;
16220   ULONGEST mask = 0;
16221
16222   auto_obstack obstack;
16223
16224   for (child_die = die->child;
16225        child_die != NULL && child_die->tag;
16226        child_die = sibling_die (child_die))
16227     {
16228       struct attribute *attr;
16229       LONGEST value;
16230       const gdb_byte *bytes;
16231       struct dwarf2_locexpr_baton *baton;
16232       const char *name;
16233
16234       if (child_die->tag != DW_TAG_enumerator)
16235         continue;
16236
16237       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16238       if (attr == NULL)
16239         continue;
16240
16241       name = dwarf2_name (child_die, cu);
16242       if (name == NULL)
16243         name = "<anonymous enumerator>";
16244
16245       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16246                                &value, &bytes, &baton);
16247       if (value < 0)
16248         {
16249           unsigned_enum = 0;
16250           flag_enum = 0;
16251         }
16252       else if ((mask & value) != 0)
16253         flag_enum = 0;
16254       else
16255         mask |= value;
16256
16257       /* If we already know that the enum type is neither unsigned, nor
16258          a flag type, no need to look at the rest of the enumerates.  */
16259       if (!unsigned_enum && !flag_enum)
16260         break;
16261     }
16262
16263   if (unsigned_enum)
16264     TYPE_UNSIGNED (type) = 1;
16265   if (flag_enum)
16266     TYPE_FLAG_ENUM (type) = 1;
16267 }
16268
16269 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16270    complete the type's fields yet, or create any symbols.  */
16271
16272 static struct type *
16273 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16274 {
16275   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16276   struct type *type;
16277   struct attribute *attr;
16278   const char *name;
16279
16280   /* If the definition of this type lives in .debug_types, read that type.
16281      Don't follow DW_AT_specification though, that will take us back up
16282      the chain and we want to go down.  */
16283   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16284   if (attr)
16285     {
16286       type = get_DW_AT_signature_type (die, attr, cu);
16287
16288       /* The type's CU may not be the same as CU.
16289          Ensure TYPE is recorded with CU in die_type_hash.  */
16290       return set_die_type (die, type, cu);
16291     }
16292
16293   type = alloc_type (objfile);
16294
16295   TYPE_CODE (type) = TYPE_CODE_ENUM;
16296   name = dwarf2_full_name (NULL, die, cu);
16297   if (name != NULL)
16298     TYPE_TAG_NAME (type) = name;
16299
16300   attr = dwarf2_attr (die, DW_AT_type, cu);
16301   if (attr != NULL)
16302     {
16303       struct type *underlying_type = die_type (die, cu);
16304
16305       TYPE_TARGET_TYPE (type) = underlying_type;
16306     }
16307
16308   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16309   if (attr)
16310     {
16311       TYPE_LENGTH (type) = DW_UNSND (attr);
16312     }
16313   else
16314     {
16315       TYPE_LENGTH (type) = 0;
16316     }
16317
16318   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16319      declared as private in the package spec, and then defined only
16320      inside the package body.  Such types are known as Taft Amendment
16321      Types.  When another package uses such a type, an incomplete DIE
16322      may be generated by the compiler.  */
16323   if (die_is_declaration (die, cu))
16324     TYPE_STUB (type) = 1;
16325
16326   /* Finish the creation of this type by using the enum's children.
16327      We must call this even when the underlying type has been provided
16328      so that we can determine if we're looking at a "flag" enum.  */
16329   update_enumeration_type_from_children (die, type, cu);
16330
16331   /* If this type has an underlying type that is not a stub, then we
16332      may use its attributes.  We always use the "unsigned" attribute
16333      in this situation, because ordinarily we guess whether the type
16334      is unsigned -- but the guess can be wrong and the underlying type
16335      can tell us the reality.  However, we defer to a local size
16336      attribute if one exists, because this lets the compiler override
16337      the underlying type if needed.  */
16338   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16339     {
16340       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16341       if (TYPE_LENGTH (type) == 0)
16342         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16343     }
16344
16345   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16346
16347   return set_die_type (die, type, cu);
16348 }
16349
16350 /* Given a pointer to a die which begins an enumeration, process all
16351    the dies that define the members of the enumeration, and create the
16352    symbol for the enumeration type.
16353
16354    NOTE: We reverse the order of the element list.  */
16355
16356 static void
16357 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16358 {
16359   struct type *this_type;
16360
16361   this_type = get_die_type (die, cu);
16362   if (this_type == NULL)
16363     this_type = read_enumeration_type (die, cu);
16364
16365   if (die->child != NULL)
16366     {
16367       struct die_info *child_die;
16368       struct symbol *sym;
16369       struct field *fields = NULL;
16370       int num_fields = 0;
16371       const char *name;
16372
16373       child_die = die->child;
16374       while (child_die && child_die->tag)
16375         {
16376           if (child_die->tag != DW_TAG_enumerator)
16377             {
16378               process_die (child_die, cu);
16379             }
16380           else
16381             {
16382               name = dwarf2_name (child_die, cu);
16383               if (name)
16384                 {
16385                   sym = new_symbol (child_die, this_type, cu);
16386
16387                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16388                     {
16389                       fields = (struct field *)
16390                         xrealloc (fields,
16391                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16392                                   * sizeof (struct field));
16393                     }
16394
16395                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16396                   FIELD_TYPE (fields[num_fields]) = NULL;
16397                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16398                   FIELD_BITSIZE (fields[num_fields]) = 0;
16399
16400                   num_fields++;
16401                 }
16402             }
16403
16404           child_die = sibling_die (child_die);
16405         }
16406
16407       if (num_fields)
16408         {
16409           TYPE_NFIELDS (this_type) = num_fields;
16410           TYPE_FIELDS (this_type) = (struct field *)
16411             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16412           memcpy (TYPE_FIELDS (this_type), fields,
16413                   sizeof (struct field) * num_fields);
16414           xfree (fields);
16415         }
16416     }
16417
16418   /* If we are reading an enum from a .debug_types unit, and the enum
16419      is a declaration, and the enum is not the signatured type in the
16420      unit, then we do not want to add a symbol for it.  Adding a
16421      symbol would in some cases obscure the true definition of the
16422      enum, giving users an incomplete type when the definition is
16423      actually available.  Note that we do not want to do this for all
16424      enums which are just declarations, because C++0x allows forward
16425      enum declarations.  */
16426   if (cu->per_cu->is_debug_types
16427       && die_is_declaration (die, cu))
16428     {
16429       struct signatured_type *sig_type;
16430
16431       sig_type = (struct signatured_type *) cu->per_cu;
16432       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16433       if (sig_type->type_offset_in_section != die->sect_off)
16434         return;
16435     }
16436
16437   new_symbol (die, this_type, cu);
16438 }
16439
16440 /* Extract all information from a DW_TAG_array_type DIE and put it in
16441    the DIE's type field.  For now, this only handles one dimensional
16442    arrays.  */
16443
16444 static struct type *
16445 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16446 {
16447   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16448   struct die_info *child_die;
16449   struct type *type;
16450   struct type *element_type, *range_type, *index_type;
16451   struct attribute *attr;
16452   const char *name;
16453   struct dynamic_prop *byte_stride_prop = NULL;
16454   unsigned int bit_stride = 0;
16455
16456   element_type = die_type (die, cu);
16457
16458   /* The die_type call above may have already set the type for this DIE.  */
16459   type = get_die_type (die, cu);
16460   if (type)
16461     return type;
16462
16463   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16464   if (attr != NULL)
16465     {
16466       int stride_ok;
16467
16468       byte_stride_prop
16469         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16470       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16471       if (!stride_ok)
16472         {
16473           complaint (&symfile_complaints,
16474                      _("unable to read array DW_AT_byte_stride "
16475                        " - DIE at 0x%x [in module %s]"),
16476                      to_underlying (die->sect_off),
16477                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16478           /* Ignore this attribute.  We will likely not be able to print
16479              arrays of this type correctly, but there is little we can do
16480              to help if we cannot read the attribute's value.  */
16481           byte_stride_prop = NULL;
16482         }
16483     }
16484
16485   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16486   if (attr != NULL)
16487     bit_stride = DW_UNSND (attr);
16488
16489   /* Irix 6.2 native cc creates array types without children for
16490      arrays with unspecified length.  */
16491   if (die->child == NULL)
16492     {
16493       index_type = objfile_type (objfile)->builtin_int;
16494       range_type = create_static_range_type (NULL, index_type, 0, -1);
16495       type = create_array_type_with_stride (NULL, element_type, range_type,
16496                                             byte_stride_prop, bit_stride);
16497       return set_die_type (die, type, cu);
16498     }
16499
16500   std::vector<struct type *> range_types;
16501   child_die = die->child;
16502   while (child_die && child_die->tag)
16503     {
16504       if (child_die->tag == DW_TAG_subrange_type)
16505         {
16506           struct type *child_type = read_type_die (child_die, cu);
16507
16508           if (child_type != NULL)
16509             {
16510               /* The range type was succesfully read.  Save it for the
16511                  array type creation.  */
16512               range_types.push_back (child_type);
16513             }
16514         }
16515       child_die = sibling_die (child_die);
16516     }
16517
16518   /* Dwarf2 dimensions are output from left to right, create the
16519      necessary array types in backwards order.  */
16520
16521   type = element_type;
16522
16523   if (read_array_order (die, cu) == DW_ORD_col_major)
16524     {
16525       int i = 0;
16526
16527       while (i < range_types.size ())
16528         type = create_array_type_with_stride (NULL, type, range_types[i++],
16529                                               byte_stride_prop, bit_stride);
16530     }
16531   else
16532     {
16533       size_t ndim = range_types.size ();
16534       while (ndim-- > 0)
16535         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16536                                               byte_stride_prop, bit_stride);
16537     }
16538
16539   /* Understand Dwarf2 support for vector types (like they occur on
16540      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16541      array type.  This is not part of the Dwarf2/3 standard yet, but a
16542      custom vendor extension.  The main difference between a regular
16543      array and the vector variant is that vectors are passed by value
16544      to functions.  */
16545   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16546   if (attr)
16547     make_vector_type (type);
16548
16549   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16550      implementation may choose to implement triple vectors using this
16551      attribute.  */
16552   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16553   if (attr)
16554     {
16555       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16556         TYPE_LENGTH (type) = DW_UNSND (attr);
16557       else
16558         complaint (&symfile_complaints,
16559                    _("DW_AT_byte_size for array type smaller "
16560                      "than the total size of elements"));
16561     }
16562
16563   name = dwarf2_name (die, cu);
16564   if (name)
16565     TYPE_NAME (type) = name;
16566
16567   /* Install the type in the die.  */
16568   set_die_type (die, type, cu);
16569
16570   /* set_die_type should be already done.  */
16571   set_descriptive_type (type, die, cu);
16572
16573   return type;
16574 }
16575
16576 static enum dwarf_array_dim_ordering
16577 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16578 {
16579   struct attribute *attr;
16580
16581   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16582
16583   if (attr)
16584     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16585
16586   /* GNU F77 is a special case, as at 08/2004 array type info is the
16587      opposite order to the dwarf2 specification, but data is still
16588      laid out as per normal fortran.
16589
16590      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16591      version checking.  */
16592
16593   if (cu->language == language_fortran
16594       && cu->producer && strstr (cu->producer, "GNU F77"))
16595     {
16596       return DW_ORD_row_major;
16597     }
16598
16599   switch (cu->language_defn->la_array_ordering)
16600     {
16601     case array_column_major:
16602       return DW_ORD_col_major;
16603     case array_row_major:
16604     default:
16605       return DW_ORD_row_major;
16606     };
16607 }
16608
16609 /* Extract all information from a DW_TAG_set_type DIE and put it in
16610    the DIE's type field.  */
16611
16612 static struct type *
16613 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16614 {
16615   struct type *domain_type, *set_type;
16616   struct attribute *attr;
16617
16618   domain_type = die_type (die, cu);
16619
16620   /* The die_type call above may have already set the type for this DIE.  */
16621   set_type = get_die_type (die, cu);
16622   if (set_type)
16623     return set_type;
16624
16625   set_type = create_set_type (NULL, domain_type);
16626
16627   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16628   if (attr)
16629     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16630
16631   return set_die_type (die, set_type, cu);
16632 }
16633
16634 /* A helper for read_common_block that creates a locexpr baton.
16635    SYM is the symbol which we are marking as computed.
16636    COMMON_DIE is the DIE for the common block.
16637    COMMON_LOC is the location expression attribute for the common
16638    block itself.
16639    MEMBER_LOC is the location expression attribute for the particular
16640    member of the common block that we are processing.
16641    CU is the CU from which the above come.  */
16642
16643 static void
16644 mark_common_block_symbol_computed (struct symbol *sym,
16645                                    struct die_info *common_die,
16646                                    struct attribute *common_loc,
16647                                    struct attribute *member_loc,
16648                                    struct dwarf2_cu *cu)
16649 {
16650   struct dwarf2_per_objfile *dwarf2_per_objfile
16651     = cu->per_cu->dwarf2_per_objfile;
16652   struct objfile *objfile = dwarf2_per_objfile->objfile;
16653   struct dwarf2_locexpr_baton *baton;
16654   gdb_byte *ptr;
16655   unsigned int cu_off;
16656   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16657   LONGEST offset = 0;
16658
16659   gdb_assert (common_loc && member_loc);
16660   gdb_assert (attr_form_is_block (common_loc));
16661   gdb_assert (attr_form_is_block (member_loc)
16662               || attr_form_is_constant (member_loc));
16663
16664   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16665   baton->per_cu = cu->per_cu;
16666   gdb_assert (baton->per_cu);
16667
16668   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16669
16670   if (attr_form_is_constant (member_loc))
16671     {
16672       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16673       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16674     }
16675   else
16676     baton->size += DW_BLOCK (member_loc)->size;
16677
16678   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16679   baton->data = ptr;
16680
16681   *ptr++ = DW_OP_call4;
16682   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16683   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16684   ptr += 4;
16685
16686   if (attr_form_is_constant (member_loc))
16687     {
16688       *ptr++ = DW_OP_addr;
16689       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16690       ptr += cu->header.addr_size;
16691     }
16692   else
16693     {
16694       /* We have to copy the data here, because DW_OP_call4 will only
16695          use a DW_AT_location attribute.  */
16696       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16697       ptr += DW_BLOCK (member_loc)->size;
16698     }
16699
16700   *ptr++ = DW_OP_plus;
16701   gdb_assert (ptr - baton->data == baton->size);
16702
16703   SYMBOL_LOCATION_BATON (sym) = baton;
16704   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16705 }
16706
16707 /* Create appropriate locally-scoped variables for all the
16708    DW_TAG_common_block entries.  Also create a struct common_block
16709    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16710    is used to sepate the common blocks name namespace from regular
16711    variable names.  */
16712
16713 static void
16714 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16715 {
16716   struct attribute *attr;
16717
16718   attr = dwarf2_attr (die, DW_AT_location, cu);
16719   if (attr)
16720     {
16721       /* Support the .debug_loc offsets.  */
16722       if (attr_form_is_block (attr))
16723         {
16724           /* Ok.  */
16725         }
16726       else if (attr_form_is_section_offset (attr))
16727         {
16728           dwarf2_complex_location_expr_complaint ();
16729           attr = NULL;
16730         }
16731       else
16732         {
16733           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16734                                                  "common block member");
16735           attr = NULL;
16736         }
16737     }
16738
16739   if (die->child != NULL)
16740     {
16741       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16742       struct die_info *child_die;
16743       size_t n_entries = 0, size;
16744       struct common_block *common_block;
16745       struct symbol *sym;
16746
16747       for (child_die = die->child;
16748            child_die && child_die->tag;
16749            child_die = sibling_die (child_die))
16750         ++n_entries;
16751
16752       size = (sizeof (struct common_block)
16753               + (n_entries - 1) * sizeof (struct symbol *));
16754       common_block
16755         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16756                                                  size);
16757       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16758       common_block->n_entries = 0;
16759
16760       for (child_die = die->child;
16761            child_die && child_die->tag;
16762            child_die = sibling_die (child_die))
16763         {
16764           /* Create the symbol in the DW_TAG_common_block block in the current
16765              symbol scope.  */
16766           sym = new_symbol (child_die, NULL, cu);
16767           if (sym != NULL)
16768             {
16769               struct attribute *member_loc;
16770
16771               common_block->contents[common_block->n_entries++] = sym;
16772
16773               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16774                                         cu);
16775               if (member_loc)
16776                 {
16777                   /* GDB has handled this for a long time, but it is
16778                      not specified by DWARF.  It seems to have been
16779                      emitted by gfortran at least as recently as:
16780                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16781                   complaint (&symfile_complaints,
16782                              _("Variable in common block has "
16783                                "DW_AT_data_member_location "
16784                                "- DIE at 0x%x [in module %s]"),
16785                              to_underlying (child_die->sect_off),
16786                              objfile_name (objfile));
16787
16788                   if (attr_form_is_section_offset (member_loc))
16789                     dwarf2_complex_location_expr_complaint ();
16790                   else if (attr_form_is_constant (member_loc)
16791                            || attr_form_is_block (member_loc))
16792                     {
16793                       if (attr)
16794                         mark_common_block_symbol_computed (sym, die, attr,
16795                                                            member_loc, cu);
16796                     }
16797                   else
16798                     dwarf2_complex_location_expr_complaint ();
16799                 }
16800             }
16801         }
16802
16803       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16804       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16805     }
16806 }
16807
16808 /* Create a type for a C++ namespace.  */
16809
16810 static struct type *
16811 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16812 {
16813   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16814   const char *previous_prefix, *name;
16815   int is_anonymous;
16816   struct type *type;
16817
16818   /* For extensions, reuse the type of the original namespace.  */
16819   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16820     {
16821       struct die_info *ext_die;
16822       struct dwarf2_cu *ext_cu = cu;
16823
16824       ext_die = dwarf2_extension (die, &ext_cu);
16825       type = read_type_die (ext_die, ext_cu);
16826
16827       /* EXT_CU may not be the same as CU.
16828          Ensure TYPE is recorded with CU in die_type_hash.  */
16829       return set_die_type (die, type, cu);
16830     }
16831
16832   name = namespace_name (die, &is_anonymous, cu);
16833
16834   /* Now build the name of the current namespace.  */
16835
16836   previous_prefix = determine_prefix (die, cu);
16837   if (previous_prefix[0] != '\0')
16838     name = typename_concat (&objfile->objfile_obstack,
16839                             previous_prefix, name, 0, cu);
16840
16841   /* Create the type.  */
16842   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16843   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16844
16845   return set_die_type (die, type, cu);
16846 }
16847
16848 /* Read a namespace scope.  */
16849
16850 static void
16851 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16852 {
16853   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16854   int is_anonymous;
16855
16856   /* Add a symbol associated to this if we haven't seen the namespace
16857      before.  Also, add a using directive if it's an anonymous
16858      namespace.  */
16859
16860   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16861     {
16862       struct type *type;
16863
16864       type = read_type_die (die, cu);
16865       new_symbol (die, type, cu);
16866
16867       namespace_name (die, &is_anonymous, cu);
16868       if (is_anonymous)
16869         {
16870           const char *previous_prefix = determine_prefix (die, cu);
16871
16872           std::vector<const char *> excludes;
16873           add_using_directive (using_directives (cu->language),
16874                                previous_prefix, TYPE_NAME (type), NULL,
16875                                NULL, excludes, 0, &objfile->objfile_obstack);
16876         }
16877     }
16878
16879   if (die->child != NULL)
16880     {
16881       struct die_info *child_die = die->child;
16882
16883       while (child_die && child_die->tag)
16884         {
16885           process_die (child_die, cu);
16886           child_die = sibling_die (child_die);
16887         }
16888     }
16889 }
16890
16891 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16892    imported module.  Still we need that type as local Fortran "use ... only"
16893    declaration imports depend on the created type in determine_prefix.  */
16894
16895 static struct type *
16896 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16897 {
16898   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16899   const char *module_name;
16900   struct type *type;
16901
16902   module_name = dwarf2_name (die, cu);
16903   if (!module_name)
16904     complaint (&symfile_complaints,
16905                _("DW_TAG_module has no name, offset 0x%x"),
16906                to_underlying (die->sect_off));
16907   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16908
16909   /* determine_prefix uses TYPE_TAG_NAME.  */
16910   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16911
16912   return set_die_type (die, type, cu);
16913 }
16914
16915 /* Read a Fortran module.  */
16916
16917 static void
16918 read_module (struct die_info *die, struct dwarf2_cu *cu)
16919 {
16920   struct die_info *child_die = die->child;
16921   struct type *type;
16922
16923   type = read_type_die (die, cu);
16924   new_symbol (die, type, cu);
16925
16926   while (child_die && child_die->tag)
16927     {
16928       process_die (child_die, cu);
16929       child_die = sibling_die (child_die);
16930     }
16931 }
16932
16933 /* Return the name of the namespace represented by DIE.  Set
16934    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16935    namespace.  */
16936
16937 static const char *
16938 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16939 {
16940   struct die_info *current_die;
16941   const char *name = NULL;
16942
16943   /* Loop through the extensions until we find a name.  */
16944
16945   for (current_die = die;
16946        current_die != NULL;
16947        current_die = dwarf2_extension (die, &cu))
16948     {
16949       /* We don't use dwarf2_name here so that we can detect the absence
16950          of a name -> anonymous namespace.  */
16951       name = dwarf2_string_attr (die, DW_AT_name, cu);
16952
16953       if (name != NULL)
16954         break;
16955     }
16956
16957   /* Is it an anonymous namespace?  */
16958
16959   *is_anonymous = (name == NULL);
16960   if (*is_anonymous)
16961     name = CP_ANONYMOUS_NAMESPACE_STR;
16962
16963   return name;
16964 }
16965
16966 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16967    the user defined type vector.  */
16968
16969 static struct type *
16970 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16971 {
16972   struct gdbarch *gdbarch
16973     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16974   struct comp_unit_head *cu_header = &cu->header;
16975   struct type *type;
16976   struct attribute *attr_byte_size;
16977   struct attribute *attr_address_class;
16978   int byte_size, addr_class;
16979   struct type *target_type;
16980
16981   target_type = die_type (die, cu);
16982
16983   /* The die_type call above may have already set the type for this DIE.  */
16984   type = get_die_type (die, cu);
16985   if (type)
16986     return type;
16987
16988   type = lookup_pointer_type (target_type);
16989
16990   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16991   if (attr_byte_size)
16992     byte_size = DW_UNSND (attr_byte_size);
16993   else
16994     byte_size = cu_header->addr_size;
16995
16996   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16997   if (attr_address_class)
16998     addr_class = DW_UNSND (attr_address_class);
16999   else
17000     addr_class = DW_ADDR_none;
17001
17002   /* If the pointer size or address class is different than the
17003      default, create a type variant marked as such and set the
17004      length accordingly.  */
17005   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17006     {
17007       if (gdbarch_address_class_type_flags_p (gdbarch))
17008         {
17009           int type_flags;
17010
17011           type_flags = gdbarch_address_class_type_flags
17012                          (gdbarch, byte_size, addr_class);
17013           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17014                       == 0);
17015           type = make_type_with_address_space (type, type_flags);
17016         }
17017       else if (TYPE_LENGTH (type) != byte_size)
17018         {
17019           complaint (&symfile_complaints,
17020                      _("invalid pointer size %d"), byte_size);
17021         }
17022       else
17023         {
17024           /* Should we also complain about unhandled address classes?  */
17025         }
17026     }
17027
17028   TYPE_LENGTH (type) = byte_size;
17029   return set_die_type (die, type, cu);
17030 }
17031
17032 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17033    the user defined type vector.  */
17034
17035 static struct type *
17036 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17037 {
17038   struct type *type;
17039   struct type *to_type;
17040   struct type *domain;
17041
17042   to_type = die_type (die, cu);
17043   domain = die_containing_type (die, cu);
17044
17045   /* The calls above may have already set the type for this DIE.  */
17046   type = get_die_type (die, cu);
17047   if (type)
17048     return type;
17049
17050   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17051     type = lookup_methodptr_type (to_type);
17052   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17053     {
17054       struct type *new_type
17055         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17056
17057       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17058                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17059                             TYPE_VARARGS (to_type));
17060       type = lookup_methodptr_type (new_type);
17061     }
17062   else
17063     type = lookup_memberptr_type (to_type, domain);
17064
17065   return set_die_type (die, type, cu);
17066 }
17067
17068 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17069    the user defined type vector.  */
17070
17071 static struct type *
17072 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17073                           enum type_code refcode)
17074 {
17075   struct comp_unit_head *cu_header = &cu->header;
17076   struct type *type, *target_type;
17077   struct attribute *attr;
17078
17079   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17080
17081   target_type = die_type (die, cu);
17082
17083   /* The die_type call above may have already set the type for this DIE.  */
17084   type = get_die_type (die, cu);
17085   if (type)
17086     return type;
17087
17088   type = lookup_reference_type (target_type, refcode);
17089   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17090   if (attr)
17091     {
17092       TYPE_LENGTH (type) = DW_UNSND (attr);
17093     }
17094   else
17095     {
17096       TYPE_LENGTH (type) = cu_header->addr_size;
17097     }
17098   return set_die_type (die, type, cu);
17099 }
17100
17101 /* Add the given cv-qualifiers to the element type of the array.  GCC
17102    outputs DWARF type qualifiers that apply to an array, not the
17103    element type.  But GDB relies on the array element type to carry
17104    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17105    specification.  */
17106
17107 static struct type *
17108 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17109                    struct type *base_type, int cnst, int voltl)
17110 {
17111   struct type *el_type, *inner_array;
17112
17113   base_type = copy_type (base_type);
17114   inner_array = base_type;
17115
17116   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17117     {
17118       TYPE_TARGET_TYPE (inner_array) =
17119         copy_type (TYPE_TARGET_TYPE (inner_array));
17120       inner_array = TYPE_TARGET_TYPE (inner_array);
17121     }
17122
17123   el_type = TYPE_TARGET_TYPE (inner_array);
17124   cnst |= TYPE_CONST (el_type);
17125   voltl |= TYPE_VOLATILE (el_type);
17126   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17127
17128   return set_die_type (die, base_type, cu);
17129 }
17130
17131 static struct type *
17132 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17133 {
17134   struct type *base_type, *cv_type;
17135
17136   base_type = die_type (die, cu);
17137
17138   /* The die_type call above may have already set the type for this DIE.  */
17139   cv_type = get_die_type (die, cu);
17140   if (cv_type)
17141     return cv_type;
17142
17143   /* In case the const qualifier is applied to an array type, the element type
17144      is so qualified, not the array type (section 6.7.3 of C99).  */
17145   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17146     return add_array_cv_type (die, cu, base_type, 1, 0);
17147
17148   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17149   return set_die_type (die, cv_type, cu);
17150 }
17151
17152 static struct type *
17153 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17154 {
17155   struct type *base_type, *cv_type;
17156
17157   base_type = die_type (die, cu);
17158
17159   /* The die_type call above may have already set the type for this DIE.  */
17160   cv_type = get_die_type (die, cu);
17161   if (cv_type)
17162     return cv_type;
17163
17164   /* In case the volatile qualifier is applied to an array type, the
17165      element type is so qualified, not the array type (section 6.7.3
17166      of C99).  */
17167   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17168     return add_array_cv_type (die, cu, base_type, 0, 1);
17169
17170   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17171   return set_die_type (die, cv_type, cu);
17172 }
17173
17174 /* Handle DW_TAG_restrict_type.  */
17175
17176 static struct type *
17177 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17178 {
17179   struct type *base_type, *cv_type;
17180
17181   base_type = die_type (die, cu);
17182
17183   /* The die_type call above may have already set the type for this DIE.  */
17184   cv_type = get_die_type (die, cu);
17185   if (cv_type)
17186     return cv_type;
17187
17188   cv_type = make_restrict_type (base_type);
17189   return set_die_type (die, cv_type, cu);
17190 }
17191
17192 /* Handle DW_TAG_atomic_type.  */
17193
17194 static struct type *
17195 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17196 {
17197   struct type *base_type, *cv_type;
17198
17199   base_type = die_type (die, cu);
17200
17201   /* The die_type call above may have already set the type for this DIE.  */
17202   cv_type = get_die_type (die, cu);
17203   if (cv_type)
17204     return cv_type;
17205
17206   cv_type = make_atomic_type (base_type);
17207   return set_die_type (die, cv_type, cu);
17208 }
17209
17210 /* Extract all information from a DW_TAG_string_type DIE and add to
17211    the user defined type vector.  It isn't really a user defined type,
17212    but it behaves like one, with other DIE's using an AT_user_def_type
17213    attribute to reference it.  */
17214
17215 static struct type *
17216 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17217 {
17218   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17219   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17220   struct type *type, *range_type, *index_type, *char_type;
17221   struct attribute *attr;
17222   unsigned int length;
17223
17224   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17225   if (attr)
17226     {
17227       length = DW_UNSND (attr);
17228     }
17229   else
17230     {
17231       /* Check for the DW_AT_byte_size attribute.  */
17232       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17233       if (attr)
17234         {
17235           length = DW_UNSND (attr);
17236         }
17237       else
17238         {
17239           length = 1;
17240         }
17241     }
17242
17243   index_type = objfile_type (objfile)->builtin_int;
17244   range_type = create_static_range_type (NULL, index_type, 1, length);
17245   char_type = language_string_char_type (cu->language_defn, gdbarch);
17246   type = create_string_type (NULL, char_type, range_type);
17247
17248   return set_die_type (die, type, cu);
17249 }
17250
17251 /* Assuming that DIE corresponds to a function, returns nonzero
17252    if the function is prototyped.  */
17253
17254 static int
17255 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17256 {
17257   struct attribute *attr;
17258
17259   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17260   if (attr && (DW_UNSND (attr) != 0))
17261     return 1;
17262
17263   /* The DWARF standard implies that the DW_AT_prototyped attribute
17264      is only meaninful for C, but the concept also extends to other
17265      languages that allow unprototyped functions (Eg: Objective C).
17266      For all other languages, assume that functions are always
17267      prototyped.  */
17268   if (cu->language != language_c
17269       && cu->language != language_objc
17270       && cu->language != language_opencl)
17271     return 1;
17272
17273   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17274      prototyped and unprototyped functions; default to prototyped,
17275      since that is more common in modern code (and RealView warns
17276      about unprototyped functions).  */
17277   if (producer_is_realview (cu->producer))
17278     return 1;
17279
17280   return 0;
17281 }
17282
17283 /* Handle DIES due to C code like:
17284
17285    struct foo
17286    {
17287    int (*funcp)(int a, long l);
17288    int b;
17289    };
17290
17291    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17292
17293 static struct type *
17294 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17295 {
17296   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17297   struct type *type;            /* Type that this function returns.  */
17298   struct type *ftype;           /* Function that returns above type.  */
17299   struct attribute *attr;
17300
17301   type = die_type (die, cu);
17302
17303   /* The die_type call above may have already set the type for this DIE.  */
17304   ftype = get_die_type (die, cu);
17305   if (ftype)
17306     return ftype;
17307
17308   ftype = lookup_function_type (type);
17309
17310   if (prototyped_function_p (die, cu))
17311     TYPE_PROTOTYPED (ftype) = 1;
17312
17313   /* Store the calling convention in the type if it's available in
17314      the subroutine die.  Otherwise set the calling convention to
17315      the default value DW_CC_normal.  */
17316   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17317   if (attr)
17318     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17319   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17320     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17321   else
17322     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17323
17324   /* Record whether the function returns normally to its caller or not
17325      if the DWARF producer set that information.  */
17326   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17327   if (attr && (DW_UNSND (attr) != 0))
17328     TYPE_NO_RETURN (ftype) = 1;
17329
17330   /* We need to add the subroutine type to the die immediately so
17331      we don't infinitely recurse when dealing with parameters
17332      declared as the same subroutine type.  */
17333   set_die_type (die, ftype, cu);
17334
17335   if (die->child != NULL)
17336     {
17337       struct type *void_type = objfile_type (objfile)->builtin_void;
17338       struct die_info *child_die;
17339       int nparams, iparams;
17340
17341       /* Count the number of parameters.
17342          FIXME: GDB currently ignores vararg functions, but knows about
17343          vararg member functions.  */
17344       nparams = 0;
17345       child_die = die->child;
17346       while (child_die && child_die->tag)
17347         {
17348           if (child_die->tag == DW_TAG_formal_parameter)
17349             nparams++;
17350           else if (child_die->tag == DW_TAG_unspecified_parameters)
17351             TYPE_VARARGS (ftype) = 1;
17352           child_die = sibling_die (child_die);
17353         }
17354
17355       /* Allocate storage for parameters and fill them in.  */
17356       TYPE_NFIELDS (ftype) = nparams;
17357       TYPE_FIELDS (ftype) = (struct field *)
17358         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17359
17360       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17361          even if we error out during the parameters reading below.  */
17362       for (iparams = 0; iparams < nparams; iparams++)
17363         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17364
17365       iparams = 0;
17366       child_die = die->child;
17367       while (child_die && child_die->tag)
17368         {
17369           if (child_die->tag == DW_TAG_formal_parameter)
17370             {
17371               struct type *arg_type;
17372
17373               /* DWARF version 2 has no clean way to discern C++
17374                  static and non-static member functions.  G++ helps
17375                  GDB by marking the first parameter for non-static
17376                  member functions (which is the this pointer) as
17377                  artificial.  We pass this information to
17378                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17379
17380                  DWARF version 3 added DW_AT_object_pointer, which GCC
17381                  4.5 does not yet generate.  */
17382               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17383               if (attr)
17384                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17385               else
17386                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17387               arg_type = die_type (child_die, cu);
17388
17389               /* RealView does not mark THIS as const, which the testsuite
17390                  expects.  GCC marks THIS as const in method definitions,
17391                  but not in the class specifications (GCC PR 43053).  */
17392               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17393                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17394                 {
17395                   int is_this = 0;
17396                   struct dwarf2_cu *arg_cu = cu;
17397                   const char *name = dwarf2_name (child_die, cu);
17398
17399                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17400                   if (attr)
17401                     {
17402                       /* If the compiler emits this, use it.  */
17403                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17404                         is_this = 1;
17405                     }
17406                   else if (name && strcmp (name, "this") == 0)
17407                     /* Function definitions will have the argument names.  */
17408                     is_this = 1;
17409                   else if (name == NULL && iparams == 0)
17410                     /* Declarations may not have the names, so like
17411                        elsewhere in GDB, assume an artificial first
17412                        argument is "this".  */
17413                     is_this = 1;
17414
17415                   if (is_this)
17416                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17417                                              arg_type, 0);
17418                 }
17419
17420               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17421               iparams++;
17422             }
17423           child_die = sibling_die (child_die);
17424         }
17425     }
17426
17427   return ftype;
17428 }
17429
17430 static struct type *
17431 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17432 {
17433   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17434   const char *name = NULL;
17435   struct type *this_type, *target_type;
17436
17437   name = dwarf2_full_name (NULL, die, cu);
17438   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17439   TYPE_TARGET_STUB (this_type) = 1;
17440   set_die_type (die, this_type, cu);
17441   target_type = die_type (die, cu);
17442   if (target_type != this_type)
17443     TYPE_TARGET_TYPE (this_type) = target_type;
17444   else
17445     {
17446       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17447          spec and cause infinite loops in GDB.  */
17448       complaint (&symfile_complaints,
17449                  _("Self-referential DW_TAG_typedef "
17450                    "- DIE at 0x%x [in module %s]"),
17451                  to_underlying (die->sect_off), objfile_name (objfile));
17452       TYPE_TARGET_TYPE (this_type) = NULL;
17453     }
17454   return this_type;
17455 }
17456
17457 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17458    (which may be different from NAME) to the architecture back-end to allow
17459    it to guess the correct format if necessary.  */
17460
17461 static struct type *
17462 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17463                         const char *name_hint)
17464 {
17465   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17466   const struct floatformat **format;
17467   struct type *type;
17468
17469   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17470   if (format)
17471     type = init_float_type (objfile, bits, name, format);
17472   else
17473     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17474
17475   return type;
17476 }
17477
17478 /* Find a representation of a given base type and install
17479    it in the TYPE field of the die.  */
17480
17481 static struct type *
17482 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17483 {
17484   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17485   struct type *type;
17486   struct attribute *attr;
17487   int encoding = 0, bits = 0;
17488   const char *name;
17489
17490   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17491   if (attr)
17492     {
17493       encoding = DW_UNSND (attr);
17494     }
17495   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17496   if (attr)
17497     {
17498       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17499     }
17500   name = dwarf2_name (die, cu);
17501   if (!name)
17502     {
17503       complaint (&symfile_complaints,
17504                  _("DW_AT_name missing from DW_TAG_base_type"));
17505     }
17506
17507   switch (encoding)
17508     {
17509       case DW_ATE_address:
17510         /* Turn DW_ATE_address into a void * pointer.  */
17511         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17512         type = init_pointer_type (objfile, bits, name, type);
17513         break;
17514       case DW_ATE_boolean:
17515         type = init_boolean_type (objfile, bits, 1, name);
17516         break;
17517       case DW_ATE_complex_float:
17518         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17519         type = init_complex_type (objfile, name, type);
17520         break;
17521       case DW_ATE_decimal_float:
17522         type = init_decfloat_type (objfile, bits, name);
17523         break;
17524       case DW_ATE_float:
17525         type = dwarf2_init_float_type (objfile, bits, name, name);
17526         break;
17527       case DW_ATE_signed:
17528         type = init_integer_type (objfile, bits, 0, name);
17529         break;
17530       case DW_ATE_unsigned:
17531         if (cu->language == language_fortran
17532             && name
17533             && startswith (name, "character("))
17534           type = init_character_type (objfile, bits, 1, name);
17535         else
17536           type = init_integer_type (objfile, bits, 1, name);
17537         break;
17538       case DW_ATE_signed_char:
17539         if (cu->language == language_ada || cu->language == language_m2
17540             || cu->language == language_pascal
17541             || cu->language == language_fortran)
17542           type = init_character_type (objfile, bits, 0, name);
17543         else
17544           type = init_integer_type (objfile, bits, 0, name);
17545         break;
17546       case DW_ATE_unsigned_char:
17547         if (cu->language == language_ada || cu->language == language_m2
17548             || cu->language == language_pascal
17549             || cu->language == language_fortran
17550             || cu->language == language_rust)
17551           type = init_character_type (objfile, bits, 1, name);
17552         else
17553           type = init_integer_type (objfile, bits, 1, name);
17554         break;
17555       case DW_ATE_UTF:
17556         {
17557           gdbarch *arch = get_objfile_arch (objfile);
17558
17559           if (bits == 16)
17560             type = builtin_type (arch)->builtin_char16;
17561           else if (bits == 32)
17562             type = builtin_type (arch)->builtin_char32;
17563           else
17564             {
17565               complaint (&symfile_complaints,
17566                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17567                          bits);
17568               type = init_integer_type (objfile, bits, 1, name);
17569             }
17570           return set_die_type (die, type, cu);
17571         }
17572         break;
17573
17574       default:
17575         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17576                    dwarf_type_encoding_name (encoding));
17577         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17578         break;
17579     }
17580
17581   if (name && strcmp (name, "char") == 0)
17582     TYPE_NOSIGN (type) = 1;
17583
17584   return set_die_type (die, type, cu);
17585 }
17586
17587 /* Parse dwarf attribute if it's a block, reference or constant and put the
17588    resulting value of the attribute into struct bound_prop.
17589    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17590
17591 static int
17592 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17593                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17594 {
17595   struct dwarf2_property_baton *baton;
17596   struct obstack *obstack
17597     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17598
17599   if (attr == NULL || prop == NULL)
17600     return 0;
17601
17602   if (attr_form_is_block (attr))
17603     {
17604       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17605       baton->referenced_type = NULL;
17606       baton->locexpr.per_cu = cu->per_cu;
17607       baton->locexpr.size = DW_BLOCK (attr)->size;
17608       baton->locexpr.data = DW_BLOCK (attr)->data;
17609       prop->data.baton = baton;
17610       prop->kind = PROP_LOCEXPR;
17611       gdb_assert (prop->data.baton != NULL);
17612     }
17613   else if (attr_form_is_ref (attr))
17614     {
17615       struct dwarf2_cu *target_cu = cu;
17616       struct die_info *target_die;
17617       struct attribute *target_attr;
17618
17619       target_die = follow_die_ref (die, attr, &target_cu);
17620       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17621       if (target_attr == NULL)
17622         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17623                                    target_cu);
17624       if (target_attr == NULL)
17625         return 0;
17626
17627       switch (target_attr->name)
17628         {
17629           case DW_AT_location:
17630             if (attr_form_is_section_offset (target_attr))
17631               {
17632                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17633                 baton->referenced_type = die_type (target_die, target_cu);
17634                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17635                 prop->data.baton = baton;
17636                 prop->kind = PROP_LOCLIST;
17637                 gdb_assert (prop->data.baton != NULL);
17638               }
17639             else if (attr_form_is_block (target_attr))
17640               {
17641                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17642                 baton->referenced_type = die_type (target_die, target_cu);
17643                 baton->locexpr.per_cu = cu->per_cu;
17644                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17645                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17646                 prop->data.baton = baton;
17647                 prop->kind = PROP_LOCEXPR;
17648                 gdb_assert (prop->data.baton != NULL);
17649               }
17650             else
17651               {
17652                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17653                                                        "dynamic property");
17654                 return 0;
17655               }
17656             break;
17657           case DW_AT_data_member_location:
17658             {
17659               LONGEST offset;
17660
17661               if (!handle_data_member_location (target_die, target_cu,
17662                                                 &offset))
17663                 return 0;
17664
17665               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17666               baton->referenced_type = read_type_die (target_die->parent,
17667                                                       target_cu);
17668               baton->offset_info.offset = offset;
17669               baton->offset_info.type = die_type (target_die, target_cu);
17670               prop->data.baton = baton;
17671               prop->kind = PROP_ADDR_OFFSET;
17672               break;
17673             }
17674         }
17675     }
17676   else if (attr_form_is_constant (attr))
17677     {
17678       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17679       prop->kind = PROP_CONST;
17680     }
17681   else
17682     {
17683       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17684                                              dwarf2_name (die, cu));
17685       return 0;
17686     }
17687
17688   return 1;
17689 }
17690
17691 /* Read the given DW_AT_subrange DIE.  */
17692
17693 static struct type *
17694 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17695 {
17696   struct type *base_type, *orig_base_type;
17697   struct type *range_type;
17698   struct attribute *attr;
17699   struct dynamic_prop low, high;
17700   int low_default_is_valid;
17701   int high_bound_is_count = 0;
17702   const char *name;
17703   LONGEST negative_mask;
17704
17705   orig_base_type = die_type (die, cu);
17706   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17707      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17708      creating the range type, but we use the result of check_typedef
17709      when examining properties of the type.  */
17710   base_type = check_typedef (orig_base_type);
17711
17712   /* The die_type call above may have already set the type for this DIE.  */
17713   range_type = get_die_type (die, cu);
17714   if (range_type)
17715     return range_type;
17716
17717   low.kind = PROP_CONST;
17718   high.kind = PROP_CONST;
17719   high.data.const_val = 0;
17720
17721   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17722      omitting DW_AT_lower_bound.  */
17723   switch (cu->language)
17724     {
17725     case language_c:
17726     case language_cplus:
17727       low.data.const_val = 0;
17728       low_default_is_valid = 1;
17729       break;
17730     case language_fortran:
17731       low.data.const_val = 1;
17732       low_default_is_valid = 1;
17733       break;
17734     case language_d:
17735     case language_objc:
17736     case language_rust:
17737       low.data.const_val = 0;
17738       low_default_is_valid = (cu->header.version >= 4);
17739       break;
17740     case language_ada:
17741     case language_m2:
17742     case language_pascal:
17743       low.data.const_val = 1;
17744       low_default_is_valid = (cu->header.version >= 4);
17745       break;
17746     default:
17747       low.data.const_val = 0;
17748       low_default_is_valid = 0;
17749       break;
17750     }
17751
17752   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17753   if (attr)
17754     attr_to_dynamic_prop (attr, die, cu, &low);
17755   else if (!low_default_is_valid)
17756     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17757                                       "- DIE at 0x%x [in module %s]"),
17758                to_underlying (die->sect_off),
17759                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17760
17761   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17762   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17763     {
17764       attr = dwarf2_attr (die, DW_AT_count, cu);
17765       if (attr_to_dynamic_prop (attr, die, cu, &high))
17766         {
17767           /* If bounds are constant do the final calculation here.  */
17768           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17769             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17770           else
17771             high_bound_is_count = 1;
17772         }
17773     }
17774
17775   /* Dwarf-2 specifications explicitly allows to create subrange types
17776      without specifying a base type.
17777      In that case, the base type must be set to the type of
17778      the lower bound, upper bound or count, in that order, if any of these
17779      three attributes references an object that has a type.
17780      If no base type is found, the Dwarf-2 specifications say that
17781      a signed integer type of size equal to the size of an address should
17782      be used.
17783      For the following C code: `extern char gdb_int [];'
17784      GCC produces an empty range DIE.
17785      FIXME: muller/2010-05-28: Possible references to object for low bound,
17786      high bound or count are not yet handled by this code.  */
17787   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17788     {
17789       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17790       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17791       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17792       struct type *int_type = objfile_type (objfile)->builtin_int;
17793
17794       /* Test "int", "long int", and "long long int" objfile types,
17795          and select the first one having a size above or equal to the
17796          architecture address size.  */
17797       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17798         base_type = int_type;
17799       else
17800         {
17801           int_type = objfile_type (objfile)->builtin_long;
17802           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17803             base_type = int_type;
17804           else
17805             {
17806               int_type = objfile_type (objfile)->builtin_long_long;
17807               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17808                 base_type = int_type;
17809             }
17810         }
17811     }
17812
17813   /* Normally, the DWARF producers are expected to use a signed
17814      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17815      But this is unfortunately not always the case, as witnessed
17816      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17817      is used instead.  To work around that ambiguity, we treat
17818      the bounds as signed, and thus sign-extend their values, when
17819      the base type is signed.  */
17820   negative_mask =
17821     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17822   if (low.kind == PROP_CONST
17823       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17824     low.data.const_val |= negative_mask;
17825   if (high.kind == PROP_CONST
17826       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17827     high.data.const_val |= negative_mask;
17828
17829   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17830
17831   if (high_bound_is_count)
17832     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17833
17834   /* Ada expects an empty array on no boundary attributes.  */
17835   if (attr == NULL && cu->language != language_ada)
17836     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17837
17838   name = dwarf2_name (die, cu);
17839   if (name)
17840     TYPE_NAME (range_type) = name;
17841
17842   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17843   if (attr)
17844     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17845
17846   set_die_type (die, range_type, cu);
17847
17848   /* set_die_type should be already done.  */
17849   set_descriptive_type (range_type, die, cu);
17850
17851   return range_type;
17852 }
17853
17854 static struct type *
17855 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17856 {
17857   struct type *type;
17858
17859   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17860                     NULL);
17861   TYPE_NAME (type) = dwarf2_name (die, cu);
17862
17863   /* In Ada, an unspecified type is typically used when the description
17864      of the type is defered to a different unit.  When encountering
17865      such a type, we treat it as a stub, and try to resolve it later on,
17866      when needed.  */
17867   if (cu->language == language_ada)
17868     TYPE_STUB (type) = 1;
17869
17870   return set_die_type (die, type, cu);
17871 }
17872
17873 /* Read a single die and all its descendents.  Set the die's sibling
17874    field to NULL; set other fields in the die correctly, and set all
17875    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17876    location of the info_ptr after reading all of those dies.  PARENT
17877    is the parent of the die in question.  */
17878
17879 static struct die_info *
17880 read_die_and_children (const struct die_reader_specs *reader,
17881                        const gdb_byte *info_ptr,
17882                        const gdb_byte **new_info_ptr,
17883                        struct die_info *parent)
17884 {
17885   struct die_info *die;
17886   const gdb_byte *cur_ptr;
17887   int has_children;
17888
17889   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17890   if (die == NULL)
17891     {
17892       *new_info_ptr = cur_ptr;
17893       return NULL;
17894     }
17895   store_in_ref_table (die, reader->cu);
17896
17897   if (has_children)
17898     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17899   else
17900     {
17901       die->child = NULL;
17902       *new_info_ptr = cur_ptr;
17903     }
17904
17905   die->sibling = NULL;
17906   die->parent = parent;
17907   return die;
17908 }
17909
17910 /* Read a die, all of its descendents, and all of its siblings; set
17911    all of the fields of all of the dies correctly.  Arguments are as
17912    in read_die_and_children.  */
17913
17914 static struct die_info *
17915 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17916                          const gdb_byte *info_ptr,
17917                          const gdb_byte **new_info_ptr,
17918                          struct die_info *parent)
17919 {
17920   struct die_info *first_die, *last_sibling;
17921   const gdb_byte *cur_ptr;
17922
17923   cur_ptr = info_ptr;
17924   first_die = last_sibling = NULL;
17925
17926   while (1)
17927     {
17928       struct die_info *die
17929         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17930
17931       if (die == NULL)
17932         {
17933           *new_info_ptr = cur_ptr;
17934           return first_die;
17935         }
17936
17937       if (!first_die)
17938         first_die = die;
17939       else
17940         last_sibling->sibling = die;
17941
17942       last_sibling = die;
17943     }
17944 }
17945
17946 /* Read a die, all of its descendents, and all of its siblings; set
17947    all of the fields of all of the dies correctly.  Arguments are as
17948    in read_die_and_children.
17949    This the main entry point for reading a DIE and all its children.  */
17950
17951 static struct die_info *
17952 read_die_and_siblings (const struct die_reader_specs *reader,
17953                        const gdb_byte *info_ptr,
17954                        const gdb_byte **new_info_ptr,
17955                        struct die_info *parent)
17956 {
17957   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17958                                                   new_info_ptr, parent);
17959
17960   if (dwarf_die_debug)
17961     {
17962       fprintf_unfiltered (gdb_stdlog,
17963                           "Read die from %s@0x%x of %s:\n",
17964                           get_section_name (reader->die_section),
17965                           (unsigned) (info_ptr - reader->die_section->buffer),
17966                           bfd_get_filename (reader->abfd));
17967       dump_die (die, dwarf_die_debug);
17968     }
17969
17970   return die;
17971 }
17972
17973 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17974    attributes.
17975    The caller is responsible for filling in the extra attributes
17976    and updating (*DIEP)->num_attrs.
17977    Set DIEP to point to a newly allocated die with its information,
17978    except for its child, sibling, and parent fields.
17979    Set HAS_CHILDREN to tell whether the die has children or not.  */
17980
17981 static const gdb_byte *
17982 read_full_die_1 (const struct die_reader_specs *reader,
17983                  struct die_info **diep, const gdb_byte *info_ptr,
17984                  int *has_children, int num_extra_attrs)
17985 {
17986   unsigned int abbrev_number, bytes_read, i;
17987   struct abbrev_info *abbrev;
17988   struct die_info *die;
17989   struct dwarf2_cu *cu = reader->cu;
17990   bfd *abfd = reader->abfd;
17991
17992   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17993   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17994   info_ptr += bytes_read;
17995   if (!abbrev_number)
17996     {
17997       *diep = NULL;
17998       *has_children = 0;
17999       return info_ptr;
18000     }
18001
18002   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18003   if (!abbrev)
18004     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18005            abbrev_number,
18006            bfd_get_filename (abfd));
18007
18008   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18009   die->sect_off = sect_off;
18010   die->tag = abbrev->tag;
18011   die->abbrev = abbrev_number;
18012
18013   /* Make the result usable.
18014      The caller needs to update num_attrs after adding the extra
18015      attributes.  */
18016   die->num_attrs = abbrev->num_attrs;
18017
18018   for (i = 0; i < abbrev->num_attrs; ++i)
18019     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18020                                info_ptr);
18021
18022   *diep = die;
18023   *has_children = abbrev->has_children;
18024   return info_ptr;
18025 }
18026
18027 /* Read a die and all its attributes.
18028    Set DIEP to point to a newly allocated die with its information,
18029    except for its child, sibling, and parent fields.
18030    Set HAS_CHILDREN to tell whether the die has children or not.  */
18031
18032 static const gdb_byte *
18033 read_full_die (const struct die_reader_specs *reader,
18034                struct die_info **diep, const gdb_byte *info_ptr,
18035                int *has_children)
18036 {
18037   const gdb_byte *result;
18038
18039   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18040
18041   if (dwarf_die_debug)
18042     {
18043       fprintf_unfiltered (gdb_stdlog,
18044                           "Read die from %s@0x%x of %s:\n",
18045                           get_section_name (reader->die_section),
18046                           (unsigned) (info_ptr - reader->die_section->buffer),
18047                           bfd_get_filename (reader->abfd));
18048       dump_die (*diep, dwarf_die_debug);
18049     }
18050
18051   return result;
18052 }
18053 \f
18054 /* Abbreviation tables.
18055
18056    In DWARF version 2, the description of the debugging information is
18057    stored in a separate .debug_abbrev section.  Before we read any
18058    dies from a section we read in all abbreviations and install them
18059    in a hash table.  */
18060
18061 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18062
18063 struct abbrev_info *
18064 abbrev_table::alloc_abbrev ()
18065 {
18066   struct abbrev_info *abbrev;
18067
18068   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18069   memset (abbrev, 0, sizeof (struct abbrev_info));
18070
18071   return abbrev;
18072 }
18073
18074 /* Add an abbreviation to the table.  */
18075
18076 void
18077 abbrev_table::add_abbrev (unsigned int abbrev_number,
18078                           struct abbrev_info *abbrev)
18079 {
18080   unsigned int hash_number;
18081
18082   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18083   abbrev->next = abbrevs[hash_number];
18084   abbrevs[hash_number] = abbrev;
18085 }
18086
18087 /* Look up an abbrev in the table.
18088    Returns NULL if the abbrev is not found.  */
18089
18090 struct abbrev_info *
18091 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18092 {
18093   unsigned int hash_number;
18094   struct abbrev_info *abbrev;
18095
18096   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18097   abbrev = abbrevs[hash_number];
18098
18099   while (abbrev)
18100     {
18101       if (abbrev->number == abbrev_number)
18102         return abbrev;
18103       abbrev = abbrev->next;
18104     }
18105   return NULL;
18106 }
18107
18108 /* Read in an abbrev table.  */
18109
18110 static abbrev_table_up
18111 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18112                          struct dwarf2_section_info *section,
18113                          sect_offset sect_off)
18114 {
18115   struct objfile *objfile = dwarf2_per_objfile->objfile;
18116   bfd *abfd = get_section_bfd_owner (section);
18117   const gdb_byte *abbrev_ptr;
18118   struct abbrev_info *cur_abbrev;
18119   unsigned int abbrev_number, bytes_read, abbrev_name;
18120   unsigned int abbrev_form;
18121   struct attr_abbrev *cur_attrs;
18122   unsigned int allocated_attrs;
18123
18124   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18125
18126   dwarf2_read_section (objfile, section);
18127   abbrev_ptr = section->buffer + to_underlying (sect_off);
18128   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18129   abbrev_ptr += bytes_read;
18130
18131   allocated_attrs = ATTR_ALLOC_CHUNK;
18132   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18133
18134   /* Loop until we reach an abbrev number of 0.  */
18135   while (abbrev_number)
18136     {
18137       cur_abbrev = abbrev_table->alloc_abbrev ();
18138
18139       /* read in abbrev header */
18140       cur_abbrev->number = abbrev_number;
18141       cur_abbrev->tag
18142         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18143       abbrev_ptr += bytes_read;
18144       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18145       abbrev_ptr += 1;
18146
18147       /* now read in declarations */
18148       for (;;)
18149         {
18150           LONGEST implicit_const;
18151
18152           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18153           abbrev_ptr += bytes_read;
18154           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18155           abbrev_ptr += bytes_read;
18156           if (abbrev_form == DW_FORM_implicit_const)
18157             {
18158               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18159                                                    &bytes_read);
18160               abbrev_ptr += bytes_read;
18161             }
18162           else
18163             {
18164               /* Initialize it due to a false compiler warning.  */
18165               implicit_const = -1;
18166             }
18167
18168           if (abbrev_name == 0)
18169             break;
18170
18171           if (cur_abbrev->num_attrs == allocated_attrs)
18172             {
18173               allocated_attrs += ATTR_ALLOC_CHUNK;
18174               cur_attrs
18175                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18176             }
18177
18178           cur_attrs[cur_abbrev->num_attrs].name
18179             = (enum dwarf_attribute) abbrev_name;
18180           cur_attrs[cur_abbrev->num_attrs].form
18181             = (enum dwarf_form) abbrev_form;
18182           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18183           ++cur_abbrev->num_attrs;
18184         }
18185
18186       cur_abbrev->attrs =
18187         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18188                    cur_abbrev->num_attrs);
18189       memcpy (cur_abbrev->attrs, cur_attrs,
18190               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18191
18192       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18193
18194       /* Get next abbreviation.
18195          Under Irix6 the abbreviations for a compilation unit are not
18196          always properly terminated with an abbrev number of 0.
18197          Exit loop if we encounter an abbreviation which we have
18198          already read (which means we are about to read the abbreviations
18199          for the next compile unit) or if the end of the abbreviation
18200          table is reached.  */
18201       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18202         break;
18203       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18204       abbrev_ptr += bytes_read;
18205       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18206         break;
18207     }
18208
18209   xfree (cur_attrs);
18210   return abbrev_table;
18211 }
18212
18213 /* Returns nonzero if TAG represents a type that we might generate a partial
18214    symbol for.  */
18215
18216 static int
18217 is_type_tag_for_partial (int tag)
18218 {
18219   switch (tag)
18220     {
18221 #if 0
18222     /* Some types that would be reasonable to generate partial symbols for,
18223        that we don't at present.  */
18224     case DW_TAG_array_type:
18225     case DW_TAG_file_type:
18226     case DW_TAG_ptr_to_member_type:
18227     case DW_TAG_set_type:
18228     case DW_TAG_string_type:
18229     case DW_TAG_subroutine_type:
18230 #endif
18231     case DW_TAG_base_type:
18232     case DW_TAG_class_type:
18233     case DW_TAG_interface_type:
18234     case DW_TAG_enumeration_type:
18235     case DW_TAG_structure_type:
18236     case DW_TAG_subrange_type:
18237     case DW_TAG_typedef:
18238     case DW_TAG_union_type:
18239       return 1;
18240     default:
18241       return 0;
18242     }
18243 }
18244
18245 /* Load all DIEs that are interesting for partial symbols into memory.  */
18246
18247 static struct partial_die_info *
18248 load_partial_dies (const struct die_reader_specs *reader,
18249                    const gdb_byte *info_ptr, int building_psymtab)
18250 {
18251   struct dwarf2_cu *cu = reader->cu;
18252   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18253   struct partial_die_info *part_die;
18254   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18255   unsigned int bytes_read;
18256   unsigned int load_all = 0;
18257   int nesting_level = 1;
18258
18259   parent_die = NULL;
18260   last_die = NULL;
18261
18262   gdb_assert (cu->per_cu != NULL);
18263   if (cu->per_cu->load_all_dies)
18264     load_all = 1;
18265
18266   cu->partial_dies
18267     = htab_create_alloc_ex (cu->header.length / 12,
18268                             partial_die_hash,
18269                             partial_die_eq,
18270                             NULL,
18271                             &cu->comp_unit_obstack,
18272                             hashtab_obstack_allocate,
18273                             dummy_obstack_deallocate);
18274
18275   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18276
18277   while (1)
18278     {
18279       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18280
18281       /* A NULL abbrev means the end of a series of children.  */
18282       if (abbrev == NULL)
18283         {
18284           if (--nesting_level == 0)
18285             {
18286               /* PART_DIE was probably the last thing allocated on the
18287                  comp_unit_obstack, so we could call obstack_free
18288                  here.  We don't do that because the waste is small,
18289                  and will be cleaned up when we're done with this
18290                  compilation unit.  This way, we're also more robust
18291                  against other users of the comp_unit_obstack.  */
18292               return first_die;
18293             }
18294           info_ptr += bytes_read;
18295           last_die = parent_die;
18296           parent_die = parent_die->die_parent;
18297           continue;
18298         }
18299
18300       /* Check for template arguments.  We never save these; if
18301          they're seen, we just mark the parent, and go on our way.  */
18302       if (parent_die != NULL
18303           && cu->language == language_cplus
18304           && (abbrev->tag == DW_TAG_template_type_param
18305               || abbrev->tag == DW_TAG_template_value_param))
18306         {
18307           parent_die->has_template_arguments = 1;
18308
18309           if (!load_all)
18310             {
18311               /* We don't need a partial DIE for the template argument.  */
18312               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18313               continue;
18314             }
18315         }
18316
18317       /* We only recurse into c++ subprograms looking for template arguments.
18318          Skip their other children.  */
18319       if (!load_all
18320           && cu->language == language_cplus
18321           && parent_die != NULL
18322           && parent_die->tag == DW_TAG_subprogram)
18323         {
18324           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18325           continue;
18326         }
18327
18328       /* Check whether this DIE is interesting enough to save.  Normally
18329          we would not be interested in members here, but there may be
18330          later variables referencing them via DW_AT_specification (for
18331          static members).  */
18332       if (!load_all
18333           && !is_type_tag_for_partial (abbrev->tag)
18334           && abbrev->tag != DW_TAG_constant
18335           && abbrev->tag != DW_TAG_enumerator
18336           && abbrev->tag != DW_TAG_subprogram
18337           && abbrev->tag != DW_TAG_inlined_subroutine
18338           && abbrev->tag != DW_TAG_lexical_block
18339           && abbrev->tag != DW_TAG_variable
18340           && abbrev->tag != DW_TAG_namespace
18341           && abbrev->tag != DW_TAG_module
18342           && abbrev->tag != DW_TAG_member
18343           && abbrev->tag != DW_TAG_imported_unit
18344           && abbrev->tag != DW_TAG_imported_declaration)
18345         {
18346           /* Otherwise we skip to the next sibling, if any.  */
18347           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18348           continue;
18349         }
18350
18351       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18352                                    info_ptr);
18353
18354       /* This two-pass algorithm for processing partial symbols has a
18355          high cost in cache pressure.  Thus, handle some simple cases
18356          here which cover the majority of C partial symbols.  DIEs
18357          which neither have specification tags in them, nor could have
18358          specification tags elsewhere pointing at them, can simply be
18359          processed and discarded.
18360
18361          This segment is also optional; scan_partial_symbols and
18362          add_partial_symbol will handle these DIEs if we chain
18363          them in normally.  When compilers which do not emit large
18364          quantities of duplicate debug information are more common,
18365          this code can probably be removed.  */
18366
18367       /* Any complete simple types at the top level (pretty much all
18368          of them, for a language without namespaces), can be processed
18369          directly.  */
18370       if (parent_die == NULL
18371           && part_die->has_specification == 0
18372           && part_die->is_declaration == 0
18373           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18374               || part_die->tag == DW_TAG_base_type
18375               || part_die->tag == DW_TAG_subrange_type))
18376         {
18377           if (building_psymtab && part_die->name != NULL)
18378             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18379                                  VAR_DOMAIN, LOC_TYPEDEF,
18380                                  &objfile->static_psymbols,
18381                                  0, cu->language, objfile);
18382           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18383           continue;
18384         }
18385
18386       /* The exception for DW_TAG_typedef with has_children above is
18387          a workaround of GCC PR debug/47510.  In the case of this complaint
18388          type_name_no_tag_or_error will error on such types later.
18389
18390          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18391          it could not find the child DIEs referenced later, this is checked
18392          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18393
18394       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18395         complaint (&symfile_complaints,
18396                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18397                      "- DIE at 0x%x [in module %s]"),
18398                    to_underlying (part_die->sect_off), objfile_name (objfile));
18399
18400       /* If we're at the second level, and we're an enumerator, and
18401          our parent has no specification (meaning possibly lives in a
18402          namespace elsewhere), then we can add the partial symbol now
18403          instead of queueing it.  */
18404       if (part_die->tag == DW_TAG_enumerator
18405           && parent_die != NULL
18406           && parent_die->die_parent == NULL
18407           && parent_die->tag == DW_TAG_enumeration_type
18408           && parent_die->has_specification == 0)
18409         {
18410           if (part_die->name == NULL)
18411             complaint (&symfile_complaints,
18412                        _("malformed enumerator DIE ignored"));
18413           else if (building_psymtab)
18414             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18415                                  VAR_DOMAIN, LOC_CONST,
18416                                  cu->language == language_cplus
18417                                  ? &objfile->global_psymbols
18418                                  : &objfile->static_psymbols,
18419                                  0, cu->language, objfile);
18420
18421           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18422           continue;
18423         }
18424
18425       /* We'll save this DIE so link it in.  */
18426       part_die->die_parent = parent_die;
18427       part_die->die_sibling = NULL;
18428       part_die->die_child = NULL;
18429
18430       if (last_die && last_die == parent_die)
18431         last_die->die_child = part_die;
18432       else if (last_die)
18433         last_die->die_sibling = part_die;
18434
18435       last_die = part_die;
18436
18437       if (first_die == NULL)
18438         first_die = part_die;
18439
18440       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18441          find interesting need to be in the hash table, because we
18442          also have the parent/sibling/child chains; only those that we
18443          might refer to by offset later during partial symbol reading.
18444
18445          For now this means things that might have be the target of a
18446          DW_AT_specification, DW_AT_abstract_origin, or
18447          DW_AT_extension.  DW_AT_extension will refer only to
18448          namespaces; DW_AT_abstract_origin refers to functions (and
18449          many things under the function DIE, but we do not recurse
18450          into function DIEs during partial symbol reading) and
18451          possibly variables as well; DW_AT_specification refers to
18452          declarations.  Declarations ought to have the DW_AT_declaration
18453          flag.  It happens that GCC forgets to put it in sometimes, but
18454          only for functions, not for types.
18455
18456          Adding more things than necessary to the hash table is harmless
18457          except for the performance cost.  Adding too few will result in
18458          wasted time in find_partial_die, when we reread the compilation
18459          unit with load_all_dies set.  */
18460
18461       if (load_all
18462           || abbrev->tag == DW_TAG_constant
18463           || abbrev->tag == DW_TAG_subprogram
18464           || abbrev->tag == DW_TAG_variable
18465           || abbrev->tag == DW_TAG_namespace
18466           || part_die->is_declaration)
18467         {
18468           void **slot;
18469
18470           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18471                                            to_underlying (part_die->sect_off),
18472                                            INSERT);
18473           *slot = part_die;
18474         }
18475
18476       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18477
18478       /* For some DIEs we want to follow their children (if any).  For C
18479          we have no reason to follow the children of structures; for other
18480          languages we have to, so that we can get at method physnames
18481          to infer fully qualified class names, for DW_AT_specification,
18482          and for C++ template arguments.  For C++, we also look one level
18483          inside functions to find template arguments (if the name of the
18484          function does not already contain the template arguments).
18485
18486          For Ada, we need to scan the children of subprograms and lexical
18487          blocks as well because Ada allows the definition of nested
18488          entities that could be interesting for the debugger, such as
18489          nested subprograms for instance.  */
18490       if (last_die->has_children
18491           && (load_all
18492               || last_die->tag == DW_TAG_namespace
18493               || last_die->tag == DW_TAG_module
18494               || last_die->tag == DW_TAG_enumeration_type
18495               || (cu->language == language_cplus
18496                   && last_die->tag == DW_TAG_subprogram
18497                   && (last_die->name == NULL
18498                       || strchr (last_die->name, '<') == NULL))
18499               || (cu->language != language_c
18500                   && (last_die->tag == DW_TAG_class_type
18501                       || last_die->tag == DW_TAG_interface_type
18502                       || last_die->tag == DW_TAG_structure_type
18503                       || last_die->tag == DW_TAG_union_type))
18504               || (cu->language == language_ada
18505                   && (last_die->tag == DW_TAG_subprogram
18506                       || last_die->tag == DW_TAG_lexical_block))))
18507         {
18508           nesting_level++;
18509           parent_die = last_die;
18510           continue;
18511         }
18512
18513       /* Otherwise we skip to the next sibling, if any.  */
18514       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18515
18516       /* Back to the top, do it again.  */
18517     }
18518 }
18519
18520 /* Read a minimal amount of information into the minimal die structure.  */
18521
18522 static const gdb_byte *
18523 read_partial_die (const struct die_reader_specs *reader,
18524                   struct partial_die_info *part_die,
18525                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18526                   const gdb_byte *info_ptr)
18527 {
18528   struct dwarf2_cu *cu = reader->cu;
18529   struct dwarf2_per_objfile *dwarf2_per_objfile
18530     = cu->per_cu->dwarf2_per_objfile;
18531   struct objfile *objfile = dwarf2_per_objfile->objfile;
18532   const gdb_byte *buffer = reader->buffer;
18533   unsigned int i;
18534   struct attribute attr;
18535   int has_low_pc_attr = 0;
18536   int has_high_pc_attr = 0;
18537   int high_pc_relative = 0;
18538
18539   memset (part_die, 0, sizeof (struct partial_die_info));
18540
18541   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18542
18543   info_ptr += abbrev_len;
18544
18545   if (abbrev == NULL)
18546     return info_ptr;
18547
18548   part_die->tag = abbrev->tag;
18549   part_die->has_children = abbrev->has_children;
18550
18551   for (i = 0; i < abbrev->num_attrs; ++i)
18552     {
18553       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18554
18555       /* Store the data if it is of an attribute we want to keep in a
18556          partial symbol table.  */
18557       switch (attr.name)
18558         {
18559         case DW_AT_name:
18560           switch (part_die->tag)
18561             {
18562             case DW_TAG_compile_unit:
18563             case DW_TAG_partial_unit:
18564             case DW_TAG_type_unit:
18565               /* Compilation units have a DW_AT_name that is a filename, not
18566                  a source language identifier.  */
18567             case DW_TAG_enumeration_type:
18568             case DW_TAG_enumerator:
18569               /* These tags always have simple identifiers already; no need
18570                  to canonicalize them.  */
18571               part_die->name = DW_STRING (&attr);
18572               break;
18573             default:
18574               part_die->name
18575                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18576                                             &objfile->per_bfd->storage_obstack);
18577               break;
18578             }
18579           break;
18580         case DW_AT_linkage_name:
18581         case DW_AT_MIPS_linkage_name:
18582           /* Note that both forms of linkage name might appear.  We
18583              assume they will be the same, and we only store the last
18584              one we see.  */
18585           if (cu->language == language_ada)
18586             part_die->name = DW_STRING (&attr);
18587           part_die->linkage_name = DW_STRING (&attr);
18588           break;
18589         case DW_AT_low_pc:
18590           has_low_pc_attr = 1;
18591           part_die->lowpc = attr_value_as_address (&attr);
18592           break;
18593         case DW_AT_high_pc:
18594           has_high_pc_attr = 1;
18595           part_die->highpc = attr_value_as_address (&attr);
18596           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18597                 high_pc_relative = 1;
18598           break;
18599         case DW_AT_location:
18600           /* Support the .debug_loc offsets.  */
18601           if (attr_form_is_block (&attr))
18602             {
18603                part_die->d.locdesc = DW_BLOCK (&attr);
18604             }
18605           else if (attr_form_is_section_offset (&attr))
18606             {
18607               dwarf2_complex_location_expr_complaint ();
18608             }
18609           else
18610             {
18611               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18612                                                      "partial symbol information");
18613             }
18614           break;
18615         case DW_AT_external:
18616           part_die->is_external = DW_UNSND (&attr);
18617           break;
18618         case DW_AT_declaration:
18619           part_die->is_declaration = DW_UNSND (&attr);
18620           break;
18621         case DW_AT_type:
18622           part_die->has_type = 1;
18623           break;
18624         case DW_AT_abstract_origin:
18625         case DW_AT_specification:
18626         case DW_AT_extension:
18627           part_die->has_specification = 1;
18628           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18629           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18630                                    || cu->per_cu->is_dwz);
18631           break;
18632         case DW_AT_sibling:
18633           /* Ignore absolute siblings, they might point outside of
18634              the current compile unit.  */
18635           if (attr.form == DW_FORM_ref_addr)
18636             complaint (&symfile_complaints,
18637                        _("ignoring absolute DW_AT_sibling"));
18638           else
18639             {
18640               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18641               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18642
18643               if (sibling_ptr < info_ptr)
18644                 complaint (&symfile_complaints,
18645                            _("DW_AT_sibling points backwards"));
18646               else if (sibling_ptr > reader->buffer_end)
18647                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18648               else
18649                 part_die->sibling = sibling_ptr;
18650             }
18651           break;
18652         case DW_AT_byte_size:
18653           part_die->has_byte_size = 1;
18654           break;
18655         case DW_AT_const_value:
18656           part_die->has_const_value = 1;
18657           break;
18658         case DW_AT_calling_convention:
18659           /* DWARF doesn't provide a way to identify a program's source-level
18660              entry point.  DW_AT_calling_convention attributes are only meant
18661              to describe functions' calling conventions.
18662
18663              However, because it's a necessary piece of information in
18664              Fortran, and before DWARF 4 DW_CC_program was the only
18665              piece of debugging information whose definition refers to
18666              a 'main program' at all, several compilers marked Fortran
18667              main programs with DW_CC_program --- even when those
18668              functions use the standard calling conventions.
18669
18670              Although DWARF now specifies a way to provide this
18671              information, we support this practice for backward
18672              compatibility.  */
18673           if (DW_UNSND (&attr) == DW_CC_program
18674               && cu->language == language_fortran)
18675             part_die->main_subprogram = 1;
18676           break;
18677         case DW_AT_inline:
18678           if (DW_UNSND (&attr) == DW_INL_inlined
18679               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18680             part_die->may_be_inlined = 1;
18681           break;
18682
18683         case DW_AT_import:
18684           if (part_die->tag == DW_TAG_imported_unit)
18685             {
18686               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18687               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18688                                   || cu->per_cu->is_dwz);
18689             }
18690           break;
18691
18692         case DW_AT_main_subprogram:
18693           part_die->main_subprogram = DW_UNSND (&attr);
18694           break;
18695
18696         default:
18697           break;
18698         }
18699     }
18700
18701   if (high_pc_relative)
18702     part_die->highpc += part_die->lowpc;
18703
18704   if (has_low_pc_attr && has_high_pc_attr)
18705     {
18706       /* When using the GNU linker, .gnu.linkonce. sections are used to
18707          eliminate duplicate copies of functions and vtables and such.
18708          The linker will arbitrarily choose one and discard the others.
18709          The AT_*_pc values for such functions refer to local labels in
18710          these sections.  If the section from that file was discarded, the
18711          labels are not in the output, so the relocs get a value of 0.
18712          If this is a discarded function, mark the pc bounds as invalid,
18713          so that GDB will ignore it.  */
18714       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18715         {
18716           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18717
18718           complaint (&symfile_complaints,
18719                      _("DW_AT_low_pc %s is zero "
18720                        "for DIE at 0x%x [in module %s]"),
18721                      paddress (gdbarch, part_die->lowpc),
18722                      to_underlying (part_die->sect_off), objfile_name (objfile));
18723         }
18724       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18725       else if (part_die->lowpc >= part_die->highpc)
18726         {
18727           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18728
18729           complaint (&symfile_complaints,
18730                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18731                        "for DIE at 0x%x [in module %s]"),
18732                      paddress (gdbarch, part_die->lowpc),
18733                      paddress (gdbarch, part_die->highpc),
18734                      to_underlying (part_die->sect_off),
18735                      objfile_name (objfile));
18736         }
18737       else
18738         part_die->has_pc_info = 1;
18739     }
18740
18741   return info_ptr;
18742 }
18743
18744 /* Find a cached partial DIE at OFFSET in CU.  */
18745
18746 static struct partial_die_info *
18747 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18748 {
18749   struct partial_die_info *lookup_die = NULL;
18750   struct partial_die_info part_die;
18751
18752   part_die.sect_off = sect_off;
18753   lookup_die = ((struct partial_die_info *)
18754                 htab_find_with_hash (cu->partial_dies, &part_die,
18755                                      to_underlying (sect_off)));
18756
18757   return lookup_die;
18758 }
18759
18760 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18761    except in the case of .debug_types DIEs which do not reference
18762    outside their CU (they do however referencing other types via
18763    DW_FORM_ref_sig8).  */
18764
18765 static struct partial_die_info *
18766 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18767 {
18768   struct dwarf2_per_objfile *dwarf2_per_objfile
18769     = cu->per_cu->dwarf2_per_objfile;
18770   struct objfile *objfile = dwarf2_per_objfile->objfile;
18771   struct dwarf2_per_cu_data *per_cu = NULL;
18772   struct partial_die_info *pd = NULL;
18773
18774   if (offset_in_dwz == cu->per_cu->is_dwz
18775       && offset_in_cu_p (&cu->header, sect_off))
18776     {
18777       pd = find_partial_die_in_comp_unit (sect_off, cu);
18778       if (pd != NULL)
18779         return pd;
18780       /* We missed recording what we needed.
18781          Load all dies and try again.  */
18782       per_cu = cu->per_cu;
18783     }
18784   else
18785     {
18786       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18787       if (cu->per_cu->is_debug_types)
18788         {
18789           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18790                    " external reference to offset 0x%x [in module %s].\n"),
18791                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18792                  bfd_get_filename (objfile->obfd));
18793         }
18794       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18795                                                  dwarf2_per_objfile);
18796
18797       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18798         load_partial_comp_unit (per_cu);
18799
18800       per_cu->cu->last_used = 0;
18801       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18802     }
18803
18804   /* If we didn't find it, and not all dies have been loaded,
18805      load them all and try again.  */
18806
18807   if (pd == NULL && per_cu->load_all_dies == 0)
18808     {
18809       per_cu->load_all_dies = 1;
18810
18811       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18812          THIS_CU->cu may already be in use.  So we can't just free it and
18813          replace its DIEs with the ones we read in.  Instead, we leave those
18814          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18815          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18816          set.  */
18817       load_partial_comp_unit (per_cu);
18818
18819       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18820     }
18821
18822   if (pd == NULL)
18823     internal_error (__FILE__, __LINE__,
18824                     _("could not find partial DIE 0x%x "
18825                       "in cache [from module %s]\n"),
18826                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18827   return pd;
18828 }
18829
18830 /* See if we can figure out if the class lives in a namespace.  We do
18831    this by looking for a member function; its demangled name will
18832    contain namespace info, if there is any.  */
18833
18834 static void
18835 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18836                                   struct dwarf2_cu *cu)
18837 {
18838   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18839      what template types look like, because the demangler
18840      frequently doesn't give the same name as the debug info.  We
18841      could fix this by only using the demangled name to get the
18842      prefix (but see comment in read_structure_type).  */
18843
18844   struct partial_die_info *real_pdi;
18845   struct partial_die_info *child_pdi;
18846
18847   /* If this DIE (this DIE's specification, if any) has a parent, then
18848      we should not do this.  We'll prepend the parent's fully qualified
18849      name when we create the partial symbol.  */
18850
18851   real_pdi = struct_pdi;
18852   while (real_pdi->has_specification)
18853     real_pdi = find_partial_die (real_pdi->spec_offset,
18854                                  real_pdi->spec_is_dwz, cu);
18855
18856   if (real_pdi->die_parent != NULL)
18857     return;
18858
18859   for (child_pdi = struct_pdi->die_child;
18860        child_pdi != NULL;
18861        child_pdi = child_pdi->die_sibling)
18862     {
18863       if (child_pdi->tag == DW_TAG_subprogram
18864           && child_pdi->linkage_name != NULL)
18865         {
18866           char *actual_class_name
18867             = language_class_name_from_physname (cu->language_defn,
18868                                                  child_pdi->linkage_name);
18869           if (actual_class_name != NULL)
18870             {
18871               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18872               struct_pdi->name
18873                 = ((const char *)
18874                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18875                                   actual_class_name,
18876                                   strlen (actual_class_name)));
18877               xfree (actual_class_name);
18878             }
18879           break;
18880         }
18881     }
18882 }
18883
18884 /* Adjust PART_DIE before generating a symbol for it.  This function
18885    may set the is_external flag or change the DIE's name.  */
18886
18887 static void
18888 fixup_partial_die (struct partial_die_info *part_die,
18889                    struct dwarf2_cu *cu)
18890 {
18891   /* Once we've fixed up a die, there's no point in doing so again.
18892      This also avoids a memory leak if we were to call
18893      guess_partial_die_structure_name multiple times.  */
18894   if (part_die->fixup_called)
18895     return;
18896
18897   /* If we found a reference attribute and the DIE has no name, try
18898      to find a name in the referred to DIE.  */
18899
18900   if (part_die->name == NULL && part_die->has_specification)
18901     {
18902       struct partial_die_info *spec_die;
18903
18904       spec_die = find_partial_die (part_die->spec_offset,
18905                                    part_die->spec_is_dwz, cu);
18906
18907       fixup_partial_die (spec_die, cu);
18908
18909       if (spec_die->name)
18910         {
18911           part_die->name = spec_die->name;
18912
18913           /* Copy DW_AT_external attribute if it is set.  */
18914           if (spec_die->is_external)
18915             part_die->is_external = spec_die->is_external;
18916         }
18917     }
18918
18919   /* Set default names for some unnamed DIEs.  */
18920
18921   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18922     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18923
18924   /* If there is no parent die to provide a namespace, and there are
18925      children, see if we can determine the namespace from their linkage
18926      name.  */
18927   if (cu->language == language_cplus
18928       && !VEC_empty (dwarf2_section_info_def,
18929                      cu->per_cu->dwarf2_per_objfile->types)
18930       && part_die->die_parent == NULL
18931       && part_die->has_children
18932       && (part_die->tag == DW_TAG_class_type
18933           || part_die->tag == DW_TAG_structure_type
18934           || part_die->tag == DW_TAG_union_type))
18935     guess_partial_die_structure_name (part_die, cu);
18936
18937   /* GCC might emit a nameless struct or union that has a linkage
18938      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18939   if (part_die->name == NULL
18940       && (part_die->tag == DW_TAG_class_type
18941           || part_die->tag == DW_TAG_interface_type
18942           || part_die->tag == DW_TAG_structure_type
18943           || part_die->tag == DW_TAG_union_type)
18944       && part_die->linkage_name != NULL)
18945     {
18946       char *demangled;
18947
18948       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18949       if (demangled)
18950         {
18951           const char *base;
18952
18953           /* Strip any leading namespaces/classes, keep only the base name.
18954              DW_AT_name for named DIEs does not contain the prefixes.  */
18955           base = strrchr (demangled, ':');
18956           if (base && base > demangled && base[-1] == ':')
18957             base++;
18958           else
18959             base = demangled;
18960
18961           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18962           part_die->name
18963             = ((const char *)
18964                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18965                               base, strlen (base)));
18966           xfree (demangled);
18967         }
18968     }
18969
18970   part_die->fixup_called = 1;
18971 }
18972
18973 /* Read an attribute value described by an attribute form.  */
18974
18975 static const gdb_byte *
18976 read_attribute_value (const struct die_reader_specs *reader,
18977                       struct attribute *attr, unsigned form,
18978                       LONGEST implicit_const, const gdb_byte *info_ptr)
18979 {
18980   struct dwarf2_cu *cu = reader->cu;
18981   struct dwarf2_per_objfile *dwarf2_per_objfile
18982     = cu->per_cu->dwarf2_per_objfile;
18983   struct objfile *objfile = dwarf2_per_objfile->objfile;
18984   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18985   bfd *abfd = reader->abfd;
18986   struct comp_unit_head *cu_header = &cu->header;
18987   unsigned int bytes_read;
18988   struct dwarf_block *blk;
18989
18990   attr->form = (enum dwarf_form) form;
18991   switch (form)
18992     {
18993     case DW_FORM_ref_addr:
18994       if (cu->header.version == 2)
18995         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18996       else
18997         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18998                                        &cu->header, &bytes_read);
18999       info_ptr += bytes_read;
19000       break;
19001     case DW_FORM_GNU_ref_alt:
19002       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19003       info_ptr += bytes_read;
19004       break;
19005     case DW_FORM_addr:
19006       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19007       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19008       info_ptr += bytes_read;
19009       break;
19010     case DW_FORM_block2:
19011       blk = dwarf_alloc_block (cu);
19012       blk->size = read_2_bytes (abfd, info_ptr);
19013       info_ptr += 2;
19014       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19015       info_ptr += blk->size;
19016       DW_BLOCK (attr) = blk;
19017       break;
19018     case DW_FORM_block4:
19019       blk = dwarf_alloc_block (cu);
19020       blk->size = read_4_bytes (abfd, info_ptr);
19021       info_ptr += 4;
19022       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19023       info_ptr += blk->size;
19024       DW_BLOCK (attr) = blk;
19025       break;
19026     case DW_FORM_data2:
19027       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19028       info_ptr += 2;
19029       break;
19030     case DW_FORM_data4:
19031       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19032       info_ptr += 4;
19033       break;
19034     case DW_FORM_data8:
19035       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19036       info_ptr += 8;
19037       break;
19038     case DW_FORM_data16:
19039       blk = dwarf_alloc_block (cu);
19040       blk->size = 16;
19041       blk->data = read_n_bytes (abfd, info_ptr, 16);
19042       info_ptr += 16;
19043       DW_BLOCK (attr) = blk;
19044       break;
19045     case DW_FORM_sec_offset:
19046       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19047       info_ptr += bytes_read;
19048       break;
19049     case DW_FORM_string:
19050       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19051       DW_STRING_IS_CANONICAL (attr) = 0;
19052       info_ptr += bytes_read;
19053       break;
19054     case DW_FORM_strp:
19055       if (!cu->per_cu->is_dwz)
19056         {
19057           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19058                                                    abfd, info_ptr, cu_header,
19059                                                    &bytes_read);
19060           DW_STRING_IS_CANONICAL (attr) = 0;
19061           info_ptr += bytes_read;
19062           break;
19063         }
19064       /* FALLTHROUGH */
19065     case DW_FORM_line_strp:
19066       if (!cu->per_cu->is_dwz)
19067         {
19068           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19069                                                         abfd, info_ptr,
19070                                                         cu_header, &bytes_read);
19071           DW_STRING_IS_CANONICAL (attr) = 0;
19072           info_ptr += bytes_read;
19073           break;
19074         }
19075       /* FALLTHROUGH */
19076     case DW_FORM_GNU_strp_alt:
19077       {
19078         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19079         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19080                                           &bytes_read);
19081
19082         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19083                                                           dwz, str_offset);
19084         DW_STRING_IS_CANONICAL (attr) = 0;
19085         info_ptr += bytes_read;
19086       }
19087       break;
19088     case DW_FORM_exprloc:
19089     case DW_FORM_block:
19090       blk = dwarf_alloc_block (cu);
19091       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19092       info_ptr += bytes_read;
19093       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19094       info_ptr += blk->size;
19095       DW_BLOCK (attr) = blk;
19096       break;
19097     case DW_FORM_block1:
19098       blk = dwarf_alloc_block (cu);
19099       blk->size = read_1_byte (abfd, info_ptr);
19100       info_ptr += 1;
19101       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19102       info_ptr += blk->size;
19103       DW_BLOCK (attr) = blk;
19104       break;
19105     case DW_FORM_data1:
19106       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19107       info_ptr += 1;
19108       break;
19109     case DW_FORM_flag:
19110       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19111       info_ptr += 1;
19112       break;
19113     case DW_FORM_flag_present:
19114       DW_UNSND (attr) = 1;
19115       break;
19116     case DW_FORM_sdata:
19117       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19118       info_ptr += bytes_read;
19119       break;
19120     case DW_FORM_udata:
19121       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19122       info_ptr += bytes_read;
19123       break;
19124     case DW_FORM_ref1:
19125       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19126                          + read_1_byte (abfd, info_ptr));
19127       info_ptr += 1;
19128       break;
19129     case DW_FORM_ref2:
19130       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19131                          + read_2_bytes (abfd, info_ptr));
19132       info_ptr += 2;
19133       break;
19134     case DW_FORM_ref4:
19135       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19136                          + read_4_bytes (abfd, info_ptr));
19137       info_ptr += 4;
19138       break;
19139     case DW_FORM_ref8:
19140       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19141                          + read_8_bytes (abfd, info_ptr));
19142       info_ptr += 8;
19143       break;
19144     case DW_FORM_ref_sig8:
19145       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19146       info_ptr += 8;
19147       break;
19148     case DW_FORM_ref_udata:
19149       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19150                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19151       info_ptr += bytes_read;
19152       break;
19153     case DW_FORM_indirect:
19154       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19155       info_ptr += bytes_read;
19156       if (form == DW_FORM_implicit_const)
19157         {
19158           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19159           info_ptr += bytes_read;
19160         }
19161       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19162                                        info_ptr);
19163       break;
19164     case DW_FORM_implicit_const:
19165       DW_SND (attr) = implicit_const;
19166       break;
19167     case DW_FORM_GNU_addr_index:
19168       if (reader->dwo_file == NULL)
19169         {
19170           /* For now flag a hard error.
19171              Later we can turn this into a complaint.  */
19172           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19173                  dwarf_form_name (form),
19174                  bfd_get_filename (abfd));
19175         }
19176       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19177       info_ptr += bytes_read;
19178       break;
19179     case DW_FORM_GNU_str_index:
19180       if (reader->dwo_file == NULL)
19181         {
19182           /* For now flag a hard error.
19183              Later we can turn this into a complaint if warranted.  */
19184           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19185                  dwarf_form_name (form),
19186                  bfd_get_filename (abfd));
19187         }
19188       {
19189         ULONGEST str_index =
19190           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19191
19192         DW_STRING (attr) = read_str_index (reader, str_index);
19193         DW_STRING_IS_CANONICAL (attr) = 0;
19194         info_ptr += bytes_read;
19195       }
19196       break;
19197     default:
19198       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19199              dwarf_form_name (form),
19200              bfd_get_filename (abfd));
19201     }
19202
19203   /* Super hack.  */
19204   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19205     attr->form = DW_FORM_GNU_ref_alt;
19206
19207   /* We have seen instances where the compiler tried to emit a byte
19208      size attribute of -1 which ended up being encoded as an unsigned
19209      0xffffffff.  Although 0xffffffff is technically a valid size value,
19210      an object of this size seems pretty unlikely so we can relatively
19211      safely treat these cases as if the size attribute was invalid and
19212      treat them as zero by default.  */
19213   if (attr->name == DW_AT_byte_size
19214       && form == DW_FORM_data4
19215       && DW_UNSND (attr) >= 0xffffffff)
19216     {
19217       complaint
19218         (&symfile_complaints,
19219          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19220          hex_string (DW_UNSND (attr)));
19221       DW_UNSND (attr) = 0;
19222     }
19223
19224   return info_ptr;
19225 }
19226
19227 /* Read an attribute described by an abbreviated attribute.  */
19228
19229 static const gdb_byte *
19230 read_attribute (const struct die_reader_specs *reader,
19231                 struct attribute *attr, struct attr_abbrev *abbrev,
19232                 const gdb_byte *info_ptr)
19233 {
19234   attr->name = abbrev->name;
19235   return read_attribute_value (reader, attr, abbrev->form,
19236                                abbrev->implicit_const, info_ptr);
19237 }
19238
19239 /* Read dwarf information from a buffer.  */
19240
19241 static unsigned int
19242 read_1_byte (bfd *abfd, const gdb_byte *buf)
19243 {
19244   return bfd_get_8 (abfd, buf);
19245 }
19246
19247 static int
19248 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19249 {
19250   return bfd_get_signed_8 (abfd, buf);
19251 }
19252
19253 static unsigned int
19254 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19255 {
19256   return bfd_get_16 (abfd, buf);
19257 }
19258
19259 static int
19260 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19261 {
19262   return bfd_get_signed_16 (abfd, buf);
19263 }
19264
19265 static unsigned int
19266 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19267 {
19268   return bfd_get_32 (abfd, buf);
19269 }
19270
19271 static int
19272 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19273 {
19274   return bfd_get_signed_32 (abfd, buf);
19275 }
19276
19277 static ULONGEST
19278 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19279 {
19280   return bfd_get_64 (abfd, buf);
19281 }
19282
19283 static CORE_ADDR
19284 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19285               unsigned int *bytes_read)
19286 {
19287   struct comp_unit_head *cu_header = &cu->header;
19288   CORE_ADDR retval = 0;
19289
19290   if (cu_header->signed_addr_p)
19291     {
19292       switch (cu_header->addr_size)
19293         {
19294         case 2:
19295           retval = bfd_get_signed_16 (abfd, buf);
19296           break;
19297         case 4:
19298           retval = bfd_get_signed_32 (abfd, buf);
19299           break;
19300         case 8:
19301           retval = bfd_get_signed_64 (abfd, buf);
19302           break;
19303         default:
19304           internal_error (__FILE__, __LINE__,
19305                           _("read_address: bad switch, signed [in module %s]"),
19306                           bfd_get_filename (abfd));
19307         }
19308     }
19309   else
19310     {
19311       switch (cu_header->addr_size)
19312         {
19313         case 2:
19314           retval = bfd_get_16 (abfd, buf);
19315           break;
19316         case 4:
19317           retval = bfd_get_32 (abfd, buf);
19318           break;
19319         case 8:
19320           retval = bfd_get_64 (abfd, buf);
19321           break;
19322         default:
19323           internal_error (__FILE__, __LINE__,
19324                           _("read_address: bad switch, "
19325                             "unsigned [in module %s]"),
19326                           bfd_get_filename (abfd));
19327         }
19328     }
19329
19330   *bytes_read = cu_header->addr_size;
19331   return retval;
19332 }
19333
19334 /* Read the initial length from a section.  The (draft) DWARF 3
19335    specification allows the initial length to take up either 4 bytes
19336    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19337    bytes describe the length and all offsets will be 8 bytes in length
19338    instead of 4.
19339
19340    An older, non-standard 64-bit format is also handled by this
19341    function.  The older format in question stores the initial length
19342    as an 8-byte quantity without an escape value.  Lengths greater
19343    than 2^32 aren't very common which means that the initial 4 bytes
19344    is almost always zero.  Since a length value of zero doesn't make
19345    sense for the 32-bit format, this initial zero can be considered to
19346    be an escape value which indicates the presence of the older 64-bit
19347    format.  As written, the code can't detect (old format) lengths
19348    greater than 4GB.  If it becomes necessary to handle lengths
19349    somewhat larger than 4GB, we could allow other small values (such
19350    as the non-sensical values of 1, 2, and 3) to also be used as
19351    escape values indicating the presence of the old format.
19352
19353    The value returned via bytes_read should be used to increment the
19354    relevant pointer after calling read_initial_length().
19355
19356    [ Note:  read_initial_length() and read_offset() are based on the
19357      document entitled "DWARF Debugging Information Format", revision
19358      3, draft 8, dated November 19, 2001.  This document was obtained
19359      from:
19360
19361         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19362
19363      This document is only a draft and is subject to change.  (So beware.)
19364
19365      Details regarding the older, non-standard 64-bit format were
19366      determined empirically by examining 64-bit ELF files produced by
19367      the SGI toolchain on an IRIX 6.5 machine.
19368
19369      - Kevin, July 16, 2002
19370    ] */
19371
19372 static LONGEST
19373 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19374 {
19375   LONGEST length = bfd_get_32 (abfd, buf);
19376
19377   if (length == 0xffffffff)
19378     {
19379       length = bfd_get_64 (abfd, buf + 4);
19380       *bytes_read = 12;
19381     }
19382   else if (length == 0)
19383     {
19384       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19385       length = bfd_get_64 (abfd, buf);
19386       *bytes_read = 8;
19387     }
19388   else
19389     {
19390       *bytes_read = 4;
19391     }
19392
19393   return length;
19394 }
19395
19396 /* Cover function for read_initial_length.
19397    Returns the length of the object at BUF, and stores the size of the
19398    initial length in *BYTES_READ and stores the size that offsets will be in
19399    *OFFSET_SIZE.
19400    If the initial length size is not equivalent to that specified in
19401    CU_HEADER then issue a complaint.
19402    This is useful when reading non-comp-unit headers.  */
19403
19404 static LONGEST
19405 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19406                                         const struct comp_unit_head *cu_header,
19407                                         unsigned int *bytes_read,
19408                                         unsigned int *offset_size)
19409 {
19410   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19411
19412   gdb_assert (cu_header->initial_length_size == 4
19413               || cu_header->initial_length_size == 8
19414               || cu_header->initial_length_size == 12);
19415
19416   if (cu_header->initial_length_size != *bytes_read)
19417     complaint (&symfile_complaints,
19418                _("intermixed 32-bit and 64-bit DWARF sections"));
19419
19420   *offset_size = (*bytes_read == 4) ? 4 : 8;
19421   return length;
19422 }
19423
19424 /* Read an offset from the data stream.  The size of the offset is
19425    given by cu_header->offset_size.  */
19426
19427 static LONGEST
19428 read_offset (bfd *abfd, const gdb_byte *buf,
19429              const struct comp_unit_head *cu_header,
19430              unsigned int *bytes_read)
19431 {
19432   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19433
19434   *bytes_read = cu_header->offset_size;
19435   return offset;
19436 }
19437
19438 /* Read an offset from the data stream.  */
19439
19440 static LONGEST
19441 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19442 {
19443   LONGEST retval = 0;
19444
19445   switch (offset_size)
19446     {
19447     case 4:
19448       retval = bfd_get_32 (abfd, buf);
19449       break;
19450     case 8:
19451       retval = bfd_get_64 (abfd, buf);
19452       break;
19453     default:
19454       internal_error (__FILE__, __LINE__,
19455                       _("read_offset_1: bad switch [in module %s]"),
19456                       bfd_get_filename (abfd));
19457     }
19458
19459   return retval;
19460 }
19461
19462 static const gdb_byte *
19463 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19464 {
19465   /* If the size of a host char is 8 bits, we can return a pointer
19466      to the buffer, otherwise we have to copy the data to a buffer
19467      allocated on the temporary obstack.  */
19468   gdb_assert (HOST_CHAR_BIT == 8);
19469   return buf;
19470 }
19471
19472 static const char *
19473 read_direct_string (bfd *abfd, const gdb_byte *buf,
19474                     unsigned int *bytes_read_ptr)
19475 {
19476   /* If the size of a host char is 8 bits, we can return a pointer
19477      to the string, otherwise we have to copy the string to a buffer
19478      allocated on the temporary obstack.  */
19479   gdb_assert (HOST_CHAR_BIT == 8);
19480   if (*buf == '\0')
19481     {
19482       *bytes_read_ptr = 1;
19483       return NULL;
19484     }
19485   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19486   return (const char *) buf;
19487 }
19488
19489 /* Return pointer to string at section SECT offset STR_OFFSET with error
19490    reporting strings FORM_NAME and SECT_NAME.  */
19491
19492 static const char *
19493 read_indirect_string_at_offset_from (struct objfile *objfile,
19494                                      bfd *abfd, LONGEST str_offset,
19495                                      struct dwarf2_section_info *sect,
19496                                      const char *form_name,
19497                                      const char *sect_name)
19498 {
19499   dwarf2_read_section (objfile, sect);
19500   if (sect->buffer == NULL)
19501     error (_("%s used without %s section [in module %s]"),
19502            form_name, sect_name, bfd_get_filename (abfd));
19503   if (str_offset >= sect->size)
19504     error (_("%s pointing outside of %s section [in module %s]"),
19505            form_name, sect_name, bfd_get_filename (abfd));
19506   gdb_assert (HOST_CHAR_BIT == 8);
19507   if (sect->buffer[str_offset] == '\0')
19508     return NULL;
19509   return (const char *) (sect->buffer + str_offset);
19510 }
19511
19512 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19513
19514 static const char *
19515 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19516                                 bfd *abfd, LONGEST str_offset)
19517 {
19518   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19519                                               abfd, str_offset,
19520                                               &dwarf2_per_objfile->str,
19521                                               "DW_FORM_strp", ".debug_str");
19522 }
19523
19524 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19525
19526 static const char *
19527 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19528                                      bfd *abfd, LONGEST str_offset)
19529 {
19530   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19531                                               abfd, str_offset,
19532                                               &dwarf2_per_objfile->line_str,
19533                                               "DW_FORM_line_strp",
19534                                               ".debug_line_str");
19535 }
19536
19537 /* Read a string at offset STR_OFFSET in the .debug_str section from
19538    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19539    the string consists of a single NUL byte, return NULL; otherwise
19540    return a pointer to the string.  */
19541
19542 static const char *
19543 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19544                                LONGEST str_offset)
19545 {
19546   dwarf2_read_section (objfile, &dwz->str);
19547
19548   if (dwz->str.buffer == NULL)
19549     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19550              "section [in module %s]"),
19551            bfd_get_filename (dwz->dwz_bfd));
19552   if (str_offset >= dwz->str.size)
19553     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19554              ".debug_str section [in module %s]"),
19555            bfd_get_filename (dwz->dwz_bfd));
19556   gdb_assert (HOST_CHAR_BIT == 8);
19557   if (dwz->str.buffer[str_offset] == '\0')
19558     return NULL;
19559   return (const char *) (dwz->str.buffer + str_offset);
19560 }
19561
19562 /* Return pointer to string at .debug_str offset as read from BUF.
19563    BUF is assumed to be in a compilation unit described by CU_HEADER.
19564    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19565
19566 static const char *
19567 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19568                       const gdb_byte *buf,
19569                       const struct comp_unit_head *cu_header,
19570                       unsigned int *bytes_read_ptr)
19571 {
19572   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19573
19574   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19575 }
19576
19577 /* Return pointer to string at .debug_line_str offset as read from BUF.
19578    BUF is assumed to be in a compilation unit described by CU_HEADER.
19579    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19580
19581 static const char *
19582 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19583                            bfd *abfd, const gdb_byte *buf,
19584                            const struct comp_unit_head *cu_header,
19585                            unsigned int *bytes_read_ptr)
19586 {
19587   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19588
19589   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19590                                               str_offset);
19591 }
19592
19593 ULONGEST
19594 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19595                           unsigned int *bytes_read_ptr)
19596 {
19597   ULONGEST result;
19598   unsigned int num_read;
19599   int shift;
19600   unsigned char byte;
19601
19602   result = 0;
19603   shift = 0;
19604   num_read = 0;
19605   while (1)
19606     {
19607       byte = bfd_get_8 (abfd, buf);
19608       buf++;
19609       num_read++;
19610       result |= ((ULONGEST) (byte & 127) << shift);
19611       if ((byte & 128) == 0)
19612         {
19613           break;
19614         }
19615       shift += 7;
19616     }
19617   *bytes_read_ptr = num_read;
19618   return result;
19619 }
19620
19621 static LONGEST
19622 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19623                     unsigned int *bytes_read_ptr)
19624 {
19625   LONGEST result;
19626   int shift, num_read;
19627   unsigned char byte;
19628
19629   result = 0;
19630   shift = 0;
19631   num_read = 0;
19632   while (1)
19633     {
19634       byte = bfd_get_8 (abfd, buf);
19635       buf++;
19636       num_read++;
19637       result |= ((LONGEST) (byte & 127) << shift);
19638       shift += 7;
19639       if ((byte & 128) == 0)
19640         {
19641           break;
19642         }
19643     }
19644   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19645     result |= -(((LONGEST) 1) << shift);
19646   *bytes_read_ptr = num_read;
19647   return result;
19648 }
19649
19650 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19651    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19652    ADDR_SIZE is the size of addresses from the CU header.  */
19653
19654 static CORE_ADDR
19655 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19656                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19657 {
19658   struct objfile *objfile = dwarf2_per_objfile->objfile;
19659   bfd *abfd = objfile->obfd;
19660   const gdb_byte *info_ptr;
19661
19662   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19663   if (dwarf2_per_objfile->addr.buffer == NULL)
19664     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19665            objfile_name (objfile));
19666   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19667     error (_("DW_FORM_addr_index pointing outside of "
19668              ".debug_addr section [in module %s]"),
19669            objfile_name (objfile));
19670   info_ptr = (dwarf2_per_objfile->addr.buffer
19671               + addr_base + addr_index * addr_size);
19672   if (addr_size == 4)
19673     return bfd_get_32 (abfd, info_ptr);
19674   else
19675     return bfd_get_64 (abfd, info_ptr);
19676 }
19677
19678 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19679
19680 static CORE_ADDR
19681 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19682 {
19683   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19684                             cu->addr_base, cu->header.addr_size);
19685 }
19686
19687 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19688
19689 static CORE_ADDR
19690 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19691                              unsigned int *bytes_read)
19692 {
19693   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19694   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19695
19696   return read_addr_index (cu, addr_index);
19697 }
19698
19699 /* Data structure to pass results from dwarf2_read_addr_index_reader
19700    back to dwarf2_read_addr_index.  */
19701
19702 struct dwarf2_read_addr_index_data
19703 {
19704   ULONGEST addr_base;
19705   int addr_size;
19706 };
19707
19708 /* die_reader_func for dwarf2_read_addr_index.  */
19709
19710 static void
19711 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19712                                const gdb_byte *info_ptr,
19713                                struct die_info *comp_unit_die,
19714                                int has_children,
19715                                void *data)
19716 {
19717   struct dwarf2_cu *cu = reader->cu;
19718   struct dwarf2_read_addr_index_data *aidata =
19719     (struct dwarf2_read_addr_index_data *) data;
19720
19721   aidata->addr_base = cu->addr_base;
19722   aidata->addr_size = cu->header.addr_size;
19723 }
19724
19725 /* Given an index in .debug_addr, fetch the value.
19726    NOTE: This can be called during dwarf expression evaluation,
19727    long after the debug information has been read, and thus per_cu->cu
19728    may no longer exist.  */
19729
19730 CORE_ADDR
19731 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19732                         unsigned int addr_index)
19733 {
19734   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19735   struct objfile *objfile = dwarf2_per_objfile->objfile;
19736   struct dwarf2_cu *cu = per_cu->cu;
19737   ULONGEST addr_base;
19738   int addr_size;
19739
19740   /* We need addr_base and addr_size.
19741      If we don't have PER_CU->cu, we have to get it.
19742      Nasty, but the alternative is storing the needed info in PER_CU,
19743      which at this point doesn't seem justified: it's not clear how frequently
19744      it would get used and it would increase the size of every PER_CU.
19745      Entry points like dwarf2_per_cu_addr_size do a similar thing
19746      so we're not in uncharted territory here.
19747      Alas we need to be a bit more complicated as addr_base is contained
19748      in the DIE.
19749
19750      We don't need to read the entire CU(/TU).
19751      We just need the header and top level die.
19752
19753      IWBN to use the aging mechanism to let us lazily later discard the CU.
19754      For now we skip this optimization.  */
19755
19756   if (cu != NULL)
19757     {
19758       addr_base = cu->addr_base;
19759       addr_size = cu->header.addr_size;
19760     }
19761   else
19762     {
19763       struct dwarf2_read_addr_index_data aidata;
19764
19765       /* Note: We can't use init_cutu_and_read_dies_simple here,
19766          we need addr_base.  */
19767       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19768                                dwarf2_read_addr_index_reader, &aidata);
19769       addr_base = aidata.addr_base;
19770       addr_size = aidata.addr_size;
19771     }
19772
19773   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19774                             addr_size);
19775 }
19776
19777 /* Given a DW_FORM_GNU_str_index, fetch the string.
19778    This is only used by the Fission support.  */
19779
19780 static const char *
19781 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19782 {
19783   struct dwarf2_cu *cu = reader->cu;
19784   struct dwarf2_per_objfile *dwarf2_per_objfile
19785     = cu->per_cu->dwarf2_per_objfile;
19786   struct objfile *objfile = dwarf2_per_objfile->objfile;
19787   const char *objf_name = objfile_name (objfile);
19788   bfd *abfd = objfile->obfd;
19789   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19790   struct dwarf2_section_info *str_offsets_section =
19791     &reader->dwo_file->sections.str_offsets;
19792   const gdb_byte *info_ptr;
19793   ULONGEST str_offset;
19794   static const char form_name[] = "DW_FORM_GNU_str_index";
19795
19796   dwarf2_read_section (objfile, str_section);
19797   dwarf2_read_section (objfile, str_offsets_section);
19798   if (str_section->buffer == NULL)
19799     error (_("%s used without .debug_str.dwo section"
19800              " in CU at offset 0x%x [in module %s]"),
19801            form_name, to_underlying (cu->header.sect_off), objf_name);
19802   if (str_offsets_section->buffer == NULL)
19803     error (_("%s used without .debug_str_offsets.dwo section"
19804              " in CU at offset 0x%x [in module %s]"),
19805            form_name, to_underlying (cu->header.sect_off), objf_name);
19806   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19807     error (_("%s pointing outside of .debug_str_offsets.dwo"
19808              " section in CU at offset 0x%x [in module %s]"),
19809            form_name, to_underlying (cu->header.sect_off), objf_name);
19810   info_ptr = (str_offsets_section->buffer
19811               + str_index * cu->header.offset_size);
19812   if (cu->header.offset_size == 4)
19813     str_offset = bfd_get_32 (abfd, info_ptr);
19814   else
19815     str_offset = bfd_get_64 (abfd, info_ptr);
19816   if (str_offset >= str_section->size)
19817     error (_("Offset from %s pointing outside of"
19818              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19819            form_name, to_underlying (cu->header.sect_off), objf_name);
19820   return (const char *) (str_section->buffer + str_offset);
19821 }
19822
19823 /* Return the length of an LEB128 number in BUF.  */
19824
19825 static int
19826 leb128_size (const gdb_byte *buf)
19827 {
19828   const gdb_byte *begin = buf;
19829   gdb_byte byte;
19830
19831   while (1)
19832     {
19833       byte = *buf++;
19834       if ((byte & 128) == 0)
19835         return buf - begin;
19836     }
19837 }
19838
19839 static void
19840 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19841 {
19842   switch (lang)
19843     {
19844     case DW_LANG_C89:
19845     case DW_LANG_C99:
19846     case DW_LANG_C11:
19847     case DW_LANG_C:
19848     case DW_LANG_UPC:
19849       cu->language = language_c;
19850       break;
19851     case DW_LANG_Java:
19852     case DW_LANG_C_plus_plus:
19853     case DW_LANG_C_plus_plus_11:
19854     case DW_LANG_C_plus_plus_14:
19855       cu->language = language_cplus;
19856       break;
19857     case DW_LANG_D:
19858       cu->language = language_d;
19859       break;
19860     case DW_LANG_Fortran77:
19861     case DW_LANG_Fortran90:
19862     case DW_LANG_Fortran95:
19863     case DW_LANG_Fortran03:
19864     case DW_LANG_Fortran08:
19865       cu->language = language_fortran;
19866       break;
19867     case DW_LANG_Go:
19868       cu->language = language_go;
19869       break;
19870     case DW_LANG_Mips_Assembler:
19871       cu->language = language_asm;
19872       break;
19873     case DW_LANG_Ada83:
19874     case DW_LANG_Ada95:
19875       cu->language = language_ada;
19876       break;
19877     case DW_LANG_Modula2:
19878       cu->language = language_m2;
19879       break;
19880     case DW_LANG_Pascal83:
19881       cu->language = language_pascal;
19882       break;
19883     case DW_LANG_ObjC:
19884       cu->language = language_objc;
19885       break;
19886     case DW_LANG_Rust:
19887     case DW_LANG_Rust_old:
19888       cu->language = language_rust;
19889       break;
19890     case DW_LANG_Cobol74:
19891     case DW_LANG_Cobol85:
19892     default:
19893       cu->language = language_minimal;
19894       break;
19895     }
19896   cu->language_defn = language_def (cu->language);
19897 }
19898
19899 /* Return the named attribute or NULL if not there.  */
19900
19901 static struct attribute *
19902 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19903 {
19904   for (;;)
19905     {
19906       unsigned int i;
19907       struct attribute *spec = NULL;
19908
19909       for (i = 0; i < die->num_attrs; ++i)
19910         {
19911           if (die->attrs[i].name == name)
19912             return &die->attrs[i];
19913           if (die->attrs[i].name == DW_AT_specification
19914               || die->attrs[i].name == DW_AT_abstract_origin)
19915             spec = &die->attrs[i];
19916         }
19917
19918       if (!spec)
19919         break;
19920
19921       die = follow_die_ref (die, spec, &cu);
19922     }
19923
19924   return NULL;
19925 }
19926
19927 /* Return the named attribute or NULL if not there,
19928    but do not follow DW_AT_specification, etc.
19929    This is for use in contexts where we're reading .debug_types dies.
19930    Following DW_AT_specification, DW_AT_abstract_origin will take us
19931    back up the chain, and we want to go down.  */
19932
19933 static struct attribute *
19934 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19935 {
19936   unsigned int i;
19937
19938   for (i = 0; i < die->num_attrs; ++i)
19939     if (die->attrs[i].name == name)
19940       return &die->attrs[i];
19941
19942   return NULL;
19943 }
19944
19945 /* Return the string associated with a string-typed attribute, or NULL if it
19946    is either not found or is of an incorrect type.  */
19947
19948 static const char *
19949 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19950 {
19951   struct attribute *attr;
19952   const char *str = NULL;
19953
19954   attr = dwarf2_attr (die, name, cu);
19955
19956   if (attr != NULL)
19957     {
19958       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19959           || attr->form == DW_FORM_string
19960           || attr->form == DW_FORM_GNU_str_index
19961           || attr->form == DW_FORM_GNU_strp_alt)
19962         str = DW_STRING (attr);
19963       else
19964         complaint (&symfile_complaints,
19965                    _("string type expected for attribute %s for "
19966                      "DIE at 0x%x in module %s"),
19967                    dwarf_attr_name (name), to_underlying (die->sect_off),
19968                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19969     }
19970
19971   return str;
19972 }
19973
19974 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19975    and holds a non-zero value.  This function should only be used for
19976    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19977
19978 static int
19979 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19980 {
19981   struct attribute *attr = dwarf2_attr (die, name, cu);
19982
19983   return (attr && DW_UNSND (attr));
19984 }
19985
19986 static int
19987 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19988 {
19989   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19990      which value is non-zero.  However, we have to be careful with
19991      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19992      (via dwarf2_flag_true_p) follows this attribute.  So we may
19993      end up accidently finding a declaration attribute that belongs
19994      to a different DIE referenced by the specification attribute,
19995      even though the given DIE does not have a declaration attribute.  */
19996   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19997           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19998 }
19999
20000 /* Return the die giving the specification for DIE, if there is
20001    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20002    containing the return value on output.  If there is no
20003    specification, but there is an abstract origin, that is
20004    returned.  */
20005
20006 static struct die_info *
20007 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20008 {
20009   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20010                                              *spec_cu);
20011
20012   if (spec_attr == NULL)
20013     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20014
20015   if (spec_attr == NULL)
20016     return NULL;
20017   else
20018     return follow_die_ref (die, spec_attr, spec_cu);
20019 }
20020
20021 /* Stub for free_line_header to match void * callback types.  */
20022
20023 static void
20024 free_line_header_voidp (void *arg)
20025 {
20026   struct line_header *lh = (struct line_header *) arg;
20027
20028   delete lh;
20029 }
20030
20031 void
20032 line_header::add_include_dir (const char *include_dir)
20033 {
20034   if (dwarf_line_debug >= 2)
20035     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20036                         include_dirs.size () + 1, include_dir);
20037
20038   include_dirs.push_back (include_dir);
20039 }
20040
20041 void
20042 line_header::add_file_name (const char *name,
20043                             dir_index d_index,
20044                             unsigned int mod_time,
20045                             unsigned int length)
20046 {
20047   if (dwarf_line_debug >= 2)
20048     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20049                         (unsigned) file_names.size () + 1, name);
20050
20051   file_names.emplace_back (name, d_index, mod_time, length);
20052 }
20053
20054 /* A convenience function to find the proper .debug_line section for a CU.  */
20055
20056 static struct dwarf2_section_info *
20057 get_debug_line_section (struct dwarf2_cu *cu)
20058 {
20059   struct dwarf2_section_info *section;
20060   struct dwarf2_per_objfile *dwarf2_per_objfile
20061     = cu->per_cu->dwarf2_per_objfile;
20062
20063   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20064      DWO file.  */
20065   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20066     section = &cu->dwo_unit->dwo_file->sections.line;
20067   else if (cu->per_cu->is_dwz)
20068     {
20069       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20070
20071       section = &dwz->line;
20072     }
20073   else
20074     section = &dwarf2_per_objfile->line;
20075
20076   return section;
20077 }
20078
20079 /* Read directory or file name entry format, starting with byte of
20080    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20081    entries count and the entries themselves in the described entry
20082    format.  */
20083
20084 static void
20085 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20086                         bfd *abfd, const gdb_byte **bufp,
20087                         struct line_header *lh,
20088                         const struct comp_unit_head *cu_header,
20089                         void (*callback) (struct line_header *lh,
20090                                           const char *name,
20091                                           dir_index d_index,
20092                                           unsigned int mod_time,
20093                                           unsigned int length))
20094 {
20095   gdb_byte format_count, formati;
20096   ULONGEST data_count, datai;
20097   const gdb_byte *buf = *bufp;
20098   const gdb_byte *format_header_data;
20099   unsigned int bytes_read;
20100
20101   format_count = read_1_byte (abfd, buf);
20102   buf += 1;
20103   format_header_data = buf;
20104   for (formati = 0; formati < format_count; formati++)
20105     {
20106       read_unsigned_leb128 (abfd, buf, &bytes_read);
20107       buf += bytes_read;
20108       read_unsigned_leb128 (abfd, buf, &bytes_read);
20109       buf += bytes_read;
20110     }
20111
20112   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20113   buf += bytes_read;
20114   for (datai = 0; datai < data_count; datai++)
20115     {
20116       const gdb_byte *format = format_header_data;
20117       struct file_entry fe;
20118
20119       for (formati = 0; formati < format_count; formati++)
20120         {
20121           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20122           format += bytes_read;
20123
20124           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20125           format += bytes_read;
20126
20127           gdb::optional<const char *> string;
20128           gdb::optional<unsigned int> uint;
20129
20130           switch (form)
20131             {
20132             case DW_FORM_string:
20133               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20134               buf += bytes_read;
20135               break;
20136
20137             case DW_FORM_line_strp:
20138               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20139                                                          abfd, buf,
20140                                                          cu_header,
20141                                                          &bytes_read));
20142               buf += bytes_read;
20143               break;
20144
20145             case DW_FORM_data1:
20146               uint.emplace (read_1_byte (abfd, buf));
20147               buf += 1;
20148               break;
20149
20150             case DW_FORM_data2:
20151               uint.emplace (read_2_bytes (abfd, buf));
20152               buf += 2;
20153               break;
20154
20155             case DW_FORM_data4:
20156               uint.emplace (read_4_bytes (abfd, buf));
20157               buf += 4;
20158               break;
20159
20160             case DW_FORM_data8:
20161               uint.emplace (read_8_bytes (abfd, buf));
20162               buf += 8;
20163               break;
20164
20165             case DW_FORM_udata:
20166               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20167               buf += bytes_read;
20168               break;
20169
20170             case DW_FORM_block:
20171               /* It is valid only for DW_LNCT_timestamp which is ignored by
20172                  current GDB.  */
20173               break;
20174             }
20175
20176           switch (content_type)
20177             {
20178             case DW_LNCT_path:
20179               if (string.has_value ())
20180                 fe.name = *string;
20181               break;
20182             case DW_LNCT_directory_index:
20183               if (uint.has_value ())
20184                 fe.d_index = (dir_index) *uint;
20185               break;
20186             case DW_LNCT_timestamp:
20187               if (uint.has_value ())
20188                 fe.mod_time = *uint;
20189               break;
20190             case DW_LNCT_size:
20191               if (uint.has_value ())
20192                 fe.length = *uint;
20193               break;
20194             case DW_LNCT_MD5:
20195               break;
20196             default:
20197               complaint (&symfile_complaints,
20198                          _("Unknown format content type %s"),
20199                          pulongest (content_type));
20200             }
20201         }
20202
20203       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20204     }
20205
20206   *bufp = buf;
20207 }
20208
20209 /* Read the statement program header starting at OFFSET in
20210    .debug_line, or .debug_line.dwo.  Return a pointer
20211    to a struct line_header, allocated using xmalloc.
20212    Returns NULL if there is a problem reading the header, e.g., if it
20213    has a version we don't understand.
20214
20215    NOTE: the strings in the include directory and file name tables of
20216    the returned object point into the dwarf line section buffer,
20217    and must not be freed.  */
20218
20219 static line_header_up
20220 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20221 {
20222   const gdb_byte *line_ptr;
20223   unsigned int bytes_read, offset_size;
20224   int i;
20225   const char *cur_dir, *cur_file;
20226   struct dwarf2_section_info *section;
20227   bfd *abfd;
20228   struct dwarf2_per_objfile *dwarf2_per_objfile
20229     = cu->per_cu->dwarf2_per_objfile;
20230
20231   section = get_debug_line_section (cu);
20232   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20233   if (section->buffer == NULL)
20234     {
20235       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20236         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20237       else
20238         complaint (&symfile_complaints, _("missing .debug_line section"));
20239       return 0;
20240     }
20241
20242   /* We can't do this until we know the section is non-empty.
20243      Only then do we know we have such a section.  */
20244   abfd = get_section_bfd_owner (section);
20245
20246   /* Make sure that at least there's room for the total_length field.
20247      That could be 12 bytes long, but we're just going to fudge that.  */
20248   if (to_underlying (sect_off) + 4 >= section->size)
20249     {
20250       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20251       return 0;
20252     }
20253
20254   line_header_up lh (new line_header ());
20255
20256   lh->sect_off = sect_off;
20257   lh->offset_in_dwz = cu->per_cu->is_dwz;
20258
20259   line_ptr = section->buffer + to_underlying (sect_off);
20260
20261   /* Read in the header.  */
20262   lh->total_length =
20263     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20264                                             &bytes_read, &offset_size);
20265   line_ptr += bytes_read;
20266   if (line_ptr + lh->total_length > (section->buffer + section->size))
20267     {
20268       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20269       return 0;
20270     }
20271   lh->statement_program_end = line_ptr + lh->total_length;
20272   lh->version = read_2_bytes (abfd, line_ptr);
20273   line_ptr += 2;
20274   if (lh->version > 5)
20275     {
20276       /* This is a version we don't understand.  The format could have
20277          changed in ways we don't handle properly so just punt.  */
20278       complaint (&symfile_complaints,
20279                  _("unsupported version in .debug_line section"));
20280       return NULL;
20281     }
20282   if (lh->version >= 5)
20283     {
20284       gdb_byte segment_selector_size;
20285
20286       /* Skip address size.  */
20287       read_1_byte (abfd, line_ptr);
20288       line_ptr += 1;
20289
20290       segment_selector_size = read_1_byte (abfd, line_ptr);
20291       line_ptr += 1;
20292       if (segment_selector_size != 0)
20293         {
20294           complaint (&symfile_complaints,
20295                      _("unsupported segment selector size %u "
20296                        "in .debug_line section"),
20297                      segment_selector_size);
20298           return NULL;
20299         }
20300     }
20301   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20302   line_ptr += offset_size;
20303   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20304   line_ptr += 1;
20305   if (lh->version >= 4)
20306     {
20307       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20308       line_ptr += 1;
20309     }
20310   else
20311     lh->maximum_ops_per_instruction = 1;
20312
20313   if (lh->maximum_ops_per_instruction == 0)
20314     {
20315       lh->maximum_ops_per_instruction = 1;
20316       complaint (&symfile_complaints,
20317                  _("invalid maximum_ops_per_instruction "
20318                    "in `.debug_line' section"));
20319     }
20320
20321   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20322   line_ptr += 1;
20323   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20324   line_ptr += 1;
20325   lh->line_range = read_1_byte (abfd, line_ptr);
20326   line_ptr += 1;
20327   lh->opcode_base = read_1_byte (abfd, line_ptr);
20328   line_ptr += 1;
20329   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20330
20331   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20332   for (i = 1; i < lh->opcode_base; ++i)
20333     {
20334       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20335       line_ptr += 1;
20336     }
20337
20338   if (lh->version >= 5)
20339     {
20340       /* Read directory table.  */
20341       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20342                               &cu->header,
20343                               [] (struct line_header *lh, const char *name,
20344                                   dir_index d_index, unsigned int mod_time,
20345                                   unsigned int length)
20346         {
20347           lh->add_include_dir (name);
20348         });
20349
20350       /* Read file name table.  */
20351       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20352                               &cu->header,
20353                               [] (struct line_header *lh, const char *name,
20354                                   dir_index d_index, unsigned int mod_time,
20355                                   unsigned int length)
20356         {
20357           lh->add_file_name (name, d_index, mod_time, length);
20358         });
20359     }
20360   else
20361     {
20362       /* Read directory table.  */
20363       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20364         {
20365           line_ptr += bytes_read;
20366           lh->add_include_dir (cur_dir);
20367         }
20368       line_ptr += bytes_read;
20369
20370       /* Read file name table.  */
20371       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20372         {
20373           unsigned int mod_time, length;
20374           dir_index d_index;
20375
20376           line_ptr += bytes_read;
20377           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20378           line_ptr += bytes_read;
20379           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20380           line_ptr += bytes_read;
20381           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20382           line_ptr += bytes_read;
20383
20384           lh->add_file_name (cur_file, d_index, mod_time, length);
20385         }
20386       line_ptr += bytes_read;
20387     }
20388   lh->statement_program_start = line_ptr;
20389
20390   if (line_ptr > (section->buffer + section->size))
20391     complaint (&symfile_complaints,
20392                _("line number info header doesn't "
20393                  "fit in `.debug_line' section"));
20394
20395   return lh;
20396 }
20397
20398 /* Subroutine of dwarf_decode_lines to simplify it.
20399    Return the file name of the psymtab for included file FILE_INDEX
20400    in line header LH of PST.
20401    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20402    If space for the result is malloc'd, it will be freed by a cleanup.
20403    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20404
20405    The function creates dangling cleanup registration.  */
20406
20407 static const char *
20408 psymtab_include_file_name (const struct line_header *lh, int file_index,
20409                            const struct partial_symtab *pst,
20410                            const char *comp_dir)
20411 {
20412   const file_entry &fe = lh->file_names[file_index];
20413   const char *include_name = fe.name;
20414   const char *include_name_to_compare = include_name;
20415   const char *pst_filename;
20416   char *copied_name = NULL;
20417   int file_is_pst;
20418
20419   const char *dir_name = fe.include_dir (lh);
20420
20421   if (!IS_ABSOLUTE_PATH (include_name)
20422       && (dir_name != NULL || comp_dir != NULL))
20423     {
20424       /* Avoid creating a duplicate psymtab for PST.
20425          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20426          Before we do the comparison, however, we need to account
20427          for DIR_NAME and COMP_DIR.
20428          First prepend dir_name (if non-NULL).  If we still don't
20429          have an absolute path prepend comp_dir (if non-NULL).
20430          However, the directory we record in the include-file's
20431          psymtab does not contain COMP_DIR (to match the
20432          corresponding symtab(s)).
20433
20434          Example:
20435
20436          bash$ cd /tmp
20437          bash$ gcc -g ./hello.c
20438          include_name = "hello.c"
20439          dir_name = "."
20440          DW_AT_comp_dir = comp_dir = "/tmp"
20441          DW_AT_name = "./hello.c"
20442
20443       */
20444
20445       if (dir_name != NULL)
20446         {
20447           char *tem = concat (dir_name, SLASH_STRING,
20448                               include_name, (char *)NULL);
20449
20450           make_cleanup (xfree, tem);
20451           include_name = tem;
20452           include_name_to_compare = include_name;
20453         }
20454       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20455         {
20456           char *tem = concat (comp_dir, SLASH_STRING,
20457                               include_name, (char *)NULL);
20458
20459           make_cleanup (xfree, tem);
20460           include_name_to_compare = tem;
20461         }
20462     }
20463
20464   pst_filename = pst->filename;
20465   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20466     {
20467       copied_name = concat (pst->dirname, SLASH_STRING,
20468                             pst_filename, (char *)NULL);
20469       pst_filename = copied_name;
20470     }
20471
20472   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20473
20474   if (copied_name != NULL)
20475     xfree (copied_name);
20476
20477   if (file_is_pst)
20478     return NULL;
20479   return include_name;
20480 }
20481
20482 /* State machine to track the state of the line number program.  */
20483
20484 class lnp_state_machine
20485 {
20486 public:
20487   /* Initialize a machine state for the start of a line number
20488      program.  */
20489   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20490
20491   file_entry *current_file ()
20492   {
20493     /* lh->file_names is 0-based, but the file name numbers in the
20494        statement program are 1-based.  */
20495     return m_line_header->file_name_at (m_file);
20496   }
20497
20498   /* Record the line in the state machine.  END_SEQUENCE is true if
20499      we're processing the end of a sequence.  */
20500   void record_line (bool end_sequence);
20501
20502   /* Check address and if invalid nop-out the rest of the lines in this
20503      sequence.  */
20504   void check_line_address (struct dwarf2_cu *cu,
20505                            const gdb_byte *line_ptr,
20506                            CORE_ADDR lowpc, CORE_ADDR address);
20507
20508   void handle_set_discriminator (unsigned int discriminator)
20509   {
20510     m_discriminator = discriminator;
20511     m_line_has_non_zero_discriminator |= discriminator != 0;
20512   }
20513
20514   /* Handle DW_LNE_set_address.  */
20515   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20516   {
20517     m_op_index = 0;
20518     address += baseaddr;
20519     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20520   }
20521
20522   /* Handle DW_LNS_advance_pc.  */
20523   void handle_advance_pc (CORE_ADDR adjust);
20524
20525   /* Handle a special opcode.  */
20526   void handle_special_opcode (unsigned char op_code);
20527
20528   /* Handle DW_LNS_advance_line.  */
20529   void handle_advance_line (int line_delta)
20530   {
20531     advance_line (line_delta);
20532   }
20533
20534   /* Handle DW_LNS_set_file.  */
20535   void handle_set_file (file_name_index file);
20536
20537   /* Handle DW_LNS_negate_stmt.  */
20538   void handle_negate_stmt ()
20539   {
20540     m_is_stmt = !m_is_stmt;
20541   }
20542
20543   /* Handle DW_LNS_const_add_pc.  */
20544   void handle_const_add_pc ();
20545
20546   /* Handle DW_LNS_fixed_advance_pc.  */
20547   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20548   {
20549     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20550     m_op_index = 0;
20551   }
20552
20553   /* Handle DW_LNS_copy.  */
20554   void handle_copy ()
20555   {
20556     record_line (false);
20557     m_discriminator = 0;
20558   }
20559
20560   /* Handle DW_LNE_end_sequence.  */
20561   void handle_end_sequence ()
20562   {
20563     m_record_line_callback = ::record_line;
20564   }
20565
20566 private:
20567   /* Advance the line by LINE_DELTA.  */
20568   void advance_line (int line_delta)
20569   {
20570     m_line += line_delta;
20571
20572     if (line_delta != 0)
20573       m_line_has_non_zero_discriminator = m_discriminator != 0;
20574   }
20575
20576   gdbarch *m_gdbarch;
20577
20578   /* True if we're recording lines.
20579      Otherwise we're building partial symtabs and are just interested in
20580      finding include files mentioned by the line number program.  */
20581   bool m_record_lines_p;
20582
20583   /* The line number header.  */
20584   line_header *m_line_header;
20585
20586   /* These are part of the standard DWARF line number state machine,
20587      and initialized according to the DWARF spec.  */
20588
20589   unsigned char m_op_index = 0;
20590   /* The line table index (1-based) of the current file.  */
20591   file_name_index m_file = (file_name_index) 1;
20592   unsigned int m_line = 1;
20593
20594   /* These are initialized in the constructor.  */
20595
20596   CORE_ADDR m_address;
20597   bool m_is_stmt;
20598   unsigned int m_discriminator;
20599
20600   /* Additional bits of state we need to track.  */
20601
20602   /* The last file that we called dwarf2_start_subfile for.
20603      This is only used for TLLs.  */
20604   unsigned int m_last_file = 0;
20605   /* The last file a line number was recorded for.  */
20606   struct subfile *m_last_subfile = NULL;
20607
20608   /* The function to call to record a line.  */
20609   record_line_ftype *m_record_line_callback = NULL;
20610
20611   /* The last line number that was recorded, used to coalesce
20612      consecutive entries for the same line.  This can happen, for
20613      example, when discriminators are present.  PR 17276.  */
20614   unsigned int m_last_line = 0;
20615   bool m_line_has_non_zero_discriminator = false;
20616 };
20617
20618 void
20619 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20620 {
20621   CORE_ADDR addr_adj = (((m_op_index + adjust)
20622                          / m_line_header->maximum_ops_per_instruction)
20623                         * m_line_header->minimum_instruction_length);
20624   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20625   m_op_index = ((m_op_index + adjust)
20626                 % m_line_header->maximum_ops_per_instruction);
20627 }
20628
20629 void
20630 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20631 {
20632   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20633   CORE_ADDR addr_adj = (((m_op_index
20634                           + (adj_opcode / m_line_header->line_range))
20635                          / m_line_header->maximum_ops_per_instruction)
20636                         * m_line_header->minimum_instruction_length);
20637   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20638   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20639                 % m_line_header->maximum_ops_per_instruction);
20640
20641   int line_delta = (m_line_header->line_base
20642                     + (adj_opcode % m_line_header->line_range));
20643   advance_line (line_delta);
20644   record_line (false);
20645   m_discriminator = 0;
20646 }
20647
20648 void
20649 lnp_state_machine::handle_set_file (file_name_index file)
20650 {
20651   m_file = file;
20652
20653   const file_entry *fe = current_file ();
20654   if (fe == NULL)
20655     dwarf2_debug_line_missing_file_complaint ();
20656   else if (m_record_lines_p)
20657     {
20658       const char *dir = fe->include_dir (m_line_header);
20659
20660       m_last_subfile = current_subfile;
20661       m_line_has_non_zero_discriminator = m_discriminator != 0;
20662       dwarf2_start_subfile (fe->name, dir);
20663     }
20664 }
20665
20666 void
20667 lnp_state_machine::handle_const_add_pc ()
20668 {
20669   CORE_ADDR adjust
20670     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20671
20672   CORE_ADDR addr_adj
20673     = (((m_op_index + adjust)
20674         / m_line_header->maximum_ops_per_instruction)
20675        * m_line_header->minimum_instruction_length);
20676
20677   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20678   m_op_index = ((m_op_index + adjust)
20679                 % m_line_header->maximum_ops_per_instruction);
20680 }
20681
20682 /* Ignore this record_line request.  */
20683
20684 static void
20685 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20686 {
20687   return;
20688 }
20689
20690 /* Return non-zero if we should add LINE to the line number table.
20691    LINE is the line to add, LAST_LINE is the last line that was added,
20692    LAST_SUBFILE is the subfile for LAST_LINE.
20693    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20694    had a non-zero discriminator.
20695
20696    We have to be careful in the presence of discriminators.
20697    E.g., for this line:
20698
20699      for (i = 0; i < 100000; i++);
20700
20701    clang can emit four line number entries for that one line,
20702    each with a different discriminator.
20703    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20704
20705    However, we want gdb to coalesce all four entries into one.
20706    Otherwise the user could stepi into the middle of the line and
20707    gdb would get confused about whether the pc really was in the
20708    middle of the line.
20709
20710    Things are further complicated by the fact that two consecutive
20711    line number entries for the same line is a heuristic used by gcc
20712    to denote the end of the prologue.  So we can't just discard duplicate
20713    entries, we have to be selective about it.  The heuristic we use is
20714    that we only collapse consecutive entries for the same line if at least
20715    one of those entries has a non-zero discriminator.  PR 17276.
20716
20717    Note: Addresses in the line number state machine can never go backwards
20718    within one sequence, thus this coalescing is ok.  */
20719
20720 static int
20721 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20722                      int line_has_non_zero_discriminator,
20723                      struct subfile *last_subfile)
20724 {
20725   if (current_subfile != last_subfile)
20726     return 1;
20727   if (line != last_line)
20728     return 1;
20729   /* Same line for the same file that we've seen already.
20730      As a last check, for pr 17276, only record the line if the line
20731      has never had a non-zero discriminator.  */
20732   if (!line_has_non_zero_discriminator)
20733     return 1;
20734   return 0;
20735 }
20736
20737 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20738    in the line table of subfile SUBFILE.  */
20739
20740 static void
20741 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20742                      unsigned int line, CORE_ADDR address,
20743                      record_line_ftype p_record_line)
20744 {
20745   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20746
20747   if (dwarf_line_debug)
20748     {
20749       fprintf_unfiltered (gdb_stdlog,
20750                           "Recording line %u, file %s, address %s\n",
20751                           line, lbasename (subfile->name),
20752                           paddress (gdbarch, address));
20753     }
20754
20755   (*p_record_line) (subfile, line, addr);
20756 }
20757
20758 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20759    Mark the end of a set of line number records.
20760    The arguments are the same as for dwarf_record_line_1.
20761    If SUBFILE is NULL the request is ignored.  */
20762
20763 static void
20764 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20765                    CORE_ADDR address, record_line_ftype p_record_line)
20766 {
20767   if (subfile == NULL)
20768     return;
20769
20770   if (dwarf_line_debug)
20771     {
20772       fprintf_unfiltered (gdb_stdlog,
20773                           "Finishing current line, file %s, address %s\n",
20774                           lbasename (subfile->name),
20775                           paddress (gdbarch, address));
20776     }
20777
20778   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20779 }
20780
20781 void
20782 lnp_state_machine::record_line (bool end_sequence)
20783 {
20784   if (dwarf_line_debug)
20785     {
20786       fprintf_unfiltered (gdb_stdlog,
20787                           "Processing actual line %u: file %u,"
20788                           " address %s, is_stmt %u, discrim %u\n",
20789                           m_line, to_underlying (m_file),
20790                           paddress (m_gdbarch, m_address),
20791                           m_is_stmt, m_discriminator);
20792     }
20793
20794   file_entry *fe = current_file ();
20795
20796   if (fe == NULL)
20797     dwarf2_debug_line_missing_file_complaint ();
20798   /* For now we ignore lines not starting on an instruction boundary.
20799      But not when processing end_sequence for compatibility with the
20800      previous version of the code.  */
20801   else if (m_op_index == 0 || end_sequence)
20802     {
20803       fe->included_p = 1;
20804       if (m_record_lines_p && m_is_stmt)
20805         {
20806           if (m_last_subfile != current_subfile || end_sequence)
20807             {
20808               dwarf_finish_line (m_gdbarch, m_last_subfile,
20809                                  m_address, m_record_line_callback);
20810             }
20811
20812           if (!end_sequence)
20813             {
20814               if (dwarf_record_line_p (m_line, m_last_line,
20815                                        m_line_has_non_zero_discriminator,
20816                                        m_last_subfile))
20817                 {
20818                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20819                                        m_line, m_address,
20820                                        m_record_line_callback);
20821                 }
20822               m_last_subfile = current_subfile;
20823               m_last_line = m_line;
20824             }
20825         }
20826     }
20827 }
20828
20829 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20830                                       bool record_lines_p)
20831 {
20832   m_gdbarch = arch;
20833   m_record_lines_p = record_lines_p;
20834   m_line_header = lh;
20835
20836   m_record_line_callback = ::record_line;
20837
20838   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20839      was a line entry for it so that the backend has a chance to adjust it
20840      and also record it in case it needs it.  This is currently used by MIPS
20841      code, cf. `mips_adjust_dwarf2_line'.  */
20842   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20843   m_is_stmt = lh->default_is_stmt;
20844   m_discriminator = 0;
20845 }
20846
20847 void
20848 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20849                                        const gdb_byte *line_ptr,
20850                                        CORE_ADDR lowpc, CORE_ADDR address)
20851 {
20852   /* If address < lowpc then it's not a usable value, it's outside the
20853      pc range of the CU.  However, we restrict the test to only address
20854      values of zero to preserve GDB's previous behaviour which is to
20855      handle the specific case of a function being GC'd by the linker.  */
20856
20857   if (address == 0 && address < lowpc)
20858     {
20859       /* This line table is for a function which has been
20860          GCd by the linker.  Ignore it.  PR gdb/12528 */
20861
20862       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20863       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20864
20865       complaint (&symfile_complaints,
20866                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20867                  line_offset, objfile_name (objfile));
20868       m_record_line_callback = noop_record_line;
20869       /* Note: record_line_callback is left as noop_record_line until
20870          we see DW_LNE_end_sequence.  */
20871     }
20872 }
20873
20874 /* Subroutine of dwarf_decode_lines to simplify it.
20875    Process the line number information in LH.
20876    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20877    program in order to set included_p for every referenced header.  */
20878
20879 static void
20880 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20881                       const int decode_for_pst_p, CORE_ADDR lowpc)
20882 {
20883   const gdb_byte *line_ptr, *extended_end;
20884   const gdb_byte *line_end;
20885   unsigned int bytes_read, extended_len;
20886   unsigned char op_code, extended_op;
20887   CORE_ADDR baseaddr;
20888   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20889   bfd *abfd = objfile->obfd;
20890   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20891   /* True if we're recording line info (as opposed to building partial
20892      symtabs and just interested in finding include files mentioned by
20893      the line number program).  */
20894   bool record_lines_p = !decode_for_pst_p;
20895
20896   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20897
20898   line_ptr = lh->statement_program_start;
20899   line_end = lh->statement_program_end;
20900
20901   /* Read the statement sequences until there's nothing left.  */
20902   while (line_ptr < line_end)
20903     {
20904       /* The DWARF line number program state machine.  Reset the state
20905          machine at the start of each sequence.  */
20906       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20907       bool end_sequence = false;
20908
20909       if (record_lines_p)
20910         {
20911           /* Start a subfile for the current file of the state
20912              machine.  */
20913           const file_entry *fe = state_machine.current_file ();
20914
20915           if (fe != NULL)
20916             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20917         }
20918
20919       /* Decode the table.  */
20920       while (line_ptr < line_end && !end_sequence)
20921         {
20922           op_code = read_1_byte (abfd, line_ptr);
20923           line_ptr += 1;
20924
20925           if (op_code >= lh->opcode_base)
20926             {
20927               /* Special opcode.  */
20928               state_machine.handle_special_opcode (op_code);
20929             }
20930           else switch (op_code)
20931             {
20932             case DW_LNS_extended_op:
20933               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20934                                                    &bytes_read);
20935               line_ptr += bytes_read;
20936               extended_end = line_ptr + extended_len;
20937               extended_op = read_1_byte (abfd, line_ptr);
20938               line_ptr += 1;
20939               switch (extended_op)
20940                 {
20941                 case DW_LNE_end_sequence:
20942                   state_machine.handle_end_sequence ();
20943                   end_sequence = true;
20944                   break;
20945                 case DW_LNE_set_address:
20946                   {
20947                     CORE_ADDR address
20948                       = read_address (abfd, line_ptr, cu, &bytes_read);
20949                     line_ptr += bytes_read;
20950
20951                     state_machine.check_line_address (cu, line_ptr,
20952                                                       lowpc, address);
20953                     state_machine.handle_set_address (baseaddr, address);
20954                   }
20955                   break;
20956                 case DW_LNE_define_file:
20957                   {
20958                     const char *cur_file;
20959                     unsigned int mod_time, length;
20960                     dir_index dindex;
20961
20962                     cur_file = read_direct_string (abfd, line_ptr,
20963                                                    &bytes_read);
20964                     line_ptr += bytes_read;
20965                     dindex = (dir_index)
20966                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20967                     line_ptr += bytes_read;
20968                     mod_time =
20969                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20970                     line_ptr += bytes_read;
20971                     length =
20972                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20973                     line_ptr += bytes_read;
20974                     lh->add_file_name (cur_file, dindex, mod_time, length);
20975                   }
20976                   break;
20977                 case DW_LNE_set_discriminator:
20978                   {
20979                     /* The discriminator is not interesting to the
20980                        debugger; just ignore it.  We still need to
20981                        check its value though:
20982                        if there are consecutive entries for the same
20983                        (non-prologue) line we want to coalesce them.
20984                        PR 17276.  */
20985                     unsigned int discr
20986                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20987                     line_ptr += bytes_read;
20988
20989                     state_machine.handle_set_discriminator (discr);
20990                   }
20991                   break;
20992                 default:
20993                   complaint (&symfile_complaints,
20994                              _("mangled .debug_line section"));
20995                   return;
20996                 }
20997               /* Make sure that we parsed the extended op correctly.  If e.g.
20998                  we expected a different address size than the producer used,
20999                  we may have read the wrong number of bytes.  */
21000               if (line_ptr != extended_end)
21001                 {
21002                   complaint (&symfile_complaints,
21003                              _("mangled .debug_line section"));
21004                   return;
21005                 }
21006               break;
21007             case DW_LNS_copy:
21008               state_machine.handle_copy ();
21009               break;
21010             case DW_LNS_advance_pc:
21011               {
21012                 CORE_ADDR adjust
21013                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21014                 line_ptr += bytes_read;
21015
21016                 state_machine.handle_advance_pc (adjust);
21017               }
21018               break;
21019             case DW_LNS_advance_line:
21020               {
21021                 int line_delta
21022                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21023                 line_ptr += bytes_read;
21024
21025                 state_machine.handle_advance_line (line_delta);
21026               }
21027               break;
21028             case DW_LNS_set_file:
21029               {
21030                 file_name_index file
21031                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21032                                                             &bytes_read);
21033                 line_ptr += bytes_read;
21034
21035                 state_machine.handle_set_file (file);
21036               }
21037               break;
21038             case DW_LNS_set_column:
21039               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21040               line_ptr += bytes_read;
21041               break;
21042             case DW_LNS_negate_stmt:
21043               state_machine.handle_negate_stmt ();
21044               break;
21045             case DW_LNS_set_basic_block:
21046               break;
21047             /* Add to the address register of the state machine the
21048                address increment value corresponding to special opcode
21049                255.  I.e., this value is scaled by the minimum
21050                instruction length since special opcode 255 would have
21051                scaled the increment.  */
21052             case DW_LNS_const_add_pc:
21053               state_machine.handle_const_add_pc ();
21054               break;
21055             case DW_LNS_fixed_advance_pc:
21056               {
21057                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21058                 line_ptr += 2;
21059
21060                 state_machine.handle_fixed_advance_pc (addr_adj);
21061               }
21062               break;
21063             default:
21064               {
21065                 /* Unknown standard opcode, ignore it.  */
21066                 int i;
21067
21068                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21069                   {
21070                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21071                     line_ptr += bytes_read;
21072                   }
21073               }
21074             }
21075         }
21076
21077       if (!end_sequence)
21078         dwarf2_debug_line_missing_end_sequence_complaint ();
21079
21080       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21081          in which case we still finish recording the last line).  */
21082       state_machine.record_line (true);
21083     }
21084 }
21085
21086 /* Decode the Line Number Program (LNP) for the given line_header
21087    structure and CU.  The actual information extracted and the type
21088    of structures created from the LNP depends on the value of PST.
21089
21090    1. If PST is NULL, then this procedure uses the data from the program
21091       to create all necessary symbol tables, and their linetables.
21092
21093    2. If PST is not NULL, this procedure reads the program to determine
21094       the list of files included by the unit represented by PST, and
21095       builds all the associated partial symbol tables.
21096
21097    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21098    It is used for relative paths in the line table.
21099    NOTE: When processing partial symtabs (pst != NULL),
21100    comp_dir == pst->dirname.
21101
21102    NOTE: It is important that psymtabs have the same file name (via strcmp)
21103    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21104    symtab we don't use it in the name of the psymtabs we create.
21105    E.g. expand_line_sal requires this when finding psymtabs to expand.
21106    A good testcase for this is mb-inline.exp.
21107
21108    LOWPC is the lowest address in CU (or 0 if not known).
21109
21110    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21111    for its PC<->lines mapping information.  Otherwise only the filename
21112    table is read in.  */
21113
21114 static void
21115 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21116                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21117                     CORE_ADDR lowpc, int decode_mapping)
21118 {
21119   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21120   const int decode_for_pst_p = (pst != NULL);
21121
21122   if (decode_mapping)
21123     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21124
21125   if (decode_for_pst_p)
21126     {
21127       int file_index;
21128
21129       /* Now that we're done scanning the Line Header Program, we can
21130          create the psymtab of each included file.  */
21131       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21132         if (lh->file_names[file_index].included_p == 1)
21133           {
21134             const char *include_name =
21135               psymtab_include_file_name (lh, file_index, pst, comp_dir);
21136             if (include_name != NULL)
21137               dwarf2_create_include_psymtab (include_name, pst, objfile);
21138           }
21139     }
21140   else
21141     {
21142       /* Make sure a symtab is created for every file, even files
21143          which contain only variables (i.e. no code with associated
21144          line numbers).  */
21145       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21146       int i;
21147
21148       for (i = 0; i < lh->file_names.size (); i++)
21149         {
21150           file_entry &fe = lh->file_names[i];
21151
21152           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21153
21154           if (current_subfile->symtab == NULL)
21155             {
21156               current_subfile->symtab
21157                 = allocate_symtab (cust, current_subfile->name);
21158             }
21159           fe.symtab = current_subfile->symtab;
21160         }
21161     }
21162 }
21163
21164 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21165    DIRNAME the name of the source directory which contains FILENAME
21166    or NULL if not known.
21167    This routine tries to keep line numbers from identical absolute and
21168    relative file names in a common subfile.
21169
21170    Using the `list' example from the GDB testsuite, which resides in
21171    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21172    of /srcdir/list0.c yields the following debugging information for list0.c:
21173
21174    DW_AT_name:          /srcdir/list0.c
21175    DW_AT_comp_dir:      /compdir
21176    files.files[0].name: list0.h
21177    files.files[0].dir:  /srcdir
21178    files.files[1].name: list0.c
21179    files.files[1].dir:  /srcdir
21180
21181    The line number information for list0.c has to end up in a single
21182    subfile, so that `break /srcdir/list0.c:1' works as expected.
21183    start_subfile will ensure that this happens provided that we pass the
21184    concatenation of files.files[1].dir and files.files[1].name as the
21185    subfile's name.  */
21186
21187 static void
21188 dwarf2_start_subfile (const char *filename, const char *dirname)
21189 {
21190   char *copy = NULL;
21191
21192   /* In order not to lose the line information directory,
21193      we concatenate it to the filename when it makes sense.
21194      Note that the Dwarf3 standard says (speaking of filenames in line
21195      information): ``The directory index is ignored for file names
21196      that represent full path names''.  Thus ignoring dirname in the
21197      `else' branch below isn't an issue.  */
21198
21199   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21200     {
21201       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21202       filename = copy;
21203     }
21204
21205   start_subfile (filename);
21206
21207   if (copy != NULL)
21208     xfree (copy);
21209 }
21210
21211 /* Start a symtab for DWARF.
21212    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21213
21214 static struct compunit_symtab *
21215 dwarf2_start_symtab (struct dwarf2_cu *cu,
21216                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21217 {
21218   struct compunit_symtab *cust
21219     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21220                     low_pc, cu->language);
21221
21222   record_debugformat ("DWARF 2");
21223   record_producer (cu->producer);
21224
21225   /* We assume that we're processing GCC output.  */
21226   processing_gcc_compilation = 2;
21227
21228   cu->processing_has_namespace_info = 0;
21229
21230   return cust;
21231 }
21232
21233 static void
21234 var_decode_location (struct attribute *attr, struct symbol *sym,
21235                      struct dwarf2_cu *cu)
21236 {
21237   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21238   struct comp_unit_head *cu_header = &cu->header;
21239
21240   /* NOTE drow/2003-01-30: There used to be a comment and some special
21241      code here to turn a symbol with DW_AT_external and a
21242      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21243      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21244      with some versions of binutils) where shared libraries could have
21245      relocations against symbols in their debug information - the
21246      minimal symbol would have the right address, but the debug info
21247      would not.  It's no longer necessary, because we will explicitly
21248      apply relocations when we read in the debug information now.  */
21249
21250   /* A DW_AT_location attribute with no contents indicates that a
21251      variable has been optimized away.  */
21252   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21253     {
21254       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21255       return;
21256     }
21257
21258   /* Handle one degenerate form of location expression specially, to
21259      preserve GDB's previous behavior when section offsets are
21260      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21261      then mark this symbol as LOC_STATIC.  */
21262
21263   if (attr_form_is_block (attr)
21264       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21265            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21266           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21267               && (DW_BLOCK (attr)->size
21268                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21269     {
21270       unsigned int dummy;
21271
21272       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21273         SYMBOL_VALUE_ADDRESS (sym) =
21274           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21275       else
21276         SYMBOL_VALUE_ADDRESS (sym) =
21277           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21278       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21279       fixup_symbol_section (sym, objfile);
21280       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21281                                               SYMBOL_SECTION (sym));
21282       return;
21283     }
21284
21285   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21286      expression evaluator, and use LOC_COMPUTED only when necessary
21287      (i.e. when the value of a register or memory location is
21288      referenced, or a thread-local block, etc.).  Then again, it might
21289      not be worthwhile.  I'm assuming that it isn't unless performance
21290      or memory numbers show me otherwise.  */
21291
21292   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21293
21294   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21295     cu->has_loclist = 1;
21296 }
21297
21298 /* Given a pointer to a DWARF information entry, figure out if we need
21299    to make a symbol table entry for it, and if so, create a new entry
21300    and return a pointer to it.
21301    If TYPE is NULL, determine symbol type from the die, otherwise
21302    used the passed type.
21303    If SPACE is not NULL, use it to hold the new symbol.  If it is
21304    NULL, allocate a new symbol on the objfile's obstack.  */
21305
21306 static struct symbol *
21307 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21308             struct symbol *space)
21309 {
21310   struct dwarf2_per_objfile *dwarf2_per_objfile
21311     = cu->per_cu->dwarf2_per_objfile;
21312   struct objfile *objfile = dwarf2_per_objfile->objfile;
21313   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21314   struct symbol *sym = NULL;
21315   const char *name;
21316   struct attribute *attr = NULL;
21317   struct attribute *attr2 = NULL;
21318   CORE_ADDR baseaddr;
21319   struct pending **list_to_add = NULL;
21320
21321   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21322
21323   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21324
21325   name = dwarf2_name (die, cu);
21326   if (name)
21327     {
21328       const char *linkagename;
21329       int suppress_add = 0;
21330
21331       if (space)
21332         sym = space;
21333       else
21334         sym = allocate_symbol (objfile);
21335       OBJSTAT (objfile, n_syms++);
21336
21337       /* Cache this symbol's name and the name's demangled form (if any).  */
21338       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21339       linkagename = dwarf2_physname (name, die, cu);
21340       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21341
21342       /* Fortran does not have mangling standard and the mangling does differ
21343          between gfortran, iFort etc.  */
21344       if (cu->language == language_fortran
21345           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21346         symbol_set_demangled_name (&(sym->ginfo),
21347                                    dwarf2_full_name (name, die, cu),
21348                                    NULL);
21349
21350       /* Default assumptions.
21351          Use the passed type or decode it from the die.  */
21352       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21353       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21354       if (type != NULL)
21355         SYMBOL_TYPE (sym) = type;
21356       else
21357         SYMBOL_TYPE (sym) = die_type (die, cu);
21358       attr = dwarf2_attr (die,
21359                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21360                           cu);
21361       if (attr)
21362         {
21363           SYMBOL_LINE (sym) = DW_UNSND (attr);
21364         }
21365
21366       attr = dwarf2_attr (die,
21367                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21368                           cu);
21369       if (attr)
21370         {
21371           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21372           struct file_entry *fe;
21373
21374           if (cu->line_header != NULL)
21375             fe = cu->line_header->file_name_at (file_index);
21376           else
21377             fe = NULL;
21378
21379           if (fe == NULL)
21380             complaint (&symfile_complaints,
21381                        _("file index out of range"));
21382           else
21383             symbol_set_symtab (sym, fe->symtab);
21384         }
21385
21386       switch (die->tag)
21387         {
21388         case DW_TAG_label:
21389           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21390           if (attr)
21391             {
21392               CORE_ADDR addr;
21393
21394               addr = attr_value_as_address (attr);
21395               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21396               SYMBOL_VALUE_ADDRESS (sym) = addr;
21397             }
21398           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21399           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21400           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21401           add_symbol_to_list (sym, cu->list_in_scope);
21402           break;
21403         case DW_TAG_subprogram:
21404           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21405              finish_block.  */
21406           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21407           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21408           if ((attr2 && (DW_UNSND (attr2) != 0))
21409               || cu->language == language_ada)
21410             {
21411               /* Subprograms marked external are stored as a global symbol.
21412                  Ada subprograms, whether marked external or not, are always
21413                  stored as a global symbol, because we want to be able to
21414                  access them globally.  For instance, we want to be able
21415                  to break on a nested subprogram without having to
21416                  specify the context.  */
21417               list_to_add = &global_symbols;
21418             }
21419           else
21420             {
21421               list_to_add = cu->list_in_scope;
21422             }
21423           break;
21424         case DW_TAG_inlined_subroutine:
21425           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21426              finish_block.  */
21427           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21428           SYMBOL_INLINED (sym) = 1;
21429           list_to_add = cu->list_in_scope;
21430           break;
21431         case DW_TAG_template_value_param:
21432           suppress_add = 1;
21433           /* Fall through.  */
21434         case DW_TAG_constant:
21435         case DW_TAG_variable:
21436         case DW_TAG_member:
21437           /* Compilation with minimal debug info may result in
21438              variables with missing type entries.  Change the
21439              misleading `void' type to something sensible.  */
21440           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21441             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21442
21443           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21444           /* In the case of DW_TAG_member, we should only be called for
21445              static const members.  */
21446           if (die->tag == DW_TAG_member)
21447             {
21448               /* dwarf2_add_field uses die_is_declaration,
21449                  so we do the same.  */
21450               gdb_assert (die_is_declaration (die, cu));
21451               gdb_assert (attr);
21452             }
21453           if (attr)
21454             {
21455               dwarf2_const_value (attr, sym, cu);
21456               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21457               if (!suppress_add)
21458                 {
21459                   if (attr2 && (DW_UNSND (attr2) != 0))
21460                     list_to_add = &global_symbols;
21461                   else
21462                     list_to_add = cu->list_in_scope;
21463                 }
21464               break;
21465             }
21466           attr = dwarf2_attr (die, DW_AT_location, cu);
21467           if (attr)
21468             {
21469               var_decode_location (attr, sym, cu);
21470               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21471
21472               /* Fortran explicitly imports any global symbols to the local
21473                  scope by DW_TAG_common_block.  */
21474               if (cu->language == language_fortran && die->parent
21475                   && die->parent->tag == DW_TAG_common_block)
21476                 attr2 = NULL;
21477
21478               if (SYMBOL_CLASS (sym) == LOC_STATIC
21479                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21480                   && !dwarf2_per_objfile->has_section_at_zero)
21481                 {
21482                   /* When a static variable is eliminated by the linker,
21483                      the corresponding debug information is not stripped
21484                      out, but the variable address is set to null;
21485                      do not add such variables into symbol table.  */
21486                 }
21487               else if (attr2 && (DW_UNSND (attr2) != 0))
21488                 {
21489                   /* Workaround gfortran PR debug/40040 - it uses
21490                      DW_AT_location for variables in -fPIC libraries which may
21491                      get overriden by other libraries/executable and get
21492                      a different address.  Resolve it by the minimal symbol
21493                      which may come from inferior's executable using copy
21494                      relocation.  Make this workaround only for gfortran as for
21495                      other compilers GDB cannot guess the minimal symbol
21496                      Fortran mangling kind.  */
21497                   if (cu->language == language_fortran && die->parent
21498                       && die->parent->tag == DW_TAG_module
21499                       && cu->producer
21500                       && startswith (cu->producer, "GNU Fortran"))
21501                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21502
21503                   /* A variable with DW_AT_external is never static,
21504                      but it may be block-scoped.  */
21505                   list_to_add = (cu->list_in_scope == &file_symbols
21506                                  ? &global_symbols : cu->list_in_scope);
21507                 }
21508               else
21509                 list_to_add = cu->list_in_scope;
21510             }
21511           else
21512             {
21513               /* We do not know the address of this symbol.
21514                  If it is an external symbol and we have type information
21515                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21516                  The address of the variable will then be determined from
21517                  the minimal symbol table whenever the variable is
21518                  referenced.  */
21519               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21520
21521               /* Fortran explicitly imports any global symbols to the local
21522                  scope by DW_TAG_common_block.  */
21523               if (cu->language == language_fortran && die->parent
21524                   && die->parent->tag == DW_TAG_common_block)
21525                 {
21526                   /* SYMBOL_CLASS doesn't matter here because
21527                      read_common_block is going to reset it.  */
21528                   if (!suppress_add)
21529                     list_to_add = cu->list_in_scope;
21530                 }
21531               else if (attr2 && (DW_UNSND (attr2) != 0)
21532                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21533                 {
21534                   /* A variable with DW_AT_external is never static, but it
21535                      may be block-scoped.  */
21536                   list_to_add = (cu->list_in_scope == &file_symbols
21537                                  ? &global_symbols : cu->list_in_scope);
21538
21539                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21540                 }
21541               else if (!die_is_declaration (die, cu))
21542                 {
21543                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21544                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21545                   if (!suppress_add)
21546                     list_to_add = cu->list_in_scope;
21547                 }
21548             }
21549           break;
21550         case DW_TAG_formal_parameter:
21551           /* If we are inside a function, mark this as an argument.  If
21552              not, we might be looking at an argument to an inlined function
21553              when we do not have enough information to show inlined frames;
21554              pretend it's a local variable in that case so that the user can
21555              still see it.  */
21556           if (context_stack_depth > 0
21557               && context_stack[context_stack_depth - 1].name != NULL)
21558             SYMBOL_IS_ARGUMENT (sym) = 1;
21559           attr = dwarf2_attr (die, DW_AT_location, cu);
21560           if (attr)
21561             {
21562               var_decode_location (attr, sym, cu);
21563             }
21564           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21565           if (attr)
21566             {
21567               dwarf2_const_value (attr, sym, cu);
21568             }
21569
21570           list_to_add = cu->list_in_scope;
21571           break;
21572         case DW_TAG_unspecified_parameters:
21573           /* From varargs functions; gdb doesn't seem to have any
21574              interest in this information, so just ignore it for now.
21575              (FIXME?) */
21576           break;
21577         case DW_TAG_template_type_param:
21578           suppress_add = 1;
21579           /* Fall through.  */
21580         case DW_TAG_class_type:
21581         case DW_TAG_interface_type:
21582         case DW_TAG_structure_type:
21583         case DW_TAG_union_type:
21584         case DW_TAG_set_type:
21585         case DW_TAG_enumeration_type:
21586           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21587           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21588
21589           {
21590             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21591                really ever be static objects: otherwise, if you try
21592                to, say, break of a class's method and you're in a file
21593                which doesn't mention that class, it won't work unless
21594                the check for all static symbols in lookup_symbol_aux
21595                saves you.  See the OtherFileClass tests in
21596                gdb.c++/namespace.exp.  */
21597
21598             if (!suppress_add)
21599               {
21600                 list_to_add = (cu->list_in_scope == &file_symbols
21601                                && cu->language == language_cplus
21602                                ? &global_symbols : cu->list_in_scope);
21603
21604                 /* The semantics of C++ state that "struct foo {
21605                    ... }" also defines a typedef for "foo".  */
21606                 if (cu->language == language_cplus
21607                     || cu->language == language_ada
21608                     || cu->language == language_d
21609                     || cu->language == language_rust)
21610                   {
21611                     /* The symbol's name is already allocated along
21612                        with this objfile, so we don't need to
21613                        duplicate it for the type.  */
21614                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21615                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21616                   }
21617               }
21618           }
21619           break;
21620         case DW_TAG_typedef:
21621           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21622           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21623           list_to_add = cu->list_in_scope;
21624           break;
21625         case DW_TAG_base_type:
21626         case DW_TAG_subrange_type:
21627           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21628           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21629           list_to_add = cu->list_in_scope;
21630           break;
21631         case DW_TAG_enumerator:
21632           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21633           if (attr)
21634             {
21635               dwarf2_const_value (attr, sym, cu);
21636             }
21637           {
21638             /* NOTE: carlton/2003-11-10: See comment above in the
21639                DW_TAG_class_type, etc. block.  */
21640
21641             list_to_add = (cu->list_in_scope == &file_symbols
21642                            && cu->language == language_cplus
21643                            ? &global_symbols : cu->list_in_scope);
21644           }
21645           break;
21646         case DW_TAG_imported_declaration:
21647         case DW_TAG_namespace:
21648           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21649           list_to_add = &global_symbols;
21650           break;
21651         case DW_TAG_module:
21652           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21653           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21654           list_to_add = &global_symbols;
21655           break;
21656         case DW_TAG_common_block:
21657           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21658           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21659           add_symbol_to_list (sym, cu->list_in_scope);
21660           break;
21661         default:
21662           /* Not a tag we recognize.  Hopefully we aren't processing
21663              trash data, but since we must specifically ignore things
21664              we don't recognize, there is nothing else we should do at
21665              this point.  */
21666           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21667                      dwarf_tag_name (die->tag));
21668           break;
21669         }
21670
21671       if (suppress_add)
21672         {
21673           sym->hash_next = objfile->template_symbols;
21674           objfile->template_symbols = sym;
21675           list_to_add = NULL;
21676         }
21677
21678       if (list_to_add != NULL)
21679         add_symbol_to_list (sym, list_to_add);
21680
21681       /* For the benefit of old versions of GCC, check for anonymous
21682          namespaces based on the demangled name.  */
21683       if (!cu->processing_has_namespace_info
21684           && cu->language == language_cplus)
21685         cp_scan_for_anonymous_namespaces (sym, objfile);
21686     }
21687   return (sym);
21688 }
21689
21690 /* Given an attr with a DW_FORM_dataN value in host byte order,
21691    zero-extend it as appropriate for the symbol's type.  The DWARF
21692    standard (v4) is not entirely clear about the meaning of using
21693    DW_FORM_dataN for a constant with a signed type, where the type is
21694    wider than the data.  The conclusion of a discussion on the DWARF
21695    list was that this is unspecified.  We choose to always zero-extend
21696    because that is the interpretation long in use by GCC.  */
21697
21698 static gdb_byte *
21699 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21700                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21701 {
21702   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21703   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21704                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21705   LONGEST l = DW_UNSND (attr);
21706
21707   if (bits < sizeof (*value) * 8)
21708     {
21709       l &= ((LONGEST) 1 << bits) - 1;
21710       *value = l;
21711     }
21712   else if (bits == sizeof (*value) * 8)
21713     *value = l;
21714   else
21715     {
21716       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21717       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21718       return bytes;
21719     }
21720
21721   return NULL;
21722 }
21723
21724 /* Read a constant value from an attribute.  Either set *VALUE, or if
21725    the value does not fit in *VALUE, set *BYTES - either already
21726    allocated on the objfile obstack, or newly allocated on OBSTACK,
21727    or, set *BATON, if we translated the constant to a location
21728    expression.  */
21729
21730 static void
21731 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21732                          const char *name, struct obstack *obstack,
21733                          struct dwarf2_cu *cu,
21734                          LONGEST *value, const gdb_byte **bytes,
21735                          struct dwarf2_locexpr_baton **baton)
21736 {
21737   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21738   struct comp_unit_head *cu_header = &cu->header;
21739   struct dwarf_block *blk;
21740   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21741                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21742
21743   *value = 0;
21744   *bytes = NULL;
21745   *baton = NULL;
21746
21747   switch (attr->form)
21748     {
21749     case DW_FORM_addr:
21750     case DW_FORM_GNU_addr_index:
21751       {
21752         gdb_byte *data;
21753
21754         if (TYPE_LENGTH (type) != cu_header->addr_size)
21755           dwarf2_const_value_length_mismatch_complaint (name,
21756                                                         cu_header->addr_size,
21757                                                         TYPE_LENGTH (type));
21758         /* Symbols of this form are reasonably rare, so we just
21759            piggyback on the existing location code rather than writing
21760            a new implementation of symbol_computed_ops.  */
21761         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21762         (*baton)->per_cu = cu->per_cu;
21763         gdb_assert ((*baton)->per_cu);
21764
21765         (*baton)->size = 2 + cu_header->addr_size;
21766         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21767         (*baton)->data = data;
21768
21769         data[0] = DW_OP_addr;
21770         store_unsigned_integer (&data[1], cu_header->addr_size,
21771                                 byte_order, DW_ADDR (attr));
21772         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21773       }
21774       break;
21775     case DW_FORM_string:
21776     case DW_FORM_strp:
21777     case DW_FORM_GNU_str_index:
21778     case DW_FORM_GNU_strp_alt:
21779       /* DW_STRING is already allocated on the objfile obstack, point
21780          directly to it.  */
21781       *bytes = (const gdb_byte *) DW_STRING (attr);
21782       break;
21783     case DW_FORM_block1:
21784     case DW_FORM_block2:
21785     case DW_FORM_block4:
21786     case DW_FORM_block:
21787     case DW_FORM_exprloc:
21788     case DW_FORM_data16:
21789       blk = DW_BLOCK (attr);
21790       if (TYPE_LENGTH (type) != blk->size)
21791         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21792                                                       TYPE_LENGTH (type));
21793       *bytes = blk->data;
21794       break;
21795
21796       /* The DW_AT_const_value attributes are supposed to carry the
21797          symbol's value "represented as it would be on the target
21798          architecture."  By the time we get here, it's already been
21799          converted to host endianness, so we just need to sign- or
21800          zero-extend it as appropriate.  */
21801     case DW_FORM_data1:
21802       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21803       break;
21804     case DW_FORM_data2:
21805       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21806       break;
21807     case DW_FORM_data4:
21808       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21809       break;
21810     case DW_FORM_data8:
21811       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21812       break;
21813
21814     case DW_FORM_sdata:
21815     case DW_FORM_implicit_const:
21816       *value = DW_SND (attr);
21817       break;
21818
21819     case DW_FORM_udata:
21820       *value = DW_UNSND (attr);
21821       break;
21822
21823     default:
21824       complaint (&symfile_complaints,
21825                  _("unsupported const value attribute form: '%s'"),
21826                  dwarf_form_name (attr->form));
21827       *value = 0;
21828       break;
21829     }
21830 }
21831
21832
21833 /* Copy constant value from an attribute to a symbol.  */
21834
21835 static void
21836 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21837                     struct dwarf2_cu *cu)
21838 {
21839   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21840   LONGEST value;
21841   const gdb_byte *bytes;
21842   struct dwarf2_locexpr_baton *baton;
21843
21844   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21845                            SYMBOL_PRINT_NAME (sym),
21846                            &objfile->objfile_obstack, cu,
21847                            &value, &bytes, &baton);
21848
21849   if (baton != NULL)
21850     {
21851       SYMBOL_LOCATION_BATON (sym) = baton;
21852       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21853     }
21854   else if (bytes != NULL)
21855      {
21856       SYMBOL_VALUE_BYTES (sym) = bytes;
21857       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21858     }
21859   else
21860     {
21861       SYMBOL_VALUE (sym) = value;
21862       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21863     }
21864 }
21865
21866 /* Return the type of the die in question using its DW_AT_type attribute.  */
21867
21868 static struct type *
21869 die_type (struct die_info *die, struct dwarf2_cu *cu)
21870 {
21871   struct attribute *type_attr;
21872
21873   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21874   if (!type_attr)
21875     {
21876       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21877       /* A missing DW_AT_type represents a void type.  */
21878       return objfile_type (objfile)->builtin_void;
21879     }
21880
21881   return lookup_die_type (die, type_attr, cu);
21882 }
21883
21884 /* True iff CU's producer generates GNAT Ada auxiliary information
21885    that allows to find parallel types through that information instead
21886    of having to do expensive parallel lookups by type name.  */
21887
21888 static int
21889 need_gnat_info (struct dwarf2_cu *cu)
21890 {
21891   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21892      of GNAT produces this auxiliary information, without any indication
21893      that it is produced.  Part of enhancing the FSF version of GNAT
21894      to produce that information will be to put in place an indicator
21895      that we can use in order to determine whether the descriptive type
21896      info is available or not.  One suggestion that has been made is
21897      to use a new attribute, attached to the CU die.  For now, assume
21898      that the descriptive type info is not available.  */
21899   return 0;
21900 }
21901
21902 /* Return the auxiliary type of the die in question using its
21903    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21904    attribute is not present.  */
21905
21906 static struct type *
21907 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21908 {
21909   struct attribute *type_attr;
21910
21911   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21912   if (!type_attr)
21913     return NULL;
21914
21915   return lookup_die_type (die, type_attr, cu);
21916 }
21917
21918 /* If DIE has a descriptive_type attribute, then set the TYPE's
21919    descriptive type accordingly.  */
21920
21921 static void
21922 set_descriptive_type (struct type *type, struct die_info *die,
21923                       struct dwarf2_cu *cu)
21924 {
21925   struct type *descriptive_type = die_descriptive_type (die, cu);
21926
21927   if (descriptive_type)
21928     {
21929       ALLOCATE_GNAT_AUX_TYPE (type);
21930       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21931     }
21932 }
21933
21934 /* Return the containing type of the die in question using its
21935    DW_AT_containing_type attribute.  */
21936
21937 static struct type *
21938 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21939 {
21940   struct attribute *type_attr;
21941   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21942
21943   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21944   if (!type_attr)
21945     error (_("Dwarf Error: Problem turning containing type into gdb type "
21946              "[in module %s]"), objfile_name (objfile));
21947
21948   return lookup_die_type (die, type_attr, cu);
21949 }
21950
21951 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21952
21953 static struct type *
21954 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21955 {
21956   struct dwarf2_per_objfile *dwarf2_per_objfile
21957     = cu->per_cu->dwarf2_per_objfile;
21958   struct objfile *objfile = dwarf2_per_objfile->objfile;
21959   char *message, *saved;
21960
21961   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21962                         objfile_name (objfile),
21963                         to_underlying (cu->header.sect_off),
21964                         to_underlying (die->sect_off));
21965   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21966                                   message, strlen (message));
21967   xfree (message);
21968
21969   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21970 }
21971
21972 /* Look up the type of DIE in CU using its type attribute ATTR.
21973    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21974    DW_AT_containing_type.
21975    If there is no type substitute an error marker.  */
21976
21977 static struct type *
21978 lookup_die_type (struct die_info *die, const struct attribute *attr,
21979                  struct dwarf2_cu *cu)
21980 {
21981   struct dwarf2_per_objfile *dwarf2_per_objfile
21982     = cu->per_cu->dwarf2_per_objfile;
21983   struct objfile *objfile = dwarf2_per_objfile->objfile;
21984   struct type *this_type;
21985
21986   gdb_assert (attr->name == DW_AT_type
21987               || attr->name == DW_AT_GNAT_descriptive_type
21988               || attr->name == DW_AT_containing_type);
21989
21990   /* First see if we have it cached.  */
21991
21992   if (attr->form == DW_FORM_GNU_ref_alt)
21993     {
21994       struct dwarf2_per_cu_data *per_cu;
21995       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21996
21997       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21998                                                  dwarf2_per_objfile);
21999       this_type = get_die_type_at_offset (sect_off, per_cu);
22000     }
22001   else if (attr_form_is_ref (attr))
22002     {
22003       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22004
22005       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22006     }
22007   else if (attr->form == DW_FORM_ref_sig8)
22008     {
22009       ULONGEST signature = DW_SIGNATURE (attr);
22010
22011       return get_signatured_type (die, signature, cu);
22012     }
22013   else
22014     {
22015       complaint (&symfile_complaints,
22016                  _("Dwarf Error: Bad type attribute %s in DIE"
22017                    " at 0x%x [in module %s]"),
22018                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
22019                  objfile_name (objfile));
22020       return build_error_marker_type (cu, die);
22021     }
22022
22023   /* If not cached we need to read it in.  */
22024
22025   if (this_type == NULL)
22026     {
22027       struct die_info *type_die = NULL;
22028       struct dwarf2_cu *type_cu = cu;
22029
22030       if (attr_form_is_ref (attr))
22031         type_die = follow_die_ref (die, attr, &type_cu);
22032       if (type_die == NULL)
22033         return build_error_marker_type (cu, die);
22034       /* If we find the type now, it's probably because the type came
22035          from an inter-CU reference and the type's CU got expanded before
22036          ours.  */
22037       this_type = read_type_die (type_die, type_cu);
22038     }
22039
22040   /* If we still don't have a type use an error marker.  */
22041
22042   if (this_type == NULL)
22043     return build_error_marker_type (cu, die);
22044
22045   return this_type;
22046 }
22047
22048 /* Return the type in DIE, CU.
22049    Returns NULL for invalid types.
22050
22051    This first does a lookup in die_type_hash,
22052    and only reads the die in if necessary.
22053
22054    NOTE: This can be called when reading in partial or full symbols.  */
22055
22056 static struct type *
22057 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22058 {
22059   struct type *this_type;
22060
22061   this_type = get_die_type (die, cu);
22062   if (this_type)
22063     return this_type;
22064
22065   return read_type_die_1 (die, cu);
22066 }
22067
22068 /* Read the type in DIE, CU.
22069    Returns NULL for invalid types.  */
22070
22071 static struct type *
22072 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22073 {
22074   struct type *this_type = NULL;
22075
22076   switch (die->tag)
22077     {
22078     case DW_TAG_class_type:
22079     case DW_TAG_interface_type:
22080     case DW_TAG_structure_type:
22081     case DW_TAG_union_type:
22082       this_type = read_structure_type (die, cu);
22083       break;
22084     case DW_TAG_enumeration_type:
22085       this_type = read_enumeration_type (die, cu);
22086       break;
22087     case DW_TAG_subprogram:
22088     case DW_TAG_subroutine_type:
22089     case DW_TAG_inlined_subroutine:
22090       this_type = read_subroutine_type (die, cu);
22091       break;
22092     case DW_TAG_array_type:
22093       this_type = read_array_type (die, cu);
22094       break;
22095     case DW_TAG_set_type:
22096       this_type = read_set_type (die, cu);
22097       break;
22098     case DW_TAG_pointer_type:
22099       this_type = read_tag_pointer_type (die, cu);
22100       break;
22101     case DW_TAG_ptr_to_member_type:
22102       this_type = read_tag_ptr_to_member_type (die, cu);
22103       break;
22104     case DW_TAG_reference_type:
22105       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22106       break;
22107     case DW_TAG_rvalue_reference_type:
22108       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22109       break;
22110     case DW_TAG_const_type:
22111       this_type = read_tag_const_type (die, cu);
22112       break;
22113     case DW_TAG_volatile_type:
22114       this_type = read_tag_volatile_type (die, cu);
22115       break;
22116     case DW_TAG_restrict_type:
22117       this_type = read_tag_restrict_type (die, cu);
22118       break;
22119     case DW_TAG_string_type:
22120       this_type = read_tag_string_type (die, cu);
22121       break;
22122     case DW_TAG_typedef:
22123       this_type = read_typedef (die, cu);
22124       break;
22125     case DW_TAG_subrange_type:
22126       this_type = read_subrange_type (die, cu);
22127       break;
22128     case DW_TAG_base_type:
22129       this_type = read_base_type (die, cu);
22130       break;
22131     case DW_TAG_unspecified_type:
22132       this_type = read_unspecified_type (die, cu);
22133       break;
22134     case DW_TAG_namespace:
22135       this_type = read_namespace_type (die, cu);
22136       break;
22137     case DW_TAG_module:
22138       this_type = read_module_type (die, cu);
22139       break;
22140     case DW_TAG_atomic_type:
22141       this_type = read_tag_atomic_type (die, cu);
22142       break;
22143     default:
22144       complaint (&symfile_complaints,
22145                  _("unexpected tag in read_type_die: '%s'"),
22146                  dwarf_tag_name (die->tag));
22147       break;
22148     }
22149
22150   return this_type;
22151 }
22152
22153 /* See if we can figure out if the class lives in a namespace.  We do
22154    this by looking for a member function; its demangled name will
22155    contain namespace info, if there is any.
22156    Return the computed name or NULL.
22157    Space for the result is allocated on the objfile's obstack.
22158    This is the full-die version of guess_partial_die_structure_name.
22159    In this case we know DIE has no useful parent.  */
22160
22161 static char *
22162 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22163 {
22164   struct die_info *spec_die;
22165   struct dwarf2_cu *spec_cu;
22166   struct die_info *child;
22167   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22168
22169   spec_cu = cu;
22170   spec_die = die_specification (die, &spec_cu);
22171   if (spec_die != NULL)
22172     {
22173       die = spec_die;
22174       cu = spec_cu;
22175     }
22176
22177   for (child = die->child;
22178        child != NULL;
22179        child = child->sibling)
22180     {
22181       if (child->tag == DW_TAG_subprogram)
22182         {
22183           const char *linkage_name = dw2_linkage_name (child, cu);
22184
22185           if (linkage_name != NULL)
22186             {
22187               char *actual_name
22188                 = language_class_name_from_physname (cu->language_defn,
22189                                                      linkage_name);
22190               char *name = NULL;
22191
22192               if (actual_name != NULL)
22193                 {
22194                   const char *die_name = dwarf2_name (die, cu);
22195
22196                   if (die_name != NULL
22197                       && strcmp (die_name, actual_name) != 0)
22198                     {
22199                       /* Strip off the class name from the full name.
22200                          We want the prefix.  */
22201                       int die_name_len = strlen (die_name);
22202                       int actual_name_len = strlen (actual_name);
22203
22204                       /* Test for '::' as a sanity check.  */
22205                       if (actual_name_len > die_name_len + 2
22206                           && actual_name[actual_name_len
22207                                          - die_name_len - 1] == ':')
22208                         name = (char *) obstack_copy0 (
22209                           &objfile->per_bfd->storage_obstack,
22210                           actual_name, actual_name_len - die_name_len - 2);
22211                     }
22212                 }
22213               xfree (actual_name);
22214               return name;
22215             }
22216         }
22217     }
22218
22219   return NULL;
22220 }
22221
22222 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22223    prefix part in such case.  See
22224    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22225
22226 static const char *
22227 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22228 {
22229   struct attribute *attr;
22230   const char *base;
22231
22232   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22233       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22234     return NULL;
22235
22236   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22237     return NULL;
22238
22239   attr = dw2_linkage_name_attr (die, cu);
22240   if (attr == NULL || DW_STRING (attr) == NULL)
22241     return NULL;
22242
22243   /* dwarf2_name had to be already called.  */
22244   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22245
22246   /* Strip the base name, keep any leading namespaces/classes.  */
22247   base = strrchr (DW_STRING (attr), ':');
22248   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22249     return "";
22250
22251   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22252   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22253                                  DW_STRING (attr),
22254                                  &base[-1] - DW_STRING (attr));
22255 }
22256
22257 /* Return the name of the namespace/class that DIE is defined within,
22258    or "" if we can't tell.  The caller should not xfree the result.
22259
22260    For example, if we're within the method foo() in the following
22261    code:
22262
22263    namespace N {
22264      class C {
22265        void foo () {
22266        }
22267      };
22268    }
22269
22270    then determine_prefix on foo's die will return "N::C".  */
22271
22272 static const char *
22273 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22274 {
22275   struct dwarf2_per_objfile *dwarf2_per_objfile
22276     = cu->per_cu->dwarf2_per_objfile;
22277   struct die_info *parent, *spec_die;
22278   struct dwarf2_cu *spec_cu;
22279   struct type *parent_type;
22280   const char *retval;
22281
22282   if (cu->language != language_cplus
22283       && cu->language != language_fortran && cu->language != language_d
22284       && cu->language != language_rust)
22285     return "";
22286
22287   retval = anonymous_struct_prefix (die, cu);
22288   if (retval)
22289     return retval;
22290
22291   /* We have to be careful in the presence of DW_AT_specification.
22292      For example, with GCC 3.4, given the code
22293
22294      namespace N {
22295        void foo() {
22296          // Definition of N::foo.
22297        }
22298      }
22299
22300      then we'll have a tree of DIEs like this:
22301
22302      1: DW_TAG_compile_unit
22303        2: DW_TAG_namespace        // N
22304          3: DW_TAG_subprogram     // declaration of N::foo
22305        4: DW_TAG_subprogram       // definition of N::foo
22306             DW_AT_specification   // refers to die #3
22307
22308      Thus, when processing die #4, we have to pretend that we're in
22309      the context of its DW_AT_specification, namely the contex of die
22310      #3.  */
22311   spec_cu = cu;
22312   spec_die = die_specification (die, &spec_cu);
22313   if (spec_die == NULL)
22314     parent = die->parent;
22315   else
22316     {
22317       parent = spec_die->parent;
22318       cu = spec_cu;
22319     }
22320
22321   if (parent == NULL)
22322     return "";
22323   else if (parent->building_fullname)
22324     {
22325       const char *name;
22326       const char *parent_name;
22327
22328       /* It has been seen on RealView 2.2 built binaries,
22329          DW_TAG_template_type_param types actually _defined_ as
22330          children of the parent class:
22331
22332          enum E {};
22333          template class <class Enum> Class{};
22334          Class<enum E> class_e;
22335
22336          1: DW_TAG_class_type (Class)
22337            2: DW_TAG_enumeration_type (E)
22338              3: DW_TAG_enumerator (enum1:0)
22339              3: DW_TAG_enumerator (enum2:1)
22340              ...
22341            2: DW_TAG_template_type_param
22342               DW_AT_type  DW_FORM_ref_udata (E)
22343
22344          Besides being broken debug info, it can put GDB into an
22345          infinite loop.  Consider:
22346
22347          When we're building the full name for Class<E>, we'll start
22348          at Class, and go look over its template type parameters,
22349          finding E.  We'll then try to build the full name of E, and
22350          reach here.  We're now trying to build the full name of E,
22351          and look over the parent DIE for containing scope.  In the
22352          broken case, if we followed the parent DIE of E, we'd again
22353          find Class, and once again go look at its template type
22354          arguments, etc., etc.  Simply don't consider such parent die
22355          as source-level parent of this die (it can't be, the language
22356          doesn't allow it), and break the loop here.  */
22357       name = dwarf2_name (die, cu);
22358       parent_name = dwarf2_name (parent, cu);
22359       complaint (&symfile_complaints,
22360                  _("template param type '%s' defined within parent '%s'"),
22361                  name ? name : "<unknown>",
22362                  parent_name ? parent_name : "<unknown>");
22363       return "";
22364     }
22365   else
22366     switch (parent->tag)
22367       {
22368       case DW_TAG_namespace:
22369         parent_type = read_type_die (parent, cu);
22370         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22371            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22372            Work around this problem here.  */
22373         if (cu->language == language_cplus
22374             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22375           return "";
22376         /* We give a name to even anonymous namespaces.  */
22377         return TYPE_TAG_NAME (parent_type);
22378       case DW_TAG_class_type:
22379       case DW_TAG_interface_type:
22380       case DW_TAG_structure_type:
22381       case DW_TAG_union_type:
22382       case DW_TAG_module:
22383         parent_type = read_type_die (parent, cu);
22384         if (TYPE_TAG_NAME (parent_type) != NULL)
22385           return TYPE_TAG_NAME (parent_type);
22386         else
22387           /* An anonymous structure is only allowed non-static data
22388              members; no typedefs, no member functions, et cetera.
22389              So it does not need a prefix.  */
22390           return "";
22391       case DW_TAG_compile_unit:
22392       case DW_TAG_partial_unit:
22393         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22394         if (cu->language == language_cplus
22395             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22396             && die->child != NULL
22397             && (die->tag == DW_TAG_class_type
22398                 || die->tag == DW_TAG_structure_type
22399                 || die->tag == DW_TAG_union_type))
22400           {
22401             char *name = guess_full_die_structure_name (die, cu);
22402             if (name != NULL)
22403               return name;
22404           }
22405         return "";
22406       case DW_TAG_enumeration_type:
22407         parent_type = read_type_die (parent, cu);
22408         if (TYPE_DECLARED_CLASS (parent_type))
22409           {
22410             if (TYPE_TAG_NAME (parent_type) != NULL)
22411               return TYPE_TAG_NAME (parent_type);
22412             return "";
22413           }
22414         /* Fall through.  */
22415       default:
22416         return determine_prefix (parent, cu);
22417       }
22418 }
22419
22420 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22421    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22422    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22423    an obconcat, otherwise allocate storage for the result.  The CU argument is
22424    used to determine the language and hence, the appropriate separator.  */
22425
22426 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22427
22428 static char *
22429 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22430                  int physname, struct dwarf2_cu *cu)
22431 {
22432   const char *lead = "";
22433   const char *sep;
22434
22435   if (suffix == NULL || suffix[0] == '\0'
22436       || prefix == NULL || prefix[0] == '\0')
22437     sep = "";
22438   else if (cu->language == language_d)
22439     {
22440       /* For D, the 'main' function could be defined in any module, but it
22441          should never be prefixed.  */
22442       if (strcmp (suffix, "D main") == 0)
22443         {
22444           prefix = "";
22445           sep = "";
22446         }
22447       else
22448         sep = ".";
22449     }
22450   else if (cu->language == language_fortran && physname)
22451     {
22452       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22453          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22454
22455       lead = "__";
22456       sep = "_MOD_";
22457     }
22458   else
22459     sep = "::";
22460
22461   if (prefix == NULL)
22462     prefix = "";
22463   if (suffix == NULL)
22464     suffix = "";
22465
22466   if (obs == NULL)
22467     {
22468       char *retval
22469         = ((char *)
22470            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22471
22472       strcpy (retval, lead);
22473       strcat (retval, prefix);
22474       strcat (retval, sep);
22475       strcat (retval, suffix);
22476       return retval;
22477     }
22478   else
22479     {
22480       /* We have an obstack.  */
22481       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22482     }
22483 }
22484
22485 /* Return sibling of die, NULL if no sibling.  */
22486
22487 static struct die_info *
22488 sibling_die (struct die_info *die)
22489 {
22490   return die->sibling;
22491 }
22492
22493 /* Get name of a die, return NULL if not found.  */
22494
22495 static const char *
22496 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22497                           struct obstack *obstack)
22498 {
22499   if (name && cu->language == language_cplus)
22500     {
22501       std::string canon_name = cp_canonicalize_string (name);
22502
22503       if (!canon_name.empty ())
22504         {
22505           if (canon_name != name)
22506             name = (const char *) obstack_copy0 (obstack,
22507                                                  canon_name.c_str (),
22508                                                  canon_name.length ());
22509         }
22510     }
22511
22512   return name;
22513 }
22514
22515 /* Get name of a die, return NULL if not found.
22516    Anonymous namespaces are converted to their magic string.  */
22517
22518 static const char *
22519 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22520 {
22521   struct attribute *attr;
22522   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22523
22524   attr = dwarf2_attr (die, DW_AT_name, cu);
22525   if ((!attr || !DW_STRING (attr))
22526       && die->tag != DW_TAG_namespace
22527       && die->tag != DW_TAG_class_type
22528       && die->tag != DW_TAG_interface_type
22529       && die->tag != DW_TAG_structure_type
22530       && die->tag != DW_TAG_union_type)
22531     return NULL;
22532
22533   switch (die->tag)
22534     {
22535     case DW_TAG_compile_unit:
22536     case DW_TAG_partial_unit:
22537       /* Compilation units have a DW_AT_name that is a filename, not
22538          a source language identifier.  */
22539     case DW_TAG_enumeration_type:
22540     case DW_TAG_enumerator:
22541       /* These tags always have simple identifiers already; no need
22542          to canonicalize them.  */
22543       return DW_STRING (attr);
22544
22545     case DW_TAG_namespace:
22546       if (attr != NULL && DW_STRING (attr) != NULL)
22547         return DW_STRING (attr);
22548       return CP_ANONYMOUS_NAMESPACE_STR;
22549
22550     case DW_TAG_class_type:
22551     case DW_TAG_interface_type:
22552     case DW_TAG_structure_type:
22553     case DW_TAG_union_type:
22554       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22555          structures or unions.  These were of the form "._%d" in GCC 4.1,
22556          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22557          and GCC 4.4.  We work around this problem by ignoring these.  */
22558       if (attr && DW_STRING (attr)
22559           && (startswith (DW_STRING (attr), "._")
22560               || startswith (DW_STRING (attr), "<anonymous")))
22561         return NULL;
22562
22563       /* GCC might emit a nameless typedef that has a linkage name.  See
22564          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22565       if (!attr || DW_STRING (attr) == NULL)
22566         {
22567           char *demangled = NULL;
22568
22569           attr = dw2_linkage_name_attr (die, cu);
22570           if (attr == NULL || DW_STRING (attr) == NULL)
22571             return NULL;
22572
22573           /* Avoid demangling DW_STRING (attr) the second time on a second
22574              call for the same DIE.  */
22575           if (!DW_STRING_IS_CANONICAL (attr))
22576             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22577
22578           if (demangled)
22579             {
22580               const char *base;
22581
22582               /* FIXME: we already did this for the partial symbol... */
22583               DW_STRING (attr)
22584                 = ((const char *)
22585                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22586                                   demangled, strlen (demangled)));
22587               DW_STRING_IS_CANONICAL (attr) = 1;
22588               xfree (demangled);
22589
22590               /* Strip any leading namespaces/classes, keep only the base name.
22591                  DW_AT_name for named DIEs does not contain the prefixes.  */
22592               base = strrchr (DW_STRING (attr), ':');
22593               if (base && base > DW_STRING (attr) && base[-1] == ':')
22594                 return &base[1];
22595               else
22596                 return DW_STRING (attr);
22597             }
22598         }
22599       break;
22600
22601     default:
22602       break;
22603     }
22604
22605   if (!DW_STRING_IS_CANONICAL (attr))
22606     {
22607       DW_STRING (attr)
22608         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22609                                     &objfile->per_bfd->storage_obstack);
22610       DW_STRING_IS_CANONICAL (attr) = 1;
22611     }
22612   return DW_STRING (attr);
22613 }
22614
22615 /* Return the die that this die in an extension of, or NULL if there
22616    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22617    containing the return value on output.  */
22618
22619 static struct die_info *
22620 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22621 {
22622   struct attribute *attr;
22623
22624   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22625   if (attr == NULL)
22626     return NULL;
22627
22628   return follow_die_ref (die, attr, ext_cu);
22629 }
22630
22631 /* Convert a DIE tag into its string name.  */
22632
22633 static const char *
22634 dwarf_tag_name (unsigned tag)
22635 {
22636   const char *name = get_DW_TAG_name (tag);
22637
22638   if (name == NULL)
22639     return "DW_TAG_<unknown>";
22640
22641   return name;
22642 }
22643
22644 /* Convert a DWARF attribute code into its string name.  */
22645
22646 static const char *
22647 dwarf_attr_name (unsigned attr)
22648 {
22649   const char *name;
22650
22651 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22652   if (attr == DW_AT_MIPS_fde)
22653     return "DW_AT_MIPS_fde";
22654 #else
22655   if (attr == DW_AT_HP_block_index)
22656     return "DW_AT_HP_block_index";
22657 #endif
22658
22659   name = get_DW_AT_name (attr);
22660
22661   if (name == NULL)
22662     return "DW_AT_<unknown>";
22663
22664   return name;
22665 }
22666
22667 /* Convert a DWARF value form code into its string name.  */
22668
22669 static const char *
22670 dwarf_form_name (unsigned form)
22671 {
22672   const char *name = get_DW_FORM_name (form);
22673
22674   if (name == NULL)
22675     return "DW_FORM_<unknown>";
22676
22677   return name;
22678 }
22679
22680 static const char *
22681 dwarf_bool_name (unsigned mybool)
22682 {
22683   if (mybool)
22684     return "TRUE";
22685   else
22686     return "FALSE";
22687 }
22688
22689 /* Convert a DWARF type code into its string name.  */
22690
22691 static const char *
22692 dwarf_type_encoding_name (unsigned enc)
22693 {
22694   const char *name = get_DW_ATE_name (enc);
22695
22696   if (name == NULL)
22697     return "DW_ATE_<unknown>";
22698
22699   return name;
22700 }
22701
22702 static void
22703 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22704 {
22705   unsigned int i;
22706
22707   print_spaces (indent, f);
22708   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22709                       dwarf_tag_name (die->tag), die->abbrev,
22710                       to_underlying (die->sect_off));
22711
22712   if (die->parent != NULL)
22713     {
22714       print_spaces (indent, f);
22715       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22716                           to_underlying (die->parent->sect_off));
22717     }
22718
22719   print_spaces (indent, f);
22720   fprintf_unfiltered (f, "  has children: %s\n",
22721            dwarf_bool_name (die->child != NULL));
22722
22723   print_spaces (indent, f);
22724   fprintf_unfiltered (f, "  attributes:\n");
22725
22726   for (i = 0; i < die->num_attrs; ++i)
22727     {
22728       print_spaces (indent, f);
22729       fprintf_unfiltered (f, "    %s (%s) ",
22730                dwarf_attr_name (die->attrs[i].name),
22731                dwarf_form_name (die->attrs[i].form));
22732
22733       switch (die->attrs[i].form)
22734         {
22735         case DW_FORM_addr:
22736         case DW_FORM_GNU_addr_index:
22737           fprintf_unfiltered (f, "address: ");
22738           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22739           break;
22740         case DW_FORM_block2:
22741         case DW_FORM_block4:
22742         case DW_FORM_block:
22743         case DW_FORM_block1:
22744           fprintf_unfiltered (f, "block: size %s",
22745                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22746           break;
22747         case DW_FORM_exprloc:
22748           fprintf_unfiltered (f, "expression: size %s",
22749                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22750           break;
22751         case DW_FORM_data16:
22752           fprintf_unfiltered (f, "constant of 16 bytes");
22753           break;
22754         case DW_FORM_ref_addr:
22755           fprintf_unfiltered (f, "ref address: ");
22756           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22757           break;
22758         case DW_FORM_GNU_ref_alt:
22759           fprintf_unfiltered (f, "alt ref address: ");
22760           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22761           break;
22762         case DW_FORM_ref1:
22763         case DW_FORM_ref2:
22764         case DW_FORM_ref4:
22765         case DW_FORM_ref8:
22766         case DW_FORM_ref_udata:
22767           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22768                               (long) (DW_UNSND (&die->attrs[i])));
22769           break;
22770         case DW_FORM_data1:
22771         case DW_FORM_data2:
22772         case DW_FORM_data4:
22773         case DW_FORM_data8:
22774         case DW_FORM_udata:
22775         case DW_FORM_sdata:
22776           fprintf_unfiltered (f, "constant: %s",
22777                               pulongest (DW_UNSND (&die->attrs[i])));
22778           break;
22779         case DW_FORM_sec_offset:
22780           fprintf_unfiltered (f, "section offset: %s",
22781                               pulongest (DW_UNSND (&die->attrs[i])));
22782           break;
22783         case DW_FORM_ref_sig8:
22784           fprintf_unfiltered (f, "signature: %s",
22785                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22786           break;
22787         case DW_FORM_string:
22788         case DW_FORM_strp:
22789         case DW_FORM_line_strp:
22790         case DW_FORM_GNU_str_index:
22791         case DW_FORM_GNU_strp_alt:
22792           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22793                    DW_STRING (&die->attrs[i])
22794                    ? DW_STRING (&die->attrs[i]) : "",
22795                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22796           break;
22797         case DW_FORM_flag:
22798           if (DW_UNSND (&die->attrs[i]))
22799             fprintf_unfiltered (f, "flag: TRUE");
22800           else
22801             fprintf_unfiltered (f, "flag: FALSE");
22802           break;
22803         case DW_FORM_flag_present:
22804           fprintf_unfiltered (f, "flag: TRUE");
22805           break;
22806         case DW_FORM_indirect:
22807           /* The reader will have reduced the indirect form to
22808              the "base form" so this form should not occur.  */
22809           fprintf_unfiltered (f, 
22810                               "unexpected attribute form: DW_FORM_indirect");
22811           break;
22812         case DW_FORM_implicit_const:
22813           fprintf_unfiltered (f, "constant: %s",
22814                               plongest (DW_SND (&die->attrs[i])));
22815           break;
22816         default:
22817           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22818                    die->attrs[i].form);
22819           break;
22820         }
22821       fprintf_unfiltered (f, "\n");
22822     }
22823 }
22824
22825 static void
22826 dump_die_for_error (struct die_info *die)
22827 {
22828   dump_die_shallow (gdb_stderr, 0, die);
22829 }
22830
22831 static void
22832 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22833 {
22834   int indent = level * 4;
22835
22836   gdb_assert (die != NULL);
22837
22838   if (level >= max_level)
22839     return;
22840
22841   dump_die_shallow (f, indent, die);
22842
22843   if (die->child != NULL)
22844     {
22845       print_spaces (indent, f);
22846       fprintf_unfiltered (f, "  Children:");
22847       if (level + 1 < max_level)
22848         {
22849           fprintf_unfiltered (f, "\n");
22850           dump_die_1 (f, level + 1, max_level, die->child);
22851         }
22852       else
22853         {
22854           fprintf_unfiltered (f,
22855                               " [not printed, max nesting level reached]\n");
22856         }
22857     }
22858
22859   if (die->sibling != NULL && level > 0)
22860     {
22861       dump_die_1 (f, level, max_level, die->sibling);
22862     }
22863 }
22864
22865 /* This is called from the pdie macro in gdbinit.in.
22866    It's not static so gcc will keep a copy callable from gdb.  */
22867
22868 void
22869 dump_die (struct die_info *die, int max_level)
22870 {
22871   dump_die_1 (gdb_stdlog, 0, max_level, die);
22872 }
22873
22874 static void
22875 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22876 {
22877   void **slot;
22878
22879   slot = htab_find_slot_with_hash (cu->die_hash, die,
22880                                    to_underlying (die->sect_off),
22881                                    INSERT);
22882
22883   *slot = die;
22884 }
22885
22886 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22887    required kind.  */
22888
22889 static sect_offset
22890 dwarf2_get_ref_die_offset (const struct attribute *attr)
22891 {
22892   if (attr_form_is_ref (attr))
22893     return (sect_offset) DW_UNSND (attr);
22894
22895   complaint (&symfile_complaints,
22896              _("unsupported die ref attribute form: '%s'"),
22897              dwarf_form_name (attr->form));
22898   return {};
22899 }
22900
22901 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22902  * the value held by the attribute is not constant.  */
22903
22904 static LONGEST
22905 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22906 {
22907   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22908     return DW_SND (attr);
22909   else if (attr->form == DW_FORM_udata
22910            || attr->form == DW_FORM_data1
22911            || attr->form == DW_FORM_data2
22912            || attr->form == DW_FORM_data4
22913            || attr->form == DW_FORM_data8)
22914     return DW_UNSND (attr);
22915   else
22916     {
22917       /* For DW_FORM_data16 see attr_form_is_constant.  */
22918       complaint (&symfile_complaints,
22919                  _("Attribute value is not a constant (%s)"),
22920                  dwarf_form_name (attr->form));
22921       return default_value;
22922     }
22923 }
22924
22925 /* Follow reference or signature attribute ATTR of SRC_DIE.
22926    On entry *REF_CU is the CU of SRC_DIE.
22927    On exit *REF_CU is the CU of the result.  */
22928
22929 static struct die_info *
22930 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22931                        struct dwarf2_cu **ref_cu)
22932 {
22933   struct die_info *die;
22934
22935   if (attr_form_is_ref (attr))
22936     die = follow_die_ref (src_die, attr, ref_cu);
22937   else if (attr->form == DW_FORM_ref_sig8)
22938     die = follow_die_sig (src_die, attr, ref_cu);
22939   else
22940     {
22941       dump_die_for_error (src_die);
22942       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22943              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22944     }
22945
22946   return die;
22947 }
22948
22949 /* Follow reference OFFSET.
22950    On entry *REF_CU is the CU of the source die referencing OFFSET.
22951    On exit *REF_CU is the CU of the result.
22952    Returns NULL if OFFSET is invalid.  */
22953
22954 static struct die_info *
22955 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22956                    struct dwarf2_cu **ref_cu)
22957 {
22958   struct die_info temp_die;
22959   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22960   struct dwarf2_per_objfile *dwarf2_per_objfile
22961     = cu->per_cu->dwarf2_per_objfile;
22962   struct objfile *objfile = dwarf2_per_objfile->objfile;
22963
22964   gdb_assert (cu->per_cu != NULL);
22965
22966   target_cu = cu;
22967
22968   if (cu->per_cu->is_debug_types)
22969     {
22970       /* .debug_types CUs cannot reference anything outside their CU.
22971          If they need to, they have to reference a signatured type via
22972          DW_FORM_ref_sig8.  */
22973       if (!offset_in_cu_p (&cu->header, sect_off))
22974         return NULL;
22975     }
22976   else if (offset_in_dwz != cu->per_cu->is_dwz
22977            || !offset_in_cu_p (&cu->header, sect_off))
22978     {
22979       struct dwarf2_per_cu_data *per_cu;
22980
22981       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22982                                                  dwarf2_per_objfile);
22983
22984       /* If necessary, add it to the queue and load its DIEs.  */
22985       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22986         load_full_comp_unit (per_cu, cu->language);
22987
22988       target_cu = per_cu->cu;
22989     }
22990   else if (cu->dies == NULL)
22991     {
22992       /* We're loading full DIEs during partial symbol reading.  */
22993       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22994       load_full_comp_unit (cu->per_cu, language_minimal);
22995     }
22996
22997   *ref_cu = target_cu;
22998   temp_die.sect_off = sect_off;
22999   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23000                                                   &temp_die,
23001                                                   to_underlying (sect_off));
23002 }
23003
23004 /* Follow reference attribute ATTR of SRC_DIE.
23005    On entry *REF_CU is the CU of SRC_DIE.
23006    On exit *REF_CU is the CU of the result.  */
23007
23008 static struct die_info *
23009 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23010                 struct dwarf2_cu **ref_cu)
23011 {
23012   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23013   struct dwarf2_cu *cu = *ref_cu;
23014   struct die_info *die;
23015
23016   die = follow_die_offset (sect_off,
23017                            (attr->form == DW_FORM_GNU_ref_alt
23018                             || cu->per_cu->is_dwz),
23019                            ref_cu);
23020   if (!die)
23021     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
23022            "at 0x%x [in module %s]"),
23023            to_underlying (sect_off), to_underlying (src_die->sect_off),
23024            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23025
23026   return die;
23027 }
23028
23029 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23030    Returned value is intended for DW_OP_call*.  Returned
23031    dwarf2_locexpr_baton->data has lifetime of
23032    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23033
23034 struct dwarf2_locexpr_baton
23035 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23036                                struct dwarf2_per_cu_data *per_cu,
23037                                CORE_ADDR (*get_frame_pc) (void *baton),
23038                                void *baton)
23039 {
23040   struct dwarf2_cu *cu;
23041   struct die_info *die;
23042   struct attribute *attr;
23043   struct dwarf2_locexpr_baton retval;
23044   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23045   struct dwarf2_per_objfile *dwarf2_per_objfile
23046     = get_dwarf2_per_objfile (objfile);
23047
23048   if (per_cu->cu == NULL)
23049     load_cu (per_cu);
23050   cu = per_cu->cu;
23051   if (cu == NULL)
23052     {
23053       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23054          Instead just throw an error, not much else we can do.  */
23055       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23056              to_underlying (sect_off), objfile_name (objfile));
23057     }
23058
23059   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23060   if (!die)
23061     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23062            to_underlying (sect_off), objfile_name (objfile));
23063
23064   attr = dwarf2_attr (die, DW_AT_location, cu);
23065   if (!attr)
23066     {
23067       /* DWARF: "If there is no such attribute, then there is no effect.".
23068          DATA is ignored if SIZE is 0.  */
23069
23070       retval.data = NULL;
23071       retval.size = 0;
23072     }
23073   else if (attr_form_is_section_offset (attr))
23074     {
23075       struct dwarf2_loclist_baton loclist_baton;
23076       CORE_ADDR pc = (*get_frame_pc) (baton);
23077       size_t size;
23078
23079       fill_in_loclist_baton (cu, &loclist_baton, attr);
23080
23081       retval.data = dwarf2_find_location_expression (&loclist_baton,
23082                                                      &size, pc);
23083       retval.size = size;
23084     }
23085   else
23086     {
23087       if (!attr_form_is_block (attr))
23088         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
23089                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23090                to_underlying (sect_off), objfile_name (objfile));
23091
23092       retval.data = DW_BLOCK (attr)->data;
23093       retval.size = DW_BLOCK (attr)->size;
23094     }
23095   retval.per_cu = cu->per_cu;
23096
23097   age_cached_comp_units (dwarf2_per_objfile);
23098
23099   return retval;
23100 }
23101
23102 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23103    offset.  */
23104
23105 struct dwarf2_locexpr_baton
23106 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23107                              struct dwarf2_per_cu_data *per_cu,
23108                              CORE_ADDR (*get_frame_pc) (void *baton),
23109                              void *baton)
23110 {
23111   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23112
23113   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23114 }
23115
23116 /* Write a constant of a given type as target-ordered bytes into
23117    OBSTACK.  */
23118
23119 static const gdb_byte *
23120 write_constant_as_bytes (struct obstack *obstack,
23121                          enum bfd_endian byte_order,
23122                          struct type *type,
23123                          ULONGEST value,
23124                          LONGEST *len)
23125 {
23126   gdb_byte *result;
23127
23128   *len = TYPE_LENGTH (type);
23129   result = (gdb_byte *) obstack_alloc (obstack, *len);
23130   store_unsigned_integer (result, *len, byte_order, value);
23131
23132   return result;
23133 }
23134
23135 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23136    pointer to the constant bytes and set LEN to the length of the
23137    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23138    does not have a DW_AT_const_value, return NULL.  */
23139
23140 const gdb_byte *
23141 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23142                              struct dwarf2_per_cu_data *per_cu,
23143                              struct obstack *obstack,
23144                              LONGEST *len)
23145 {
23146   struct dwarf2_cu *cu;
23147   struct die_info *die;
23148   struct attribute *attr;
23149   const gdb_byte *result = NULL;
23150   struct type *type;
23151   LONGEST value;
23152   enum bfd_endian byte_order;
23153   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23154
23155   if (per_cu->cu == NULL)
23156     load_cu (per_cu);
23157   cu = per_cu->cu;
23158   if (cu == NULL)
23159     {
23160       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23161          Instead just throw an error, not much else we can do.  */
23162       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23163              to_underlying (sect_off), objfile_name (objfile));
23164     }
23165
23166   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23167   if (!die)
23168     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23169            to_underlying (sect_off), objfile_name (objfile));
23170
23171
23172   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23173   if (attr == NULL)
23174     return NULL;
23175
23176   byte_order = (bfd_big_endian (objfile->obfd)
23177                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23178
23179   switch (attr->form)
23180     {
23181     case DW_FORM_addr:
23182     case DW_FORM_GNU_addr_index:
23183       {
23184         gdb_byte *tem;
23185
23186         *len = cu->header.addr_size;
23187         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23188         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23189         result = tem;
23190       }
23191       break;
23192     case DW_FORM_string:
23193     case DW_FORM_strp:
23194     case DW_FORM_GNU_str_index:
23195     case DW_FORM_GNU_strp_alt:
23196       /* DW_STRING is already allocated on the objfile obstack, point
23197          directly to it.  */
23198       result = (const gdb_byte *) DW_STRING (attr);
23199       *len = strlen (DW_STRING (attr));
23200       break;
23201     case DW_FORM_block1:
23202     case DW_FORM_block2:
23203     case DW_FORM_block4:
23204     case DW_FORM_block:
23205     case DW_FORM_exprloc:
23206     case DW_FORM_data16:
23207       result = DW_BLOCK (attr)->data;
23208       *len = DW_BLOCK (attr)->size;
23209       break;
23210
23211       /* The DW_AT_const_value attributes are supposed to carry the
23212          symbol's value "represented as it would be on the target
23213          architecture."  By the time we get here, it's already been
23214          converted to host endianness, so we just need to sign- or
23215          zero-extend it as appropriate.  */
23216     case DW_FORM_data1:
23217       type = die_type (die, cu);
23218       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23219       if (result == NULL)
23220         result = write_constant_as_bytes (obstack, byte_order,
23221                                           type, value, len);
23222       break;
23223     case DW_FORM_data2:
23224       type = die_type (die, cu);
23225       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23226       if (result == NULL)
23227         result = write_constant_as_bytes (obstack, byte_order,
23228                                           type, value, len);
23229       break;
23230     case DW_FORM_data4:
23231       type = die_type (die, cu);
23232       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23233       if (result == NULL)
23234         result = write_constant_as_bytes (obstack, byte_order,
23235                                           type, value, len);
23236       break;
23237     case DW_FORM_data8:
23238       type = die_type (die, cu);
23239       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23240       if (result == NULL)
23241         result = write_constant_as_bytes (obstack, byte_order,
23242                                           type, value, len);
23243       break;
23244
23245     case DW_FORM_sdata:
23246     case DW_FORM_implicit_const:
23247       type = die_type (die, cu);
23248       result = write_constant_as_bytes (obstack, byte_order,
23249                                         type, DW_SND (attr), len);
23250       break;
23251
23252     case DW_FORM_udata:
23253       type = die_type (die, cu);
23254       result = write_constant_as_bytes (obstack, byte_order,
23255                                         type, DW_UNSND (attr), len);
23256       break;
23257
23258     default:
23259       complaint (&symfile_complaints,
23260                  _("unsupported const value attribute form: '%s'"),
23261                  dwarf_form_name (attr->form));
23262       break;
23263     }
23264
23265   return result;
23266 }
23267
23268 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23269    valid type for this die is found.  */
23270
23271 struct type *
23272 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23273                                 struct dwarf2_per_cu_data *per_cu)
23274 {
23275   struct dwarf2_cu *cu;
23276   struct die_info *die;
23277
23278   if (per_cu->cu == NULL)
23279     load_cu (per_cu);
23280   cu = per_cu->cu;
23281   if (!cu)
23282     return NULL;
23283
23284   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23285   if (!die)
23286     return NULL;
23287
23288   return die_type (die, cu);
23289 }
23290
23291 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23292    PER_CU.  */
23293
23294 struct type *
23295 dwarf2_get_die_type (cu_offset die_offset,
23296                      struct dwarf2_per_cu_data *per_cu)
23297 {
23298   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23299   return get_die_type_at_offset (die_offset_sect, per_cu);
23300 }
23301
23302 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23303    On entry *REF_CU is the CU of SRC_DIE.
23304    On exit *REF_CU is the CU of the result.
23305    Returns NULL if the referenced DIE isn't found.  */
23306
23307 static struct die_info *
23308 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23309                   struct dwarf2_cu **ref_cu)
23310 {
23311   struct die_info temp_die;
23312   struct dwarf2_cu *sig_cu;
23313   struct die_info *die;
23314
23315   /* While it might be nice to assert sig_type->type == NULL here,
23316      we can get here for DW_AT_imported_declaration where we need
23317      the DIE not the type.  */
23318
23319   /* If necessary, add it to the queue and load its DIEs.  */
23320
23321   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23322     read_signatured_type (sig_type);
23323
23324   sig_cu = sig_type->per_cu.cu;
23325   gdb_assert (sig_cu != NULL);
23326   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23327   temp_die.sect_off = sig_type->type_offset_in_section;
23328   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23329                                                  to_underlying (temp_die.sect_off));
23330   if (die)
23331     {
23332       struct dwarf2_per_objfile *dwarf2_per_objfile
23333         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23334
23335       /* For .gdb_index version 7 keep track of included TUs.
23336          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23337       if (dwarf2_per_objfile->index_table != NULL
23338           && dwarf2_per_objfile->index_table->version <= 7)
23339         {
23340           VEC_safe_push (dwarf2_per_cu_ptr,
23341                          (*ref_cu)->per_cu->imported_symtabs,
23342                          sig_cu->per_cu);
23343         }
23344
23345       *ref_cu = sig_cu;
23346       return die;
23347     }
23348
23349   return NULL;
23350 }
23351
23352 /* Follow signatured type referenced by ATTR in SRC_DIE.
23353    On entry *REF_CU is the CU of SRC_DIE.
23354    On exit *REF_CU is the CU of the result.
23355    The result is the DIE of the type.
23356    If the referenced type cannot be found an error is thrown.  */
23357
23358 static struct die_info *
23359 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23360                 struct dwarf2_cu **ref_cu)
23361 {
23362   ULONGEST signature = DW_SIGNATURE (attr);
23363   struct signatured_type *sig_type;
23364   struct die_info *die;
23365
23366   gdb_assert (attr->form == DW_FORM_ref_sig8);
23367
23368   sig_type = lookup_signatured_type (*ref_cu, signature);
23369   /* sig_type will be NULL if the signatured type is missing from
23370      the debug info.  */
23371   if (sig_type == NULL)
23372     {
23373       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23374                " from DIE at 0x%x [in module %s]"),
23375              hex_string (signature), to_underlying (src_die->sect_off),
23376              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23377     }
23378
23379   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23380   if (die == NULL)
23381     {
23382       dump_die_for_error (src_die);
23383       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23384                " from DIE at 0x%x [in module %s]"),
23385              hex_string (signature), to_underlying (src_die->sect_off),
23386              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23387     }
23388
23389   return die;
23390 }
23391
23392 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23393    reading in and processing the type unit if necessary.  */
23394
23395 static struct type *
23396 get_signatured_type (struct die_info *die, ULONGEST signature,
23397                      struct dwarf2_cu *cu)
23398 {
23399   struct dwarf2_per_objfile *dwarf2_per_objfile
23400     = cu->per_cu->dwarf2_per_objfile;
23401   struct signatured_type *sig_type;
23402   struct dwarf2_cu *type_cu;
23403   struct die_info *type_die;
23404   struct type *type;
23405
23406   sig_type = lookup_signatured_type (cu, signature);
23407   /* sig_type will be NULL if the signatured type is missing from
23408      the debug info.  */
23409   if (sig_type == NULL)
23410     {
23411       complaint (&symfile_complaints,
23412                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23413                    " from DIE at 0x%x [in module %s]"),
23414                  hex_string (signature), to_underlying (die->sect_off),
23415                  objfile_name (dwarf2_per_objfile->objfile));
23416       return build_error_marker_type (cu, die);
23417     }
23418
23419   /* If we already know the type we're done.  */
23420   if (sig_type->type != NULL)
23421     return sig_type->type;
23422
23423   type_cu = cu;
23424   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23425   if (type_die != NULL)
23426     {
23427       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23428          is created.  This is important, for example, because for c++ classes
23429          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23430       type = read_type_die (type_die, type_cu);
23431       if (type == NULL)
23432         {
23433           complaint (&symfile_complaints,
23434                      _("Dwarf Error: Cannot build signatured type %s"
23435                        " referenced from DIE at 0x%x [in module %s]"),
23436                      hex_string (signature), to_underlying (die->sect_off),
23437                      objfile_name (dwarf2_per_objfile->objfile));
23438           type = build_error_marker_type (cu, die);
23439         }
23440     }
23441   else
23442     {
23443       complaint (&symfile_complaints,
23444                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23445                    " from DIE at 0x%x [in module %s]"),
23446                  hex_string (signature), to_underlying (die->sect_off),
23447                  objfile_name (dwarf2_per_objfile->objfile));
23448       type = build_error_marker_type (cu, die);
23449     }
23450   sig_type->type = type;
23451
23452   return type;
23453 }
23454
23455 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23456    reading in and processing the type unit if necessary.  */
23457
23458 static struct type *
23459 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23460                           struct dwarf2_cu *cu) /* ARI: editCase function */
23461 {
23462   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23463   if (attr_form_is_ref (attr))
23464     {
23465       struct dwarf2_cu *type_cu = cu;
23466       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23467
23468       return read_type_die (type_die, type_cu);
23469     }
23470   else if (attr->form == DW_FORM_ref_sig8)
23471     {
23472       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23473     }
23474   else
23475     {
23476       struct dwarf2_per_objfile *dwarf2_per_objfile
23477         = cu->per_cu->dwarf2_per_objfile;
23478
23479       complaint (&symfile_complaints,
23480                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23481                    " at 0x%x [in module %s]"),
23482                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23483                  objfile_name (dwarf2_per_objfile->objfile));
23484       return build_error_marker_type (cu, die);
23485     }
23486 }
23487
23488 /* Load the DIEs associated with type unit PER_CU into memory.  */
23489
23490 static void
23491 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23492 {
23493   struct signatured_type *sig_type;
23494
23495   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23496   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23497
23498   /* We have the per_cu, but we need the signatured_type.
23499      Fortunately this is an easy translation.  */
23500   gdb_assert (per_cu->is_debug_types);
23501   sig_type = (struct signatured_type *) per_cu;
23502
23503   gdb_assert (per_cu->cu == NULL);
23504
23505   read_signatured_type (sig_type);
23506
23507   gdb_assert (per_cu->cu != NULL);
23508 }
23509
23510 /* die_reader_func for read_signatured_type.
23511    This is identical to load_full_comp_unit_reader,
23512    but is kept separate for now.  */
23513
23514 static void
23515 read_signatured_type_reader (const struct die_reader_specs *reader,
23516                              const gdb_byte *info_ptr,
23517                              struct die_info *comp_unit_die,
23518                              int has_children,
23519                              void *data)
23520 {
23521   struct dwarf2_cu *cu = reader->cu;
23522
23523   gdb_assert (cu->die_hash == NULL);
23524   cu->die_hash =
23525     htab_create_alloc_ex (cu->header.length / 12,
23526                           die_hash,
23527                           die_eq,
23528                           NULL,
23529                           &cu->comp_unit_obstack,
23530                           hashtab_obstack_allocate,
23531                           dummy_obstack_deallocate);
23532
23533   if (has_children)
23534     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23535                                                   &info_ptr, comp_unit_die);
23536   cu->dies = comp_unit_die;
23537   /* comp_unit_die is not stored in die_hash, no need.  */
23538
23539   /* We try not to read any attributes in this function, because not
23540      all CUs needed for references have been loaded yet, and symbol
23541      table processing isn't initialized.  But we have to set the CU language,
23542      or we won't be able to build types correctly.
23543      Similarly, if we do not read the producer, we can not apply
23544      producer-specific interpretation.  */
23545   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23546 }
23547
23548 /* Read in a signatured type and build its CU and DIEs.
23549    If the type is a stub for the real type in a DWO file,
23550    read in the real type from the DWO file as well.  */
23551
23552 static void
23553 read_signatured_type (struct signatured_type *sig_type)
23554 {
23555   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23556
23557   gdb_assert (per_cu->is_debug_types);
23558   gdb_assert (per_cu->cu == NULL);
23559
23560   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23561                            read_signatured_type_reader, NULL);
23562   sig_type->per_cu.tu_read = 1;
23563 }
23564
23565 /* Decode simple location descriptions.
23566    Given a pointer to a dwarf block that defines a location, compute
23567    the location and return the value.
23568
23569    NOTE drow/2003-11-18: This function is called in two situations
23570    now: for the address of static or global variables (partial symbols
23571    only) and for offsets into structures which are expected to be
23572    (more or less) constant.  The partial symbol case should go away,
23573    and only the constant case should remain.  That will let this
23574    function complain more accurately.  A few special modes are allowed
23575    without complaint for global variables (for instance, global
23576    register values and thread-local values).
23577
23578    A location description containing no operations indicates that the
23579    object is optimized out.  The return value is 0 for that case.
23580    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23581    callers will only want a very basic result and this can become a
23582    complaint.
23583
23584    Note that stack[0] is unused except as a default error return.  */
23585
23586 static CORE_ADDR
23587 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23588 {
23589   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23590   size_t i;
23591   size_t size = blk->size;
23592   const gdb_byte *data = blk->data;
23593   CORE_ADDR stack[64];
23594   int stacki;
23595   unsigned int bytes_read, unsnd;
23596   gdb_byte op;
23597
23598   i = 0;
23599   stacki = 0;
23600   stack[stacki] = 0;
23601   stack[++stacki] = 0;
23602
23603   while (i < size)
23604     {
23605       op = data[i++];
23606       switch (op)
23607         {
23608         case DW_OP_lit0:
23609         case DW_OP_lit1:
23610         case DW_OP_lit2:
23611         case DW_OP_lit3:
23612         case DW_OP_lit4:
23613         case DW_OP_lit5:
23614         case DW_OP_lit6:
23615         case DW_OP_lit7:
23616         case DW_OP_lit8:
23617         case DW_OP_lit9:
23618         case DW_OP_lit10:
23619         case DW_OP_lit11:
23620         case DW_OP_lit12:
23621         case DW_OP_lit13:
23622         case DW_OP_lit14:
23623         case DW_OP_lit15:
23624         case DW_OP_lit16:
23625         case DW_OP_lit17:
23626         case DW_OP_lit18:
23627         case DW_OP_lit19:
23628         case DW_OP_lit20:
23629         case DW_OP_lit21:
23630         case DW_OP_lit22:
23631         case DW_OP_lit23:
23632         case DW_OP_lit24:
23633         case DW_OP_lit25:
23634         case DW_OP_lit26:
23635         case DW_OP_lit27:
23636         case DW_OP_lit28:
23637         case DW_OP_lit29:
23638         case DW_OP_lit30:
23639         case DW_OP_lit31:
23640           stack[++stacki] = op - DW_OP_lit0;
23641           break;
23642
23643         case DW_OP_reg0:
23644         case DW_OP_reg1:
23645         case DW_OP_reg2:
23646         case DW_OP_reg3:
23647         case DW_OP_reg4:
23648         case DW_OP_reg5:
23649         case DW_OP_reg6:
23650         case DW_OP_reg7:
23651         case DW_OP_reg8:
23652         case DW_OP_reg9:
23653         case DW_OP_reg10:
23654         case DW_OP_reg11:
23655         case DW_OP_reg12:
23656         case DW_OP_reg13:
23657         case DW_OP_reg14:
23658         case DW_OP_reg15:
23659         case DW_OP_reg16:
23660         case DW_OP_reg17:
23661         case DW_OP_reg18:
23662         case DW_OP_reg19:
23663         case DW_OP_reg20:
23664         case DW_OP_reg21:
23665         case DW_OP_reg22:
23666         case DW_OP_reg23:
23667         case DW_OP_reg24:
23668         case DW_OP_reg25:
23669         case DW_OP_reg26:
23670         case DW_OP_reg27:
23671         case DW_OP_reg28:
23672         case DW_OP_reg29:
23673         case DW_OP_reg30:
23674         case DW_OP_reg31:
23675           stack[++stacki] = op - DW_OP_reg0;
23676           if (i < size)
23677             dwarf2_complex_location_expr_complaint ();
23678           break;
23679
23680         case DW_OP_regx:
23681           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23682           i += bytes_read;
23683           stack[++stacki] = unsnd;
23684           if (i < size)
23685             dwarf2_complex_location_expr_complaint ();
23686           break;
23687
23688         case DW_OP_addr:
23689           stack[++stacki] = read_address (objfile->obfd, &data[i],
23690                                           cu, &bytes_read);
23691           i += bytes_read;
23692           break;
23693
23694         case DW_OP_const1u:
23695           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23696           i += 1;
23697           break;
23698
23699         case DW_OP_const1s:
23700           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23701           i += 1;
23702           break;
23703
23704         case DW_OP_const2u:
23705           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23706           i += 2;
23707           break;
23708
23709         case DW_OP_const2s:
23710           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23711           i += 2;
23712           break;
23713
23714         case DW_OP_const4u:
23715           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23716           i += 4;
23717           break;
23718
23719         case DW_OP_const4s:
23720           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23721           i += 4;
23722           break;
23723
23724         case DW_OP_const8u:
23725           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23726           i += 8;
23727           break;
23728
23729         case DW_OP_constu:
23730           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23731                                                   &bytes_read);
23732           i += bytes_read;
23733           break;
23734
23735         case DW_OP_consts:
23736           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23737           i += bytes_read;
23738           break;
23739
23740         case DW_OP_dup:
23741           stack[stacki + 1] = stack[stacki];
23742           stacki++;
23743           break;
23744
23745         case DW_OP_plus:
23746           stack[stacki - 1] += stack[stacki];
23747           stacki--;
23748           break;
23749
23750         case DW_OP_plus_uconst:
23751           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23752                                                  &bytes_read);
23753           i += bytes_read;
23754           break;
23755
23756         case DW_OP_minus:
23757           stack[stacki - 1] -= stack[stacki];
23758           stacki--;
23759           break;
23760
23761         case DW_OP_deref:
23762           /* If we're not the last op, then we definitely can't encode
23763              this using GDB's address_class enum.  This is valid for partial
23764              global symbols, although the variable's address will be bogus
23765              in the psymtab.  */
23766           if (i < size)
23767             dwarf2_complex_location_expr_complaint ();
23768           break;
23769
23770         case DW_OP_GNU_push_tls_address:
23771         case DW_OP_form_tls_address:
23772           /* The top of the stack has the offset from the beginning
23773              of the thread control block at which the variable is located.  */
23774           /* Nothing should follow this operator, so the top of stack would
23775              be returned.  */
23776           /* This is valid for partial global symbols, but the variable's
23777              address will be bogus in the psymtab.  Make it always at least
23778              non-zero to not look as a variable garbage collected by linker
23779              which have DW_OP_addr 0.  */
23780           if (i < size)
23781             dwarf2_complex_location_expr_complaint ();
23782           stack[stacki]++;
23783           break;
23784
23785         case DW_OP_GNU_uninit:
23786           break;
23787
23788         case DW_OP_GNU_addr_index:
23789         case DW_OP_GNU_const_index:
23790           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23791                                                          &bytes_read);
23792           i += bytes_read;
23793           break;
23794
23795         default:
23796           {
23797             const char *name = get_DW_OP_name (op);
23798
23799             if (name)
23800               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23801                          name);
23802             else
23803               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23804                          op);
23805           }
23806
23807           return (stack[stacki]);
23808         }
23809
23810       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23811          outside of the allocated space.  Also enforce minimum>0.  */
23812       if (stacki >= ARRAY_SIZE (stack) - 1)
23813         {
23814           complaint (&symfile_complaints,
23815                      _("location description stack overflow"));
23816           return 0;
23817         }
23818
23819       if (stacki <= 0)
23820         {
23821           complaint (&symfile_complaints,
23822                      _("location description stack underflow"));
23823           return 0;
23824         }
23825     }
23826   return (stack[stacki]);
23827 }
23828
23829 /* memory allocation interface */
23830
23831 static struct dwarf_block *
23832 dwarf_alloc_block (struct dwarf2_cu *cu)
23833 {
23834   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23835 }
23836
23837 static struct die_info *
23838 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23839 {
23840   struct die_info *die;
23841   size_t size = sizeof (struct die_info);
23842
23843   if (num_attrs > 1)
23844     size += (num_attrs - 1) * sizeof (struct attribute);
23845
23846   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23847   memset (die, 0, sizeof (struct die_info));
23848   return (die);
23849 }
23850
23851 \f
23852 /* Macro support.  */
23853
23854 /* Return file name relative to the compilation directory of file number I in
23855    *LH's file name table.  The result is allocated using xmalloc; the caller is
23856    responsible for freeing it.  */
23857
23858 static char *
23859 file_file_name (int file, struct line_header *lh)
23860 {
23861   /* Is the file number a valid index into the line header's file name
23862      table?  Remember that file numbers start with one, not zero.  */
23863   if (1 <= file && file <= lh->file_names.size ())
23864     {
23865       const file_entry &fe = lh->file_names[file - 1];
23866
23867       if (!IS_ABSOLUTE_PATH (fe.name))
23868         {
23869           const char *dir = fe.include_dir (lh);
23870           if (dir != NULL)
23871             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23872         }
23873       return xstrdup (fe.name);
23874     }
23875   else
23876     {
23877       /* The compiler produced a bogus file number.  We can at least
23878          record the macro definitions made in the file, even if we
23879          won't be able to find the file by name.  */
23880       char fake_name[80];
23881
23882       xsnprintf (fake_name, sizeof (fake_name),
23883                  "<bad macro file number %d>", file);
23884
23885       complaint (&symfile_complaints,
23886                  _("bad file number in macro information (%d)"),
23887                  file);
23888
23889       return xstrdup (fake_name);
23890     }
23891 }
23892
23893 /* Return the full name of file number I in *LH's file name table.
23894    Use COMP_DIR as the name of the current directory of the
23895    compilation.  The result is allocated using xmalloc; the caller is
23896    responsible for freeing it.  */
23897 static char *
23898 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23899 {
23900   /* Is the file number a valid index into the line header's file name
23901      table?  Remember that file numbers start with one, not zero.  */
23902   if (1 <= file && file <= lh->file_names.size ())
23903     {
23904       char *relative = file_file_name (file, lh);
23905
23906       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23907         return relative;
23908       return reconcat (relative, comp_dir, SLASH_STRING,
23909                        relative, (char *) NULL);
23910     }
23911   else
23912     return file_file_name (file, lh);
23913 }
23914
23915
23916 static struct macro_source_file *
23917 macro_start_file (int file, int line,
23918                   struct macro_source_file *current_file,
23919                   struct line_header *lh)
23920 {
23921   /* File name relative to the compilation directory of this source file.  */
23922   char *file_name = file_file_name (file, lh);
23923
23924   if (! current_file)
23925     {
23926       /* Note: We don't create a macro table for this compilation unit
23927          at all until we actually get a filename.  */
23928       struct macro_table *macro_table = get_macro_table ();
23929
23930       /* If we have no current file, then this must be the start_file
23931          directive for the compilation unit's main source file.  */
23932       current_file = macro_set_main (macro_table, file_name);
23933       macro_define_special (macro_table);
23934     }
23935   else
23936     current_file = macro_include (current_file, line, file_name);
23937
23938   xfree (file_name);
23939
23940   return current_file;
23941 }
23942
23943 static const char *
23944 consume_improper_spaces (const char *p, const char *body)
23945 {
23946   if (*p == ' ')
23947     {
23948       complaint (&symfile_complaints,
23949                  _("macro definition contains spaces "
23950                    "in formal argument list:\n`%s'"),
23951                  body);
23952
23953       while (*p == ' ')
23954         p++;
23955     }
23956
23957   return p;
23958 }
23959
23960
23961 static void
23962 parse_macro_definition (struct macro_source_file *file, int line,
23963                         const char *body)
23964 {
23965   const char *p;
23966
23967   /* The body string takes one of two forms.  For object-like macro
23968      definitions, it should be:
23969
23970         <macro name> " " <definition>
23971
23972      For function-like macro definitions, it should be:
23973
23974         <macro name> "() " <definition>
23975      or
23976         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23977
23978      Spaces may appear only where explicitly indicated, and in the
23979      <definition>.
23980
23981      The Dwarf 2 spec says that an object-like macro's name is always
23982      followed by a space, but versions of GCC around March 2002 omit
23983      the space when the macro's definition is the empty string.
23984
23985      The Dwarf 2 spec says that there should be no spaces between the
23986      formal arguments in a function-like macro's formal argument list,
23987      but versions of GCC around March 2002 include spaces after the
23988      commas.  */
23989
23990
23991   /* Find the extent of the macro name.  The macro name is terminated
23992      by either a space or null character (for an object-like macro) or
23993      an opening paren (for a function-like macro).  */
23994   for (p = body; *p; p++)
23995     if (*p == ' ' || *p == '(')
23996       break;
23997
23998   if (*p == ' ' || *p == '\0')
23999     {
24000       /* It's an object-like macro.  */
24001       int name_len = p - body;
24002       char *name = savestring (body, name_len);
24003       const char *replacement;
24004
24005       if (*p == ' ')
24006         replacement = body + name_len + 1;
24007       else
24008         {
24009           dwarf2_macro_malformed_definition_complaint (body);
24010           replacement = body + name_len;
24011         }
24012
24013       macro_define_object (file, line, name, replacement);
24014
24015       xfree (name);
24016     }
24017   else if (*p == '(')
24018     {
24019       /* It's a function-like macro.  */
24020       char *name = savestring (body, p - body);
24021       int argc = 0;
24022       int argv_size = 1;
24023       char **argv = XNEWVEC (char *, argv_size);
24024
24025       p++;
24026
24027       p = consume_improper_spaces (p, body);
24028
24029       /* Parse the formal argument list.  */
24030       while (*p && *p != ')')
24031         {
24032           /* Find the extent of the current argument name.  */
24033           const char *arg_start = p;
24034
24035           while (*p && *p != ',' && *p != ')' && *p != ' ')
24036             p++;
24037
24038           if (! *p || p == arg_start)
24039             dwarf2_macro_malformed_definition_complaint (body);
24040           else
24041             {
24042               /* Make sure argv has room for the new argument.  */
24043               if (argc >= argv_size)
24044                 {
24045                   argv_size *= 2;
24046                   argv = XRESIZEVEC (char *, argv, argv_size);
24047                 }
24048
24049               argv[argc++] = savestring (arg_start, p - arg_start);
24050             }
24051
24052           p = consume_improper_spaces (p, body);
24053
24054           /* Consume the comma, if present.  */
24055           if (*p == ',')
24056             {
24057               p++;
24058
24059               p = consume_improper_spaces (p, body);
24060             }
24061         }
24062
24063       if (*p == ')')
24064         {
24065           p++;
24066
24067           if (*p == ' ')
24068             /* Perfectly formed definition, no complaints.  */
24069             macro_define_function (file, line, name,
24070                                    argc, (const char **) argv,
24071                                    p + 1);
24072           else if (*p == '\0')
24073             {
24074               /* Complain, but do define it.  */
24075               dwarf2_macro_malformed_definition_complaint (body);
24076               macro_define_function (file, line, name,
24077                                      argc, (const char **) argv,
24078                                      p);
24079             }
24080           else
24081             /* Just complain.  */
24082             dwarf2_macro_malformed_definition_complaint (body);
24083         }
24084       else
24085         /* Just complain.  */
24086         dwarf2_macro_malformed_definition_complaint (body);
24087
24088       xfree (name);
24089       {
24090         int i;
24091
24092         for (i = 0; i < argc; i++)
24093           xfree (argv[i]);
24094       }
24095       xfree (argv);
24096     }
24097   else
24098     dwarf2_macro_malformed_definition_complaint (body);
24099 }
24100
24101 /* Skip some bytes from BYTES according to the form given in FORM.
24102    Returns the new pointer.  */
24103
24104 static const gdb_byte *
24105 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24106                  enum dwarf_form form,
24107                  unsigned int offset_size,
24108                  struct dwarf2_section_info *section)
24109 {
24110   unsigned int bytes_read;
24111
24112   switch (form)
24113     {
24114     case DW_FORM_data1:
24115     case DW_FORM_flag:
24116       ++bytes;
24117       break;
24118
24119     case DW_FORM_data2:
24120       bytes += 2;
24121       break;
24122
24123     case DW_FORM_data4:
24124       bytes += 4;
24125       break;
24126
24127     case DW_FORM_data8:
24128       bytes += 8;
24129       break;
24130
24131     case DW_FORM_data16:
24132       bytes += 16;
24133       break;
24134
24135     case DW_FORM_string:
24136       read_direct_string (abfd, bytes, &bytes_read);
24137       bytes += bytes_read;
24138       break;
24139
24140     case DW_FORM_sec_offset:
24141     case DW_FORM_strp:
24142     case DW_FORM_GNU_strp_alt:
24143       bytes += offset_size;
24144       break;
24145
24146     case DW_FORM_block:
24147       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24148       bytes += bytes_read;
24149       break;
24150
24151     case DW_FORM_block1:
24152       bytes += 1 + read_1_byte (abfd, bytes);
24153       break;
24154     case DW_FORM_block2:
24155       bytes += 2 + read_2_bytes (abfd, bytes);
24156       break;
24157     case DW_FORM_block4:
24158       bytes += 4 + read_4_bytes (abfd, bytes);
24159       break;
24160
24161     case DW_FORM_sdata:
24162     case DW_FORM_udata:
24163     case DW_FORM_GNU_addr_index:
24164     case DW_FORM_GNU_str_index:
24165       bytes = gdb_skip_leb128 (bytes, buffer_end);
24166       if (bytes == NULL)
24167         {
24168           dwarf2_section_buffer_overflow_complaint (section);
24169           return NULL;
24170         }
24171       break;
24172
24173     case DW_FORM_implicit_const:
24174       break;
24175
24176     default:
24177       {
24178         complaint (&symfile_complaints,
24179                    _("invalid form 0x%x in `%s'"),
24180                    form, get_section_name (section));
24181         return NULL;
24182       }
24183     }
24184
24185   return bytes;
24186 }
24187
24188 /* A helper for dwarf_decode_macros that handles skipping an unknown
24189    opcode.  Returns an updated pointer to the macro data buffer; or,
24190    on error, issues a complaint and returns NULL.  */
24191
24192 static const gdb_byte *
24193 skip_unknown_opcode (unsigned int opcode,
24194                      const gdb_byte **opcode_definitions,
24195                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24196                      bfd *abfd,
24197                      unsigned int offset_size,
24198                      struct dwarf2_section_info *section)
24199 {
24200   unsigned int bytes_read, i;
24201   unsigned long arg;
24202   const gdb_byte *defn;
24203
24204   if (opcode_definitions[opcode] == NULL)
24205     {
24206       complaint (&symfile_complaints,
24207                  _("unrecognized DW_MACFINO opcode 0x%x"),
24208                  opcode);
24209       return NULL;
24210     }
24211
24212   defn = opcode_definitions[opcode];
24213   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24214   defn += bytes_read;
24215
24216   for (i = 0; i < arg; ++i)
24217     {
24218       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24219                                  (enum dwarf_form) defn[i], offset_size,
24220                                  section);
24221       if (mac_ptr == NULL)
24222         {
24223           /* skip_form_bytes already issued the complaint.  */
24224           return NULL;
24225         }
24226     }
24227
24228   return mac_ptr;
24229 }
24230
24231 /* A helper function which parses the header of a macro section.
24232    If the macro section is the extended (for now called "GNU") type,
24233    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24234    the header, or issues a complaint and returns NULL on error.  */
24235
24236 static const gdb_byte *
24237 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24238                           bfd *abfd,
24239                           const gdb_byte *mac_ptr,
24240                           unsigned int *offset_size,
24241                           int section_is_gnu)
24242 {
24243   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24244
24245   if (section_is_gnu)
24246     {
24247       unsigned int version, flags;
24248
24249       version = read_2_bytes (abfd, mac_ptr);
24250       if (version != 4 && version != 5)
24251         {
24252           complaint (&symfile_complaints,
24253                      _("unrecognized version `%d' in .debug_macro section"),
24254                      version);
24255           return NULL;
24256         }
24257       mac_ptr += 2;
24258
24259       flags = read_1_byte (abfd, mac_ptr);
24260       ++mac_ptr;
24261       *offset_size = (flags & 1) ? 8 : 4;
24262
24263       if ((flags & 2) != 0)
24264         /* We don't need the line table offset.  */
24265         mac_ptr += *offset_size;
24266
24267       /* Vendor opcode descriptions.  */
24268       if ((flags & 4) != 0)
24269         {
24270           unsigned int i, count;
24271
24272           count = read_1_byte (abfd, mac_ptr);
24273           ++mac_ptr;
24274           for (i = 0; i < count; ++i)
24275             {
24276               unsigned int opcode, bytes_read;
24277               unsigned long arg;
24278
24279               opcode = read_1_byte (abfd, mac_ptr);
24280               ++mac_ptr;
24281               opcode_definitions[opcode] = mac_ptr;
24282               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24283               mac_ptr += bytes_read;
24284               mac_ptr += arg;
24285             }
24286         }
24287     }
24288
24289   return mac_ptr;
24290 }
24291
24292 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24293    including DW_MACRO_import.  */
24294
24295 static void
24296 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24297                           bfd *abfd,
24298                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24299                           struct macro_source_file *current_file,
24300                           struct line_header *lh,
24301                           struct dwarf2_section_info *section,
24302                           int section_is_gnu, int section_is_dwz,
24303                           unsigned int offset_size,
24304                           htab_t include_hash)
24305 {
24306   struct objfile *objfile = dwarf2_per_objfile->objfile;
24307   enum dwarf_macro_record_type macinfo_type;
24308   int at_commandline;
24309   const gdb_byte *opcode_definitions[256];
24310
24311   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24312                                       &offset_size, section_is_gnu);
24313   if (mac_ptr == NULL)
24314     {
24315       /* We already issued a complaint.  */
24316       return;
24317     }
24318
24319   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24320      GDB is still reading the definitions from command line.  First
24321      DW_MACINFO_start_file will need to be ignored as it was already executed
24322      to create CURRENT_FILE for the main source holding also the command line
24323      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24324      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24325
24326   at_commandline = 1;
24327
24328   do
24329     {
24330       /* Do we at least have room for a macinfo type byte?  */
24331       if (mac_ptr >= mac_end)
24332         {
24333           dwarf2_section_buffer_overflow_complaint (section);
24334           break;
24335         }
24336
24337       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24338       mac_ptr++;
24339
24340       /* Note that we rely on the fact that the corresponding GNU and
24341          DWARF constants are the same.  */
24342       DIAGNOSTIC_PUSH
24343       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24344       switch (macinfo_type)
24345         {
24346           /* A zero macinfo type indicates the end of the macro
24347              information.  */
24348         case 0:
24349           break;
24350
24351         case DW_MACRO_define:
24352         case DW_MACRO_undef:
24353         case DW_MACRO_define_strp:
24354         case DW_MACRO_undef_strp:
24355         case DW_MACRO_define_sup:
24356         case DW_MACRO_undef_sup:
24357           {
24358             unsigned int bytes_read;
24359             int line;
24360             const char *body;
24361             int is_define;
24362
24363             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24364             mac_ptr += bytes_read;
24365
24366             if (macinfo_type == DW_MACRO_define
24367                 || macinfo_type == DW_MACRO_undef)
24368               {
24369                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24370                 mac_ptr += bytes_read;
24371               }
24372             else
24373               {
24374                 LONGEST str_offset;
24375
24376                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24377                 mac_ptr += offset_size;
24378
24379                 if (macinfo_type == DW_MACRO_define_sup
24380                     || macinfo_type == DW_MACRO_undef_sup
24381                     || section_is_dwz)
24382                   {
24383                     struct dwz_file *dwz
24384                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24385
24386                     body = read_indirect_string_from_dwz (objfile,
24387                                                           dwz, str_offset);
24388                   }
24389                 else
24390                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24391                                                          abfd, str_offset);
24392               }
24393
24394             is_define = (macinfo_type == DW_MACRO_define
24395                          || macinfo_type == DW_MACRO_define_strp
24396                          || macinfo_type == DW_MACRO_define_sup);
24397             if (! current_file)
24398               {
24399                 /* DWARF violation as no main source is present.  */
24400                 complaint (&symfile_complaints,
24401                            _("debug info with no main source gives macro %s "
24402                              "on line %d: %s"),
24403                            is_define ? _("definition") : _("undefinition"),
24404                            line, body);
24405                 break;
24406               }
24407             if ((line == 0 && !at_commandline)
24408                 || (line != 0 && at_commandline))
24409               complaint (&symfile_complaints,
24410                          _("debug info gives %s macro %s with %s line %d: %s"),
24411                          at_commandline ? _("command-line") : _("in-file"),
24412                          is_define ? _("definition") : _("undefinition"),
24413                          line == 0 ? _("zero") : _("non-zero"), line, body);
24414
24415             if (is_define)
24416               parse_macro_definition (current_file, line, body);
24417             else
24418               {
24419                 gdb_assert (macinfo_type == DW_MACRO_undef
24420                             || macinfo_type == DW_MACRO_undef_strp
24421                             || macinfo_type == DW_MACRO_undef_sup);
24422                 macro_undef (current_file, line, body);
24423               }
24424           }
24425           break;
24426
24427         case DW_MACRO_start_file:
24428           {
24429             unsigned int bytes_read;
24430             int line, file;
24431
24432             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24433             mac_ptr += bytes_read;
24434             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24435             mac_ptr += bytes_read;
24436
24437             if ((line == 0 && !at_commandline)
24438                 || (line != 0 && at_commandline))
24439               complaint (&symfile_complaints,
24440                          _("debug info gives source %d included "
24441                            "from %s at %s line %d"),
24442                          file, at_commandline ? _("command-line") : _("file"),
24443                          line == 0 ? _("zero") : _("non-zero"), line);
24444
24445             if (at_commandline)
24446               {
24447                 /* This DW_MACRO_start_file was executed in the
24448                    pass one.  */
24449                 at_commandline = 0;
24450               }
24451             else
24452               current_file = macro_start_file (file, line, current_file, lh);
24453           }
24454           break;
24455
24456         case DW_MACRO_end_file:
24457           if (! current_file)
24458             complaint (&symfile_complaints,
24459                        _("macro debug info has an unmatched "
24460                          "`close_file' directive"));
24461           else
24462             {
24463               current_file = current_file->included_by;
24464               if (! current_file)
24465                 {
24466                   enum dwarf_macro_record_type next_type;
24467
24468                   /* GCC circa March 2002 doesn't produce the zero
24469                      type byte marking the end of the compilation
24470                      unit.  Complain if it's not there, but exit no
24471                      matter what.  */
24472
24473                   /* Do we at least have room for a macinfo type byte?  */
24474                   if (mac_ptr >= mac_end)
24475                     {
24476                       dwarf2_section_buffer_overflow_complaint (section);
24477                       return;
24478                     }
24479
24480                   /* We don't increment mac_ptr here, so this is just
24481                      a look-ahead.  */
24482                   next_type
24483                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24484                                                                   mac_ptr);
24485                   if (next_type != 0)
24486                     complaint (&symfile_complaints,
24487                                _("no terminating 0-type entry for "
24488                                  "macros in `.debug_macinfo' section"));
24489
24490                   return;
24491                 }
24492             }
24493           break;
24494
24495         case DW_MACRO_import:
24496         case DW_MACRO_import_sup:
24497           {
24498             LONGEST offset;
24499             void **slot;
24500             bfd *include_bfd = abfd;
24501             struct dwarf2_section_info *include_section = section;
24502             const gdb_byte *include_mac_end = mac_end;
24503             int is_dwz = section_is_dwz;
24504             const gdb_byte *new_mac_ptr;
24505
24506             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24507             mac_ptr += offset_size;
24508
24509             if (macinfo_type == DW_MACRO_import_sup)
24510               {
24511                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24512
24513                 dwarf2_read_section (objfile, &dwz->macro);
24514
24515                 include_section = &dwz->macro;
24516                 include_bfd = get_section_bfd_owner (include_section);
24517                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24518                 is_dwz = 1;
24519               }
24520
24521             new_mac_ptr = include_section->buffer + offset;
24522             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24523
24524             if (*slot != NULL)
24525               {
24526                 /* This has actually happened; see
24527                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24528                 complaint (&symfile_complaints,
24529                            _("recursive DW_MACRO_import in "
24530                              ".debug_macro section"));
24531               }
24532             else
24533               {
24534                 *slot = (void *) new_mac_ptr;
24535
24536                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24537                                           include_bfd, new_mac_ptr,
24538                                           include_mac_end, current_file, lh,
24539                                           section, section_is_gnu, is_dwz,
24540                                           offset_size, include_hash);
24541
24542                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24543               }
24544           }
24545           break;
24546
24547         case DW_MACINFO_vendor_ext:
24548           if (!section_is_gnu)
24549             {
24550               unsigned int bytes_read;
24551
24552               /* This reads the constant, but since we don't recognize
24553                  any vendor extensions, we ignore it.  */
24554               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24555               mac_ptr += bytes_read;
24556               read_direct_string (abfd, mac_ptr, &bytes_read);
24557               mac_ptr += bytes_read;
24558
24559               /* We don't recognize any vendor extensions.  */
24560               break;
24561             }
24562           /* FALLTHROUGH */
24563
24564         default:
24565           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24566                                          mac_ptr, mac_end, abfd, offset_size,
24567                                          section);
24568           if (mac_ptr == NULL)
24569             return;
24570           break;
24571         }
24572       DIAGNOSTIC_POP
24573     } while (macinfo_type != 0);
24574 }
24575
24576 static void
24577 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24578                      int section_is_gnu)
24579 {
24580   struct dwarf2_per_objfile *dwarf2_per_objfile
24581     = cu->per_cu->dwarf2_per_objfile;
24582   struct objfile *objfile = dwarf2_per_objfile->objfile;
24583   struct line_header *lh = cu->line_header;
24584   bfd *abfd;
24585   const gdb_byte *mac_ptr, *mac_end;
24586   struct macro_source_file *current_file = 0;
24587   enum dwarf_macro_record_type macinfo_type;
24588   unsigned int offset_size = cu->header.offset_size;
24589   const gdb_byte *opcode_definitions[256];
24590   void **slot;
24591   struct dwarf2_section_info *section;
24592   const char *section_name;
24593
24594   if (cu->dwo_unit != NULL)
24595     {
24596       if (section_is_gnu)
24597         {
24598           section = &cu->dwo_unit->dwo_file->sections.macro;
24599           section_name = ".debug_macro.dwo";
24600         }
24601       else
24602         {
24603           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24604           section_name = ".debug_macinfo.dwo";
24605         }
24606     }
24607   else
24608     {
24609       if (section_is_gnu)
24610         {
24611           section = &dwarf2_per_objfile->macro;
24612           section_name = ".debug_macro";
24613         }
24614       else
24615         {
24616           section = &dwarf2_per_objfile->macinfo;
24617           section_name = ".debug_macinfo";
24618         }
24619     }
24620
24621   dwarf2_read_section (objfile, section);
24622   if (section->buffer == NULL)
24623     {
24624       complaint (&symfile_complaints, _("missing %s section"), section_name);
24625       return;
24626     }
24627   abfd = get_section_bfd_owner (section);
24628
24629   /* First pass: Find the name of the base filename.
24630      This filename is needed in order to process all macros whose definition
24631      (or undefinition) comes from the command line.  These macros are defined
24632      before the first DW_MACINFO_start_file entry, and yet still need to be
24633      associated to the base file.
24634
24635      To determine the base file name, we scan the macro definitions until we
24636      reach the first DW_MACINFO_start_file entry.  We then initialize
24637      CURRENT_FILE accordingly so that any macro definition found before the
24638      first DW_MACINFO_start_file can still be associated to the base file.  */
24639
24640   mac_ptr = section->buffer + offset;
24641   mac_end = section->buffer + section->size;
24642
24643   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24644                                       &offset_size, section_is_gnu);
24645   if (mac_ptr == NULL)
24646     {
24647       /* We already issued a complaint.  */
24648       return;
24649     }
24650
24651   do
24652     {
24653       /* Do we at least have room for a macinfo type byte?  */
24654       if (mac_ptr >= mac_end)
24655         {
24656           /* Complaint is printed during the second pass as GDB will probably
24657              stop the first pass earlier upon finding
24658              DW_MACINFO_start_file.  */
24659           break;
24660         }
24661
24662       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24663       mac_ptr++;
24664
24665       /* Note that we rely on the fact that the corresponding GNU and
24666          DWARF constants are the same.  */
24667       DIAGNOSTIC_PUSH
24668       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24669       switch (macinfo_type)
24670         {
24671           /* A zero macinfo type indicates the end of the macro
24672              information.  */
24673         case 0:
24674           break;
24675
24676         case DW_MACRO_define:
24677         case DW_MACRO_undef:
24678           /* Only skip the data by MAC_PTR.  */
24679           {
24680             unsigned int bytes_read;
24681
24682             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24683             mac_ptr += bytes_read;
24684             read_direct_string (abfd, mac_ptr, &bytes_read);
24685             mac_ptr += bytes_read;
24686           }
24687           break;
24688
24689         case DW_MACRO_start_file:
24690           {
24691             unsigned int bytes_read;
24692             int line, file;
24693
24694             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24695             mac_ptr += bytes_read;
24696             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24697             mac_ptr += bytes_read;
24698
24699             current_file = macro_start_file (file, line, current_file, lh);
24700           }
24701           break;
24702
24703         case DW_MACRO_end_file:
24704           /* No data to skip by MAC_PTR.  */
24705           break;
24706
24707         case DW_MACRO_define_strp:
24708         case DW_MACRO_undef_strp:
24709         case DW_MACRO_define_sup:
24710         case DW_MACRO_undef_sup:
24711           {
24712             unsigned int bytes_read;
24713
24714             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24715             mac_ptr += bytes_read;
24716             mac_ptr += offset_size;
24717           }
24718           break;
24719
24720         case DW_MACRO_import:
24721         case DW_MACRO_import_sup:
24722           /* Note that, according to the spec, a transparent include
24723              chain cannot call DW_MACRO_start_file.  So, we can just
24724              skip this opcode.  */
24725           mac_ptr += offset_size;
24726           break;
24727
24728         case DW_MACINFO_vendor_ext:
24729           /* Only skip the data by MAC_PTR.  */
24730           if (!section_is_gnu)
24731             {
24732               unsigned int bytes_read;
24733
24734               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24735               mac_ptr += bytes_read;
24736               read_direct_string (abfd, mac_ptr, &bytes_read);
24737               mac_ptr += bytes_read;
24738             }
24739           /* FALLTHROUGH */
24740
24741         default:
24742           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24743                                          mac_ptr, mac_end, abfd, offset_size,
24744                                          section);
24745           if (mac_ptr == NULL)
24746             return;
24747           break;
24748         }
24749       DIAGNOSTIC_POP
24750     } while (macinfo_type != 0 && current_file == NULL);
24751
24752   /* Second pass: Process all entries.
24753
24754      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24755      command-line macro definitions/undefinitions.  This flag is unset when we
24756      reach the first DW_MACINFO_start_file entry.  */
24757
24758   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24759                                            htab_eq_pointer,
24760                                            NULL, xcalloc, xfree));
24761   mac_ptr = section->buffer + offset;
24762   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24763   *slot = (void *) mac_ptr;
24764   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24765                             abfd, mac_ptr, mac_end,
24766                             current_file, lh, section,
24767                             section_is_gnu, 0, offset_size,
24768                             include_hash.get ());
24769 }
24770
24771 /* Check if the attribute's form is a DW_FORM_block*
24772    if so return true else false.  */
24773
24774 static int
24775 attr_form_is_block (const struct attribute *attr)
24776 {
24777   return (attr == NULL ? 0 :
24778       attr->form == DW_FORM_block1
24779       || attr->form == DW_FORM_block2
24780       || attr->form == DW_FORM_block4
24781       || attr->form == DW_FORM_block
24782       || attr->form == DW_FORM_exprloc);
24783 }
24784
24785 /* Return non-zero if ATTR's value is a section offset --- classes
24786    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24787    You may use DW_UNSND (attr) to retrieve such offsets.
24788
24789    Section 7.5.4, "Attribute Encodings", explains that no attribute
24790    may have a value that belongs to more than one of these classes; it
24791    would be ambiguous if we did, because we use the same forms for all
24792    of them.  */
24793
24794 static int
24795 attr_form_is_section_offset (const struct attribute *attr)
24796 {
24797   return (attr->form == DW_FORM_data4
24798           || attr->form == DW_FORM_data8
24799           || attr->form == DW_FORM_sec_offset);
24800 }
24801
24802 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24803    zero otherwise.  When this function returns true, you can apply
24804    dwarf2_get_attr_constant_value to it.
24805
24806    However, note that for some attributes you must check
24807    attr_form_is_section_offset before using this test.  DW_FORM_data4
24808    and DW_FORM_data8 are members of both the constant class, and of
24809    the classes that contain offsets into other debug sections
24810    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24811    that, if an attribute's can be either a constant or one of the
24812    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24813    taken as section offsets, not constants.
24814
24815    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24816    cannot handle that.  */
24817
24818 static int
24819 attr_form_is_constant (const struct attribute *attr)
24820 {
24821   switch (attr->form)
24822     {
24823     case DW_FORM_sdata:
24824     case DW_FORM_udata:
24825     case DW_FORM_data1:
24826     case DW_FORM_data2:
24827     case DW_FORM_data4:
24828     case DW_FORM_data8:
24829     case DW_FORM_implicit_const:
24830       return 1;
24831     default:
24832       return 0;
24833     }
24834 }
24835
24836
24837 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24838    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24839
24840 static int
24841 attr_form_is_ref (const struct attribute *attr)
24842 {
24843   switch (attr->form)
24844     {
24845     case DW_FORM_ref_addr:
24846     case DW_FORM_ref1:
24847     case DW_FORM_ref2:
24848     case DW_FORM_ref4:
24849     case DW_FORM_ref8:
24850     case DW_FORM_ref_udata:
24851     case DW_FORM_GNU_ref_alt:
24852       return 1;
24853     default:
24854       return 0;
24855     }
24856 }
24857
24858 /* Return the .debug_loc section to use for CU.
24859    For DWO files use .debug_loc.dwo.  */
24860
24861 static struct dwarf2_section_info *
24862 cu_debug_loc_section (struct dwarf2_cu *cu)
24863 {
24864   struct dwarf2_per_objfile *dwarf2_per_objfile
24865     = cu->per_cu->dwarf2_per_objfile;
24866
24867   if (cu->dwo_unit)
24868     {
24869       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24870       
24871       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24872     }
24873   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24874                                   : &dwarf2_per_objfile->loc);
24875 }
24876
24877 /* A helper function that fills in a dwarf2_loclist_baton.  */
24878
24879 static void
24880 fill_in_loclist_baton (struct dwarf2_cu *cu,
24881                        struct dwarf2_loclist_baton *baton,
24882                        const struct attribute *attr)
24883 {
24884   struct dwarf2_per_objfile *dwarf2_per_objfile
24885     = cu->per_cu->dwarf2_per_objfile;
24886   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24887
24888   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24889
24890   baton->per_cu = cu->per_cu;
24891   gdb_assert (baton->per_cu);
24892   /* We don't know how long the location list is, but make sure we
24893      don't run off the edge of the section.  */
24894   baton->size = section->size - DW_UNSND (attr);
24895   baton->data = section->buffer + DW_UNSND (attr);
24896   baton->base_address = cu->base_address;
24897   baton->from_dwo = cu->dwo_unit != NULL;
24898 }
24899
24900 static void
24901 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24902                              struct dwarf2_cu *cu, int is_block)
24903 {
24904   struct dwarf2_per_objfile *dwarf2_per_objfile
24905     = cu->per_cu->dwarf2_per_objfile;
24906   struct objfile *objfile = dwarf2_per_objfile->objfile;
24907   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24908
24909   if (attr_form_is_section_offset (attr)
24910       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24911          the section.  If so, fall through to the complaint in the
24912          other branch.  */
24913       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24914     {
24915       struct dwarf2_loclist_baton *baton;
24916
24917       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24918
24919       fill_in_loclist_baton (cu, baton, attr);
24920
24921       if (cu->base_known == 0)
24922         complaint (&symfile_complaints,
24923                    _("Location list used without "
24924                      "specifying the CU base address."));
24925
24926       SYMBOL_ACLASS_INDEX (sym) = (is_block
24927                                    ? dwarf2_loclist_block_index
24928                                    : dwarf2_loclist_index);
24929       SYMBOL_LOCATION_BATON (sym) = baton;
24930     }
24931   else
24932     {
24933       struct dwarf2_locexpr_baton *baton;
24934
24935       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24936       baton->per_cu = cu->per_cu;
24937       gdb_assert (baton->per_cu);
24938
24939       if (attr_form_is_block (attr))
24940         {
24941           /* Note that we're just copying the block's data pointer
24942              here, not the actual data.  We're still pointing into the
24943              info_buffer for SYM's objfile; right now we never release
24944              that buffer, but when we do clean up properly this may
24945              need to change.  */
24946           baton->size = DW_BLOCK (attr)->size;
24947           baton->data = DW_BLOCK (attr)->data;
24948         }
24949       else
24950         {
24951           dwarf2_invalid_attrib_class_complaint ("location description",
24952                                                  SYMBOL_NATURAL_NAME (sym));
24953           baton->size = 0;
24954         }
24955
24956       SYMBOL_ACLASS_INDEX (sym) = (is_block
24957                                    ? dwarf2_locexpr_block_index
24958                                    : dwarf2_locexpr_index);
24959       SYMBOL_LOCATION_BATON (sym) = baton;
24960     }
24961 }
24962
24963 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24964    came from a separate debuginfo file, then the master objfile is
24965    returned.  */
24966
24967 struct objfile *
24968 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24969 {
24970   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24971
24972   /* Return the master objfile, so that we can report and look up the
24973      correct file containing this variable.  */
24974   if (objfile->separate_debug_objfile_backlink)
24975     objfile = objfile->separate_debug_objfile_backlink;
24976
24977   return objfile;
24978 }
24979
24980 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24981    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24982    CU_HEADERP first.  */
24983
24984 static const struct comp_unit_head *
24985 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24986                        struct dwarf2_per_cu_data *per_cu)
24987 {
24988   const gdb_byte *info_ptr;
24989
24990   if (per_cu->cu)
24991     return &per_cu->cu->header;
24992
24993   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24994
24995   memset (cu_headerp, 0, sizeof (*cu_headerp));
24996   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24997                        rcuh_kind::COMPILE);
24998
24999   return cu_headerp;
25000 }
25001
25002 /* Return the address size given in the compilation unit header for CU.  */
25003
25004 int
25005 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25006 {
25007   struct comp_unit_head cu_header_local;
25008   const struct comp_unit_head *cu_headerp;
25009
25010   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25011
25012   return cu_headerp->addr_size;
25013 }
25014
25015 /* Return the offset size given in the compilation unit header for CU.  */
25016
25017 int
25018 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25019 {
25020   struct comp_unit_head cu_header_local;
25021   const struct comp_unit_head *cu_headerp;
25022
25023   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25024
25025   return cu_headerp->offset_size;
25026 }
25027
25028 /* See its dwarf2loc.h declaration.  */
25029
25030 int
25031 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25032 {
25033   struct comp_unit_head cu_header_local;
25034   const struct comp_unit_head *cu_headerp;
25035
25036   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25037
25038   if (cu_headerp->version == 2)
25039     return cu_headerp->addr_size;
25040   else
25041     return cu_headerp->offset_size;
25042 }
25043
25044 /* Return the text offset of the CU.  The returned offset comes from
25045    this CU's objfile.  If this objfile came from a separate debuginfo
25046    file, then the offset may be different from the corresponding
25047    offset in the parent objfile.  */
25048
25049 CORE_ADDR
25050 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25051 {
25052   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25053
25054   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25055 }
25056
25057 /* Return DWARF version number of PER_CU.  */
25058
25059 short
25060 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25061 {
25062   return per_cu->dwarf_version;
25063 }
25064
25065 /* Locate the .debug_info compilation unit from CU's objfile which contains
25066    the DIE at OFFSET.  Raises an error on failure.  */
25067
25068 static struct dwarf2_per_cu_data *
25069 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25070                                   unsigned int offset_in_dwz,
25071                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25072 {
25073   struct dwarf2_per_cu_data *this_cu;
25074   int low, high;
25075   const sect_offset *cu_off;
25076
25077   low = 0;
25078   high = dwarf2_per_objfile->n_comp_units - 1;
25079   while (high > low)
25080     {
25081       struct dwarf2_per_cu_data *mid_cu;
25082       int mid = low + (high - low) / 2;
25083
25084       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25085       cu_off = &mid_cu->sect_off;
25086       if (mid_cu->is_dwz > offset_in_dwz
25087           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25088         high = mid;
25089       else
25090         low = mid + 1;
25091     }
25092   gdb_assert (low == high);
25093   this_cu = dwarf2_per_objfile->all_comp_units[low];
25094   cu_off = &this_cu->sect_off;
25095   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25096     {
25097       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25098         error (_("Dwarf Error: could not find partial DIE containing "
25099                "offset 0x%x [in module %s]"),
25100                to_underlying (sect_off),
25101                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25102
25103       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25104                   <= sect_off);
25105       return dwarf2_per_objfile->all_comp_units[low-1];
25106     }
25107   else
25108     {
25109       this_cu = dwarf2_per_objfile->all_comp_units[low];
25110       if (low == dwarf2_per_objfile->n_comp_units - 1
25111           && sect_off >= this_cu->sect_off + this_cu->length)
25112         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
25113       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25114       return this_cu;
25115     }
25116 }
25117
25118 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25119
25120 static void
25121 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
25122 {
25123   memset (cu, 0, sizeof (*cu));
25124   per_cu->cu = cu;
25125   cu->per_cu = per_cu;
25126   obstack_init (&cu->comp_unit_obstack);
25127 }
25128
25129 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25130
25131 static void
25132 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25133                        enum language pretend_language)
25134 {
25135   struct attribute *attr;
25136
25137   /* Set the language we're debugging.  */
25138   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25139   if (attr)
25140     set_cu_language (DW_UNSND (attr), cu);
25141   else
25142     {
25143       cu->language = pretend_language;
25144       cu->language_defn = language_def (cu->language);
25145     }
25146
25147   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25148 }
25149
25150 /* Release one cached compilation unit, CU.  We unlink it from the tree
25151    of compilation units, but we don't remove it from the read_in_chain;
25152    the caller is responsible for that.
25153    NOTE: DATA is a void * because this function is also used as a
25154    cleanup routine.  */
25155
25156 static void
25157 free_heap_comp_unit (void *data)
25158 {
25159   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25160
25161   gdb_assert (cu->per_cu != NULL);
25162   cu->per_cu->cu = NULL;
25163   cu->per_cu = NULL;
25164
25165   obstack_free (&cu->comp_unit_obstack, NULL);
25166
25167   xfree (cu);
25168 }
25169
25170 /* This cleanup function is passed the address of a dwarf2_cu on the stack
25171    when we're finished with it.  We can't free the pointer itself, but be
25172    sure to unlink it from the cache.  Also release any associated storage.  */
25173
25174 static void
25175 free_stack_comp_unit (void *data)
25176 {
25177   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25178
25179   gdb_assert (cu->per_cu != NULL);
25180   cu->per_cu->cu = NULL;
25181   cu->per_cu = NULL;
25182
25183   obstack_free (&cu->comp_unit_obstack, NULL);
25184   cu->partial_dies = NULL;
25185 }
25186
25187 /* Free all cached compilation units.  */
25188
25189 static void
25190 free_cached_comp_units (void *data)
25191 {
25192   struct dwarf2_per_objfile *dwarf2_per_objfile
25193     = (struct dwarf2_per_objfile *) data;
25194
25195   dwarf2_per_objfile->free_cached_comp_units ();
25196 }
25197
25198 /* Increase the age counter on each cached compilation unit, and free
25199    any that are too old.  */
25200
25201 static void
25202 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25203 {
25204   struct dwarf2_per_cu_data *per_cu, **last_chain;
25205
25206   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25207   per_cu = dwarf2_per_objfile->read_in_chain;
25208   while (per_cu != NULL)
25209     {
25210       per_cu->cu->last_used ++;
25211       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25212         dwarf2_mark (per_cu->cu);
25213       per_cu = per_cu->cu->read_in_chain;
25214     }
25215
25216   per_cu = dwarf2_per_objfile->read_in_chain;
25217   last_chain = &dwarf2_per_objfile->read_in_chain;
25218   while (per_cu != NULL)
25219     {
25220       struct dwarf2_per_cu_data *next_cu;
25221
25222       next_cu = per_cu->cu->read_in_chain;
25223
25224       if (!per_cu->cu->mark)
25225         {
25226           free_heap_comp_unit (per_cu->cu);
25227           *last_chain = next_cu;
25228         }
25229       else
25230         last_chain = &per_cu->cu->read_in_chain;
25231
25232       per_cu = next_cu;
25233     }
25234 }
25235
25236 /* Remove a single compilation unit from the cache.  */
25237
25238 static void
25239 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25240 {
25241   struct dwarf2_per_cu_data *per_cu, **last_chain;
25242   struct dwarf2_per_objfile *dwarf2_per_objfile
25243     = target_per_cu->dwarf2_per_objfile;
25244
25245   per_cu = dwarf2_per_objfile->read_in_chain;
25246   last_chain = &dwarf2_per_objfile->read_in_chain;
25247   while (per_cu != NULL)
25248     {
25249       struct dwarf2_per_cu_data *next_cu;
25250
25251       next_cu = per_cu->cu->read_in_chain;
25252
25253       if (per_cu == target_per_cu)
25254         {
25255           free_heap_comp_unit (per_cu->cu);
25256           per_cu->cu = NULL;
25257           *last_chain = next_cu;
25258           break;
25259         }
25260       else
25261         last_chain = &per_cu->cu->read_in_chain;
25262
25263       per_cu = next_cu;
25264     }
25265 }
25266
25267 /* Release all extra memory associated with OBJFILE.  */
25268
25269 void
25270 dwarf2_free_objfile (struct objfile *objfile)
25271 {
25272   struct dwarf2_per_objfile *dwarf2_per_objfile
25273     = get_dwarf2_per_objfile (objfile);
25274
25275   if (dwarf2_per_objfile == NULL)
25276     return;
25277
25278   dwarf2_per_objfile->~dwarf2_per_objfile ();
25279 }
25280
25281 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25282    We store these in a hash table separate from the DIEs, and preserve them
25283    when the DIEs are flushed out of cache.
25284
25285    The CU "per_cu" pointer is needed because offset alone is not enough to
25286    uniquely identify the type.  A file may have multiple .debug_types sections,
25287    or the type may come from a DWO file.  Furthermore, while it's more logical
25288    to use per_cu->section+offset, with Fission the section with the data is in
25289    the DWO file but we don't know that section at the point we need it.
25290    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25291    because we can enter the lookup routine, get_die_type_at_offset, from
25292    outside this file, and thus won't necessarily have PER_CU->cu.
25293    Fortunately, PER_CU is stable for the life of the objfile.  */
25294
25295 struct dwarf2_per_cu_offset_and_type
25296 {
25297   const struct dwarf2_per_cu_data *per_cu;
25298   sect_offset sect_off;
25299   struct type *type;
25300 };
25301
25302 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25303
25304 static hashval_t
25305 per_cu_offset_and_type_hash (const void *item)
25306 {
25307   const struct dwarf2_per_cu_offset_and_type *ofs
25308     = (const struct dwarf2_per_cu_offset_and_type *) item;
25309
25310   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25311 }
25312
25313 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25314
25315 static int
25316 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25317 {
25318   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25319     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25320   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25321     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25322
25323   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25324           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25325 }
25326
25327 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25328    table if necessary.  For convenience, return TYPE.
25329
25330    The DIEs reading must have careful ordering to:
25331     * Not cause infite loops trying to read in DIEs as a prerequisite for
25332       reading current DIE.
25333     * Not trying to dereference contents of still incompletely read in types
25334       while reading in other DIEs.
25335     * Enable referencing still incompletely read in types just by a pointer to
25336       the type without accessing its fields.
25337
25338    Therefore caller should follow these rules:
25339      * Try to fetch any prerequisite types we may need to build this DIE type
25340        before building the type and calling set_die_type.
25341      * After building type call set_die_type for current DIE as soon as
25342        possible before fetching more types to complete the current type.
25343      * Make the type as complete as possible before fetching more types.  */
25344
25345 static struct type *
25346 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25347 {
25348   struct dwarf2_per_objfile *dwarf2_per_objfile
25349     = cu->per_cu->dwarf2_per_objfile;
25350   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25351   struct objfile *objfile = dwarf2_per_objfile->objfile;
25352   struct attribute *attr;
25353   struct dynamic_prop prop;
25354
25355   /* For Ada types, make sure that the gnat-specific data is always
25356      initialized (if not already set).  There are a few types where
25357      we should not be doing so, because the type-specific area is
25358      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25359      where the type-specific area is used to store the floatformat).
25360      But this is not a problem, because the gnat-specific information
25361      is actually not needed for these types.  */
25362   if (need_gnat_info (cu)
25363       && TYPE_CODE (type) != TYPE_CODE_FUNC
25364       && TYPE_CODE (type) != TYPE_CODE_FLT
25365       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25366       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25367       && TYPE_CODE (type) != TYPE_CODE_METHOD
25368       && !HAVE_GNAT_AUX_INFO (type))
25369     INIT_GNAT_SPECIFIC (type);
25370
25371   /* Read DW_AT_allocated and set in type.  */
25372   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25373   if (attr_form_is_block (attr))
25374     {
25375       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25376         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25377     }
25378   else if (attr != NULL)
25379     {
25380       complaint (&symfile_complaints,
25381                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25382                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25383                  to_underlying (die->sect_off));
25384     }
25385
25386   /* Read DW_AT_associated and set in type.  */
25387   attr = dwarf2_attr (die, DW_AT_associated, cu);
25388   if (attr_form_is_block (attr))
25389     {
25390       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25391         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25392     }
25393   else if (attr != NULL)
25394     {
25395       complaint (&symfile_complaints,
25396                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25397                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25398                  to_underlying (die->sect_off));
25399     }
25400
25401   /* Read DW_AT_data_location and set in type.  */
25402   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25403   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25404     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25405
25406   if (dwarf2_per_objfile->die_type_hash == NULL)
25407     {
25408       dwarf2_per_objfile->die_type_hash =
25409         htab_create_alloc_ex (127,
25410                               per_cu_offset_and_type_hash,
25411                               per_cu_offset_and_type_eq,
25412                               NULL,
25413                               &objfile->objfile_obstack,
25414                               hashtab_obstack_allocate,
25415                               dummy_obstack_deallocate);
25416     }
25417
25418   ofs.per_cu = cu->per_cu;
25419   ofs.sect_off = die->sect_off;
25420   ofs.type = type;
25421   slot = (struct dwarf2_per_cu_offset_and_type **)
25422     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25423   if (*slot)
25424     complaint (&symfile_complaints,
25425                _("A problem internal to GDB: DIE 0x%x has type already set"),
25426                to_underlying (die->sect_off));
25427   *slot = XOBNEW (&objfile->objfile_obstack,
25428                   struct dwarf2_per_cu_offset_and_type);
25429   **slot = ofs;
25430   return type;
25431 }
25432
25433 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25434    or return NULL if the die does not have a saved type.  */
25435
25436 static struct type *
25437 get_die_type_at_offset (sect_offset sect_off,
25438                         struct dwarf2_per_cu_data *per_cu)
25439 {
25440   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25441   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25442
25443   if (dwarf2_per_objfile->die_type_hash == NULL)
25444     return NULL;
25445
25446   ofs.per_cu = per_cu;
25447   ofs.sect_off = sect_off;
25448   slot = ((struct dwarf2_per_cu_offset_and_type *)
25449           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25450   if (slot)
25451     return slot->type;
25452   else
25453     return NULL;
25454 }
25455
25456 /* Look up the type for DIE in CU in die_type_hash,
25457    or return NULL if DIE does not have a saved type.  */
25458
25459 static struct type *
25460 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25461 {
25462   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25463 }
25464
25465 /* Add a dependence relationship from CU to REF_PER_CU.  */
25466
25467 static void
25468 dwarf2_add_dependence (struct dwarf2_cu *cu,
25469                        struct dwarf2_per_cu_data *ref_per_cu)
25470 {
25471   void **slot;
25472
25473   if (cu->dependencies == NULL)
25474     cu->dependencies
25475       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25476                               NULL, &cu->comp_unit_obstack,
25477                               hashtab_obstack_allocate,
25478                               dummy_obstack_deallocate);
25479
25480   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25481   if (*slot == NULL)
25482     *slot = ref_per_cu;
25483 }
25484
25485 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25486    Set the mark field in every compilation unit in the
25487    cache that we must keep because we are keeping CU.  */
25488
25489 static int
25490 dwarf2_mark_helper (void **slot, void *data)
25491 {
25492   struct dwarf2_per_cu_data *per_cu;
25493
25494   per_cu = (struct dwarf2_per_cu_data *) *slot;
25495
25496   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25497      reading of the chain.  As such dependencies remain valid it is not much
25498      useful to track and undo them during QUIT cleanups.  */
25499   if (per_cu->cu == NULL)
25500     return 1;
25501
25502   if (per_cu->cu->mark)
25503     return 1;
25504   per_cu->cu->mark = 1;
25505
25506   if (per_cu->cu->dependencies != NULL)
25507     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25508
25509   return 1;
25510 }
25511
25512 /* Set the mark field in CU and in every other compilation unit in the
25513    cache that we must keep because we are keeping CU.  */
25514
25515 static void
25516 dwarf2_mark (struct dwarf2_cu *cu)
25517 {
25518   if (cu->mark)
25519     return;
25520   cu->mark = 1;
25521   if (cu->dependencies != NULL)
25522     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25523 }
25524
25525 static void
25526 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25527 {
25528   while (per_cu)
25529     {
25530       per_cu->cu->mark = 0;
25531       per_cu = per_cu->cu->read_in_chain;
25532     }
25533 }
25534
25535 /* Trivial hash function for partial_die_info: the hash value of a DIE
25536    is its offset in .debug_info for this objfile.  */
25537
25538 static hashval_t
25539 partial_die_hash (const void *item)
25540 {
25541   const struct partial_die_info *part_die
25542     = (const struct partial_die_info *) item;
25543
25544   return to_underlying (part_die->sect_off);
25545 }
25546
25547 /* Trivial comparison function for partial_die_info structures: two DIEs
25548    are equal if they have the same offset.  */
25549
25550 static int
25551 partial_die_eq (const void *item_lhs, const void *item_rhs)
25552 {
25553   const struct partial_die_info *part_die_lhs
25554     = (const struct partial_die_info *) item_lhs;
25555   const struct partial_die_info *part_die_rhs
25556     = (const struct partial_die_info *) item_rhs;
25557
25558   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25559 }
25560
25561 static struct cmd_list_element *set_dwarf_cmdlist;
25562 static struct cmd_list_element *show_dwarf_cmdlist;
25563
25564 static void
25565 set_dwarf_cmd (const char *args, int from_tty)
25566 {
25567   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25568              gdb_stdout);
25569 }
25570
25571 static void
25572 show_dwarf_cmd (const char *args, int from_tty)
25573 {
25574   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25575 }
25576
25577 /* Free data associated with OBJFILE, if necessary.  */
25578
25579 static void
25580 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25581 {
25582   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25583   int ix;
25584
25585   for (ix = 0; ix < data->n_comp_units; ++ix)
25586    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25587
25588   for (ix = 0; ix < data->n_type_units; ++ix)
25589     VEC_free (dwarf2_per_cu_ptr,
25590               data->all_type_units[ix]->per_cu.imported_symtabs);
25591   xfree (data->all_type_units);
25592
25593   VEC_free (dwarf2_section_info_def, data->types);
25594
25595   if (data->dwo_files)
25596     free_dwo_files (data->dwo_files, objfile);
25597   if (data->dwp_file)
25598     gdb_bfd_unref (data->dwp_file->dbfd);
25599
25600   if (data->dwz_file && data->dwz_file->dwz_bfd)
25601     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25602
25603   if (data->index_table != NULL)
25604     data->index_table->~mapped_index ();
25605 }
25606
25607 \f
25608 /* The "save gdb-index" command.  */
25609
25610 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25611    error checking.  */
25612
25613 static void
25614 file_write (FILE *file, const void *data, size_t size)
25615 {
25616   if (fwrite (data, 1, size, file) != size)
25617     error (_("couldn't data write to file"));
25618 }
25619
25620 /* Write the contents of VEC to FILE, with error checking.  */
25621
25622 template<typename Elem, typename Alloc>
25623 static void
25624 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25625 {
25626   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25627 }
25628
25629 /* In-memory buffer to prepare data to be written later to a file.  */
25630 class data_buf
25631 {
25632 public:
25633   /* Copy DATA to the end of the buffer.  */
25634   template<typename T>
25635   void append_data (const T &data)
25636   {
25637     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25638                reinterpret_cast<const gdb_byte *> (&data + 1),
25639                grow (sizeof (data)));
25640   }
25641
25642   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25643      terminating zero is appended too.  */
25644   void append_cstr0 (const char *cstr)
25645   {
25646     const size_t size = strlen (cstr) + 1;
25647     std::copy (cstr, cstr + size, grow (size));
25648   }
25649
25650   /* Store INPUT as ULEB128 to the end of buffer.  */
25651   void append_unsigned_leb128 (ULONGEST input)
25652   {
25653     for (;;)
25654       {
25655         gdb_byte output = input & 0x7f;
25656         input >>= 7;
25657         if (input)
25658           output |= 0x80;
25659         append_data (output);
25660         if (input == 0)
25661           break;
25662       }
25663   }
25664
25665   /* Accept a host-format integer in VAL and append it to the buffer
25666      as a target-format integer which is LEN bytes long.  */
25667   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25668   {
25669     ::store_unsigned_integer (grow (len), len, byte_order, val);
25670   }
25671
25672   /* Return the size of the buffer.  */
25673   size_t size () const
25674   {
25675     return m_vec.size ();
25676   }
25677
25678   /* Return true iff the buffer is empty.  */
25679   bool empty () const
25680   {
25681     return m_vec.empty ();
25682   }
25683
25684   /* Write the buffer to FILE.  */
25685   void file_write (FILE *file) const
25686   {
25687     ::file_write (file, m_vec);
25688   }
25689
25690 private:
25691   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25692      the start of the new block.  */
25693   gdb_byte *grow (size_t size)
25694   {
25695     m_vec.resize (m_vec.size () + size);
25696     return &*m_vec.end () - size;
25697   }
25698
25699   gdb::byte_vector m_vec;
25700 };
25701
25702 /* An entry in the symbol table.  */
25703 struct symtab_index_entry
25704 {
25705   /* The name of the symbol.  */
25706   const char *name;
25707   /* The offset of the name in the constant pool.  */
25708   offset_type index_offset;
25709   /* A sorted vector of the indices of all the CUs that hold an object
25710      of this name.  */
25711   std::vector<offset_type> cu_indices;
25712 };
25713
25714 /* The symbol table.  This is a power-of-2-sized hash table.  */
25715 struct mapped_symtab
25716 {
25717   mapped_symtab ()
25718   {
25719     data.resize (1024);
25720   }
25721
25722   offset_type n_elements = 0;
25723   std::vector<symtab_index_entry> data;
25724 };
25725
25726 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25727    the slot.
25728    
25729    Function is used only during write_hash_table so no index format backward
25730    compatibility is needed.  */
25731
25732 static symtab_index_entry &
25733 find_slot (struct mapped_symtab *symtab, const char *name)
25734 {
25735   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25736
25737   index = hash & (symtab->data.size () - 1);
25738   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25739
25740   for (;;)
25741     {
25742       if (symtab->data[index].name == NULL
25743           || strcmp (name, symtab->data[index].name) == 0)
25744         return symtab->data[index];
25745       index = (index + step) & (symtab->data.size () - 1);
25746     }
25747 }
25748
25749 /* Expand SYMTAB's hash table.  */
25750
25751 static void
25752 hash_expand (struct mapped_symtab *symtab)
25753 {
25754   auto old_entries = std::move (symtab->data);
25755
25756   symtab->data.clear ();
25757   symtab->data.resize (old_entries.size () * 2);
25758
25759   for (auto &it : old_entries)
25760     if (it.name != NULL)
25761       {
25762         auto &ref = find_slot (symtab, it.name);
25763         ref = std::move (it);
25764       }
25765 }
25766
25767 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25768    CU_INDEX is the index of the CU in which the symbol appears.
25769    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25770
25771 static void
25772 add_index_entry (struct mapped_symtab *symtab, const char *name,
25773                  int is_static, gdb_index_symbol_kind kind,
25774                  offset_type cu_index)
25775 {
25776   offset_type cu_index_and_attrs;
25777
25778   ++symtab->n_elements;
25779   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25780     hash_expand (symtab);
25781
25782   symtab_index_entry &slot = find_slot (symtab, name);
25783   if (slot.name == NULL)
25784     {
25785       slot.name = name;
25786       /* index_offset is set later.  */
25787     }
25788
25789   cu_index_and_attrs = 0;
25790   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25791   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25792   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25793
25794   /* We don't want to record an index value twice as we want to avoid the
25795      duplication.
25796      We process all global symbols and then all static symbols
25797      (which would allow us to avoid the duplication by only having to check
25798      the last entry pushed), but a symbol could have multiple kinds in one CU.
25799      To keep things simple we don't worry about the duplication here and
25800      sort and uniqufy the list after we've processed all symbols.  */
25801   slot.cu_indices.push_back (cu_index_and_attrs);
25802 }
25803
25804 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25805
25806 static void
25807 uniquify_cu_indices (struct mapped_symtab *symtab)
25808 {
25809   for (auto &entry : symtab->data)
25810     {
25811       if (entry.name != NULL && !entry.cu_indices.empty ())
25812         {
25813           auto &cu_indices = entry.cu_indices;
25814           std::sort (cu_indices.begin (), cu_indices.end ());
25815           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25816           cu_indices.erase (from, cu_indices.end ());
25817         }
25818     }
25819 }
25820
25821 /* A form of 'const char *' suitable for container keys.  Only the
25822    pointer is stored.  The strings themselves are compared, not the
25823    pointers.  */
25824 class c_str_view
25825 {
25826 public:
25827   c_str_view (const char *cstr)
25828     : m_cstr (cstr)
25829   {}
25830
25831   bool operator== (const c_str_view &other) const
25832   {
25833     return strcmp (m_cstr, other.m_cstr) == 0;
25834   }
25835
25836   /* Return the underlying C string.  Note, the returned string is
25837      only a reference with lifetime of this object.  */
25838   const char *c_str () const
25839   {
25840     return m_cstr;
25841   }
25842
25843 private:
25844   friend class c_str_view_hasher;
25845   const char *const m_cstr;
25846 };
25847
25848 /* A std::unordered_map::hasher for c_str_view that uses the right
25849    hash function for strings in a mapped index.  */
25850 class c_str_view_hasher
25851 {
25852 public:
25853   size_t operator () (const c_str_view &x) const
25854   {
25855     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25856   }
25857 };
25858
25859 /* A std::unordered_map::hasher for std::vector<>.  */
25860 template<typename T>
25861 class vector_hasher
25862 {
25863 public:
25864   size_t operator () (const std::vector<T> &key) const
25865   {
25866     return iterative_hash (key.data (),
25867                            sizeof (key.front ()) * key.size (), 0);
25868   }
25869 };
25870
25871 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25872    constant pool entries going into the data buffer CPOOL.  */
25873
25874 static void
25875 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25876 {
25877   {
25878     /* Elements are sorted vectors of the indices of all the CUs that
25879        hold an object of this name.  */
25880     std::unordered_map<std::vector<offset_type>, offset_type,
25881                        vector_hasher<offset_type>>
25882       symbol_hash_table;
25883
25884     /* We add all the index vectors to the constant pool first, to
25885        ensure alignment is ok.  */
25886     for (symtab_index_entry &entry : symtab->data)
25887       {
25888         if (entry.name == NULL)
25889           continue;
25890         gdb_assert (entry.index_offset == 0);
25891
25892         /* Finding before inserting is faster than always trying to
25893            insert, because inserting always allocates a node, does the
25894            lookup, and then destroys the new node if another node
25895            already had the same key.  C++17 try_emplace will avoid
25896            this.  */
25897         const auto found
25898           = symbol_hash_table.find (entry.cu_indices);
25899         if (found != symbol_hash_table.end ())
25900           {
25901             entry.index_offset = found->second;
25902             continue;
25903           }
25904
25905         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25906         entry.index_offset = cpool.size ();
25907         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25908         for (const auto index : entry.cu_indices)
25909           cpool.append_data (MAYBE_SWAP (index));
25910       }
25911   }
25912
25913   /* Now write out the hash table.  */
25914   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25915   for (const auto &entry : symtab->data)
25916     {
25917       offset_type str_off, vec_off;
25918
25919       if (entry.name != NULL)
25920         {
25921           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25922           if (insertpair.second)
25923             cpool.append_cstr0 (entry.name);
25924           str_off = insertpair.first->second;
25925           vec_off = entry.index_offset;
25926         }
25927       else
25928         {
25929           /* While 0 is a valid constant pool index, it is not valid
25930              to have 0 for both offsets.  */
25931           str_off = 0;
25932           vec_off = 0;
25933         }
25934
25935       output.append_data (MAYBE_SWAP (str_off));
25936       output.append_data (MAYBE_SWAP (vec_off));
25937     }
25938 }
25939
25940 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25941
25942 /* Helper struct for building the address table.  */
25943 struct addrmap_index_data
25944 {
25945   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25946     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25947   {}
25948
25949   struct objfile *objfile;
25950   data_buf &addr_vec;
25951   psym_index_map &cu_index_htab;
25952
25953   /* Non-zero if the previous_* fields are valid.
25954      We can't write an entry until we see the next entry (since it is only then
25955      that we know the end of the entry).  */
25956   int previous_valid;
25957   /* Index of the CU in the table of all CUs in the index file.  */
25958   unsigned int previous_cu_index;
25959   /* Start address of the CU.  */
25960   CORE_ADDR previous_cu_start;
25961 };
25962
25963 /* Write an address entry to ADDR_VEC.  */
25964
25965 static void
25966 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25967                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25968 {
25969   CORE_ADDR baseaddr;
25970
25971   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25972
25973   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25974   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25975   addr_vec.append_data (MAYBE_SWAP (cu_index));
25976 }
25977
25978 /* Worker function for traversing an addrmap to build the address table.  */
25979
25980 static int
25981 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25982 {
25983   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25984   struct partial_symtab *pst = (struct partial_symtab *) obj;
25985
25986   if (data->previous_valid)
25987     add_address_entry (data->objfile, data->addr_vec,
25988                        data->previous_cu_start, start_addr,
25989                        data->previous_cu_index);
25990
25991   data->previous_cu_start = start_addr;
25992   if (pst != NULL)
25993     {
25994       const auto it = data->cu_index_htab.find (pst);
25995       gdb_assert (it != data->cu_index_htab.cend ());
25996       data->previous_cu_index = it->second;
25997       data->previous_valid = 1;
25998     }
25999   else
26000     data->previous_valid = 0;
26001
26002   return 0;
26003 }
26004
26005 /* Write OBJFILE's address map to ADDR_VEC.
26006    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
26007    in the index file.  */
26008
26009 static void
26010 write_address_map (struct objfile *objfile, data_buf &addr_vec,
26011                    psym_index_map &cu_index_htab)
26012 {
26013   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
26014
26015   /* When writing the address table, we have to cope with the fact that
26016      the addrmap iterator only provides the start of a region; we have to
26017      wait until the next invocation to get the start of the next region.  */
26018
26019   addrmap_index_data.objfile = objfile;
26020   addrmap_index_data.previous_valid = 0;
26021
26022   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
26023                    &addrmap_index_data);
26024
26025   /* It's highly unlikely the last entry (end address = 0xff...ff)
26026      is valid, but we should still handle it.
26027      The end address is recorded as the start of the next region, but that
26028      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
26029      anyway.  */
26030   if (addrmap_index_data.previous_valid)
26031     add_address_entry (objfile, addr_vec,
26032                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
26033                        addrmap_index_data.previous_cu_index);
26034 }
26035
26036 /* Return the symbol kind of PSYM.  */
26037
26038 static gdb_index_symbol_kind
26039 symbol_kind (struct partial_symbol *psym)
26040 {
26041   domain_enum domain = PSYMBOL_DOMAIN (psym);
26042   enum address_class aclass = PSYMBOL_CLASS (psym);
26043
26044   switch (domain)
26045     {
26046     case VAR_DOMAIN:
26047       switch (aclass)
26048         {
26049         case LOC_BLOCK:
26050           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
26051         case LOC_TYPEDEF:
26052           return GDB_INDEX_SYMBOL_KIND_TYPE;
26053         case LOC_COMPUTED:
26054         case LOC_CONST_BYTES:
26055         case LOC_OPTIMIZED_OUT:
26056         case LOC_STATIC:
26057           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26058         case LOC_CONST:
26059           /* Note: It's currently impossible to recognize psyms as enum values
26060              short of reading the type info.  For now punt.  */
26061           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26062         default:
26063           /* There are other LOC_FOO values that one might want to classify
26064              as variables, but dwarf2read.c doesn't currently use them.  */
26065           return GDB_INDEX_SYMBOL_KIND_OTHER;
26066         }
26067     case STRUCT_DOMAIN:
26068       return GDB_INDEX_SYMBOL_KIND_TYPE;
26069     default:
26070       return GDB_INDEX_SYMBOL_KIND_OTHER;
26071     }
26072 }
26073
26074 /* Add a list of partial symbols to SYMTAB.  */
26075
26076 static void
26077 write_psymbols (struct mapped_symtab *symtab,
26078                 std::unordered_set<partial_symbol *> &psyms_seen,
26079                 struct partial_symbol **psymp,
26080                 int count,
26081                 offset_type cu_index,
26082                 int is_static)
26083 {
26084   for (; count-- > 0; ++psymp)
26085     {
26086       struct partial_symbol *psym = *psymp;
26087
26088       if (SYMBOL_LANGUAGE (psym) == language_ada)
26089         error (_("Ada is not currently supported by the index"));
26090
26091       /* Only add a given psymbol once.  */
26092       if (psyms_seen.insert (psym).second)
26093         {
26094           gdb_index_symbol_kind kind = symbol_kind (psym);
26095
26096           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26097                            is_static, kind, cu_index);
26098         }
26099     }
26100 }
26101
26102 /* A helper struct used when iterating over debug_types.  */
26103 struct signatured_type_index_data
26104 {
26105   signatured_type_index_data (data_buf &types_list_,
26106                               std::unordered_set<partial_symbol *> &psyms_seen_)
26107     : types_list (types_list_), psyms_seen (psyms_seen_)
26108   {}
26109
26110   struct objfile *objfile;
26111   struct mapped_symtab *symtab;
26112   data_buf &types_list;
26113   std::unordered_set<partial_symbol *> &psyms_seen;
26114   int cu_index;
26115 };
26116
26117 /* A helper function that writes a single signatured_type to an
26118    obstack.  */
26119
26120 static int
26121 write_one_signatured_type (void **slot, void *d)
26122 {
26123   struct signatured_type_index_data *info
26124     = (struct signatured_type_index_data *) d;
26125   struct signatured_type *entry = (struct signatured_type *) *slot;
26126   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26127
26128   write_psymbols (info->symtab,
26129                   info->psyms_seen,
26130                   &info->objfile->global_psymbols[psymtab->globals_offset],
26131                   psymtab->n_global_syms, info->cu_index,
26132                   0);
26133   write_psymbols (info->symtab,
26134                   info->psyms_seen,
26135                   &info->objfile->static_psymbols[psymtab->statics_offset],
26136                   psymtab->n_static_syms, info->cu_index,
26137                   1);
26138
26139   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26140                                 to_underlying (entry->per_cu.sect_off));
26141   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26142                                 to_underlying (entry->type_offset_in_tu));
26143   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26144
26145   ++info->cu_index;
26146
26147   return 1;
26148 }
26149
26150 /* Recurse into all "included" dependencies and count their symbols as
26151    if they appeared in this psymtab.  */
26152
26153 static void
26154 recursively_count_psymbols (struct partial_symtab *psymtab,
26155                             size_t &psyms_seen)
26156 {
26157   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26158     if (psymtab->dependencies[i]->user != NULL)
26159       recursively_count_psymbols (psymtab->dependencies[i],
26160                                   psyms_seen);
26161
26162   psyms_seen += psymtab->n_global_syms;
26163   psyms_seen += psymtab->n_static_syms;
26164 }
26165
26166 /* Recurse into all "included" dependencies and write their symbols as
26167    if they appeared in this psymtab.  */
26168
26169 static void
26170 recursively_write_psymbols (struct objfile *objfile,
26171                             struct partial_symtab *psymtab,
26172                             struct mapped_symtab *symtab,
26173                             std::unordered_set<partial_symbol *> &psyms_seen,
26174                             offset_type cu_index)
26175 {
26176   int i;
26177
26178   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26179     if (psymtab->dependencies[i]->user != NULL)
26180       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26181                                   symtab, psyms_seen, cu_index);
26182
26183   write_psymbols (symtab,
26184                   psyms_seen,
26185                   &objfile->global_psymbols[psymtab->globals_offset],
26186                   psymtab->n_global_syms, cu_index,
26187                   0);
26188   write_psymbols (symtab,
26189                   psyms_seen,
26190                   &objfile->static_psymbols[psymtab->statics_offset],
26191                   psymtab->n_static_syms, cu_index,
26192                   1);
26193 }
26194
26195 /* DWARF-5 .debug_names builder.  */
26196 class debug_names
26197 {
26198 public:
26199   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26200                bfd_endian dwarf5_byte_order)
26201     : m_dwarf5_byte_order (dwarf5_byte_order),
26202       m_dwarf32 (dwarf5_byte_order),
26203       m_dwarf64 (dwarf5_byte_order),
26204       m_dwarf (is_dwarf64
26205                ? static_cast<dwarf &> (m_dwarf64)
26206                : static_cast<dwarf &> (m_dwarf32)),
26207       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26208       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26209       m_debugstrlookup (dwarf2_per_objfile)
26210   {}
26211
26212   int dwarf5_offset_size () const
26213   {
26214     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26215     return dwarf5_is_dwarf64 ? 8 : 4;
26216   }
26217
26218   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26219   enum class unit_kind { cu, tu };
26220
26221   /* Insert one symbol.  */
26222   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26223                unit_kind kind)
26224   {
26225     const int dwarf_tag = psymbol_tag (psym);
26226     if (dwarf_tag == 0)
26227       return;
26228     const char *const name = SYMBOL_SEARCH_NAME (psym);
26229     const auto insertpair
26230       = m_name_to_value_set.emplace (c_str_view (name),
26231                                      std::set<symbol_value> ());
26232     std::set<symbol_value> &value_set = insertpair.first->second;
26233     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26234   }
26235
26236   /* Build all the tables.  All symbols must be already inserted.
26237      This function does not call file_write, caller has to do it
26238      afterwards.  */
26239   void build ()
26240   {
26241     /* Verify the build method has not be called twice.  */
26242     gdb_assert (m_abbrev_table.empty ());
26243     const size_t name_count = m_name_to_value_set.size ();
26244     m_bucket_table.resize
26245       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26246     m_hash_table.reserve (name_count);
26247     m_name_table_string_offs.reserve (name_count);
26248     m_name_table_entry_offs.reserve (name_count);
26249
26250     /* Map each hash of symbol to its name and value.  */
26251     struct hash_it_pair
26252     {
26253       uint32_t hash;
26254       decltype (m_name_to_value_set)::const_iterator it;
26255     };
26256     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26257     bucket_hash.resize (m_bucket_table.size ());
26258     for (decltype (m_name_to_value_set)::const_iterator it
26259            = m_name_to_value_set.cbegin ();
26260          it != m_name_to_value_set.cend ();
26261          ++it)
26262       {
26263         const char *const name = it->first.c_str ();
26264         const uint32_t hash = dwarf5_djb_hash (name);
26265         hash_it_pair hashitpair;
26266         hashitpair.hash = hash;
26267         hashitpair.it = it;
26268         auto &slot = bucket_hash[hash % bucket_hash.size()];
26269         slot.push_front (std::move (hashitpair));
26270       }
26271     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26272       {
26273         const std::forward_list<hash_it_pair> &hashitlist
26274           = bucket_hash[bucket_ix];
26275         if (hashitlist.empty ())
26276           continue;
26277         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26278         /* The hashes array is indexed starting at 1.  */
26279         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26280                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26281                                 m_hash_table.size () + 1);
26282         for (const hash_it_pair &hashitpair : hashitlist)
26283           {
26284             m_hash_table.push_back (0);
26285             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26286                                                         (&m_hash_table.back ()),
26287                                     sizeof (m_hash_table.back ()),
26288                                     m_dwarf5_byte_order, hashitpair.hash);
26289             const c_str_view &name = hashitpair.it->first;
26290             const std::set<symbol_value> &value_set = hashitpair.it->second;
26291             m_name_table_string_offs.push_back_reorder
26292               (m_debugstrlookup.lookup (name.c_str ()));
26293             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26294             gdb_assert (!value_set.empty ());
26295             for (const symbol_value &value : value_set)
26296               {
26297                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26298                                                         value.is_static,
26299                                                         value.kind)];
26300                 if (idx == 0)
26301                   {
26302                     idx = m_idx_next++;
26303                     m_abbrev_table.append_unsigned_leb128 (idx);
26304                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26305                     m_abbrev_table.append_unsigned_leb128
26306                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26307                                                            : DW_IDX_type_unit);
26308                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26309                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26310                                                            ? DW_IDX_GNU_internal
26311                                                            : DW_IDX_GNU_external);
26312                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26313
26314                     /* Terminate attributes list.  */
26315                     m_abbrev_table.append_unsigned_leb128 (0);
26316                     m_abbrev_table.append_unsigned_leb128 (0);
26317                   }
26318
26319                 m_entry_pool.append_unsigned_leb128 (idx);
26320                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26321               }
26322
26323             /* Terminate the list of CUs.  */
26324             m_entry_pool.append_unsigned_leb128 (0);
26325           }
26326       }
26327     gdb_assert (m_hash_table.size () == name_count);
26328
26329     /* Terminate tags list.  */
26330     m_abbrev_table.append_unsigned_leb128 (0);
26331   }
26332
26333   /* Return .debug_names bucket count.  This must be called only after
26334      calling the build method.  */
26335   uint32_t bucket_count () const
26336   {
26337     /* Verify the build method has been already called.  */
26338     gdb_assert (!m_abbrev_table.empty ());
26339     const uint32_t retval = m_bucket_table.size ();
26340
26341     /* Check for overflow.  */
26342     gdb_assert (retval == m_bucket_table.size ());
26343     return retval;
26344   }
26345
26346   /* Return .debug_names names count.  This must be called only after
26347      calling the build method.  */
26348   uint32_t name_count () const
26349   {
26350     /* Verify the build method has been already called.  */
26351     gdb_assert (!m_abbrev_table.empty ());
26352     const uint32_t retval = m_hash_table.size ();
26353
26354     /* Check for overflow.  */
26355     gdb_assert (retval == m_hash_table.size ());
26356     return retval;
26357   }
26358
26359   /* Return number of bytes of .debug_names abbreviation table.  This
26360      must be called only after calling the build method.  */
26361   uint32_t abbrev_table_bytes () const
26362   {
26363     gdb_assert (!m_abbrev_table.empty ());
26364     return m_abbrev_table.size ();
26365   }
26366
26367   /* Recurse into all "included" dependencies and store their symbols
26368      as if they appeared in this psymtab.  */
26369   void recursively_write_psymbols
26370     (struct objfile *objfile,
26371      struct partial_symtab *psymtab,
26372      std::unordered_set<partial_symbol *> &psyms_seen,
26373      int cu_index)
26374   {
26375     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26376       if (psymtab->dependencies[i]->user != NULL)
26377         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26378                                     psyms_seen, cu_index);
26379
26380     write_psymbols (psyms_seen,
26381                     &objfile->global_psymbols[psymtab->globals_offset],
26382                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26383     write_psymbols (psyms_seen,
26384                     &objfile->static_psymbols[psymtab->statics_offset],
26385                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26386   }
26387
26388   /* Return number of bytes the .debug_names section will have.  This
26389      must be called only after calling the build method.  */
26390   size_t bytes () const
26391   {
26392     /* Verify the build method has been already called.  */
26393     gdb_assert (!m_abbrev_table.empty ());
26394     size_t expected_bytes = 0;
26395     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26396     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26397     expected_bytes += m_name_table_string_offs.bytes ();
26398     expected_bytes += m_name_table_entry_offs.bytes ();
26399     expected_bytes += m_abbrev_table.size ();
26400     expected_bytes += m_entry_pool.size ();
26401     return expected_bytes;
26402   }
26403
26404   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26405      FILE_STR.  This must be called only after calling the build
26406      method.  */
26407   void file_write (FILE *file_names, FILE *file_str) const
26408   {
26409     /* Verify the build method has been already called.  */
26410     gdb_assert (!m_abbrev_table.empty ());
26411     ::file_write (file_names, m_bucket_table);
26412     ::file_write (file_names, m_hash_table);
26413     m_name_table_string_offs.file_write (file_names);
26414     m_name_table_entry_offs.file_write (file_names);
26415     m_abbrev_table.file_write (file_names);
26416     m_entry_pool.file_write (file_names);
26417     m_debugstrlookup.file_write (file_str);
26418   }
26419
26420   /* A helper user data for write_one_signatured_type.  */
26421   class write_one_signatured_type_data
26422   {
26423   public:
26424     write_one_signatured_type_data (debug_names &nametable_,
26425                                     signatured_type_index_data &&info_)
26426     : nametable (nametable_), info (std::move (info_))
26427     {}
26428     debug_names &nametable;
26429     struct signatured_type_index_data info;
26430   };
26431
26432   /* A helper function to pass write_one_signatured_type to
26433      htab_traverse_noresize.  */
26434   static int
26435   write_one_signatured_type (void **slot, void *d)
26436   {
26437     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26438     struct signatured_type_index_data *info = &data->info;
26439     struct signatured_type *entry = (struct signatured_type *) *slot;
26440
26441     data->nametable.write_one_signatured_type (entry, info);
26442
26443     return 1;
26444   }
26445
26446 private:
26447
26448   /* Storage for symbol names mapping them to their .debug_str section
26449      offsets.  */
26450   class debug_str_lookup
26451   {
26452   public:
26453
26454     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26455        All .debug_str section strings are automatically stored.  */
26456     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26457       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26458         m_dwarf2_per_objfile (dwarf2_per_objfile)
26459     {
26460       dwarf2_read_section (dwarf2_per_objfile->objfile,
26461                            &dwarf2_per_objfile->str);
26462       if (dwarf2_per_objfile->str.buffer == NULL)
26463         return;
26464       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26465            data < (dwarf2_per_objfile->str.buffer
26466                    + dwarf2_per_objfile->str.size);)
26467         {
26468           const char *const s = reinterpret_cast<const char *> (data);
26469           const auto insertpair
26470             = m_str_table.emplace (c_str_view (s),
26471                                    data - dwarf2_per_objfile->str.buffer);
26472           if (!insertpair.second)
26473             complaint (&symfile_complaints,
26474                        _("Duplicate string \"%s\" in "
26475                          ".debug_str section [in module %s]"),
26476                        s, bfd_get_filename (m_abfd));
26477           data += strlen (s) + 1;
26478         }
26479     }
26480
26481     /* Return offset of symbol name S in the .debug_str section.  Add
26482        such symbol to the section's end if it does not exist there
26483        yet.  */
26484     size_t lookup (const char *s)
26485     {
26486       const auto it = m_str_table.find (c_str_view (s));
26487       if (it != m_str_table.end ())
26488         return it->second;
26489       const size_t offset = (m_dwarf2_per_objfile->str.size
26490                              + m_str_add_buf.size ());
26491       m_str_table.emplace (c_str_view (s), offset);
26492       m_str_add_buf.append_cstr0 (s);
26493       return offset;
26494     }
26495
26496     /* Append the end of the .debug_str section to FILE.  */
26497     void file_write (FILE *file) const
26498     {
26499       m_str_add_buf.file_write (file);
26500     }
26501
26502   private:
26503     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26504     bfd *const m_abfd;
26505     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26506
26507     /* Data to add at the end of .debug_str for new needed symbol names.  */
26508     data_buf m_str_add_buf;
26509   };
26510
26511   /* Container to map used DWARF tags to their .debug_names abbreviation
26512      tags.  */
26513   class index_key
26514   {
26515   public:
26516     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26517       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26518     {
26519     }
26520
26521     bool
26522     operator== (const index_key &other) const
26523     {
26524       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26525               && kind == other.kind);
26526     }
26527
26528     const int dwarf_tag;
26529     const bool is_static;
26530     const unit_kind kind;
26531   };
26532
26533   /* Provide std::unordered_map::hasher for index_key.  */
26534   class index_key_hasher
26535   {
26536   public:
26537     size_t
26538     operator () (const index_key &key) const
26539     {
26540       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26541     }
26542   };
26543
26544   /* Parameters of one symbol entry.  */
26545   class symbol_value
26546   {
26547   public:
26548     const int dwarf_tag, cu_index;
26549     const bool is_static;
26550     const unit_kind kind;
26551
26552     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26553                   unit_kind kind_)
26554       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26555         kind (kind_)
26556     {}
26557
26558     bool
26559     operator< (const symbol_value &other) const
26560     {
26561 #define X(n) \
26562   do \
26563     { \
26564       if (n < other.n) \
26565         return true; \
26566       if (n > other.n) \
26567         return false; \
26568     } \
26569   while (0)
26570       X (dwarf_tag);
26571       X (is_static);
26572       X (kind);
26573       X (cu_index);
26574 #undef X
26575       return false;
26576     }
26577   };
26578
26579   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26580      output.  */
26581   class offset_vec
26582   {
26583   protected:
26584     const bfd_endian dwarf5_byte_order;
26585   public:
26586     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26587       : dwarf5_byte_order (dwarf5_byte_order_)
26588     {}
26589
26590     /* Call std::vector::reserve for NELEM elements.  */
26591     virtual void reserve (size_t nelem) = 0;
26592
26593     /* Call std::vector::push_back with store_unsigned_integer byte
26594        reordering for ELEM.  */
26595     virtual void push_back_reorder (size_t elem) = 0;
26596
26597     /* Return expected output size in bytes.  */
26598     virtual size_t bytes () const = 0;
26599
26600     /* Write name table to FILE.  */
26601     virtual void file_write (FILE *file) const = 0;
26602   };
26603
26604   /* Template to unify DWARF-32 and DWARF-64 output.  */
26605   template<typename OffsetSize>
26606   class offset_vec_tmpl : public offset_vec
26607   {
26608   public:
26609     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26610       : offset_vec (dwarf5_byte_order_)
26611     {}
26612
26613     /* Implement offset_vec::reserve.  */
26614     void reserve (size_t nelem) override
26615     {
26616       m_vec.reserve (nelem);
26617     }
26618
26619     /* Implement offset_vec::push_back_reorder.  */
26620     void push_back_reorder (size_t elem) override
26621     {
26622       m_vec.push_back (elem);
26623       /* Check for overflow.  */
26624       gdb_assert (m_vec.back () == elem);
26625       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26626                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26627     }
26628
26629     /* Implement offset_vec::bytes.  */
26630     size_t bytes () const override
26631     {
26632       return m_vec.size () * sizeof (m_vec[0]);
26633     }
26634
26635     /* Implement offset_vec::file_write.  */
26636     void file_write (FILE *file) const override
26637     {
26638       ::file_write (file, m_vec);
26639     }
26640
26641   private:
26642     std::vector<OffsetSize> m_vec;
26643   };
26644
26645   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26646      respecting name table width.  */
26647   class dwarf
26648   {
26649   public:
26650     offset_vec &name_table_string_offs, &name_table_entry_offs;
26651
26652     dwarf (offset_vec &name_table_string_offs_,
26653            offset_vec &name_table_entry_offs_)
26654       : name_table_string_offs (name_table_string_offs_),
26655         name_table_entry_offs (name_table_entry_offs_)
26656     {
26657     }
26658   };
26659
26660   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26661      respecting name table width.  */
26662   template<typename OffsetSize>
26663   class dwarf_tmpl : public dwarf
26664   {
26665   public:
26666     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26667       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26668         m_name_table_string_offs (dwarf5_byte_order_),
26669         m_name_table_entry_offs (dwarf5_byte_order_)
26670     {}
26671
26672   private:
26673     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26674     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26675   };
26676
26677   /* Try to reconstruct original DWARF tag for given partial_symbol.
26678      This function is not DWARF-5 compliant but it is sufficient for
26679      GDB as a DWARF-5 index consumer.  */
26680   static int psymbol_tag (const struct partial_symbol *psym)
26681   {
26682     domain_enum domain = PSYMBOL_DOMAIN (psym);
26683     enum address_class aclass = PSYMBOL_CLASS (psym);
26684
26685     switch (domain)
26686       {
26687       case VAR_DOMAIN:
26688         switch (aclass)
26689           {
26690           case LOC_BLOCK:
26691             return DW_TAG_subprogram;
26692           case LOC_TYPEDEF:
26693             return DW_TAG_typedef;
26694           case LOC_COMPUTED:
26695           case LOC_CONST_BYTES:
26696           case LOC_OPTIMIZED_OUT:
26697           case LOC_STATIC:
26698             return DW_TAG_variable;
26699           case LOC_CONST:
26700             /* Note: It's currently impossible to recognize psyms as enum values
26701                short of reading the type info.  For now punt.  */
26702             return DW_TAG_variable;
26703           default:
26704             /* There are other LOC_FOO values that one might want to classify
26705                as variables, but dwarf2read.c doesn't currently use them.  */
26706             return DW_TAG_variable;
26707           }
26708       case STRUCT_DOMAIN:
26709         return DW_TAG_structure_type;
26710       default:
26711         return 0;
26712       }
26713   }
26714
26715   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26716   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26717                        struct partial_symbol **psymp, int count, int cu_index,
26718                        bool is_static, unit_kind kind)
26719   {
26720     for (; count-- > 0; ++psymp)
26721       {
26722         struct partial_symbol *psym = *psymp;
26723
26724         if (SYMBOL_LANGUAGE (psym) == language_ada)
26725           error (_("Ada is not currently supported by the index"));
26726
26727         /* Only add a given psymbol once.  */
26728         if (psyms_seen.insert (psym).second)
26729           insert (psym, cu_index, is_static, kind);
26730       }
26731   }
26732
26733   /* A helper function that writes a single signatured_type
26734      to a debug_names.  */
26735   void
26736   write_one_signatured_type (struct signatured_type *entry,
26737                              struct signatured_type_index_data *info)
26738   {
26739     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26740
26741     write_psymbols (info->psyms_seen,
26742                     &info->objfile->global_psymbols[psymtab->globals_offset],
26743                     psymtab->n_global_syms, info->cu_index, false,
26744                     unit_kind::tu);
26745     write_psymbols (info->psyms_seen,
26746                     &info->objfile->static_psymbols[psymtab->statics_offset],
26747                     psymtab->n_static_syms, info->cu_index, true,
26748                     unit_kind::tu);
26749
26750     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26751                                   to_underlying (entry->per_cu.sect_off));
26752
26753     ++info->cu_index;
26754   }
26755
26756   /* Store value of each symbol.  */
26757   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26758     m_name_to_value_set;
26759
26760   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26761      order.  */
26762   std::vector<uint32_t> m_bucket_table;
26763   std::vector<uint32_t> m_hash_table;
26764
26765   const bfd_endian m_dwarf5_byte_order;
26766   dwarf_tmpl<uint32_t> m_dwarf32;
26767   dwarf_tmpl<uint64_t> m_dwarf64;
26768   dwarf &m_dwarf;
26769   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26770   debug_str_lookup m_debugstrlookup;
26771
26772   /* Map each used .debug_names abbreviation tag parameter to its
26773      index value.  */
26774   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26775
26776   /* Next unused .debug_names abbreviation tag for
26777      m_indexkey_to_idx.  */
26778   int m_idx_next = 1;
26779
26780   /* .debug_names abbreviation table.  */
26781   data_buf m_abbrev_table;
26782
26783   /* .debug_names entry pool.  */
26784   data_buf m_entry_pool;
26785 };
26786
26787 /* Return iff any of the needed offsets does not fit into 32-bit
26788    .debug_names section.  */
26789
26790 static bool
26791 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26792 {
26793   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26794     {
26795       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26796
26797       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26798         return true;
26799     }
26800   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26801     {
26802       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26803       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26804
26805       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26806         return true;
26807     }
26808   return false;
26809 }
26810
26811 /* The psyms_seen set is potentially going to be largish (~40k
26812    elements when indexing a -g3 build of GDB itself).  Estimate the
26813    number of elements in order to avoid too many rehashes, which
26814    require rebuilding buckets and thus many trips to
26815    malloc/free.  */
26816
26817 static size_t
26818 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26819 {
26820   size_t psyms_count = 0;
26821   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26822     {
26823       struct dwarf2_per_cu_data *per_cu
26824         = dwarf2_per_objfile->all_comp_units[i];
26825       struct partial_symtab *psymtab = per_cu->v.psymtab;
26826
26827       if (psymtab != NULL && psymtab->user == NULL)
26828         recursively_count_psymbols (psymtab, psyms_count);
26829     }
26830   /* Generating an index for gdb itself shows a ratio of
26831      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26832   return psyms_count / 4;
26833 }
26834
26835 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26836    Return how many bytes were expected to be written into OUT_FILE.  */
26837
26838 static size_t
26839 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26840 {
26841   struct objfile *objfile = dwarf2_per_objfile->objfile;
26842   mapped_symtab symtab;
26843   data_buf cu_list;
26844
26845   /* While we're scanning CU's create a table that maps a psymtab pointer
26846      (which is what addrmap records) to its index (which is what is recorded
26847      in the index file).  This will later be needed to write the address
26848      table.  */
26849   psym_index_map cu_index_htab;
26850   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26851
26852   /* The CU list is already sorted, so we don't need to do additional
26853      work here.  Also, the debug_types entries do not appear in
26854      all_comp_units, but only in their own hash table.  */
26855
26856   std::unordered_set<partial_symbol *> psyms_seen
26857     (psyms_seen_size (dwarf2_per_objfile));
26858   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26859     {
26860       struct dwarf2_per_cu_data *per_cu
26861         = dwarf2_per_objfile->all_comp_units[i];
26862       struct partial_symtab *psymtab = per_cu->v.psymtab;
26863
26864       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26865          It may be referenced from a local scope but in such case it does not
26866          need to be present in .gdb_index.  */
26867       if (psymtab == NULL)
26868         continue;
26869
26870       if (psymtab->user == NULL)
26871         recursively_write_psymbols (objfile, psymtab, &symtab,
26872                                     psyms_seen, i);
26873
26874       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26875       gdb_assert (insertpair.second);
26876
26877       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26878                            to_underlying (per_cu->sect_off));
26879       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26880     }
26881
26882   /* Dump the address map.  */
26883   data_buf addr_vec;
26884   write_address_map (objfile, addr_vec, cu_index_htab);
26885
26886   /* Write out the .debug_type entries, if any.  */
26887   data_buf types_cu_list;
26888   if (dwarf2_per_objfile->signatured_types)
26889     {
26890       signatured_type_index_data sig_data (types_cu_list,
26891                                            psyms_seen);
26892
26893       sig_data.objfile = objfile;
26894       sig_data.symtab = &symtab;
26895       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26896       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26897                               write_one_signatured_type, &sig_data);
26898     }
26899
26900   /* Now that we've processed all symbols we can shrink their cu_indices
26901      lists.  */
26902   uniquify_cu_indices (&symtab);
26903
26904   data_buf symtab_vec, constant_pool;
26905   write_hash_table (&symtab, symtab_vec, constant_pool);
26906
26907   data_buf contents;
26908   const offset_type size_of_contents = 6 * sizeof (offset_type);
26909   offset_type total_len = size_of_contents;
26910
26911   /* The version number.  */
26912   contents.append_data (MAYBE_SWAP (8));
26913
26914   /* The offset of the CU list from the start of the file.  */
26915   contents.append_data (MAYBE_SWAP (total_len));
26916   total_len += cu_list.size ();
26917
26918   /* The offset of the types CU list from the start of the file.  */
26919   contents.append_data (MAYBE_SWAP (total_len));
26920   total_len += types_cu_list.size ();
26921
26922   /* The offset of the address table from the start of the file.  */
26923   contents.append_data (MAYBE_SWAP (total_len));
26924   total_len += addr_vec.size ();
26925
26926   /* The offset of the symbol table from the start of the file.  */
26927   contents.append_data (MAYBE_SWAP (total_len));
26928   total_len += symtab_vec.size ();
26929
26930   /* The offset of the constant pool from the start of the file.  */
26931   contents.append_data (MAYBE_SWAP (total_len));
26932   total_len += constant_pool.size ();
26933
26934   gdb_assert (contents.size () == size_of_contents);
26935
26936   contents.file_write (out_file);
26937   cu_list.file_write (out_file);
26938   types_cu_list.file_write (out_file);
26939   addr_vec.file_write (out_file);
26940   symtab_vec.file_write (out_file);
26941   constant_pool.file_write (out_file);
26942
26943   return total_len;
26944 }
26945
26946 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26947 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26948
26949 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26950    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26951    many bytes were expected to be written into OUT_FILE.  */
26952
26953 static size_t
26954 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
26955                    FILE *out_file, FILE *out_file_str)
26956 {
26957   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
26958   struct objfile *objfile = dwarf2_per_objfile->objfile;
26959   const enum bfd_endian dwarf5_byte_order
26960     = gdbarch_byte_order (get_objfile_arch (objfile));
26961
26962   /* The CU list is already sorted, so we don't need to do additional
26963      work here.  Also, the debug_types entries do not appear in
26964      all_comp_units, but only in their own hash table.  */
26965   data_buf cu_list;
26966   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
26967                          dwarf5_byte_order);
26968   std::unordered_set<partial_symbol *>
26969     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
26970   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26971     {
26972       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26973       partial_symtab *psymtab = per_cu->v.psymtab;
26974
26975       /* CU of a shared file from 'dwz -m' may be unused by this main
26976          file.  It may be referenced from a local scope but in such
26977          case it does not need to be present in .debug_names.  */
26978       if (psymtab == NULL)
26979         continue;
26980
26981       if (psymtab->user == NULL)
26982         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26983
26984       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
26985                            to_underlying (per_cu->sect_off));
26986     }
26987
26988   /* Write out the .debug_type entries, if any.  */
26989   data_buf types_cu_list;
26990   if (dwarf2_per_objfile->signatured_types)
26991     {
26992       debug_names::write_one_signatured_type_data sig_data (nametable,
26993                         signatured_type_index_data (types_cu_list, psyms_seen));
26994
26995       sig_data.info.objfile = objfile;
26996       /* It is used only for gdb_index.  */
26997       sig_data.info.symtab = nullptr;
26998       sig_data.info.cu_index = 0;
26999       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27000                               debug_names::write_one_signatured_type,
27001                               &sig_data);
27002     }
27003
27004   nametable.build ();
27005
27006   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
27007
27008   const offset_type bytes_of_header
27009     = ((dwarf5_is_dwarf64 ? 12 : 4)
27010        + 2 + 2 + 7 * 4
27011        + sizeof (dwarf5_gdb_augmentation));
27012   size_t expected_bytes = 0;
27013   expected_bytes += bytes_of_header;
27014   expected_bytes += cu_list.size ();
27015   expected_bytes += types_cu_list.size ();
27016   expected_bytes += nametable.bytes ();
27017   data_buf header;
27018
27019   if (!dwarf5_is_dwarf64)
27020     {
27021       const uint64_t size64 = expected_bytes - 4;
27022       gdb_assert (size64 < 0xfffffff0);
27023       header.append_uint (4, dwarf5_byte_order, size64);
27024     }
27025   else
27026     {
27027       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
27028       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
27029     }
27030
27031   /* The version number.  */
27032   header.append_uint (2, dwarf5_byte_order, 5);
27033
27034   /* Padding.  */
27035   header.append_uint (2, dwarf5_byte_order, 0);
27036
27037   /* comp_unit_count - The number of CUs in the CU list.  */
27038   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
27039
27040   /* local_type_unit_count - The number of TUs in the local TU
27041      list.  */
27042   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
27043
27044   /* foreign_type_unit_count - The number of TUs in the foreign TU
27045      list.  */
27046   header.append_uint (4, dwarf5_byte_order, 0);
27047
27048   /* bucket_count - The number of hash buckets in the hash lookup
27049      table.  */
27050   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
27051
27052   /* name_count - The number of unique names in the index.  */
27053   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
27054
27055   /* abbrev_table_size - The size in bytes of the abbreviations
27056      table.  */
27057   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
27058
27059   /* augmentation_string_size - The size in bytes of the augmentation
27060      string.  This value is rounded up to a multiple of 4.  */
27061   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
27062   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
27063   header.append_data (dwarf5_gdb_augmentation);
27064
27065   gdb_assert (header.size () == bytes_of_header);
27066
27067   header.file_write (out_file);
27068   cu_list.file_write (out_file);
27069   types_cu_list.file_write (out_file);
27070   nametable.file_write (out_file, out_file_str);
27071
27072   return expected_bytes;
27073 }
27074
27075 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
27076    position is at the end of the file.  */
27077
27078 static void
27079 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27080 {
27081   const auto file_size = ftell (file);
27082   if (file_size == -1)
27083     error (_("Can't get `%s' size"), filename);
27084   gdb_assert (file_size == expected_size);
27085 }
27086
27087 /* Create an index file for OBJFILE in the directory DIR.  */
27088
27089 static void
27090 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27091                          const char *dir,
27092                          dw_index_kind index_kind)
27093 {
27094   struct objfile *objfile = dwarf2_per_objfile->objfile;
27095
27096   if (dwarf2_per_objfile->using_index)
27097     error (_("Cannot use an index to create the index"));
27098
27099   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27100     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27101
27102   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27103     return;
27104
27105   struct stat st;
27106   if (stat (objfile_name (objfile), &st) < 0)
27107     perror_with_name (objfile_name (objfile));
27108
27109   std::string filename (std::string (dir) + SLASH_STRING
27110                         + lbasename (objfile_name (objfile))
27111                         + (index_kind == dw_index_kind::DEBUG_NAMES
27112                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27113
27114   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27115   if (!out_file)
27116     error (_("Can't open `%s' for writing"), filename.c_str ());
27117
27118   /* Order matters here; we want FILE to be closed before FILENAME is
27119      unlinked, because on MS-Windows one cannot delete a file that is
27120      still open.  (Don't call anything here that might throw until
27121      file_closer is created.)  */
27122   gdb::unlinker unlink_file (filename.c_str ());
27123   gdb_file_up close_out_file (out_file);
27124
27125   if (index_kind == dw_index_kind::DEBUG_NAMES)
27126     {
27127       std::string filename_str (std::string (dir) + SLASH_STRING
27128                                 + lbasename (objfile_name (objfile))
27129                                 + DEBUG_STR_SUFFIX);
27130       FILE *out_file_str
27131         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27132       if (!out_file_str)
27133         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27134       gdb::unlinker unlink_file_str (filename_str.c_str ());
27135       gdb_file_up close_out_file_str (out_file_str);
27136
27137       const size_t total_len
27138         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27139       assert_file_size (out_file, filename.c_str (), total_len);
27140
27141       /* We want to keep the file .debug_str file too.  */
27142       unlink_file_str.keep ();
27143     }
27144   else
27145     {
27146       const size_t total_len
27147         = write_gdbindex (dwarf2_per_objfile, out_file);
27148       assert_file_size (out_file, filename.c_str (), total_len);
27149     }
27150
27151   /* We want to keep the file.  */
27152   unlink_file.keep ();
27153 }
27154
27155 /* Implementation of the `save gdb-index' command.
27156    
27157    Note that the .gdb_index file format used by this command is
27158    documented in the GDB manual.  Any changes here must be documented
27159    there.  */
27160
27161 static void
27162 save_gdb_index_command (const char *arg, int from_tty)
27163 {
27164   struct objfile *objfile;
27165   const char dwarf5space[] = "-dwarf-5 ";
27166   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27167
27168   if (!arg)
27169     arg = "";
27170
27171   arg = skip_spaces (arg);
27172   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27173     {
27174       index_kind = dw_index_kind::DEBUG_NAMES;
27175       arg += strlen (dwarf5space);
27176       arg = skip_spaces (arg);
27177     }
27178
27179   if (!*arg)
27180     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27181
27182   ALL_OBJFILES (objfile)
27183   {
27184     struct stat st;
27185
27186     /* If the objfile does not correspond to an actual file, skip it.  */
27187     if (stat (objfile_name (objfile), &st) < 0)
27188       continue;
27189
27190     struct dwarf2_per_objfile *dwarf2_per_objfile
27191       = get_dwarf2_per_objfile (objfile);
27192
27193     if (dwarf2_per_objfile != NULL)
27194       {
27195         TRY
27196           {
27197             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27198           }
27199         CATCH (except, RETURN_MASK_ERROR)
27200           {
27201             exception_fprintf (gdb_stderr, except,
27202                                _("Error while writing index for `%s': "),
27203                                objfile_name (objfile));
27204           }
27205         END_CATCH
27206       }
27207
27208   }
27209 }
27210
27211 \f
27212
27213 int dwarf_always_disassemble;
27214
27215 static void
27216 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27217                                struct cmd_list_element *c, const char *value)
27218 {
27219   fprintf_filtered (file,
27220                     _("Whether to always disassemble "
27221                       "DWARF expressions is %s.\n"),
27222                     value);
27223 }
27224
27225 static void
27226 show_check_physname (struct ui_file *file, int from_tty,
27227                      struct cmd_list_element *c, const char *value)
27228 {
27229   fprintf_filtered (file,
27230                     _("Whether to check \"physname\" is %s.\n"),
27231                     value);
27232 }
27233
27234 void
27235 _initialize_dwarf2_read (void)
27236 {
27237   struct cmd_list_element *c;
27238
27239   dwarf2_objfile_data_key
27240     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
27241
27242   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27243 Set DWARF specific variables.\n\
27244 Configure DWARF variables such as the cache size"),
27245                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27246                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27247
27248   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27249 Show DWARF specific variables\n\
27250 Show DWARF variables such as the cache size"),
27251                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27252                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27253
27254   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27255                             &dwarf_max_cache_age, _("\
27256 Set the upper bound on the age of cached DWARF compilation units."), _("\
27257 Show the upper bound on the age of cached DWARF compilation units."), _("\
27258 A higher limit means that cached compilation units will be stored\n\
27259 in memory longer, and more total memory will be used.  Zero disables\n\
27260 caching, which can slow down startup."),
27261                             NULL,
27262                             show_dwarf_max_cache_age,
27263                             &set_dwarf_cmdlist,
27264                             &show_dwarf_cmdlist);
27265
27266   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27267                            &dwarf_always_disassemble, _("\
27268 Set whether `info address' always disassembles DWARF expressions."), _("\
27269 Show whether `info address' always disassembles DWARF expressions."), _("\
27270 When enabled, DWARF expressions are always printed in an assembly-like\n\
27271 syntax.  When disabled, expressions will be printed in a more\n\
27272 conversational style, when possible."),
27273                            NULL,
27274                            show_dwarf_always_disassemble,
27275                            &set_dwarf_cmdlist,
27276                            &show_dwarf_cmdlist);
27277
27278   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27279 Set debugging of the DWARF reader."), _("\
27280 Show debugging of the DWARF reader."), _("\
27281 When enabled (non-zero), debugging messages are printed during DWARF\n\
27282 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27283 information.  A value greater than 1 provides more verbose information."),
27284                             NULL,
27285                             NULL,
27286                             &setdebuglist, &showdebuglist);
27287
27288   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27289 Set debugging of the DWARF DIE reader."), _("\
27290 Show debugging of the DWARF DIE reader."), _("\
27291 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27292 The value is the maximum depth to print."),
27293                              NULL,
27294                              NULL,
27295                              &setdebuglist, &showdebuglist);
27296
27297   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27298 Set debugging of the dwarf line reader."), _("\
27299 Show debugging of the dwarf line reader."), _("\
27300 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27301 A value of 1 (one) provides basic information.\n\
27302 A value greater than 1 provides more verbose information."),
27303                              NULL,
27304                              NULL,
27305                              &setdebuglist, &showdebuglist);
27306
27307   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27308 Set cross-checking of \"physname\" code against demangler."), _("\
27309 Show cross-checking of \"physname\" code against demangler."), _("\
27310 When enabled, GDB's internal \"physname\" code is checked against\n\
27311 the demangler."),
27312                            NULL, show_check_physname,
27313                            &setdebuglist, &showdebuglist);
27314
27315   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27316                            no_class, &use_deprecated_index_sections, _("\
27317 Set whether to use deprecated gdb_index sections."), _("\
27318 Show whether to use deprecated gdb_index sections."), _("\
27319 When enabled, deprecated .gdb_index sections are used anyway.\n\
27320 Normally they are ignored either because of a missing feature or\n\
27321 performance issue.\n\
27322 Warning: This option must be enabled before gdb reads the file."),
27323                            NULL,
27324                            NULL,
27325                            &setlist, &showlist);
27326
27327   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27328                _("\
27329 Save a gdb-index file.\n\
27330 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27331 \n\
27332 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27333 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27334 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27335                &save_cmdlist);
27336   set_cmd_completer (c, filename_completer);
27337
27338   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27339                                                         &dwarf2_locexpr_funcs);
27340   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27341                                                         &dwarf2_loclist_funcs);
27342
27343   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27344                                         &dwarf2_block_frame_base_locexpr_funcs);
27345   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27346                                         &dwarf2_block_frame_base_loclist_funcs);
27347
27348 #if GDB_SELF_TEST
27349   selftests::register_test ("dw2_expand_symtabs_matching",
27350                             selftests::dw2_expand_symtabs_matching::run_test);
27351 #endif
27352 }