Remove dwarf2_per_objfile global
[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 dwarf2_per_objfile containing this compilation unit.  */
665   struct dwarf2_per_objfile *dwarf2_per_objfile;
666
667   /* The header of the compilation unit.  */
668   struct comp_unit_head header;
669
670   /* Base address of this compilation unit.  */
671   CORE_ADDR base_address;
672
673   /* Non-zero if base_address has been set.  */
674   int base_known;
675
676   /* The language we are debugging.  */
677   enum language language;
678   const struct language_defn *language_defn;
679
680   const char *producer;
681
682   /* The generic symbol table building routines have separate lists for
683      file scope symbols and all all other scopes (local scopes).  So
684      we need to select the right one to pass to add_symbol_to_list().
685      We do it by keeping a pointer to the correct list in list_in_scope.
686
687      FIXME: The original dwarf code just treated the file scope as the
688      first local scope, and all other local scopes as nested local
689      scopes, and worked fine.  Check to see if we really need to
690      distinguish these in buildsym.c.  */
691   struct pending **list_in_scope;
692
693   /* The abbrev table for this CU.
694      Normally this points to the abbrev table in the objfile.
695      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
696   struct abbrev_table *abbrev_table;
697
698   /* Hash table holding all the loaded partial DIEs
699      with partial_die->offset.SECT_OFF as hash.  */
700   htab_t partial_dies;
701
702   /* Storage for things with the same lifetime as this read-in compilation
703      unit, including partial DIEs.  */
704   struct obstack comp_unit_obstack;
705
706   /* When multiple dwarf2_cu structures are living in memory, this field
707      chains them all together, so that they can be released efficiently.
708      We will probably also want a generation counter so that most-recently-used
709      compilation units are cached...  */
710   struct dwarf2_per_cu_data *read_in_chain;
711
712   /* Backlink to our per_cu entry.  */
713   struct dwarf2_per_cu_data *per_cu;
714
715   /* How many compilation units ago was this CU last referenced?  */
716   int last_used;
717
718   /* A hash table of DIE cu_offset for following references with
719      die_info->offset.sect_off as hash.  */
720   htab_t die_hash;
721
722   /* Full DIEs if read in.  */
723   struct die_info *dies;
724
725   /* A set of pointers to dwarf2_per_cu_data objects for compilation
726      units referenced by this one.  Only set during full symbol processing;
727      partial symbol tables do not have dependencies.  */
728   htab_t dependencies;
729
730   /* Header data from the line table, during full symbol processing.  */
731   struct line_header *line_header;
732   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
733      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
734      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
735      to the line header as long as this DIE is being processed.  See
736      process_die_scope.  */
737   die_info *line_header_die_owner;
738
739   /* A list of methods which need to have physnames computed
740      after all type information has been read.  */
741   VEC (delayed_method_info) *method_list;
742
743   /* To be copied to symtab->call_site_htab.  */
744   htab_t call_site_htab;
745
746   /* Non-NULL if this CU came from a DWO file.
747      There is an invariant here that is important to remember:
748      Except for attributes copied from the top level DIE in the "main"
749      (or "stub") file in preparation for reading the DWO file
750      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
751      Either there isn't a DWO file (in which case this is NULL and the point
752      is moot), or there is and either we're not going to read it (in which
753      case this is NULL) or there is and we are reading it (in which case this
754      is non-NULL).  */
755   struct dwo_unit *dwo_unit;
756
757   /* The DW_AT_addr_base attribute if present, zero otherwise
758      (zero is a valid value though).
759      Note this value comes from the Fission stub CU/TU's DIE.  */
760   ULONGEST addr_base;
761
762   /* The DW_AT_ranges_base attribute if present, zero otherwise
763      (zero is a valid value though).
764      Note this value comes from the Fission stub CU/TU's DIE.
765      Also note that the value is zero in the non-DWO case so this value can
766      be used without needing to know whether DWO files are in use or not.
767      N.B. This does not apply to DW_AT_ranges appearing in
768      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
769      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
770      DW_AT_ranges_base *would* have to be applied, and we'd have to care
771      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
772   ULONGEST ranges_base;
773
774   /* Mark used when releasing cached dies.  */
775   unsigned int mark : 1;
776
777   /* This CU references .debug_loc.  See the symtab->locations_valid field.
778      This test is imperfect as there may exist optimized debug code not using
779      any location list and still facing inlining issues if handled as
780      unoptimized code.  For a future better test see GCC PR other/32998.  */
781   unsigned int has_loclist : 1;
782
783   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
784      if all the producer_is_* fields are valid.  This information is cached
785      because profiling CU expansion showed excessive time spent in
786      producer_is_gxx_lt_4_6.  */
787   unsigned int checked_producer : 1;
788   unsigned int producer_is_gxx_lt_4_6 : 1;
789   unsigned int producer_is_gcc_lt_4_3 : 1;
790   unsigned int producer_is_icc_lt_14 : 1;
791
792   /* When set, the file that we're processing is known to have
793      debugging info for C++ namespaces.  GCC 3.3.x did not produce
794      this information, but later versions do.  */
795
796   unsigned int processing_has_namespace_info : 1;
797 };
798
799 /* Persistent data held for a compilation unit, even when not
800    processing it.  We put a pointer to this structure in the
801    read_symtab_private field of the psymtab.  */
802
803 struct dwarf2_per_cu_data
804 {
805   /* The start offset and length of this compilation unit.
806      NOTE: Unlike comp_unit_head.length, this length includes
807      initial_length_size.
808      If the DIE refers to a DWO file, this is always of the original die,
809      not the DWO file.  */
810   sect_offset sect_off;
811   unsigned int length;
812
813   /* DWARF standard version this data has been read from (such as 4 or 5).  */
814   short dwarf_version;
815
816   /* Flag indicating this compilation unit will be read in before
817      any of the current compilation units are processed.  */
818   unsigned int queued : 1;
819
820   /* This flag will be set when reading partial DIEs if we need to load
821      absolutely all DIEs for this compilation unit, instead of just the ones
822      we think are interesting.  It gets set if we look for a DIE in the
823      hash table and don't find it.  */
824   unsigned int load_all_dies : 1;
825
826   /* Non-zero if this CU is from .debug_types.
827      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
828      this is non-zero.  */
829   unsigned int is_debug_types : 1;
830
831   /* Non-zero if this CU is from the .dwz file.  */
832   unsigned int is_dwz : 1;
833
834   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
835      This flag is only valid if is_debug_types is true.
836      We can't read a CU directly from a DWO file: There are required
837      attributes in the stub.  */
838   unsigned int reading_dwo_directly : 1;
839
840   /* Non-zero if the TU has been read.
841      This is used to assist the "Stay in DWO Optimization" for Fission:
842      When reading a DWO, it's faster to read TUs from the DWO instead of
843      fetching them from random other DWOs (due to comdat folding).
844      If the TU has already been read, the optimization is unnecessary
845      (and unwise - we don't want to change where gdb thinks the TU lives
846      "midflight").
847      This flag is only valid if is_debug_types is true.  */
848   unsigned int tu_read : 1;
849
850   /* The section this CU/TU lives in.
851      If the DIE refers to a DWO file, this is always the original die,
852      not the DWO file.  */
853   struct dwarf2_section_info *section;
854
855   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
856      of the CU cache it gets reset to NULL again.  This is left as NULL for
857      dummy CUs (a CU header, but nothing else).  */
858   struct dwarf2_cu *cu;
859
860   /* The corresponding dwarf2_per_objfile.  */
861   struct dwarf2_per_objfile *dwarf2_per_objfile;
862
863   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
864      is active.  Otherwise, the 'psymtab' field is active.  */
865   union
866   {
867     /* The partial symbol table associated with this compilation unit,
868        or NULL for unread partial units.  */
869     struct partial_symtab *psymtab;
870
871     /* Data needed by the "quick" functions.  */
872     struct dwarf2_per_cu_quick_data *quick;
873   } v;
874
875   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
876      while reading psymtabs, used to compute the psymtab dependencies,
877      and then cleared.  Then it is filled in again while reading full
878      symbols, and only deleted when the objfile is destroyed.
879
880      This is also used to work around a difference between the way gold
881      generates .gdb_index version <=7 and the way gdb does.  Arguably this
882      is a gold bug.  For symbols coming from TUs, gold records in the index
883      the CU that includes the TU instead of the TU itself.  This breaks
884      dw2_lookup_symbol: It assumes that if the index says symbol X lives
885      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
886      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
887      we need to look in TU Z to find X.  Fortunately, this is akin to
888      DW_TAG_imported_unit, so we just use the same mechanism: For
889      .gdb_index version <=7 this also records the TUs that the CU referred
890      to.  Concurrently with this change gdb was modified to emit version 8
891      indices so we only pay a price for gold generated indices.
892      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
893   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
894 };
895
896 /* Entry in the signatured_types hash table.  */
897
898 struct signatured_type
899 {
900   /* The "per_cu" object of this type.
901      This struct is used iff per_cu.is_debug_types.
902      N.B.: This is the first member so that it's easy to convert pointers
903      between them.  */
904   struct dwarf2_per_cu_data per_cu;
905
906   /* The type's signature.  */
907   ULONGEST signature;
908
909   /* Offset in the TU of the type's DIE, as read from the TU header.
910      If this TU is a DWO stub and the definition lives in a DWO file
911      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
912   cu_offset type_offset_in_tu;
913
914   /* Offset in the section of the type's DIE.
915      If the definition lives in a DWO file, this is the offset in the
916      .debug_types.dwo section.
917      The value is zero until the actual value is known.
918      Zero is otherwise not a valid section offset.  */
919   sect_offset type_offset_in_section;
920
921   /* Type units are grouped by their DW_AT_stmt_list entry so that they
922      can share them.  This points to the containing symtab.  */
923   struct type_unit_group *type_unit_group;
924
925   /* The type.
926      The first time we encounter this type we fully read it in and install it
927      in the symbol tables.  Subsequent times we only need the type.  */
928   struct type *type;
929
930   /* Containing DWO unit.
931      This field is valid iff per_cu.reading_dwo_directly.  */
932   struct dwo_unit *dwo_unit;
933 };
934
935 typedef struct signatured_type *sig_type_ptr;
936 DEF_VEC_P (sig_type_ptr);
937
938 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
939    This includes type_unit_group and quick_file_names.  */
940
941 struct stmt_list_hash
942 {
943   /* The DWO unit this table is from or NULL if there is none.  */
944   struct dwo_unit *dwo_unit;
945
946   /* Offset in .debug_line or .debug_line.dwo.  */
947   sect_offset line_sect_off;
948 };
949
950 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
951    an object of this type.  */
952
953 struct type_unit_group
954 {
955   /* dwarf2read.c's main "handle" on a TU symtab.
956      To simplify things we create an artificial CU that "includes" all the
957      type units using this stmt_list so that the rest of the code still has
958      a "per_cu" handle on the symtab.
959      This PER_CU is recognized by having no section.  */
960 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
961   struct dwarf2_per_cu_data per_cu;
962
963   /* The TUs that share this DW_AT_stmt_list entry.
964      This is added to while parsing type units to build partial symtabs,
965      and is deleted afterwards and not used again.  */
966   VEC (sig_type_ptr) *tus;
967
968   /* The compunit symtab.
969      Type units in a group needn't all be defined in the same source file,
970      so we create an essentially anonymous symtab as the compunit symtab.  */
971   struct compunit_symtab *compunit_symtab;
972
973   /* The data used to construct the hash key.  */
974   struct stmt_list_hash hash;
975
976   /* The number of symtabs from the line header.
977      The value here must match line_header.num_file_names.  */
978   unsigned int num_symtabs;
979
980   /* The symbol tables for this TU (obtained from the files listed in
981      DW_AT_stmt_list).
982      WARNING: The order of entries here must match the order of entries
983      in the line header.  After the first TU using this type_unit_group, the
984      line header for the subsequent TUs is recreated from this.  This is done
985      because we need to use the same symtabs for each TU using the same
986      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
987      there's no guarantee the line header doesn't have duplicate entries.  */
988   struct symtab **symtabs;
989 };
990
991 /* These sections are what may appear in a (real or virtual) DWO file.  */
992
993 struct dwo_sections
994 {
995   struct dwarf2_section_info abbrev;
996   struct dwarf2_section_info line;
997   struct dwarf2_section_info loc;
998   struct dwarf2_section_info loclists;
999   struct dwarf2_section_info macinfo;
1000   struct dwarf2_section_info macro;
1001   struct dwarf2_section_info str;
1002   struct dwarf2_section_info str_offsets;
1003   /* In the case of a virtual DWO file, these two are unused.  */
1004   struct dwarf2_section_info info;
1005   VEC (dwarf2_section_info_def) *types;
1006 };
1007
1008 /* CUs/TUs in DWP/DWO files.  */
1009
1010 struct dwo_unit
1011 {
1012   /* Backlink to the containing struct dwo_file.  */
1013   struct dwo_file *dwo_file;
1014
1015   /* The "id" that distinguishes this CU/TU.
1016      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1017      Since signatures came first, we stick with it for consistency.  */
1018   ULONGEST signature;
1019
1020   /* The section this CU/TU lives in, in the DWO file.  */
1021   struct dwarf2_section_info *section;
1022
1023   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1024   sect_offset sect_off;
1025   unsigned int length;
1026
1027   /* For types, offset in the type's DIE of the type defined by this TU.  */
1028   cu_offset type_offset_in_tu;
1029 };
1030
1031 /* include/dwarf2.h defines the DWP section codes.
1032    It defines a max value but it doesn't define a min value, which we
1033    use for error checking, so provide one.  */
1034
1035 enum dwp_v2_section_ids
1036 {
1037   DW_SECT_MIN = 1
1038 };
1039
1040 /* Data for one DWO file.
1041
1042    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1043    appears in a DWP file).  DWP files don't really have DWO files per se -
1044    comdat folding of types "loses" the DWO file they came from, and from
1045    a high level view DWP files appear to contain a mass of random types.
1046    However, to maintain consistency with the non-DWP case we pretend DWP
1047    files contain virtual DWO files, and we assign each TU with one virtual
1048    DWO file (generally based on the line and abbrev section offsets -
1049    a heuristic that seems to work in practice).  */
1050
1051 struct dwo_file
1052 {
1053   /* The DW_AT_GNU_dwo_name attribute.
1054      For virtual DWO files the name is constructed from the section offsets
1055      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1056      from related CU+TUs.  */
1057   const char *dwo_name;
1058
1059   /* The DW_AT_comp_dir attribute.  */
1060   const char *comp_dir;
1061
1062   /* The bfd, when the file is open.  Otherwise this is NULL.
1063      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1064   bfd *dbfd;
1065
1066   /* The sections that make up this DWO file.
1067      Remember that for virtual DWO files in DWP V2, these are virtual
1068      sections (for lack of a better name).  */
1069   struct dwo_sections sections;
1070
1071   /* The CUs in the file.
1072      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1073      an extension to handle LLVM's Link Time Optimization output (where
1074      multiple source files may be compiled into a single object/dwo pair). */
1075   htab_t cus;
1076
1077   /* Table of TUs in the file.
1078      Each element is a struct dwo_unit.  */
1079   htab_t tus;
1080 };
1081
1082 /* These sections are what may appear in a DWP file.  */
1083
1084 struct dwp_sections
1085 {
1086   /* These are used by both DWP version 1 and 2.  */
1087   struct dwarf2_section_info str;
1088   struct dwarf2_section_info cu_index;
1089   struct dwarf2_section_info tu_index;
1090
1091   /* These are only used by DWP version 2 files.
1092      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1093      sections are referenced by section number, and are not recorded here.
1094      In DWP version 2 there is at most one copy of all these sections, each
1095      section being (effectively) comprised of the concatenation of all of the
1096      individual sections that exist in the version 1 format.
1097      To keep the code simple we treat each of these concatenated pieces as a
1098      section itself (a virtual section?).  */
1099   struct dwarf2_section_info abbrev;
1100   struct dwarf2_section_info info;
1101   struct dwarf2_section_info line;
1102   struct dwarf2_section_info loc;
1103   struct dwarf2_section_info macinfo;
1104   struct dwarf2_section_info macro;
1105   struct dwarf2_section_info str_offsets;
1106   struct dwarf2_section_info types;
1107 };
1108
1109 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1110    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1111
1112 struct virtual_v1_dwo_sections
1113 {
1114   struct dwarf2_section_info abbrev;
1115   struct dwarf2_section_info line;
1116   struct dwarf2_section_info loc;
1117   struct dwarf2_section_info macinfo;
1118   struct dwarf2_section_info macro;
1119   struct dwarf2_section_info str_offsets;
1120   /* Each DWP hash table entry records one CU or one TU.
1121      That is recorded here, and copied to dwo_unit.section.  */
1122   struct dwarf2_section_info info_or_types;
1123 };
1124
1125 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1126    In version 2, the sections of the DWO files are concatenated together
1127    and stored in one section of that name.  Thus each ELF section contains
1128    several "virtual" sections.  */
1129
1130 struct virtual_v2_dwo_sections
1131 {
1132   bfd_size_type abbrev_offset;
1133   bfd_size_type abbrev_size;
1134
1135   bfd_size_type line_offset;
1136   bfd_size_type line_size;
1137
1138   bfd_size_type loc_offset;
1139   bfd_size_type loc_size;
1140
1141   bfd_size_type macinfo_offset;
1142   bfd_size_type macinfo_size;
1143
1144   bfd_size_type macro_offset;
1145   bfd_size_type macro_size;
1146
1147   bfd_size_type str_offsets_offset;
1148   bfd_size_type str_offsets_size;
1149
1150   /* Each DWP hash table entry records one CU or one TU.
1151      That is recorded here, and copied to dwo_unit.section.  */
1152   bfd_size_type info_or_types_offset;
1153   bfd_size_type info_or_types_size;
1154 };
1155
1156 /* Contents of DWP hash tables.  */
1157
1158 struct dwp_hash_table
1159 {
1160   uint32_t version, nr_columns;
1161   uint32_t nr_units, nr_slots;
1162   const gdb_byte *hash_table, *unit_table;
1163   union
1164   {
1165     struct
1166     {
1167       const gdb_byte *indices;
1168     } v1;
1169     struct
1170     {
1171       /* This is indexed by column number and gives the id of the section
1172          in that column.  */
1173 #define MAX_NR_V2_DWO_SECTIONS \
1174   (1 /* .debug_info or .debug_types */ \
1175    + 1 /* .debug_abbrev */ \
1176    + 1 /* .debug_line */ \
1177    + 1 /* .debug_loc */ \
1178    + 1 /* .debug_str_offsets */ \
1179    + 1 /* .debug_macro or .debug_macinfo */)
1180       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1181       const gdb_byte *offsets;
1182       const gdb_byte *sizes;
1183     } v2;
1184   } section_pool;
1185 };
1186
1187 /* Data for one DWP file.  */
1188
1189 struct dwp_file
1190 {
1191   /* Name of the file.  */
1192   const char *name;
1193
1194   /* File format version.  */
1195   int version;
1196
1197   /* The bfd.  */
1198   bfd *dbfd;
1199
1200   /* Section info for this file.  */
1201   struct dwp_sections sections;
1202
1203   /* Table of CUs in the file.  */
1204   const struct dwp_hash_table *cus;
1205
1206   /* Table of TUs in the file.  */
1207   const struct dwp_hash_table *tus;
1208
1209   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1210   htab_t loaded_cus;
1211   htab_t loaded_tus;
1212
1213   /* Table to map ELF section numbers to their sections.
1214      This is only needed for the DWP V1 file format.  */
1215   unsigned int num_sections;
1216   asection **elf_sections;
1217 };
1218
1219 /* This represents a '.dwz' file.  */
1220
1221 struct dwz_file
1222 {
1223   /* A dwz file can only contain a few sections.  */
1224   struct dwarf2_section_info abbrev;
1225   struct dwarf2_section_info info;
1226   struct dwarf2_section_info str;
1227   struct dwarf2_section_info line;
1228   struct dwarf2_section_info macro;
1229   struct dwarf2_section_info gdb_index;
1230   struct dwarf2_section_info debug_names;
1231
1232   /* The dwz's BFD.  */
1233   bfd *dwz_bfd;
1234 };
1235
1236 /* Struct used to pass misc. parameters to read_die_and_children, et
1237    al.  which are used for both .debug_info and .debug_types dies.
1238    All parameters here are unchanging for the life of the call.  This
1239    struct exists to abstract away the constant parameters of die reading.  */
1240
1241 struct die_reader_specs
1242 {
1243   /* The bfd of die_section.  */
1244   bfd* abfd;
1245
1246   /* The CU of the DIE we are parsing.  */
1247   struct dwarf2_cu *cu;
1248
1249   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1250   struct dwo_file *dwo_file;
1251
1252   /* The section the die comes from.
1253      This is either .debug_info or .debug_types, or the .dwo variants.  */
1254   struct dwarf2_section_info *die_section;
1255
1256   /* die_section->buffer.  */
1257   const gdb_byte *buffer;
1258
1259   /* The end of the buffer.  */
1260   const gdb_byte *buffer_end;
1261
1262   /* The value of the DW_AT_comp_dir attribute.  */
1263   const char *comp_dir;
1264 };
1265
1266 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1267 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1268                                       const gdb_byte *info_ptr,
1269                                       struct die_info *comp_unit_die,
1270                                       int has_children,
1271                                       void *data);
1272
1273 /* A 1-based directory index.  This is a strong typedef to prevent
1274    accidentally using a directory index as a 0-based index into an
1275    array/vector.  */
1276 enum class dir_index : unsigned int {};
1277
1278 /* Likewise, a 1-based file name index.  */
1279 enum class file_name_index : unsigned int {};
1280
1281 struct file_entry
1282 {
1283   file_entry () = default;
1284
1285   file_entry (const char *name_, dir_index d_index_,
1286               unsigned int mod_time_, unsigned int length_)
1287     : name (name_),
1288       d_index (d_index_),
1289       mod_time (mod_time_),
1290       length (length_)
1291   {}
1292
1293   /* Return the include directory at D_INDEX stored in LH.  Returns
1294      NULL if D_INDEX is out of bounds.  */
1295   const char *include_dir (const line_header *lh) const;
1296
1297   /* The file name.  Note this is an observing pointer.  The memory is
1298      owned by debug_line_buffer.  */
1299   const char *name {};
1300
1301   /* The directory index (1-based).  */
1302   dir_index d_index {};
1303
1304   unsigned int mod_time {};
1305
1306   unsigned int length {};
1307
1308   /* True if referenced by the Line Number Program.  */
1309   bool included_p {};
1310
1311   /* The associated symbol table, if any.  */
1312   struct symtab *symtab {};
1313 };
1314
1315 /* The line number information for a compilation unit (found in the
1316    .debug_line section) begins with a "statement program header",
1317    which contains the following information.  */
1318 struct line_header
1319 {
1320   line_header ()
1321     : offset_in_dwz {}
1322   {}
1323
1324   /* Add an entry to the include directory table.  */
1325   void add_include_dir (const char *include_dir);
1326
1327   /* Add an entry to the file name table.  */
1328   void add_file_name (const char *name, dir_index d_index,
1329                       unsigned int mod_time, unsigned int length);
1330
1331   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1332      is out of bounds.  */
1333   const char *include_dir_at (dir_index index) const
1334   {
1335     /* Convert directory index number (1-based) to vector index
1336        (0-based).  */
1337     size_t vec_index = to_underlying (index) - 1;
1338
1339     if (vec_index >= include_dirs.size ())
1340       return NULL;
1341     return include_dirs[vec_index];
1342   }
1343
1344   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1345      is out of bounds.  */
1346   file_entry *file_name_at (file_name_index index)
1347   {
1348     /* Convert file name index number (1-based) to vector index
1349        (0-based).  */
1350     size_t vec_index = to_underlying (index) - 1;
1351
1352     if (vec_index >= file_names.size ())
1353       return NULL;
1354     return &file_names[vec_index];
1355   }
1356
1357   /* Const version of the above.  */
1358   const file_entry *file_name_at (unsigned int index) const
1359   {
1360     if (index >= file_names.size ())
1361       return NULL;
1362     return &file_names[index];
1363   }
1364
1365   /* Offset of line number information in .debug_line section.  */
1366   sect_offset sect_off {};
1367
1368   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1369   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1370
1371   unsigned int total_length {};
1372   unsigned short version {};
1373   unsigned int header_length {};
1374   unsigned char minimum_instruction_length {};
1375   unsigned char maximum_ops_per_instruction {};
1376   unsigned char default_is_stmt {};
1377   int line_base {};
1378   unsigned char line_range {};
1379   unsigned char opcode_base {};
1380
1381   /* standard_opcode_lengths[i] is the number of operands for the
1382      standard opcode whose value is i.  This means that
1383      standard_opcode_lengths[0] is unused, and the last meaningful
1384      element is standard_opcode_lengths[opcode_base - 1].  */
1385   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1386
1387   /* The include_directories table.  Note these are observing
1388      pointers.  The memory is owned by debug_line_buffer.  */
1389   std::vector<const char *> include_dirs;
1390
1391   /* The file_names table.  */
1392   std::vector<file_entry> file_names;
1393
1394   /* The start and end of the statement program following this
1395      header.  These point into dwarf2_per_objfile->line_buffer.  */
1396   const gdb_byte *statement_program_start {}, *statement_program_end {};
1397 };
1398
1399 typedef std::unique_ptr<line_header> line_header_up;
1400
1401 const char *
1402 file_entry::include_dir (const line_header *lh) const
1403 {
1404   return lh->include_dir_at (d_index);
1405 }
1406
1407 /* When we construct a partial symbol table entry we only
1408    need this much information.  */
1409 struct partial_die_info
1410   {
1411     /* Offset of this DIE.  */
1412     sect_offset sect_off;
1413
1414     /* DWARF-2 tag for this DIE.  */
1415     ENUM_BITFIELD(dwarf_tag) tag : 16;
1416
1417     /* Assorted flags describing the data found in this DIE.  */
1418     unsigned int has_children : 1;
1419     unsigned int is_external : 1;
1420     unsigned int is_declaration : 1;
1421     unsigned int has_type : 1;
1422     unsigned int has_specification : 1;
1423     unsigned int has_pc_info : 1;
1424     unsigned int may_be_inlined : 1;
1425
1426     /* This DIE has been marked DW_AT_main_subprogram.  */
1427     unsigned int main_subprogram : 1;
1428
1429     /* Flag set if the SCOPE field of this structure has been
1430        computed.  */
1431     unsigned int scope_set : 1;
1432
1433     /* Flag set if the DIE has a byte_size attribute.  */
1434     unsigned int has_byte_size : 1;
1435
1436     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1437     unsigned int has_const_value : 1;
1438
1439     /* Flag set if any of the DIE's children are template arguments.  */
1440     unsigned int has_template_arguments : 1;
1441
1442     /* Flag set if fixup_partial_die has been called on this die.  */
1443     unsigned int fixup_called : 1;
1444
1445     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1446     unsigned int is_dwz : 1;
1447
1448     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1449     unsigned int spec_is_dwz : 1;
1450
1451     /* The name of this DIE.  Normally the value of DW_AT_name, but
1452        sometimes a default name for unnamed DIEs.  */
1453     const char *name;
1454
1455     /* The linkage name, if present.  */
1456     const char *linkage_name;
1457
1458     /* The scope to prepend to our children.  This is generally
1459        allocated on the comp_unit_obstack, so will disappear
1460        when this compilation unit leaves the cache.  */
1461     const char *scope;
1462
1463     /* Some data associated with the partial DIE.  The tag determines
1464        which field is live.  */
1465     union
1466     {
1467       /* The location description associated with this DIE, if any.  */
1468       struct dwarf_block *locdesc;
1469       /* The offset of an import, for DW_TAG_imported_unit.  */
1470       sect_offset sect_off;
1471     } d;
1472
1473     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1474     CORE_ADDR lowpc;
1475     CORE_ADDR highpc;
1476
1477     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1478        DW_AT_sibling, if any.  */
1479     /* NOTE: This member isn't strictly necessary, read_partial_die could
1480        return DW_AT_sibling values to its caller load_partial_dies.  */
1481     const gdb_byte *sibling;
1482
1483     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1484        DW_AT_specification (or DW_AT_abstract_origin or
1485        DW_AT_extension).  */
1486     sect_offset spec_offset;
1487
1488     /* Pointers to this DIE's parent, first child, and next sibling,
1489        if any.  */
1490     struct partial_die_info *die_parent, *die_child, *die_sibling;
1491   };
1492
1493 /* This data structure holds the information of an abbrev.  */
1494 struct abbrev_info
1495   {
1496     unsigned int number;        /* number identifying abbrev */
1497     enum dwarf_tag tag;         /* dwarf tag */
1498     unsigned short has_children;                /* boolean */
1499     unsigned short num_attrs;   /* number of attributes */
1500     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1501     struct abbrev_info *next;   /* next in chain */
1502   };
1503
1504 struct attr_abbrev
1505   {
1506     ENUM_BITFIELD(dwarf_attribute) name : 16;
1507     ENUM_BITFIELD(dwarf_form) form : 16;
1508
1509     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1510     LONGEST implicit_const;
1511   };
1512
1513 /* Size of abbrev_table.abbrev_hash_table.  */
1514 #define ABBREV_HASH_SIZE 121
1515
1516 /* Top level data structure to contain an abbreviation table.  */
1517
1518 struct abbrev_table
1519 {
1520   /* Where the abbrev table came from.
1521      This is used as a sanity check when the table is used.  */
1522   sect_offset sect_off;
1523
1524   /* Storage for the abbrev table.  */
1525   struct obstack abbrev_obstack;
1526
1527   /* Hash table of abbrevs.
1528      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1529      It could be statically allocated, but the previous code didn't so we
1530      don't either.  */
1531   struct abbrev_info **abbrevs;
1532 };
1533
1534 /* Attributes have a name and a value.  */
1535 struct attribute
1536   {
1537     ENUM_BITFIELD(dwarf_attribute) name : 16;
1538     ENUM_BITFIELD(dwarf_form) form : 15;
1539
1540     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1541        field should be in u.str (existing only for DW_STRING) but it is kept
1542        here for better struct attribute alignment.  */
1543     unsigned int string_is_canonical : 1;
1544
1545     union
1546       {
1547         const char *str;
1548         struct dwarf_block *blk;
1549         ULONGEST unsnd;
1550         LONGEST snd;
1551         CORE_ADDR addr;
1552         ULONGEST signature;
1553       }
1554     u;
1555   };
1556
1557 /* This data structure holds a complete die structure.  */
1558 struct die_info
1559   {
1560     /* DWARF-2 tag for this DIE.  */
1561     ENUM_BITFIELD(dwarf_tag) tag : 16;
1562
1563     /* Number of attributes */
1564     unsigned char num_attrs;
1565
1566     /* True if we're presently building the full type name for the
1567        type derived from this DIE.  */
1568     unsigned char building_fullname : 1;
1569
1570     /* True if this die is in process.  PR 16581.  */
1571     unsigned char in_process : 1;
1572
1573     /* Abbrev number */
1574     unsigned int abbrev;
1575
1576     /* Offset in .debug_info or .debug_types section.  */
1577     sect_offset sect_off;
1578
1579     /* The dies in a compilation unit form an n-ary tree.  PARENT
1580        points to this die's parent; CHILD points to the first child of
1581        this node; and all the children of a given node are chained
1582        together via their SIBLING fields.  */
1583     struct die_info *child;     /* Its first child, if any.  */
1584     struct die_info *sibling;   /* Its next sibling, if any.  */
1585     struct die_info *parent;    /* Its parent, if any.  */
1586
1587     /* An array of attributes, with NUM_ATTRS elements.  There may be
1588        zero, but it's not common and zero-sized arrays are not
1589        sufficiently portable C.  */
1590     struct attribute attrs[1];
1591   };
1592
1593 /* Get at parts of an attribute structure.  */
1594
1595 #define DW_STRING(attr)    ((attr)->u.str)
1596 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1597 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1598 #define DW_BLOCK(attr)     ((attr)->u.blk)
1599 #define DW_SND(attr)       ((attr)->u.snd)
1600 #define DW_ADDR(attr)      ((attr)->u.addr)
1601 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1602
1603 /* Blocks are a bunch of untyped bytes.  */
1604 struct dwarf_block
1605   {
1606     size_t size;
1607
1608     /* Valid only if SIZE is not zero.  */
1609     const gdb_byte *data;
1610   };
1611
1612 #ifndef ATTR_ALLOC_CHUNK
1613 #define ATTR_ALLOC_CHUNK 4
1614 #endif
1615
1616 /* Allocate fields for structs, unions and enums in this size.  */
1617 #ifndef DW_FIELD_ALLOC_CHUNK
1618 #define DW_FIELD_ALLOC_CHUNK 4
1619 #endif
1620
1621 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1622    but this would require a corresponding change in unpack_field_as_long
1623    and friends.  */
1624 static int bits_per_byte = 8;
1625
1626 struct nextfield
1627 {
1628   struct nextfield *next;
1629   int accessibility;
1630   int virtuality;
1631   struct field field;
1632 };
1633
1634 struct nextfnfield
1635 {
1636   struct nextfnfield *next;
1637   struct fn_field fnfield;
1638 };
1639
1640 struct fnfieldlist
1641 {
1642   const char *name;
1643   int length;
1644   struct nextfnfield *head;
1645 };
1646
1647 struct decl_field_list
1648 {
1649   struct decl_field field;
1650   struct decl_field_list *next;
1651 };
1652
1653 /* The routines that read and process dies for a C struct or C++ class
1654    pass lists of data member fields and lists of member function fields
1655    in an instance of a field_info structure, as defined below.  */
1656 struct field_info
1657   {
1658     /* List of data member and baseclasses fields.  */
1659     struct nextfield *fields, *baseclasses;
1660
1661     /* Number of fields (including baseclasses).  */
1662     int nfields;
1663
1664     /* Number of baseclasses.  */
1665     int nbaseclasses;
1666
1667     /* Set if the accesibility of one of the fields is not public.  */
1668     int non_public_fields;
1669
1670     /* Member function fieldlist array, contains name of possibly overloaded
1671        member function, number of overloaded member functions and a pointer
1672        to the head of the member function field chain.  */
1673     struct fnfieldlist *fnfieldlists;
1674
1675     /* Number of entries in the fnfieldlists array.  */
1676     int nfnfields;
1677
1678     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1679        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1680     struct decl_field_list *typedef_field_list;
1681     unsigned typedef_field_list_count;
1682
1683     /* Nested types defined by this class and the number of elements in this
1684        list.  */
1685     struct decl_field_list *nested_types_list;
1686     unsigned nested_types_list_count;
1687   };
1688
1689 /* One item on the queue of compilation units to read in full symbols
1690    for.  */
1691 struct dwarf2_queue_item
1692 {
1693   struct dwarf2_per_cu_data *per_cu;
1694   enum language pretend_language;
1695   struct dwarf2_queue_item *next;
1696 };
1697
1698 /* The current queue.  */
1699 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1700
1701 /* Loaded secondary compilation units are kept in memory until they
1702    have not been referenced for the processing of this many
1703    compilation units.  Set this to zero to disable caching.  Cache
1704    sizes of up to at least twenty will improve startup time for
1705    typical inter-CU-reference binaries, at an obvious memory cost.  */
1706 static int dwarf_max_cache_age = 5;
1707 static void
1708 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1709                           struct cmd_list_element *c, const char *value)
1710 {
1711   fprintf_filtered (file, _("The upper bound on the age of cached "
1712                             "DWARF compilation units is %s.\n"),
1713                     value);
1714 }
1715 \f
1716 /* local function prototypes */
1717
1718 static const char *get_section_name (const struct dwarf2_section_info *);
1719
1720 static const char *get_section_file_name (const struct dwarf2_section_info *);
1721
1722 static void dwarf2_find_base_address (struct die_info *die,
1723                                       struct dwarf2_cu *cu);
1724
1725 static struct partial_symtab *create_partial_symtab
1726   (struct dwarf2_per_cu_data *per_cu, const char *name);
1727
1728 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1729                                         const gdb_byte *info_ptr,
1730                                         struct die_info *type_unit_die,
1731                                         int has_children, void *data);
1732
1733 static void dwarf2_build_psymtabs_hard
1734   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1735
1736 static void scan_partial_symbols (struct partial_die_info *,
1737                                   CORE_ADDR *, CORE_ADDR *,
1738                                   int, struct dwarf2_cu *);
1739
1740 static void add_partial_symbol (struct partial_die_info *,
1741                                 struct dwarf2_cu *);
1742
1743 static void add_partial_namespace (struct partial_die_info *pdi,
1744                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1745                                    int set_addrmap, struct dwarf2_cu *cu);
1746
1747 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1748                                 CORE_ADDR *highpc, int set_addrmap,
1749                                 struct dwarf2_cu *cu);
1750
1751 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1752                                      struct dwarf2_cu *cu);
1753
1754 static void add_partial_subprogram (struct partial_die_info *pdi,
1755                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1756                                     int need_pc, struct dwarf2_cu *cu);
1757
1758 static void dwarf2_read_symtab (struct partial_symtab *,
1759                                 struct objfile *);
1760
1761 static void psymtab_to_symtab_1 (struct partial_symtab *);
1762
1763 static struct abbrev_info *abbrev_table_lookup_abbrev
1764   (const struct abbrev_table *, unsigned int);
1765
1766 static struct abbrev_table *abbrev_table_read_table
1767   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1768    sect_offset);
1769
1770 static void abbrev_table_free (struct abbrev_table *);
1771
1772 static void abbrev_table_free_cleanup (void *);
1773
1774 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1775                                  struct dwarf2_section_info *);
1776
1777 static void dwarf2_free_abbrev_table (void *);
1778
1779 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1780
1781 static struct partial_die_info *load_partial_dies
1782   (const struct die_reader_specs *, const gdb_byte *, int);
1783
1784 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1785                                          struct partial_die_info *,
1786                                          struct abbrev_info *,
1787                                          unsigned int,
1788                                          const gdb_byte *);
1789
1790 static struct partial_die_info *find_partial_die (sect_offset, int,
1791                                                   struct dwarf2_cu *);
1792
1793 static void fixup_partial_die (struct partial_die_info *,
1794                                struct dwarf2_cu *);
1795
1796 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1797                                        struct attribute *, struct attr_abbrev *,
1798                                        const gdb_byte *);
1799
1800 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1801
1802 static int read_1_signed_byte (bfd *, const gdb_byte *);
1803
1804 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1805
1806 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1807
1808 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1809
1810 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1811                                unsigned int *);
1812
1813 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1814
1815 static LONGEST read_checked_initial_length_and_offset
1816   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1817    unsigned int *, unsigned int *);
1818
1819 static LONGEST read_offset (bfd *, const gdb_byte *,
1820                             const struct comp_unit_head *,
1821                             unsigned int *);
1822
1823 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1824
1825 static sect_offset read_abbrev_offset
1826   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1827    struct dwarf2_section_info *, sect_offset);
1828
1829 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1830
1831 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1832
1833 static const char *read_indirect_string
1834   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1835    const struct comp_unit_head *, unsigned int *);
1836
1837 static const char *read_indirect_line_string
1838   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1839    const struct comp_unit_head *, unsigned int *);
1840
1841 static const char *read_indirect_string_at_offset
1842   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1843    LONGEST str_offset);
1844
1845 static const char *read_indirect_string_from_dwz
1846   (struct objfile *objfile, struct dwz_file *, LONGEST);
1847
1848 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1849
1850 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1851                                               const gdb_byte *,
1852                                               unsigned int *);
1853
1854 static const char *read_str_index (const struct die_reader_specs *reader,
1855                                    ULONGEST str_index);
1856
1857 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1858
1859 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1860                                       struct dwarf2_cu *);
1861
1862 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1863                                                 unsigned int);
1864
1865 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1866                                        struct dwarf2_cu *cu);
1867
1868 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1869                                struct dwarf2_cu *cu);
1870
1871 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1872
1873 static struct die_info *die_specification (struct die_info *die,
1874                                            struct dwarf2_cu **);
1875
1876 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1877                                                 struct dwarf2_cu *cu);
1878
1879 static void dwarf_decode_lines (struct line_header *, const char *,
1880                                 struct dwarf2_cu *, struct partial_symtab *,
1881                                 CORE_ADDR, int decode_mapping);
1882
1883 static void dwarf2_start_subfile (const char *, const char *);
1884
1885 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1886                                                     const char *, const char *,
1887                                                     CORE_ADDR);
1888
1889 static struct symbol *new_symbol (struct die_info *, struct type *,
1890                                   struct dwarf2_cu *);
1891
1892 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1893                                        struct dwarf2_cu *, struct symbol *);
1894
1895 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1896                                 struct dwarf2_cu *);
1897
1898 static void dwarf2_const_value_attr (const struct attribute *attr,
1899                                      struct type *type,
1900                                      const char *name,
1901                                      struct obstack *obstack,
1902                                      struct dwarf2_cu *cu, LONGEST *value,
1903                                      const gdb_byte **bytes,
1904                                      struct dwarf2_locexpr_baton **baton);
1905
1906 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1907
1908 static int need_gnat_info (struct dwarf2_cu *);
1909
1910 static struct type *die_descriptive_type (struct die_info *,
1911                                           struct dwarf2_cu *);
1912
1913 static void set_descriptive_type (struct type *, struct die_info *,
1914                                   struct dwarf2_cu *);
1915
1916 static struct type *die_containing_type (struct die_info *,
1917                                          struct dwarf2_cu *);
1918
1919 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1920                                      struct dwarf2_cu *);
1921
1922 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1923
1924 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1925
1926 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1927
1928 static char *typename_concat (struct obstack *obs, const char *prefix,
1929                               const char *suffix, int physname,
1930                               struct dwarf2_cu *cu);
1931
1932 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1933
1934 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1935
1936 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1937
1938 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1939
1940 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1941
1942 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1943
1944 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1945                                struct dwarf2_cu *, struct partial_symtab *);
1946
1947 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1948    values.  Keep the items ordered with increasing constraints compliance.  */
1949 enum pc_bounds_kind
1950 {
1951   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1952   PC_BOUNDS_NOT_PRESENT,
1953
1954   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1955      were present but they do not form a valid range of PC addresses.  */
1956   PC_BOUNDS_INVALID,
1957
1958   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1959   PC_BOUNDS_RANGES,
1960
1961   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1962   PC_BOUNDS_HIGH_LOW,
1963 };
1964
1965 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1966                                                  CORE_ADDR *, CORE_ADDR *,
1967                                                  struct dwarf2_cu *,
1968                                                  struct partial_symtab *);
1969
1970 static void get_scope_pc_bounds (struct die_info *,
1971                                  CORE_ADDR *, CORE_ADDR *,
1972                                  struct dwarf2_cu *);
1973
1974 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1975                                         CORE_ADDR, struct dwarf2_cu *);
1976
1977 static void dwarf2_add_field (struct field_info *, struct die_info *,
1978                               struct dwarf2_cu *);
1979
1980 static void dwarf2_attach_fields_to_type (struct field_info *,
1981                                           struct type *, struct dwarf2_cu *);
1982
1983 static void dwarf2_add_member_fn (struct field_info *,
1984                                   struct die_info *, struct type *,
1985                                   struct dwarf2_cu *);
1986
1987 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1988                                              struct type *,
1989                                              struct dwarf2_cu *);
1990
1991 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1992
1993 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1994
1995 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1996
1997 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1998
1999 static struct using_direct **using_directives (enum language);
2000
2001 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
2002
2003 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
2004
2005 static struct type *read_module_type (struct die_info *die,
2006                                       struct dwarf2_cu *cu);
2007
2008 static const char *namespace_name (struct die_info *die,
2009                                    int *is_anonymous, struct dwarf2_cu *);
2010
2011 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2012
2013 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2014
2015 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2016                                                        struct dwarf2_cu *);
2017
2018 static struct die_info *read_die_and_siblings_1
2019   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2020    struct die_info *);
2021
2022 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2023                                                const gdb_byte *info_ptr,
2024                                                const gdb_byte **new_info_ptr,
2025                                                struct die_info *parent);
2026
2027 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2028                                         struct die_info **, const gdb_byte *,
2029                                         int *, int);
2030
2031 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2032                                       struct die_info **, const gdb_byte *,
2033                                       int *);
2034
2035 static void process_die (struct die_info *, struct dwarf2_cu *);
2036
2037 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2038                                              struct obstack *);
2039
2040 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2041
2042 static const char *dwarf2_full_name (const char *name,
2043                                      struct die_info *die,
2044                                      struct dwarf2_cu *cu);
2045
2046 static const char *dwarf2_physname (const char *name, struct die_info *die,
2047                                     struct dwarf2_cu *cu);
2048
2049 static struct die_info *dwarf2_extension (struct die_info *die,
2050                                           struct dwarf2_cu **);
2051
2052 static const char *dwarf_tag_name (unsigned int);
2053
2054 static const char *dwarf_attr_name (unsigned int);
2055
2056 static const char *dwarf_form_name (unsigned int);
2057
2058 static const char *dwarf_bool_name (unsigned int);
2059
2060 static const char *dwarf_type_encoding_name (unsigned int);
2061
2062 static struct die_info *sibling_die (struct die_info *);
2063
2064 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2065
2066 static void dump_die_for_error (struct die_info *);
2067
2068 static void dump_die_1 (struct ui_file *, int level, int max_level,
2069                         struct die_info *);
2070
2071 /*static*/ void dump_die (struct die_info *, int max_level);
2072
2073 static void store_in_ref_table (struct die_info *,
2074                                 struct dwarf2_cu *);
2075
2076 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2077
2078 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2079
2080 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2081                                                const struct attribute *,
2082                                                struct dwarf2_cu **);
2083
2084 static struct die_info *follow_die_ref (struct die_info *,
2085                                         const struct attribute *,
2086                                         struct dwarf2_cu **);
2087
2088 static struct die_info *follow_die_sig (struct die_info *,
2089                                         const struct attribute *,
2090                                         struct dwarf2_cu **);
2091
2092 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2093                                          struct dwarf2_cu *);
2094
2095 static struct type *get_DW_AT_signature_type (struct die_info *,
2096                                               const struct attribute *,
2097                                               struct dwarf2_cu *);
2098
2099 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2100
2101 static void read_signatured_type (struct signatured_type *);
2102
2103 static int attr_to_dynamic_prop (const struct attribute *attr,
2104                                  struct die_info *die, struct dwarf2_cu *cu,
2105                                  struct dynamic_prop *prop);
2106
2107 /* memory allocation interface */
2108
2109 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2110
2111 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2112
2113 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2114
2115 static int attr_form_is_block (const struct attribute *);
2116
2117 static int attr_form_is_section_offset (const struct attribute *);
2118
2119 static int attr_form_is_constant (const struct attribute *);
2120
2121 static int attr_form_is_ref (const struct attribute *);
2122
2123 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2124                                    struct dwarf2_loclist_baton *baton,
2125                                    const struct attribute *attr);
2126
2127 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2128                                          struct symbol *sym,
2129                                          struct dwarf2_cu *cu,
2130                                          int is_block);
2131
2132 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2133                                      const gdb_byte *info_ptr,
2134                                      struct abbrev_info *abbrev);
2135
2136 static void free_stack_comp_unit (void *);
2137
2138 static hashval_t partial_die_hash (const void *item);
2139
2140 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2141
2142 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2143   (sect_offset sect_off, unsigned int offset_in_dwz,
2144    struct dwarf2_per_objfile *dwarf2_per_objfile);
2145
2146 static void init_one_comp_unit (struct dwarf2_cu *cu,
2147                                 struct dwarf2_per_cu_data *per_cu);
2148
2149 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2150                                    struct die_info *comp_unit_die,
2151                                    enum language pretend_language);
2152
2153 static void free_heap_comp_unit (void *);
2154
2155 static void free_cached_comp_units (void *);
2156
2157 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2158
2159 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2160
2161 static struct type *set_die_type (struct die_info *, struct type *,
2162                                   struct dwarf2_cu *);
2163
2164 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2165
2166 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2167
2168 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2169                                  enum language);
2170
2171 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2172                                     enum language);
2173
2174 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2175                                     enum language);
2176
2177 static void dwarf2_add_dependence (struct dwarf2_cu *,
2178                                    struct dwarf2_per_cu_data *);
2179
2180 static void dwarf2_mark (struct dwarf2_cu *);
2181
2182 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2183
2184 static struct type *get_die_type_at_offset (sect_offset,
2185                                             struct dwarf2_per_cu_data *);
2186
2187 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2188
2189 static void dwarf2_release_queue (void *dummy);
2190
2191 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2192                              enum language pretend_language);
2193
2194 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2195
2196 /* The return type of find_file_and_directory.  Note, the enclosed
2197    string pointers are only valid while this object is valid.  */
2198
2199 struct file_and_directory
2200 {
2201   /* The filename.  This is never NULL.  */
2202   const char *name;
2203
2204   /* The compilation directory.  NULL if not known.  If we needed to
2205      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2206      points directly to the DW_AT_comp_dir string attribute owned by
2207      the obstack that owns the DIE.  */
2208   const char *comp_dir;
2209
2210   /* If we needed to build a new string for comp_dir, this is what
2211      owns the storage.  */
2212   std::string comp_dir_storage;
2213 };
2214
2215 static file_and_directory find_file_and_directory (struct die_info *die,
2216                                                    struct dwarf2_cu *cu);
2217
2218 static char *file_full_name (int file, struct line_header *lh,
2219                              const char *comp_dir);
2220
2221 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2222 enum class rcuh_kind { COMPILE, TYPE };
2223
2224 static const gdb_byte *read_and_check_comp_unit_head
2225   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2226    struct comp_unit_head *header,
2227    struct dwarf2_section_info *section,
2228    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2229    rcuh_kind section_kind);
2230
2231 static void init_cutu_and_read_dies
2232   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2233    int use_existing_cu, int keep,
2234    die_reader_func_ftype *die_reader_func, void *data);
2235
2236 static void init_cutu_and_read_dies_simple
2237   (struct dwarf2_per_cu_data *this_cu,
2238    die_reader_func_ftype *die_reader_func, void *data);
2239
2240 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2241
2242 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2243
2244 static struct dwo_unit *lookup_dwo_unit_in_dwp
2245   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2246    struct dwp_file *dwp_file, const char *comp_dir,
2247    ULONGEST signature, int is_debug_types);
2248
2249 static struct dwp_file *get_dwp_file
2250   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2251
2252 static struct dwo_unit *lookup_dwo_comp_unit
2253   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2254
2255 static struct dwo_unit *lookup_dwo_type_unit
2256   (struct signatured_type *, const char *, const char *);
2257
2258 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2259
2260 static void free_dwo_file_cleanup (void *);
2261
2262 struct free_dwo_file_cleanup_data
2263 {
2264   struct dwo_file *dwo_file;
2265   struct dwarf2_per_objfile *dwarf2_per_objfile;
2266 };
2267
2268 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2269
2270 static void check_producer (struct dwarf2_cu *cu);
2271
2272 static void free_line_header_voidp (void *arg);
2273 \f
2274 /* Various complaints about symbol reading that don't abort the process.  */
2275
2276 static void
2277 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2278 {
2279   complaint (&symfile_complaints,
2280              _("statement list doesn't fit in .debug_line section"));
2281 }
2282
2283 static void
2284 dwarf2_debug_line_missing_file_complaint (void)
2285 {
2286   complaint (&symfile_complaints,
2287              _(".debug_line section has line data without a file"));
2288 }
2289
2290 static void
2291 dwarf2_debug_line_missing_end_sequence_complaint (void)
2292 {
2293   complaint (&symfile_complaints,
2294              _(".debug_line section has line "
2295                "program sequence without an end"));
2296 }
2297
2298 static void
2299 dwarf2_complex_location_expr_complaint (void)
2300 {
2301   complaint (&symfile_complaints, _("location expression too complex"));
2302 }
2303
2304 static void
2305 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2306                                               int arg3)
2307 {
2308   complaint (&symfile_complaints,
2309              _("const value length mismatch for '%s', got %d, expected %d"),
2310              arg1, arg2, arg3);
2311 }
2312
2313 static void
2314 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2315 {
2316   complaint (&symfile_complaints,
2317              _("debug info runs off end of %s section"
2318                " [in module %s]"),
2319              get_section_name (section),
2320              get_section_file_name (section));
2321 }
2322
2323 static void
2324 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2325 {
2326   complaint (&symfile_complaints,
2327              _("macro debug info contains a "
2328                "malformed macro definition:\n`%s'"),
2329              arg1);
2330 }
2331
2332 static void
2333 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2334 {
2335   complaint (&symfile_complaints,
2336              _("invalid attribute class or form for '%s' in '%s'"),
2337              arg1, arg2);
2338 }
2339
2340 /* Hash function for line_header_hash.  */
2341
2342 static hashval_t
2343 line_header_hash (const struct line_header *ofs)
2344 {
2345   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2346 }
2347
2348 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2349
2350 static hashval_t
2351 line_header_hash_voidp (const void *item)
2352 {
2353   const struct line_header *ofs = (const struct line_header *) item;
2354
2355   return line_header_hash (ofs);
2356 }
2357
2358 /* Equality function for line_header_hash.  */
2359
2360 static int
2361 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2362 {
2363   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2364   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2365
2366   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2367           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2368 }
2369
2370 \f
2371
2372 /* Read the given attribute value as an address, taking the attribute's
2373    form into account.  */
2374
2375 static CORE_ADDR
2376 attr_value_as_address (struct attribute *attr)
2377 {
2378   CORE_ADDR addr;
2379
2380   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2381     {
2382       /* Aside from a few clearly defined exceptions, attributes that
2383          contain an address must always be in DW_FORM_addr form.
2384          Unfortunately, some compilers happen to be violating this
2385          requirement by encoding addresses using other forms, such
2386          as DW_FORM_data4 for example.  For those broken compilers,
2387          we try to do our best, without any guarantee of success,
2388          to interpret the address correctly.  It would also be nice
2389          to generate a complaint, but that would require us to maintain
2390          a list of legitimate cases where a non-address form is allowed,
2391          as well as update callers to pass in at least the CU's DWARF
2392          version.  This is more overhead than what we're willing to
2393          expand for a pretty rare case.  */
2394       addr = DW_UNSND (attr);
2395     }
2396   else
2397     addr = DW_ADDR (attr);
2398
2399   return addr;
2400 }
2401
2402 /* The suffix for an index file.  */
2403 #define INDEX4_SUFFIX ".gdb-index"
2404 #define INDEX5_SUFFIX ".debug_names"
2405 #define DEBUG_STR_SUFFIX ".debug_str"
2406
2407 /* See declaration.  */
2408
2409 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2410                                         const dwarf2_debug_sections *names)
2411   : objfile (objfile_)
2412 {
2413   if (names == NULL)
2414     names = &dwarf2_elf_names;
2415
2416   bfd *obfd = objfile->obfd;
2417
2418   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2419     locate_sections (obfd, sec, *names);
2420 }
2421
2422 dwarf2_per_objfile::~dwarf2_per_objfile ()
2423 {
2424   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2425   free_cached_comp_units ();
2426
2427   if (quick_file_names_table)
2428     htab_delete (quick_file_names_table);
2429
2430   if (line_header_hash)
2431     htab_delete (line_header_hash);
2432
2433   /* Everything else should be on the objfile obstack.  */
2434 }
2435
2436 /* See declaration.  */
2437
2438 void
2439 dwarf2_per_objfile::free_cached_comp_units ()
2440 {
2441   dwarf2_per_cu_data *per_cu = read_in_chain;
2442   dwarf2_per_cu_data **last_chain = &read_in_chain;
2443   while (per_cu != NULL)
2444     {
2445       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2446
2447       free_heap_comp_unit (per_cu->cu);
2448       *last_chain = next_cu;
2449       per_cu = next_cu;
2450     }
2451 }
2452
2453 /* Try to locate the sections we need for DWARF 2 debugging
2454    information and return true if we have enough to do something.
2455    NAMES points to the dwarf2 section names, or is NULL if the standard
2456    ELF names are used.  */
2457
2458 int
2459 dwarf2_has_info (struct objfile *objfile,
2460                  const struct dwarf2_debug_sections *names)
2461 {
2462   if (objfile->flags & OBJF_READNEVER)
2463     return 0;
2464
2465   struct dwarf2_per_objfile *dwarf2_per_objfile
2466     = get_dwarf2_per_objfile (objfile);
2467
2468   if (dwarf2_per_objfile == NULL)
2469     {
2470       /* Initialize per-objfile state.  */
2471       struct dwarf2_per_objfile *data
2472         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2473
2474       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2475       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2476     }
2477   return (!dwarf2_per_objfile->info.is_virtual
2478           && dwarf2_per_objfile->info.s.section != NULL
2479           && !dwarf2_per_objfile->abbrev.is_virtual
2480           && dwarf2_per_objfile->abbrev.s.section != NULL);
2481 }
2482
2483 /* Return the containing section of virtual section SECTION.  */
2484
2485 static struct dwarf2_section_info *
2486 get_containing_section (const struct dwarf2_section_info *section)
2487 {
2488   gdb_assert (section->is_virtual);
2489   return section->s.containing_section;
2490 }
2491
2492 /* Return the bfd owner of SECTION.  */
2493
2494 static struct bfd *
2495 get_section_bfd_owner (const struct dwarf2_section_info *section)
2496 {
2497   if (section->is_virtual)
2498     {
2499       section = get_containing_section (section);
2500       gdb_assert (!section->is_virtual);
2501     }
2502   return section->s.section->owner;
2503 }
2504
2505 /* Return the bfd section of SECTION.
2506    Returns NULL if the section is not present.  */
2507
2508 static asection *
2509 get_section_bfd_section (const struct dwarf2_section_info *section)
2510 {
2511   if (section->is_virtual)
2512     {
2513       section = get_containing_section (section);
2514       gdb_assert (!section->is_virtual);
2515     }
2516   return section->s.section;
2517 }
2518
2519 /* Return the name of SECTION.  */
2520
2521 static const char *
2522 get_section_name (const struct dwarf2_section_info *section)
2523 {
2524   asection *sectp = get_section_bfd_section (section);
2525
2526   gdb_assert (sectp != NULL);
2527   return bfd_section_name (get_section_bfd_owner (section), sectp);
2528 }
2529
2530 /* Return the name of the file SECTION is in.  */
2531
2532 static const char *
2533 get_section_file_name (const struct dwarf2_section_info *section)
2534 {
2535   bfd *abfd = get_section_bfd_owner (section);
2536
2537   return bfd_get_filename (abfd);
2538 }
2539
2540 /* Return the id of SECTION.
2541    Returns 0 if SECTION doesn't exist.  */
2542
2543 static int
2544 get_section_id (const struct dwarf2_section_info *section)
2545 {
2546   asection *sectp = get_section_bfd_section (section);
2547
2548   if (sectp == NULL)
2549     return 0;
2550   return sectp->id;
2551 }
2552
2553 /* Return the flags of SECTION.
2554    SECTION (or containing section if this is a virtual section) must exist.  */
2555
2556 static int
2557 get_section_flags (const struct dwarf2_section_info *section)
2558 {
2559   asection *sectp = get_section_bfd_section (section);
2560
2561   gdb_assert (sectp != NULL);
2562   return bfd_get_section_flags (sectp->owner, sectp);
2563 }
2564
2565 /* When loading sections, we look either for uncompressed section or for
2566    compressed section names.  */
2567
2568 static int
2569 section_is_p (const char *section_name,
2570               const struct dwarf2_section_names *names)
2571 {
2572   if (names->normal != NULL
2573       && strcmp (section_name, names->normal) == 0)
2574     return 1;
2575   if (names->compressed != NULL
2576       && strcmp (section_name, names->compressed) == 0)
2577     return 1;
2578   return 0;
2579 }
2580
2581 /* See declaration.  */
2582
2583 void
2584 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2585                                      const dwarf2_debug_sections &names)
2586 {
2587   flagword aflag = bfd_get_section_flags (abfd, sectp);
2588
2589   if ((aflag & SEC_HAS_CONTENTS) == 0)
2590     {
2591     }
2592   else if (section_is_p (sectp->name, &names.info))
2593     {
2594       this->info.s.section = sectp;
2595       this->info.size = bfd_get_section_size (sectp);
2596     }
2597   else if (section_is_p (sectp->name, &names.abbrev))
2598     {
2599       this->abbrev.s.section = sectp;
2600       this->abbrev.size = bfd_get_section_size (sectp);
2601     }
2602   else if (section_is_p (sectp->name, &names.line))
2603     {
2604       this->line.s.section = sectp;
2605       this->line.size = bfd_get_section_size (sectp);
2606     }
2607   else if (section_is_p (sectp->name, &names.loc))
2608     {
2609       this->loc.s.section = sectp;
2610       this->loc.size = bfd_get_section_size (sectp);
2611     }
2612   else if (section_is_p (sectp->name, &names.loclists))
2613     {
2614       this->loclists.s.section = sectp;
2615       this->loclists.size = bfd_get_section_size (sectp);
2616     }
2617   else if (section_is_p (sectp->name, &names.macinfo))
2618     {
2619       this->macinfo.s.section = sectp;
2620       this->macinfo.size = bfd_get_section_size (sectp);
2621     }
2622   else if (section_is_p (sectp->name, &names.macro))
2623     {
2624       this->macro.s.section = sectp;
2625       this->macro.size = bfd_get_section_size (sectp);
2626     }
2627   else if (section_is_p (sectp->name, &names.str))
2628     {
2629       this->str.s.section = sectp;
2630       this->str.size = bfd_get_section_size (sectp);
2631     }
2632   else if (section_is_p (sectp->name, &names.line_str))
2633     {
2634       this->line_str.s.section = sectp;
2635       this->line_str.size = bfd_get_section_size (sectp);
2636     }
2637   else if (section_is_p (sectp->name, &names.addr))
2638     {
2639       this->addr.s.section = sectp;
2640       this->addr.size = bfd_get_section_size (sectp);
2641     }
2642   else if (section_is_p (sectp->name, &names.frame))
2643     {
2644       this->frame.s.section = sectp;
2645       this->frame.size = bfd_get_section_size (sectp);
2646     }
2647   else if (section_is_p (sectp->name, &names.eh_frame))
2648     {
2649       this->eh_frame.s.section = sectp;
2650       this->eh_frame.size = bfd_get_section_size (sectp);
2651     }
2652   else if (section_is_p (sectp->name, &names.ranges))
2653     {
2654       this->ranges.s.section = sectp;
2655       this->ranges.size = bfd_get_section_size (sectp);
2656     }
2657   else if (section_is_p (sectp->name, &names.rnglists))
2658     {
2659       this->rnglists.s.section = sectp;
2660       this->rnglists.size = bfd_get_section_size (sectp);
2661     }
2662   else if (section_is_p (sectp->name, &names.types))
2663     {
2664       struct dwarf2_section_info type_section;
2665
2666       memset (&type_section, 0, sizeof (type_section));
2667       type_section.s.section = sectp;
2668       type_section.size = bfd_get_section_size (sectp);
2669
2670       VEC_safe_push (dwarf2_section_info_def, this->types,
2671                      &type_section);
2672     }
2673   else if (section_is_p (sectp->name, &names.gdb_index))
2674     {
2675       this->gdb_index.s.section = sectp;
2676       this->gdb_index.size = bfd_get_section_size (sectp);
2677     }
2678   else if (section_is_p (sectp->name, &names.debug_names))
2679     {
2680       this->debug_names.s.section = sectp;
2681       this->debug_names.size = bfd_get_section_size (sectp);
2682     }
2683   else if (section_is_p (sectp->name, &names.debug_aranges))
2684     {
2685       this->debug_aranges.s.section = sectp;
2686       this->debug_aranges.size = bfd_get_section_size (sectp);
2687     }
2688
2689   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2690       && bfd_section_vma (abfd, sectp) == 0)
2691     this->has_section_at_zero = true;
2692 }
2693
2694 /* A helper function that decides whether a section is empty,
2695    or not present.  */
2696
2697 static int
2698 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2699 {
2700   if (section->is_virtual)
2701     return section->size == 0;
2702   return section->s.section == NULL || section->size == 0;
2703 }
2704
2705 /* Read the contents of the section INFO.
2706    OBJFILE is the main object file, but not necessarily the file where
2707    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2708    of the DWO file.
2709    If the section is compressed, uncompress it before returning.  */
2710
2711 static void
2712 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2713 {
2714   asection *sectp;
2715   bfd *abfd;
2716   gdb_byte *buf, *retbuf;
2717
2718   if (info->readin)
2719     return;
2720   info->buffer = NULL;
2721   info->readin = 1;
2722
2723   if (dwarf2_section_empty_p (info))
2724     return;
2725
2726   sectp = get_section_bfd_section (info);
2727
2728   /* If this is a virtual section we need to read in the real one first.  */
2729   if (info->is_virtual)
2730     {
2731       struct dwarf2_section_info *containing_section =
2732         get_containing_section (info);
2733
2734       gdb_assert (sectp != NULL);
2735       if ((sectp->flags & SEC_RELOC) != 0)
2736         {
2737           error (_("Dwarf Error: DWP format V2 with relocations is not"
2738                    " supported in section %s [in module %s]"),
2739                  get_section_name (info), get_section_file_name (info));
2740         }
2741       dwarf2_read_section (objfile, containing_section);
2742       /* Other code should have already caught virtual sections that don't
2743          fit.  */
2744       gdb_assert (info->virtual_offset + info->size
2745                   <= containing_section->size);
2746       /* If the real section is empty or there was a problem reading the
2747          section we shouldn't get here.  */
2748       gdb_assert (containing_section->buffer != NULL);
2749       info->buffer = containing_section->buffer + info->virtual_offset;
2750       return;
2751     }
2752
2753   /* If the section has relocations, we must read it ourselves.
2754      Otherwise we attach it to the BFD.  */
2755   if ((sectp->flags & SEC_RELOC) == 0)
2756     {
2757       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2758       return;
2759     }
2760
2761   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2762   info->buffer = buf;
2763
2764   /* When debugging .o files, we may need to apply relocations; see
2765      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2766      We never compress sections in .o files, so we only need to
2767      try this when the section is not compressed.  */
2768   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2769   if (retbuf != NULL)
2770     {
2771       info->buffer = retbuf;
2772       return;
2773     }
2774
2775   abfd = get_section_bfd_owner (info);
2776   gdb_assert (abfd != NULL);
2777
2778   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2779       || bfd_bread (buf, info->size, abfd) != info->size)
2780     {
2781       error (_("Dwarf Error: Can't read DWARF data"
2782                " in section %s [in module %s]"),
2783              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2784     }
2785 }
2786
2787 /* A helper function that returns the size of a section in a safe way.
2788    If you are positive that the section has been read before using the
2789    size, then it is safe to refer to the dwarf2_section_info object's
2790    "size" field directly.  In other cases, you must call this
2791    function, because for compressed sections the size field is not set
2792    correctly until the section has been read.  */
2793
2794 static bfd_size_type
2795 dwarf2_section_size (struct objfile *objfile,
2796                      struct dwarf2_section_info *info)
2797 {
2798   if (!info->readin)
2799     dwarf2_read_section (objfile, info);
2800   return info->size;
2801 }
2802
2803 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2804    SECTION_NAME.  */
2805
2806 void
2807 dwarf2_get_section_info (struct objfile *objfile,
2808                          enum dwarf2_section_enum sect,
2809                          asection **sectp, const gdb_byte **bufp,
2810                          bfd_size_type *sizep)
2811 {
2812   struct dwarf2_per_objfile *data
2813     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2814                                                   dwarf2_objfile_data_key);
2815   struct dwarf2_section_info *info;
2816
2817   /* We may see an objfile without any DWARF, in which case we just
2818      return nothing.  */
2819   if (data == NULL)
2820     {
2821       *sectp = NULL;
2822       *bufp = NULL;
2823       *sizep = 0;
2824       return;
2825     }
2826   switch (sect)
2827     {
2828     case DWARF2_DEBUG_FRAME:
2829       info = &data->frame;
2830       break;
2831     case DWARF2_EH_FRAME:
2832       info = &data->eh_frame;
2833       break;
2834     default:
2835       gdb_assert_not_reached ("unexpected section");
2836     }
2837
2838   dwarf2_read_section (objfile, info);
2839
2840   *sectp = get_section_bfd_section (info);
2841   *bufp = info->buffer;
2842   *sizep = info->size;
2843 }
2844
2845 /* A helper function to find the sections for a .dwz file.  */
2846
2847 static void
2848 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2849 {
2850   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2851
2852   /* Note that we only support the standard ELF names, because .dwz
2853      is ELF-only (at the time of writing).  */
2854   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2855     {
2856       dwz_file->abbrev.s.section = sectp;
2857       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2858     }
2859   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2860     {
2861       dwz_file->info.s.section = sectp;
2862       dwz_file->info.size = bfd_get_section_size (sectp);
2863     }
2864   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2865     {
2866       dwz_file->str.s.section = sectp;
2867       dwz_file->str.size = bfd_get_section_size (sectp);
2868     }
2869   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2870     {
2871       dwz_file->line.s.section = sectp;
2872       dwz_file->line.size = bfd_get_section_size (sectp);
2873     }
2874   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2875     {
2876       dwz_file->macro.s.section = sectp;
2877       dwz_file->macro.size = bfd_get_section_size (sectp);
2878     }
2879   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2880     {
2881       dwz_file->gdb_index.s.section = sectp;
2882       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2883     }
2884   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2885     {
2886       dwz_file->debug_names.s.section = sectp;
2887       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2888     }
2889 }
2890
2891 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2892    there is no .gnu_debugaltlink section in the file.  Error if there
2893    is such a section but the file cannot be found.  */
2894
2895 static struct dwz_file *
2896 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2897 {
2898   const char *filename;
2899   struct dwz_file *result;
2900   bfd_size_type buildid_len_arg;
2901   size_t buildid_len;
2902   bfd_byte *buildid;
2903
2904   if (dwarf2_per_objfile->dwz_file != NULL)
2905     return dwarf2_per_objfile->dwz_file;
2906
2907   bfd_set_error (bfd_error_no_error);
2908   gdb::unique_xmalloc_ptr<char> data
2909     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2910                                   &buildid_len_arg, &buildid));
2911   if (data == NULL)
2912     {
2913       if (bfd_get_error () == bfd_error_no_error)
2914         return NULL;
2915       error (_("could not read '.gnu_debugaltlink' section: %s"),
2916              bfd_errmsg (bfd_get_error ()));
2917     }
2918
2919   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2920
2921   buildid_len = (size_t) buildid_len_arg;
2922
2923   filename = data.get ();
2924
2925   std::string abs_storage;
2926   if (!IS_ABSOLUTE_PATH (filename))
2927     {
2928       gdb::unique_xmalloc_ptr<char> abs
2929         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2930
2931       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2932       filename = abs_storage.c_str ();
2933     }
2934
2935   /* First try the file name given in the section.  If that doesn't
2936      work, try to use the build-id instead.  */
2937   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2938   if (dwz_bfd != NULL)
2939     {
2940       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2941         dwz_bfd.release ();
2942     }
2943
2944   if (dwz_bfd == NULL)
2945     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2946
2947   if (dwz_bfd == NULL)
2948     error (_("could not find '.gnu_debugaltlink' file for %s"),
2949            objfile_name (dwarf2_per_objfile->objfile));
2950
2951   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2952                            struct dwz_file);
2953   result->dwz_bfd = dwz_bfd.release ();
2954
2955   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2956
2957   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2958   dwarf2_per_objfile->dwz_file = result;
2959   return result;
2960 }
2961 \f
2962 /* DWARF quick_symbols_functions support.  */
2963
2964 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2965    unique line tables, so we maintain a separate table of all .debug_line
2966    derived entries to support the sharing.
2967    All the quick functions need is the list of file names.  We discard the
2968    line_header when we're done and don't need to record it here.  */
2969 struct quick_file_names
2970 {
2971   /* The data used to construct the hash key.  */
2972   struct stmt_list_hash hash;
2973
2974   /* The number of entries in file_names, real_names.  */
2975   unsigned int num_file_names;
2976
2977   /* The file names from the line table, after being run through
2978      file_full_name.  */
2979   const char **file_names;
2980
2981   /* The file names from the line table after being run through
2982      gdb_realpath.  These are computed lazily.  */
2983   const char **real_names;
2984 };
2985
2986 /* When using the index (and thus not using psymtabs), each CU has an
2987    object of this type.  This is used to hold information needed by
2988    the various "quick" methods.  */
2989 struct dwarf2_per_cu_quick_data
2990 {
2991   /* The file table.  This can be NULL if there was no file table
2992      or it's currently not read in.
2993      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2994   struct quick_file_names *file_names;
2995
2996   /* The corresponding symbol table.  This is NULL if symbols for this
2997      CU have not yet been read.  */
2998   struct compunit_symtab *compunit_symtab;
2999
3000   /* A temporary mark bit used when iterating over all CUs in
3001      expand_symtabs_matching.  */
3002   unsigned int mark : 1;
3003
3004   /* True if we've tried to read the file table and found there isn't one.
3005      There will be no point in trying to read it again next time.  */
3006   unsigned int no_file_data : 1;
3007 };
3008
3009 /* Utility hash function for a stmt_list_hash.  */
3010
3011 static hashval_t
3012 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3013 {
3014   hashval_t v = 0;
3015
3016   if (stmt_list_hash->dwo_unit != NULL)
3017     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3018   v += to_underlying (stmt_list_hash->line_sect_off);
3019   return v;
3020 }
3021
3022 /* Utility equality function for a stmt_list_hash.  */
3023
3024 static int
3025 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3026                     const struct stmt_list_hash *rhs)
3027 {
3028   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3029     return 0;
3030   if (lhs->dwo_unit != NULL
3031       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3032     return 0;
3033
3034   return lhs->line_sect_off == rhs->line_sect_off;
3035 }
3036
3037 /* Hash function for a quick_file_names.  */
3038
3039 static hashval_t
3040 hash_file_name_entry (const void *e)
3041 {
3042   const struct quick_file_names *file_data
3043     = (const struct quick_file_names *) e;
3044
3045   return hash_stmt_list_entry (&file_data->hash);
3046 }
3047
3048 /* Equality function for a quick_file_names.  */
3049
3050 static int
3051 eq_file_name_entry (const void *a, const void *b)
3052 {
3053   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3054   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3055
3056   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3057 }
3058
3059 /* Delete function for a quick_file_names.  */
3060
3061 static void
3062 delete_file_name_entry (void *e)
3063 {
3064   struct quick_file_names *file_data = (struct quick_file_names *) e;
3065   int i;
3066
3067   for (i = 0; i < file_data->num_file_names; ++i)
3068     {
3069       xfree ((void*) file_data->file_names[i]);
3070       if (file_data->real_names)
3071         xfree ((void*) file_data->real_names[i]);
3072     }
3073
3074   /* The space for the struct itself lives on objfile_obstack,
3075      so we don't free it here.  */
3076 }
3077
3078 /* Create a quick_file_names hash table.  */
3079
3080 static htab_t
3081 create_quick_file_names_table (unsigned int nr_initial_entries)
3082 {
3083   return htab_create_alloc (nr_initial_entries,
3084                             hash_file_name_entry, eq_file_name_entry,
3085                             delete_file_name_entry, xcalloc, xfree);
3086 }
3087
3088 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3089    have to be created afterwards.  You should call age_cached_comp_units after
3090    processing PER_CU->CU.  dw2_setup must have been already called.  */
3091
3092 static void
3093 load_cu (struct dwarf2_per_cu_data *per_cu)
3094 {
3095   if (per_cu->is_debug_types)
3096     load_full_type_unit (per_cu);
3097   else
3098     load_full_comp_unit (per_cu, language_minimal);
3099
3100   if (per_cu->cu == NULL)
3101     return;  /* Dummy CU.  */
3102
3103   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3104 }
3105
3106 /* Read in the symbols for PER_CU.  */
3107
3108 static void
3109 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3110 {
3111   struct cleanup *back_to;
3112   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3113
3114   /* Skip type_unit_groups, reading the type units they contain
3115      is handled elsewhere.  */
3116   if (IS_TYPE_UNIT_GROUP (per_cu))
3117     return;
3118
3119   back_to = make_cleanup (dwarf2_release_queue, NULL);
3120
3121   if (dwarf2_per_objfile->using_index
3122       ? per_cu->v.quick->compunit_symtab == NULL
3123       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3124     {
3125       queue_comp_unit (per_cu, language_minimal);
3126       load_cu (per_cu);
3127
3128       /* If we just loaded a CU from a DWO, and we're working with an index
3129          that may badly handle TUs, load all the TUs in that DWO as well.
3130          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3131       if (!per_cu->is_debug_types
3132           && per_cu->cu != NULL
3133           && per_cu->cu->dwo_unit != NULL
3134           && dwarf2_per_objfile->index_table != NULL
3135           && dwarf2_per_objfile->index_table->version <= 7
3136           /* DWP files aren't supported yet.  */
3137           && get_dwp_file (dwarf2_per_objfile) == NULL)
3138         queue_and_load_all_dwo_tus (per_cu);
3139     }
3140
3141   process_queue (dwarf2_per_objfile);
3142
3143   /* Age the cache, releasing compilation units that have not
3144      been used recently.  */
3145   age_cached_comp_units (dwarf2_per_objfile);
3146
3147   do_cleanups (back_to);
3148 }
3149
3150 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3151    the objfile from which this CU came.  Returns the resulting symbol
3152    table.  */
3153
3154 static struct compunit_symtab *
3155 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3156 {
3157   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3158
3159   gdb_assert (dwarf2_per_objfile->using_index);
3160   if (!per_cu->v.quick->compunit_symtab)
3161     {
3162       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3163                                               dwarf2_per_objfile);
3164       scoped_restore decrementer = increment_reading_symtab ();
3165       dw2_do_instantiate_symtab (per_cu);
3166       process_cu_includes (dwarf2_per_objfile);
3167       do_cleanups (back_to);
3168     }
3169
3170   return per_cu->v.quick->compunit_symtab;
3171 }
3172
3173 /* Return the CU/TU given its index.
3174
3175    This is intended for loops like:
3176
3177    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3178                     + dwarf2_per_objfile->n_type_units); ++i)
3179      {
3180        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3181
3182        ...;
3183      }
3184 */
3185
3186 static struct dwarf2_per_cu_data *
3187 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3188               int index)
3189 {
3190   if (index >= dwarf2_per_objfile->n_comp_units)
3191     {
3192       index -= dwarf2_per_objfile->n_comp_units;
3193       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3194       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3195     }
3196
3197   return dwarf2_per_objfile->all_comp_units[index];
3198 }
3199
3200 /* Return the CU given its index.
3201    This differs from dw2_get_cutu in that it's for when you know INDEX
3202    refers to a CU.  */
3203
3204 static struct dwarf2_per_cu_data *
3205 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3206 {
3207   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3208
3209   return dwarf2_per_objfile->all_comp_units[index];
3210 }
3211
3212 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3213    objfile_obstack, and constructed with the specified field
3214    values.  */
3215
3216 static dwarf2_per_cu_data *
3217 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3218                           struct dwarf2_section_info *section,
3219                           int is_dwz,
3220                           sect_offset sect_off, ULONGEST length)
3221 {
3222   struct objfile *objfile = dwarf2_per_objfile->objfile;
3223   dwarf2_per_cu_data *the_cu
3224     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3225                      struct dwarf2_per_cu_data);
3226   the_cu->sect_off = sect_off;
3227   the_cu->length = length;
3228   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3229   the_cu->section = section;
3230   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3231                                    struct dwarf2_per_cu_quick_data);
3232   the_cu->is_dwz = is_dwz;
3233   return the_cu;
3234 }
3235
3236 /* A helper for create_cus_from_index that handles a given list of
3237    CUs.  */
3238
3239 static void
3240 create_cus_from_index_list (struct objfile *objfile,
3241                             const gdb_byte *cu_list, offset_type n_elements,
3242                             struct dwarf2_section_info *section,
3243                             int is_dwz,
3244                             int base_offset)
3245 {
3246   offset_type i;
3247   struct dwarf2_per_objfile *dwarf2_per_objfile
3248     = get_dwarf2_per_objfile (objfile);
3249
3250   for (i = 0; i < n_elements; i += 2)
3251     {
3252       gdb_static_assert (sizeof (ULONGEST) >= 8);
3253
3254       sect_offset sect_off
3255         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3256       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3257       cu_list += 2 * 8;
3258
3259       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3260         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3261                                      sect_off, length);
3262     }
3263 }
3264
3265 /* Read the CU list from the mapped index, and use it to create all
3266    the CU objects for this objfile.  */
3267
3268 static void
3269 create_cus_from_index (struct objfile *objfile,
3270                        const gdb_byte *cu_list, offset_type cu_list_elements,
3271                        const gdb_byte *dwz_list, offset_type dwz_elements)
3272 {
3273   struct dwz_file *dwz;
3274   struct dwarf2_per_objfile *dwarf2_per_objfile
3275     = get_dwarf2_per_objfile (objfile);
3276
3277   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3278   dwarf2_per_objfile->all_comp_units =
3279     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3280                dwarf2_per_objfile->n_comp_units);
3281
3282   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3283                               &dwarf2_per_objfile->info, 0, 0);
3284
3285   if (dwz_elements == 0)
3286     return;
3287
3288   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3289   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3290                               cu_list_elements / 2);
3291 }
3292
3293 /* Create the signatured type hash table from the index.  */
3294
3295 static void
3296 create_signatured_type_table_from_index (struct objfile *objfile,
3297                                          struct dwarf2_section_info *section,
3298                                          const gdb_byte *bytes,
3299                                          offset_type elements)
3300 {
3301   offset_type i;
3302   htab_t sig_types_hash;
3303   struct dwarf2_per_objfile *dwarf2_per_objfile
3304     = get_dwarf2_per_objfile (objfile);
3305
3306   dwarf2_per_objfile->n_type_units
3307     = dwarf2_per_objfile->n_allocated_type_units
3308     = elements / 3;
3309   dwarf2_per_objfile->all_type_units =
3310     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3311
3312   sig_types_hash = allocate_signatured_type_table (objfile);
3313
3314   for (i = 0; i < elements; i += 3)
3315     {
3316       struct signatured_type *sig_type;
3317       ULONGEST signature;
3318       void **slot;
3319       cu_offset type_offset_in_tu;
3320
3321       gdb_static_assert (sizeof (ULONGEST) >= 8);
3322       sect_offset sect_off
3323         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3324       type_offset_in_tu
3325         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3326                                                 BFD_ENDIAN_LITTLE);
3327       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3328       bytes += 3 * 8;
3329
3330       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3331                                  struct signatured_type);
3332       sig_type->signature = signature;
3333       sig_type->type_offset_in_tu = type_offset_in_tu;
3334       sig_type->per_cu.is_debug_types = 1;
3335       sig_type->per_cu.section = section;
3336       sig_type->per_cu.sect_off = sect_off;
3337       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3338       sig_type->per_cu.v.quick
3339         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3340                           struct dwarf2_per_cu_quick_data);
3341
3342       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3343       *slot = sig_type;
3344
3345       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3346     }
3347
3348   dwarf2_per_objfile->signatured_types = sig_types_hash;
3349 }
3350
3351 /* Create the signatured type hash table from .debug_names.  */
3352
3353 static void
3354 create_signatured_type_table_from_debug_names
3355   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3356    const mapped_debug_names &map,
3357    struct dwarf2_section_info *section,
3358    struct dwarf2_section_info *abbrev_section)
3359 {
3360   struct objfile *objfile = dwarf2_per_objfile->objfile;
3361
3362   dwarf2_read_section (objfile, section);
3363   dwarf2_read_section (objfile, abbrev_section);
3364
3365   dwarf2_per_objfile->n_type_units
3366     = dwarf2_per_objfile->n_allocated_type_units
3367     = map.tu_count;
3368   dwarf2_per_objfile->all_type_units
3369     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3370
3371   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3372
3373   for (uint32_t i = 0; i < map.tu_count; ++i)
3374     {
3375       struct signatured_type *sig_type;
3376       ULONGEST signature;
3377       void **slot;
3378       cu_offset type_offset_in_tu;
3379
3380       sect_offset sect_off
3381         = (sect_offset) (extract_unsigned_integer
3382                          (map.tu_table_reordered + i * map.offset_size,
3383                           map.offset_size,
3384                           map.dwarf5_byte_order));
3385
3386       comp_unit_head cu_header;
3387       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3388                                      abbrev_section,
3389                                      section->buffer + to_underlying (sect_off),
3390                                      rcuh_kind::TYPE);
3391
3392       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3393                                  struct signatured_type);
3394       sig_type->signature = cu_header.signature;
3395       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3396       sig_type->per_cu.is_debug_types = 1;
3397       sig_type->per_cu.section = section;
3398       sig_type->per_cu.sect_off = sect_off;
3399       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3400       sig_type->per_cu.v.quick
3401         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3402                           struct dwarf2_per_cu_quick_data);
3403
3404       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3405       *slot = sig_type;
3406
3407       dwarf2_per_objfile->all_type_units[i] = sig_type;
3408     }
3409
3410   dwarf2_per_objfile->signatured_types = sig_types_hash;
3411 }
3412
3413 /* Read the address map data from the mapped index, and use it to
3414    populate the objfile's psymtabs_addrmap.  */
3415
3416 static void
3417 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3418                            struct mapped_index *index)
3419 {
3420   struct objfile *objfile = dwarf2_per_objfile->objfile;
3421   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3422   const gdb_byte *iter, *end;
3423   struct addrmap *mutable_map;
3424   CORE_ADDR baseaddr;
3425
3426   auto_obstack temp_obstack;
3427
3428   mutable_map = addrmap_create_mutable (&temp_obstack);
3429
3430   iter = index->address_table.data ();
3431   end = iter + index->address_table.size ();
3432
3433   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3434
3435   while (iter < end)
3436     {
3437       ULONGEST hi, lo, cu_index;
3438       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3439       iter += 8;
3440       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3441       iter += 8;
3442       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3443       iter += 4;
3444
3445       if (lo > hi)
3446         {
3447           complaint (&symfile_complaints,
3448                      _(".gdb_index address table has invalid range (%s - %s)"),
3449                      hex_string (lo), hex_string (hi));
3450           continue;
3451         }
3452
3453       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3454         {
3455           complaint (&symfile_complaints,
3456                      _(".gdb_index address table has invalid CU number %u"),
3457                      (unsigned) cu_index);
3458           continue;
3459         }
3460
3461       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3462       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3463       addrmap_set_empty (mutable_map, lo, hi - 1,
3464                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3465     }
3466
3467   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3468                                                     &objfile->objfile_obstack);
3469 }
3470
3471 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3472    populate the objfile's psymtabs_addrmap.  */
3473
3474 static void
3475 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3476                              struct dwarf2_section_info *section)
3477 {
3478   struct objfile *objfile = dwarf2_per_objfile->objfile;
3479   bfd *abfd = objfile->obfd;
3480   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3481   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3482                                        SECT_OFF_TEXT (objfile));
3483
3484   auto_obstack temp_obstack;
3485   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3486
3487   std::unordered_map<sect_offset,
3488                      dwarf2_per_cu_data *,
3489                      gdb::hash_enum<sect_offset>>
3490     debug_info_offset_to_per_cu;
3491   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3492     {
3493       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3494       const auto insertpair
3495         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3496       if (!insertpair.second)
3497         {
3498           warning (_("Section .debug_aranges in %s has duplicate "
3499                      "debug_info_offset %u, ignoring .debug_aranges."),
3500                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3501           return;
3502         }
3503     }
3504
3505   dwarf2_read_section (objfile, section);
3506
3507   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3508
3509   const gdb_byte *addr = section->buffer;
3510
3511   while (addr < section->buffer + section->size)
3512     {
3513       const gdb_byte *const entry_addr = addr;
3514       unsigned int bytes_read;
3515
3516       const LONGEST entry_length = read_initial_length (abfd, addr,
3517                                                         &bytes_read);
3518       addr += bytes_read;
3519
3520       const gdb_byte *const entry_end = addr + entry_length;
3521       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3522       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3523       if (addr + entry_length > section->buffer + section->size)
3524         {
3525           warning (_("Section .debug_aranges in %s entry at offset %zu "
3526                      "length %s exceeds section length %s, "
3527                      "ignoring .debug_aranges."),
3528                    objfile_name (objfile), entry_addr - section->buffer,
3529                    plongest (bytes_read + entry_length),
3530                    pulongest (section->size));
3531           return;
3532         }
3533
3534       /* The version number.  */
3535       const uint16_t version = read_2_bytes (abfd, addr);
3536       addr += 2;
3537       if (version != 2)
3538         {
3539           warning (_("Section .debug_aranges in %s entry at offset %zu "
3540                      "has unsupported version %d, ignoring .debug_aranges."),
3541                    objfile_name (objfile), entry_addr - section->buffer,
3542                    version);
3543           return;
3544         }
3545
3546       const uint64_t debug_info_offset
3547         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3548       addr += offset_size;
3549       const auto per_cu_it
3550         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3551       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3552         {
3553           warning (_("Section .debug_aranges in %s entry at offset %zu "
3554                      "debug_info_offset %s does not exists, "
3555                      "ignoring .debug_aranges."),
3556                    objfile_name (objfile), entry_addr - section->buffer,
3557                    pulongest (debug_info_offset));
3558           return;
3559         }
3560       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3561
3562       const uint8_t address_size = *addr++;
3563       if (address_size < 1 || address_size > 8)
3564         {
3565           warning (_("Section .debug_aranges in %s entry at offset %zu "
3566                      "address_size %u is invalid, ignoring .debug_aranges."),
3567                    objfile_name (objfile), entry_addr - section->buffer,
3568                    address_size);
3569           return;
3570         }
3571
3572       const uint8_t segment_selector_size = *addr++;
3573       if (segment_selector_size != 0)
3574         {
3575           warning (_("Section .debug_aranges in %s entry at offset %zu "
3576                      "segment_selector_size %u is not supported, "
3577                      "ignoring .debug_aranges."),
3578                    objfile_name (objfile), entry_addr - section->buffer,
3579                    segment_selector_size);
3580           return;
3581         }
3582
3583       /* Must pad to an alignment boundary that is twice the address
3584          size.  It is undocumented by the DWARF standard but GCC does
3585          use it.  */
3586       for (size_t padding = ((-(addr - section->buffer))
3587                              & (2 * address_size - 1));
3588            padding > 0; padding--)
3589         if (*addr++ != 0)
3590           {
3591             warning (_("Section .debug_aranges in %s entry at offset %zu "
3592                        "padding is not zero, ignoring .debug_aranges."),
3593                      objfile_name (objfile), entry_addr - section->buffer);
3594             return;
3595           }
3596
3597       for (;;)
3598         {
3599           if (addr + 2 * address_size > entry_end)
3600             {
3601               warning (_("Section .debug_aranges in %s entry at offset %zu "
3602                          "address list is not properly terminated, "
3603                          "ignoring .debug_aranges."),
3604                        objfile_name (objfile), entry_addr - section->buffer);
3605               return;
3606             }
3607           ULONGEST start = extract_unsigned_integer (addr, address_size,
3608                                                      dwarf5_byte_order);
3609           addr += address_size;
3610           ULONGEST length = extract_unsigned_integer (addr, address_size,
3611                                                       dwarf5_byte_order);
3612           addr += address_size;
3613           if (start == 0 && length == 0)
3614             break;
3615           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3616             {
3617               /* Symbol was eliminated due to a COMDAT group.  */
3618               continue;
3619             }
3620           ULONGEST end = start + length;
3621           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3622           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3623           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3624         }
3625     }
3626
3627   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3628                                                     &objfile->objfile_obstack);
3629 }
3630
3631 /* The hash function for strings in the mapped index.  This is the same as
3632    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3633    implementation.  This is necessary because the hash function is tied to the
3634    format of the mapped index file.  The hash values do not have to match with
3635    SYMBOL_HASH_NEXT.
3636    
3637    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3638
3639 static hashval_t
3640 mapped_index_string_hash (int index_version, const void *p)
3641 {
3642   const unsigned char *str = (const unsigned char *) p;
3643   hashval_t r = 0;
3644   unsigned char c;
3645
3646   while ((c = *str++) != 0)
3647     {
3648       if (index_version >= 5)
3649         c = tolower (c);
3650       r = r * 67 + c - 113;
3651     }
3652
3653   return r;
3654 }
3655
3656 /* Find a slot in the mapped index INDEX for the object named NAME.
3657    If NAME is found, set *VEC_OUT to point to the CU vector in the
3658    constant pool and return true.  If NAME cannot be found, return
3659    false.  */
3660
3661 static bool
3662 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3663                           offset_type **vec_out)
3664 {
3665   offset_type hash;
3666   offset_type slot, step;
3667   int (*cmp) (const char *, const char *);
3668
3669   gdb::unique_xmalloc_ptr<char> without_params;
3670   if (current_language->la_language == language_cplus
3671       || current_language->la_language == language_fortran
3672       || current_language->la_language == language_d)
3673     {
3674       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3675          not contain any.  */
3676
3677       if (strchr (name, '(') != NULL)
3678         {
3679           without_params = cp_remove_params (name);
3680
3681           if (without_params != NULL)
3682             name = without_params.get ();
3683         }
3684     }
3685
3686   /* Index version 4 did not support case insensitive searches.  But the
3687      indices for case insensitive languages are built in lowercase, therefore
3688      simulate our NAME being searched is also lowercased.  */
3689   hash = mapped_index_string_hash ((index->version == 4
3690                                     && case_sensitivity == case_sensitive_off
3691                                     ? 5 : index->version),
3692                                    name);
3693
3694   slot = hash & (index->symbol_table.size () - 1);
3695   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3696   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3697
3698   for (;;)
3699     {
3700       const char *str;
3701
3702       const auto &bucket = index->symbol_table[slot];
3703       if (bucket.name == 0 && bucket.vec == 0)
3704         return false;
3705
3706       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3707       if (!cmp (name, str))
3708         {
3709           *vec_out = (offset_type *) (index->constant_pool
3710                                       + MAYBE_SWAP (bucket.vec));
3711           return true;
3712         }
3713
3714       slot = (slot + step) & (index->symbol_table.size () - 1);
3715     }
3716 }
3717
3718 /* A helper function that reads the .gdb_index from SECTION and fills
3719    in MAP.  FILENAME is the name of the file containing the section;
3720    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3721    ok to use deprecated sections.
3722
3723    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3724    out parameters that are filled in with information about the CU and
3725    TU lists in the section.
3726
3727    Returns 1 if all went well, 0 otherwise.  */
3728
3729 static int
3730 read_index_from_section (struct objfile *objfile,
3731                          const char *filename,
3732                          int deprecated_ok,
3733                          struct dwarf2_section_info *section,
3734                          struct mapped_index *map,
3735                          const gdb_byte **cu_list,
3736                          offset_type *cu_list_elements,
3737                          const gdb_byte **types_list,
3738                          offset_type *types_list_elements)
3739 {
3740   const gdb_byte *addr;
3741   offset_type version;
3742   offset_type *metadata;
3743   int i;
3744
3745   if (dwarf2_section_empty_p (section))
3746     return 0;
3747
3748   /* Older elfutils strip versions could keep the section in the main
3749      executable while splitting it for the separate debug info file.  */
3750   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3751     return 0;
3752
3753   dwarf2_read_section (objfile, section);
3754
3755   addr = section->buffer;
3756   /* Version check.  */
3757   version = MAYBE_SWAP (*(offset_type *) addr);
3758   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3759      causes the index to behave very poorly for certain requests.  Version 3
3760      contained incomplete addrmap.  So, it seems better to just ignore such
3761      indices.  */
3762   if (version < 4)
3763     {
3764       static int warning_printed = 0;
3765       if (!warning_printed)
3766         {
3767           warning (_("Skipping obsolete .gdb_index section in %s."),
3768                    filename);
3769           warning_printed = 1;
3770         }
3771       return 0;
3772     }
3773   /* Index version 4 uses a different hash function than index version
3774      5 and later.
3775
3776      Versions earlier than 6 did not emit psymbols for inlined
3777      functions.  Using these files will cause GDB not to be able to
3778      set breakpoints on inlined functions by name, so we ignore these
3779      indices unless the user has done
3780      "set use-deprecated-index-sections on".  */
3781   if (version < 6 && !deprecated_ok)
3782     {
3783       static int warning_printed = 0;
3784       if (!warning_printed)
3785         {
3786           warning (_("\
3787 Skipping deprecated .gdb_index section in %s.\n\
3788 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3789 to use the section anyway."),
3790                    filename);
3791           warning_printed = 1;
3792         }
3793       return 0;
3794     }
3795   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3796      of the TU (for symbols coming from TUs),
3797      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3798      Plus gold-generated indices can have duplicate entries for global symbols,
3799      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3800      These are just performance bugs, and we can't distinguish gdb-generated
3801      indices from gold-generated ones, so issue no warning here.  */
3802
3803   /* Indexes with higher version than the one supported by GDB may be no
3804      longer backward compatible.  */
3805   if (version > 8)
3806     return 0;
3807
3808   map->version = version;
3809   map->total_size = section->size;
3810
3811   metadata = (offset_type *) (addr + sizeof (offset_type));
3812
3813   i = 0;
3814   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3815   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3816                        / 8);
3817   ++i;
3818
3819   *types_list = addr + MAYBE_SWAP (metadata[i]);
3820   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3821                            - MAYBE_SWAP (metadata[i]))
3822                           / 8);
3823   ++i;
3824
3825   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3826   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3827   map->address_table
3828     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3829   ++i;
3830
3831   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3832   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3833   map->symbol_table
3834     = gdb::array_view<mapped_index::symbol_table_slot>
3835        ((mapped_index::symbol_table_slot *) symbol_table,
3836         (mapped_index::symbol_table_slot *) symbol_table_end);
3837
3838   ++i;
3839   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3840
3841   return 1;
3842 }
3843
3844 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3845    elements of all the CUs and return 1.  Otherwise, return 0.  */
3846
3847 static int
3848 dwarf2_read_index (struct objfile *objfile)
3849 {
3850   struct mapped_index local_map, *map;
3851   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3852   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3853   struct dwz_file *dwz;
3854   struct dwarf2_per_objfile *dwarf2_per_objfile
3855     = get_dwarf2_per_objfile (objfile);
3856
3857   if (!read_index_from_section (objfile, objfile_name (objfile),
3858                                 use_deprecated_index_sections,
3859                                 &dwarf2_per_objfile->gdb_index, &local_map,
3860                                 &cu_list, &cu_list_elements,
3861                                 &types_list, &types_list_elements))
3862     return 0;
3863
3864   /* Don't use the index if it's empty.  */
3865   if (local_map.symbol_table.empty ())
3866     return 0;
3867
3868   /* If there is a .dwz file, read it so we can get its CU list as
3869      well.  */
3870   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3871   if (dwz != NULL)
3872     {
3873       struct mapped_index dwz_map;
3874       const gdb_byte *dwz_types_ignore;
3875       offset_type dwz_types_elements_ignore;
3876
3877       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3878                                     1,
3879                                     &dwz->gdb_index, &dwz_map,
3880                                     &dwz_list, &dwz_list_elements,
3881                                     &dwz_types_ignore,
3882                                     &dwz_types_elements_ignore))
3883         {
3884           warning (_("could not read '.gdb_index' section from %s; skipping"),
3885                    bfd_get_filename (dwz->dwz_bfd));
3886           return 0;
3887         }
3888     }
3889
3890   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3891                          dwz_list_elements);
3892
3893   if (types_list_elements)
3894     {
3895       struct dwarf2_section_info *section;
3896
3897       /* We can only handle a single .debug_types when we have an
3898          index.  */
3899       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3900         return 0;
3901
3902       section = VEC_index (dwarf2_section_info_def,
3903                            dwarf2_per_objfile->types, 0);
3904
3905       create_signatured_type_table_from_index (objfile, section, types_list,
3906                                                types_list_elements);
3907     }
3908
3909   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3910
3911   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3912   map = new (map) mapped_index ();
3913   *map = local_map;
3914
3915   dwarf2_per_objfile->index_table = map;
3916   dwarf2_per_objfile->using_index = 1;
3917   dwarf2_per_objfile->quick_file_names_table =
3918     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3919
3920   return 1;
3921 }
3922
3923 /* die_reader_func for dw2_get_file_names.  */
3924
3925 static void
3926 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3927                            const gdb_byte *info_ptr,
3928                            struct die_info *comp_unit_die,
3929                            int has_children,
3930                            void *data)
3931 {
3932   struct dwarf2_cu *cu = reader->cu;
3933   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3934   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
3935   struct objfile *objfile = dwarf2_per_objfile->objfile;
3936   struct dwarf2_per_cu_data *lh_cu;
3937   struct attribute *attr;
3938   int i;
3939   void **slot;
3940   struct quick_file_names *qfn;
3941
3942   gdb_assert (! this_cu->is_debug_types);
3943
3944   /* Our callers never want to match partial units -- instead they
3945      will match the enclosing full CU.  */
3946   if (comp_unit_die->tag == DW_TAG_partial_unit)
3947     {
3948       this_cu->v.quick->no_file_data = 1;
3949       return;
3950     }
3951
3952   lh_cu = this_cu;
3953   slot = NULL;
3954
3955   line_header_up lh;
3956   sect_offset line_offset {};
3957
3958   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3959   if (attr)
3960     {
3961       struct quick_file_names find_entry;
3962
3963       line_offset = (sect_offset) DW_UNSND (attr);
3964
3965       /* We may have already read in this line header (TU line header sharing).
3966          If we have we're done.  */
3967       find_entry.hash.dwo_unit = cu->dwo_unit;
3968       find_entry.hash.line_sect_off = line_offset;
3969       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3970                              &find_entry, INSERT);
3971       if (*slot != NULL)
3972         {
3973           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3974           return;
3975         }
3976
3977       lh = dwarf_decode_line_header (line_offset, cu);
3978     }
3979   if (lh == NULL)
3980     {
3981       lh_cu->v.quick->no_file_data = 1;
3982       return;
3983     }
3984
3985   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3986   qfn->hash.dwo_unit = cu->dwo_unit;
3987   qfn->hash.line_sect_off = line_offset;
3988   gdb_assert (slot != NULL);
3989   *slot = qfn;
3990
3991   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3992
3993   qfn->num_file_names = lh->file_names.size ();
3994   qfn->file_names =
3995     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3996   for (i = 0; i < lh->file_names.size (); ++i)
3997     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3998   qfn->real_names = NULL;
3999
4000   lh_cu->v.quick->file_names = qfn;
4001 }
4002
4003 /* A helper for the "quick" functions which attempts to read the line
4004    table for THIS_CU.  */
4005
4006 static struct quick_file_names *
4007 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4008 {
4009   /* This should never be called for TUs.  */
4010   gdb_assert (! this_cu->is_debug_types);
4011   /* Nor type unit groups.  */
4012   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4013
4014   if (this_cu->v.quick->file_names != NULL)
4015     return this_cu->v.quick->file_names;
4016   /* If we know there is no line data, no point in looking again.  */
4017   if (this_cu->v.quick->no_file_data)
4018     return NULL;
4019
4020   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4021
4022   if (this_cu->v.quick->no_file_data)
4023     return NULL;
4024   return this_cu->v.quick->file_names;
4025 }
4026
4027 /* A helper for the "quick" functions which computes and caches the
4028    real path for a given file name from the line table.  */
4029
4030 static const char *
4031 dw2_get_real_path (struct objfile *objfile,
4032                    struct quick_file_names *qfn, int index)
4033 {
4034   if (qfn->real_names == NULL)
4035     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4036                                       qfn->num_file_names, const char *);
4037
4038   if (qfn->real_names[index] == NULL)
4039     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4040
4041   return qfn->real_names[index];
4042 }
4043
4044 static struct symtab *
4045 dw2_find_last_source_symtab (struct objfile *objfile)
4046 {
4047   struct dwarf2_per_objfile *dwarf2_per_objfile
4048     = get_dwarf2_per_objfile (objfile);
4049   int index = dwarf2_per_objfile->n_comp_units - 1;
4050   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4051   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4052
4053   if (cust == NULL)
4054     return NULL;
4055
4056   return compunit_primary_filetab (cust);
4057 }
4058
4059 /* Traversal function for dw2_forget_cached_source_info.  */
4060
4061 static int
4062 dw2_free_cached_file_names (void **slot, void *info)
4063 {
4064   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4065
4066   if (file_data->real_names)
4067     {
4068       int i;
4069
4070       for (i = 0; i < file_data->num_file_names; ++i)
4071         {
4072           xfree ((void*) file_data->real_names[i]);
4073           file_data->real_names[i] = NULL;
4074         }
4075     }
4076
4077   return 1;
4078 }
4079
4080 static void
4081 dw2_forget_cached_source_info (struct objfile *objfile)
4082 {
4083   struct dwarf2_per_objfile *dwarf2_per_objfile
4084     = get_dwarf2_per_objfile (objfile);
4085
4086   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4087                           dw2_free_cached_file_names, NULL);
4088 }
4089
4090 /* Helper function for dw2_map_symtabs_matching_filename that expands
4091    the symtabs and calls the iterator.  */
4092
4093 static int
4094 dw2_map_expand_apply (struct objfile *objfile,
4095                       struct dwarf2_per_cu_data *per_cu,
4096                       const char *name, const char *real_path,
4097                       gdb::function_view<bool (symtab *)> callback)
4098 {
4099   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4100
4101   /* Don't visit already-expanded CUs.  */
4102   if (per_cu->v.quick->compunit_symtab)
4103     return 0;
4104
4105   /* This may expand more than one symtab, and we want to iterate over
4106      all of them.  */
4107   dw2_instantiate_symtab (per_cu);
4108
4109   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4110                                     last_made, callback);
4111 }
4112
4113 /* Implementation of the map_symtabs_matching_filename method.  */
4114
4115 static bool
4116 dw2_map_symtabs_matching_filename
4117   (struct objfile *objfile, const char *name, const char *real_path,
4118    gdb::function_view<bool (symtab *)> callback)
4119 {
4120   int i;
4121   const char *name_basename = lbasename (name);
4122   struct dwarf2_per_objfile *dwarf2_per_objfile
4123     = get_dwarf2_per_objfile (objfile);
4124
4125   /* The rule is CUs specify all the files, including those used by
4126      any TU, so there's no need to scan TUs here.  */
4127
4128   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4129     {
4130       int j;
4131       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4132       struct quick_file_names *file_data;
4133
4134       /* We only need to look at symtabs not already expanded.  */
4135       if (per_cu->v.quick->compunit_symtab)
4136         continue;
4137
4138       file_data = dw2_get_file_names (per_cu);
4139       if (file_data == NULL)
4140         continue;
4141
4142       for (j = 0; j < file_data->num_file_names; ++j)
4143         {
4144           const char *this_name = file_data->file_names[j];
4145           const char *this_real_name;
4146
4147           if (compare_filenames_for_search (this_name, name))
4148             {
4149               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4150                                         callback))
4151                 return true;
4152               continue;
4153             }
4154
4155           /* Before we invoke realpath, which can get expensive when many
4156              files are involved, do a quick comparison of the basenames.  */
4157           if (! basenames_may_differ
4158               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4159             continue;
4160
4161           this_real_name = dw2_get_real_path (objfile, file_data, j);
4162           if (compare_filenames_for_search (this_real_name, name))
4163             {
4164               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4165                                         callback))
4166                 return true;
4167               continue;
4168             }
4169
4170           if (real_path != NULL)
4171             {
4172               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4173               gdb_assert (IS_ABSOLUTE_PATH (name));
4174               if (this_real_name != NULL
4175                   && FILENAME_CMP (real_path, this_real_name) == 0)
4176                 {
4177                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4178                                             callback))
4179                     return true;
4180                   continue;
4181                 }
4182             }
4183         }
4184     }
4185
4186   return false;
4187 }
4188
4189 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4190
4191 struct dw2_symtab_iterator
4192 {
4193   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4194   struct dwarf2_per_objfile *dwarf2_per_objfile;
4195   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4196   int want_specific_block;
4197   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4198      Unused if !WANT_SPECIFIC_BLOCK.  */
4199   int block_index;
4200   /* The kind of symbol we're looking for.  */
4201   domain_enum domain;
4202   /* The list of CUs from the index entry of the symbol,
4203      or NULL if not found.  */
4204   offset_type *vec;
4205   /* The next element in VEC to look at.  */
4206   int next;
4207   /* The number of elements in VEC, or zero if there is no match.  */
4208   int length;
4209   /* Have we seen a global version of the symbol?
4210      If so we can ignore all further global instances.
4211      This is to work around gold/15646, inefficient gold-generated
4212      indices.  */
4213   int global_seen;
4214 };
4215
4216 /* Initialize the index symtab iterator ITER.
4217    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4218    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4219
4220 static void
4221 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4222                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4223                       int want_specific_block,
4224                       int block_index,
4225                       domain_enum domain,
4226                       const char *name)
4227 {
4228   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4229   iter->want_specific_block = want_specific_block;
4230   iter->block_index = block_index;
4231   iter->domain = domain;
4232   iter->next = 0;
4233   iter->global_seen = 0;
4234
4235   mapped_index *index = dwarf2_per_objfile->index_table;
4236
4237   /* index is NULL if OBJF_READNOW.  */
4238   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4239     iter->length = MAYBE_SWAP (*iter->vec);
4240   else
4241     {
4242       iter->vec = NULL;
4243       iter->length = 0;
4244     }
4245 }
4246
4247 /* Return the next matching CU or NULL if there are no more.  */
4248
4249 static struct dwarf2_per_cu_data *
4250 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4251 {
4252   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4253
4254   for ( ; iter->next < iter->length; ++iter->next)
4255     {
4256       offset_type cu_index_and_attrs =
4257         MAYBE_SWAP (iter->vec[iter->next + 1]);
4258       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4259       struct dwarf2_per_cu_data *per_cu;
4260       int want_static = iter->block_index != GLOBAL_BLOCK;
4261       /* This value is only valid for index versions >= 7.  */
4262       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4263       gdb_index_symbol_kind symbol_kind =
4264         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4265       /* Only check the symbol attributes if they're present.
4266          Indices prior to version 7 don't record them,
4267          and indices >= 7 may elide them for certain symbols
4268          (gold does this).  */
4269       int attrs_valid =
4270         (dwarf2_per_objfile->index_table->version >= 7
4271          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4272
4273       /* Don't crash on bad data.  */
4274       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4275                        + dwarf2_per_objfile->n_type_units))
4276         {
4277           complaint (&symfile_complaints,
4278                      _(".gdb_index entry has bad CU index"
4279                        " [in module %s]"),
4280                      objfile_name (dwarf2_per_objfile->objfile));
4281           continue;
4282         }
4283
4284       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4285
4286       /* Skip if already read in.  */
4287       if (per_cu->v.quick->compunit_symtab)
4288         continue;
4289
4290       /* Check static vs global.  */
4291       if (attrs_valid)
4292         {
4293           if (iter->want_specific_block
4294               && want_static != is_static)
4295             continue;
4296           /* Work around gold/15646.  */
4297           if (!is_static && iter->global_seen)
4298             continue;
4299           if (!is_static)
4300             iter->global_seen = 1;
4301         }
4302
4303       /* Only check the symbol's kind if it has one.  */
4304       if (attrs_valid)
4305         {
4306           switch (iter->domain)
4307             {
4308             case VAR_DOMAIN:
4309               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4310                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4311                   /* Some types are also in VAR_DOMAIN.  */
4312                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4313                 continue;
4314               break;
4315             case STRUCT_DOMAIN:
4316               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4317                 continue;
4318               break;
4319             case LABEL_DOMAIN:
4320               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4321                 continue;
4322               break;
4323             default:
4324               break;
4325             }
4326         }
4327
4328       ++iter->next;
4329       return per_cu;
4330     }
4331
4332   return NULL;
4333 }
4334
4335 static struct compunit_symtab *
4336 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4337                    const char *name, domain_enum domain)
4338 {
4339   struct compunit_symtab *stab_best = NULL;
4340   struct dwarf2_per_objfile *dwarf2_per_objfile
4341     = get_dwarf2_per_objfile (objfile);
4342
4343   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4344
4345   struct dw2_symtab_iterator iter;
4346   struct dwarf2_per_cu_data *per_cu;
4347
4348   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4349
4350   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4351     {
4352       struct symbol *sym, *with_opaque = NULL;
4353       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4354       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4355       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4356
4357       sym = block_find_symbol (block, name, domain,
4358                                block_find_non_opaque_type_preferred,
4359                                &with_opaque);
4360
4361       /* Some caution must be observed with overloaded functions
4362          and methods, since the index will not contain any overload
4363          information (but NAME might contain it).  */
4364
4365       if (sym != NULL
4366           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4367         return stab;
4368       if (with_opaque != NULL
4369           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4370         stab_best = stab;
4371
4372       /* Keep looking through other CUs.  */
4373     }
4374
4375   return stab_best;
4376 }
4377
4378 static void
4379 dw2_print_stats (struct objfile *objfile)
4380 {
4381   struct dwarf2_per_objfile *dwarf2_per_objfile
4382     = get_dwarf2_per_objfile (objfile);
4383   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4384   int count = 0;
4385
4386   for (int i = 0; i < total; ++i)
4387     {
4388       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4389
4390       if (!per_cu->v.quick->compunit_symtab)
4391         ++count;
4392     }
4393   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4394   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4395 }
4396
4397 /* This dumps minimal information about the index.
4398    It is called via "mt print objfiles".
4399    One use is to verify .gdb_index has been loaded by the
4400    gdb.dwarf2/gdb-index.exp testcase.  */
4401
4402 static void
4403 dw2_dump (struct objfile *objfile)
4404 {
4405   struct dwarf2_per_objfile *dwarf2_per_objfile
4406     = get_dwarf2_per_objfile (objfile);
4407
4408   gdb_assert (dwarf2_per_objfile->using_index);
4409   printf_filtered (".gdb_index:");
4410   if (dwarf2_per_objfile->index_table != NULL)
4411     {
4412       printf_filtered (" version %d\n",
4413                        dwarf2_per_objfile->index_table->version);
4414     }
4415   else
4416     printf_filtered (" faked for \"readnow\"\n");
4417   printf_filtered ("\n");
4418 }
4419
4420 static void
4421 dw2_relocate (struct objfile *objfile,
4422               const struct section_offsets *new_offsets,
4423               const struct section_offsets *delta)
4424 {
4425   /* There's nothing to relocate here.  */
4426 }
4427
4428 static void
4429 dw2_expand_symtabs_for_function (struct objfile *objfile,
4430                                  const char *func_name)
4431 {
4432   struct dwarf2_per_objfile *dwarf2_per_objfile
4433     = get_dwarf2_per_objfile (objfile);
4434
4435   struct dw2_symtab_iterator iter;
4436   struct dwarf2_per_cu_data *per_cu;
4437
4438   /* Note: It doesn't matter what we pass for block_index here.  */
4439   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4440                         func_name);
4441
4442   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4443     dw2_instantiate_symtab (per_cu);
4444
4445 }
4446
4447 static void
4448 dw2_expand_all_symtabs (struct objfile *objfile)
4449 {
4450   struct dwarf2_per_objfile *dwarf2_per_objfile
4451     = get_dwarf2_per_objfile (objfile);
4452   int total_units = (dwarf2_per_objfile->n_comp_units
4453                      + dwarf2_per_objfile->n_type_units);
4454
4455   for (int i = 0; i < total_units; ++i)
4456     {
4457       struct dwarf2_per_cu_data *per_cu
4458         = dw2_get_cutu (dwarf2_per_objfile, i);
4459
4460       dw2_instantiate_symtab (per_cu);
4461     }
4462 }
4463
4464 static void
4465 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4466                                   const char *fullname)
4467 {
4468   struct dwarf2_per_objfile *dwarf2_per_objfile
4469     = get_dwarf2_per_objfile (objfile);
4470
4471   /* We don't need to consider type units here.
4472      This is only called for examining code, e.g. expand_line_sal.
4473      There can be an order of magnitude (or more) more type units
4474      than comp units, and we avoid them if we can.  */
4475
4476   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4477     {
4478       int j;
4479       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4480       struct quick_file_names *file_data;
4481
4482       /* We only need to look at symtabs not already expanded.  */
4483       if (per_cu->v.quick->compunit_symtab)
4484         continue;
4485
4486       file_data = dw2_get_file_names (per_cu);
4487       if (file_data == NULL)
4488         continue;
4489
4490       for (j = 0; j < file_data->num_file_names; ++j)
4491         {
4492           const char *this_fullname = file_data->file_names[j];
4493
4494           if (filename_cmp (this_fullname, fullname) == 0)
4495             {
4496               dw2_instantiate_symtab (per_cu);
4497               break;
4498             }
4499         }
4500     }
4501 }
4502
4503 static void
4504 dw2_map_matching_symbols (struct objfile *objfile,
4505                           const char * name, domain_enum domain,
4506                           int global,
4507                           int (*callback) (struct block *,
4508                                            struct symbol *, void *),
4509                           void *data, symbol_name_match_type match,
4510                           symbol_compare_ftype *ordered_compare)
4511 {
4512   /* Currently unimplemented; used for Ada.  The function can be called if the
4513      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4514      does not look for non-Ada symbols this function should just return.  */
4515 }
4516
4517 /* Symbol name matcher for .gdb_index names.
4518
4519    Symbol names in .gdb_index have a few particularities:
4520
4521    - There's no indication of which is the language of each symbol.
4522
4523      Since each language has its own symbol name matching algorithm,
4524      and we don't know which language is the right one, we must match
4525      each symbol against all languages.  This would be a potential
4526      performance problem if it were not mitigated by the
4527      mapped_index::name_components lookup table, which significantly
4528      reduces the number of times we need to call into this matcher,
4529      making it a non-issue.
4530
4531    - Symbol names in the index have no overload (parameter)
4532      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4533      appear as "foo" in the index, for example.
4534
4535      This means that the lookup names passed to the symbol name
4536      matcher functions must have no parameter information either
4537      because (e.g.) symbol search name "foo" does not match
4538      lookup-name "foo(int)" [while swapping search name for lookup
4539      name would match].
4540 */
4541 class gdb_index_symbol_name_matcher
4542 {
4543 public:
4544   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4545   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4546
4547   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4548      Returns true if any matcher matches.  */
4549   bool matches (const char *symbol_name);
4550
4551 private:
4552   /* A reference to the lookup name we're matching against.  */
4553   const lookup_name_info &m_lookup_name;
4554
4555   /* A vector holding all the different symbol name matchers, for all
4556      languages.  */
4557   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4558 };
4559
4560 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4561   (const lookup_name_info &lookup_name)
4562     : m_lookup_name (lookup_name)
4563 {
4564   /* Prepare the vector of comparison functions upfront, to avoid
4565      doing the same work for each symbol.  Care is taken to avoid
4566      matching with the same matcher more than once if/when multiple
4567      languages use the same matcher function.  */
4568   auto &matchers = m_symbol_name_matcher_funcs;
4569   matchers.reserve (nr_languages);
4570
4571   matchers.push_back (default_symbol_name_matcher);
4572
4573   for (int i = 0; i < nr_languages; i++)
4574     {
4575       const language_defn *lang = language_def ((enum language) i);
4576       if (lang->la_get_symbol_name_matcher != NULL)
4577         {
4578           symbol_name_matcher_ftype *name_matcher
4579             = lang->la_get_symbol_name_matcher (m_lookup_name);
4580
4581           /* Don't insert the same comparison routine more than once.
4582              Note that we do this linear walk instead of a cheaper
4583              sorted insert, or use a std::set or something like that,
4584              because relative order of function addresses is not
4585              stable.  This is not a problem in practice because the
4586              number of supported languages is low, and the cost here
4587              is tiny compared to the number of searches we'll do
4588              afterwards using this object.  */
4589           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4590               == matchers.end ())
4591             matchers.push_back (name_matcher);
4592         }
4593     }
4594 }
4595
4596 bool
4597 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4598 {
4599   for (auto matches_name : m_symbol_name_matcher_funcs)
4600     if (matches_name (symbol_name, m_lookup_name, NULL))
4601       return true;
4602
4603   return false;
4604 }
4605
4606 /* Starting from a search name, return the string that finds the upper
4607    bound of all strings that start with SEARCH_NAME in a sorted name
4608    list.  Returns the empty string to indicate that the upper bound is
4609    the end of the list.  */
4610
4611 static std::string
4612 make_sort_after_prefix_name (const char *search_name)
4613 {
4614   /* When looking to complete "func", we find the upper bound of all
4615      symbols that start with "func" by looking for where we'd insert
4616      the closest string that would follow "func" in lexicographical
4617      order.  Usually, that's "func"-with-last-character-incremented,
4618      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4619      will be UTF-8 multi-byte sequences, but we can't be certain.
4620      Especially mind the 0xff character, which is a valid character in
4621      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4622      rule out compilers allowing it in identifiers.  Note that
4623      conveniently, strcmp/strcasecmp are specified to compare
4624      characters interpreted as unsigned char.  So what we do is treat
4625      the whole string as a base 256 number composed of a sequence of
4626      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4627      to 0, and carries 1 to the following more-significant position.
4628      If the very first character in SEARCH_NAME ends up incremented
4629      and carries/overflows, then the upper bound is the end of the
4630      list.  The string after the empty string is also the empty
4631      string.
4632
4633      Some examples of this operation:
4634
4635        SEARCH_NAME  => "+1" RESULT
4636
4637        "abc"              => "abd"
4638        "ab\xff"           => "ac"
4639        "\xff" "a" "\xff"  => "\xff" "b"
4640        "\xff"             => ""
4641        "\xff\xff"         => ""
4642        ""                 => ""
4643
4644      Then, with these symbols for example:
4645
4646       func
4647       func1
4648       fund
4649
4650      completing "func" looks for symbols between "func" and
4651      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4652      which finds "func" and "func1", but not "fund".
4653
4654      And with:
4655
4656       funcÿ     (Latin1 'ÿ' [0xff])
4657       funcÿ1
4658       fund
4659
4660      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4661      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4662
4663      And with:
4664
4665       ÿÿ        (Latin1 'ÿ' [0xff])
4666       ÿÿ1
4667
4668      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4669      the end of the list.
4670   */
4671   std::string after = search_name;
4672   while (!after.empty () && (unsigned char) after.back () == 0xff)
4673     after.pop_back ();
4674   if (!after.empty ())
4675     after.back () = (unsigned char) after.back () + 1;
4676   return after;
4677 }
4678
4679 /* See declaration.  */
4680
4681 std::pair<std::vector<name_component>::const_iterator,
4682           std::vector<name_component>::const_iterator>
4683 mapped_index_base::find_name_components_bounds
4684   (const lookup_name_info &lookup_name_without_params) const
4685 {
4686   auto *name_cmp
4687     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4688
4689   const char *cplus
4690     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4691
4692   /* Comparison function object for lower_bound that matches against a
4693      given symbol name.  */
4694   auto lookup_compare_lower = [&] (const name_component &elem,
4695                                    const char *name)
4696     {
4697       const char *elem_qualified = this->symbol_name_at (elem.idx);
4698       const char *elem_name = elem_qualified + elem.name_offset;
4699       return name_cmp (elem_name, name) < 0;
4700     };
4701
4702   /* Comparison function object for upper_bound that matches against a
4703      given symbol name.  */
4704   auto lookup_compare_upper = [&] (const char *name,
4705                                    const name_component &elem)
4706     {
4707       const char *elem_qualified = this->symbol_name_at (elem.idx);
4708       const char *elem_name = elem_qualified + elem.name_offset;
4709       return name_cmp (name, elem_name) < 0;
4710     };
4711
4712   auto begin = this->name_components.begin ();
4713   auto end = this->name_components.end ();
4714
4715   /* Find the lower bound.  */
4716   auto lower = [&] ()
4717     {
4718       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4719         return begin;
4720       else
4721         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4722     } ();
4723
4724   /* Find the upper bound.  */
4725   auto upper = [&] ()
4726     {
4727       if (lookup_name_without_params.completion_mode ())
4728         {
4729           /* In completion mode, we want UPPER to point past all
4730              symbols names that have the same prefix.  I.e., with
4731              these symbols, and completing "func":
4732
4733               function        << lower bound
4734               function1
4735               other_function  << upper bound
4736
4737              We find the upper bound by looking for the insertion
4738              point of "func"-with-last-character-incremented,
4739              i.e. "fund".  */
4740           std::string after = make_sort_after_prefix_name (cplus);
4741           if (after.empty ())
4742             return end;
4743           return std::lower_bound (lower, end, after.c_str (),
4744                                    lookup_compare_lower);
4745         }
4746       else
4747         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4748     } ();
4749
4750   return {lower, upper};
4751 }
4752
4753 /* See declaration.  */
4754
4755 void
4756 mapped_index_base::build_name_components ()
4757 {
4758   if (!this->name_components.empty ())
4759     return;
4760
4761   this->name_components_casing = case_sensitivity;
4762   auto *name_cmp
4763     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4764
4765   /* The code below only knows how to break apart components of C++
4766      symbol names (and other languages that use '::' as
4767      namespace/module separator).  If we add support for wild matching
4768      to some language that uses some other operator (E.g., Ada, Go and
4769      D use '.'), then we'll need to try splitting the symbol name
4770      according to that language too.  Note that Ada does support wild
4771      matching, but doesn't currently support .gdb_index.  */
4772   auto count = this->symbol_name_count ();
4773   for (offset_type idx = 0; idx < count; idx++)
4774     {
4775       if (this->symbol_name_slot_invalid (idx))
4776         continue;
4777
4778       const char *name = this->symbol_name_at (idx);
4779
4780       /* Add each name component to the name component table.  */
4781       unsigned int previous_len = 0;
4782       for (unsigned int current_len = cp_find_first_component (name);
4783            name[current_len] != '\0';
4784            current_len += cp_find_first_component (name + current_len))
4785         {
4786           gdb_assert (name[current_len] == ':');
4787           this->name_components.push_back ({previous_len, idx});
4788           /* Skip the '::'.  */
4789           current_len += 2;
4790           previous_len = current_len;
4791         }
4792       this->name_components.push_back ({previous_len, idx});
4793     }
4794
4795   /* Sort name_components elements by name.  */
4796   auto name_comp_compare = [&] (const name_component &left,
4797                                 const name_component &right)
4798     {
4799       const char *left_qualified = this->symbol_name_at (left.idx);
4800       const char *right_qualified = this->symbol_name_at (right.idx);
4801
4802       const char *left_name = left_qualified + left.name_offset;
4803       const char *right_name = right_qualified + right.name_offset;
4804
4805       return name_cmp (left_name, right_name) < 0;
4806     };
4807
4808   std::sort (this->name_components.begin (),
4809              this->name_components.end (),
4810              name_comp_compare);
4811 }
4812
4813 /* Helper for dw2_expand_symtabs_matching that works with a
4814    mapped_index_base instead of the containing objfile.  This is split
4815    to a separate function in order to be able to unit test the
4816    name_components matching using a mock mapped_index_base.  For each
4817    symbol name that matches, calls MATCH_CALLBACK, passing it the
4818    symbol's index in the mapped_index_base symbol table.  */
4819
4820 static void
4821 dw2_expand_symtabs_matching_symbol
4822   (mapped_index_base &index,
4823    const lookup_name_info &lookup_name_in,
4824    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4825    enum search_domain kind,
4826    gdb::function_view<void (offset_type)> match_callback)
4827 {
4828   lookup_name_info lookup_name_without_params
4829     = lookup_name_in.make_ignore_params ();
4830   gdb_index_symbol_name_matcher lookup_name_matcher
4831     (lookup_name_without_params);
4832
4833   /* Build the symbol name component sorted vector, if we haven't
4834      yet.  */
4835   index.build_name_components ();
4836
4837   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4838
4839   /* Now for each symbol name in range, check to see if we have a name
4840      match, and if so, call the MATCH_CALLBACK callback.  */
4841
4842   /* The same symbol may appear more than once in the range though.
4843      E.g., if we're looking for symbols that complete "w", and we have
4844      a symbol named "w1::w2", we'll find the two name components for
4845      that same symbol in the range.  To be sure we only call the
4846      callback once per symbol, we first collect the symbol name
4847      indexes that matched in a temporary vector and ignore
4848      duplicates.  */
4849   std::vector<offset_type> matches;
4850   matches.reserve (std::distance (bounds.first, bounds.second));
4851
4852   for (; bounds.first != bounds.second; ++bounds.first)
4853     {
4854       const char *qualified = index.symbol_name_at (bounds.first->idx);
4855
4856       if (!lookup_name_matcher.matches (qualified)
4857           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4858         continue;
4859
4860       matches.push_back (bounds.first->idx);
4861     }
4862
4863   std::sort (matches.begin (), matches.end ());
4864
4865   /* Finally call the callback, once per match.  */
4866   ULONGEST prev = -1;
4867   for (offset_type idx : matches)
4868     {
4869       if (prev != idx)
4870         {
4871           match_callback (idx);
4872           prev = idx;
4873         }
4874     }
4875
4876   /* Above we use a type wider than idx's for 'prev', since 0 and
4877      (offset_type)-1 are both possible values.  */
4878   static_assert (sizeof (prev) > sizeof (offset_type), "");
4879 }
4880
4881 #if GDB_SELF_TEST
4882
4883 namespace selftests { namespace dw2_expand_symtabs_matching {
4884
4885 /* A mock .gdb_index/.debug_names-like name index table, enough to
4886    exercise dw2_expand_symtabs_matching_symbol, which works with the
4887    mapped_index_base interface.  Builds an index from the symbol list
4888    passed as parameter to the constructor.  */
4889 class mock_mapped_index : public mapped_index_base
4890 {
4891 public:
4892   mock_mapped_index (gdb::array_view<const char *> symbols)
4893     : m_symbol_table (symbols)
4894   {}
4895
4896   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4897
4898   /* Return the number of names in the symbol table.  */
4899   virtual size_t symbol_name_count () const
4900   {
4901     return m_symbol_table.size ();
4902   }
4903
4904   /* Get the name of the symbol at IDX in the symbol table.  */
4905   virtual const char *symbol_name_at (offset_type idx) const
4906   {
4907     return m_symbol_table[idx];
4908   }
4909
4910 private:
4911   gdb::array_view<const char *> m_symbol_table;
4912 };
4913
4914 /* Convenience function that converts a NULL pointer to a "<null>"
4915    string, to pass to print routines.  */
4916
4917 static const char *
4918 string_or_null (const char *str)
4919 {
4920   return str != NULL ? str : "<null>";
4921 }
4922
4923 /* Check if a lookup_name_info built from
4924    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4925    index.  EXPECTED_LIST is the list of expected matches, in expected
4926    matching order.  If no match expected, then an empty list is
4927    specified.  Returns true on success.  On failure prints a warning
4928    indicating the file:line that failed, and returns false.  */
4929
4930 static bool
4931 check_match (const char *file, int line,
4932              mock_mapped_index &mock_index,
4933              const char *name, symbol_name_match_type match_type,
4934              bool completion_mode,
4935              std::initializer_list<const char *> expected_list)
4936 {
4937   lookup_name_info lookup_name (name, match_type, completion_mode);
4938
4939   bool matched = true;
4940
4941   auto mismatch = [&] (const char *expected_str,
4942                        const char *got)
4943   {
4944     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4945                "expected=\"%s\", got=\"%s\"\n"),
4946              file, line,
4947              (match_type == symbol_name_match_type::FULL
4948               ? "FULL" : "WILD"),
4949              name, string_or_null (expected_str), string_or_null (got));
4950     matched = false;
4951   };
4952
4953   auto expected_it = expected_list.begin ();
4954   auto expected_end = expected_list.end ();
4955
4956   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4957                                       NULL, ALL_DOMAIN,
4958                                       [&] (offset_type idx)
4959   {
4960     const char *matched_name = mock_index.symbol_name_at (idx);
4961     const char *expected_str
4962       = expected_it == expected_end ? NULL : *expected_it++;
4963
4964     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4965       mismatch (expected_str, matched_name);
4966   });
4967
4968   const char *expected_str
4969   = expected_it == expected_end ? NULL : *expected_it++;
4970   if (expected_str != NULL)
4971     mismatch (expected_str, NULL);
4972
4973   return matched;
4974 }
4975
4976 /* The symbols added to the mock mapped_index for testing (in
4977    canonical form).  */
4978 static const char *test_symbols[] = {
4979   "function",
4980   "std::bar",
4981   "std::zfunction",
4982   "std::zfunction2",
4983   "w1::w2",
4984   "ns::foo<char*>",
4985   "ns::foo<int>",
4986   "ns::foo<long>",
4987   "ns2::tmpl<int>::foo2",
4988   "(anonymous namespace)::A::B::C",
4989
4990   /* These are used to check that the increment-last-char in the
4991      matching algorithm for completion doesn't match "t1_fund" when
4992      completing "t1_func".  */
4993   "t1_func",
4994   "t1_func1",
4995   "t1_fund",
4996   "t1_fund1",
4997
4998   /* A UTF-8 name with multi-byte sequences to make sure that
4999      cp-name-parser understands this as a single identifier ("função"
5000      is "function" in PT).  */
5001   u8"u8função",
5002
5003   /* \377 (0xff) is Latin1 'ÿ'.  */
5004   "yfunc\377",
5005
5006   /* \377 (0xff) is Latin1 'ÿ'.  */
5007   "\377",
5008   "\377\377123",
5009
5010   /* A name with all sorts of complications.  Starts with "z" to make
5011      it easier for the completion tests below.  */
5012 #define Z_SYM_NAME \
5013   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5014     "::tuple<(anonymous namespace)::ui*, " \
5015     "std::default_delete<(anonymous namespace)::ui>, void>"
5016
5017   Z_SYM_NAME
5018 };
5019
5020 /* Returns true if the mapped_index_base::find_name_component_bounds
5021    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5022    in completion mode.  */
5023
5024 static bool
5025 check_find_bounds_finds (mapped_index_base &index,
5026                          const char *search_name,
5027                          gdb::array_view<const char *> expected_syms)
5028 {
5029   lookup_name_info lookup_name (search_name,
5030                                 symbol_name_match_type::FULL, true);
5031
5032   auto bounds = index.find_name_components_bounds (lookup_name);
5033
5034   size_t distance = std::distance (bounds.first, bounds.second);
5035   if (distance != expected_syms.size ())
5036     return false;
5037
5038   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5039     {
5040       auto nc_elem = bounds.first + exp_elem;
5041       const char *qualified = index.symbol_name_at (nc_elem->idx);
5042       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5043         return false;
5044     }
5045
5046   return true;
5047 }
5048
5049 /* Test the lower-level mapped_index::find_name_component_bounds
5050    method.  */
5051
5052 static void
5053 test_mapped_index_find_name_component_bounds ()
5054 {
5055   mock_mapped_index mock_index (test_symbols);
5056
5057   mock_index.build_name_components ();
5058
5059   /* Test the lower-level mapped_index::find_name_component_bounds
5060      method in completion mode.  */
5061   {
5062     static const char *expected_syms[] = {
5063       "t1_func",
5064       "t1_func1",
5065     };
5066
5067     SELF_CHECK (check_find_bounds_finds (mock_index,
5068                                          "t1_func", expected_syms));
5069   }
5070
5071   /* Check that the increment-last-char in the name matching algorithm
5072      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5073   {
5074     static const char *expected_syms1[] = {
5075       "\377",
5076       "\377\377123",
5077     };
5078     SELF_CHECK (check_find_bounds_finds (mock_index,
5079                                          "\377", expected_syms1));
5080
5081     static const char *expected_syms2[] = {
5082       "\377\377123",
5083     };
5084     SELF_CHECK (check_find_bounds_finds (mock_index,
5085                                          "\377\377", expected_syms2));
5086   }
5087 }
5088
5089 /* Test dw2_expand_symtabs_matching_symbol.  */
5090
5091 static void
5092 test_dw2_expand_symtabs_matching_symbol ()
5093 {
5094   mock_mapped_index mock_index (test_symbols);
5095
5096   /* We let all tests run until the end even if some fails, for debug
5097      convenience.  */
5098   bool any_mismatch = false;
5099
5100   /* Create the expected symbols list (an initializer_list).  Needed
5101      because lists have commas, and we need to pass them to CHECK,
5102      which is a macro.  */
5103 #define EXPECT(...) { __VA_ARGS__ }
5104
5105   /* Wrapper for check_match that passes down the current
5106      __FILE__/__LINE__.  */
5107 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5108   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5109                                 mock_index,                             \
5110                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5111                                 EXPECTED_LIST)
5112
5113   /* Identity checks.  */
5114   for (const char *sym : test_symbols)
5115     {
5116       /* Should be able to match all existing symbols.  */
5117       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5118                    EXPECT (sym));
5119
5120       /* Should be able to match all existing symbols with
5121          parameters.  */
5122       std::string with_params = std::string (sym) + "(int)";
5123       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5124                    EXPECT (sym));
5125
5126       /* Should be able to match all existing symbols with
5127          parameters and qualifiers.  */
5128       with_params = std::string (sym) + " ( int ) const";
5129       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5130                    EXPECT (sym));
5131
5132       /* This should really find sym, but cp-name-parser.y doesn't
5133          know about lvalue/rvalue qualifiers yet.  */
5134       with_params = std::string (sym) + " ( int ) &&";
5135       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5136                    {});
5137     }
5138
5139   /* Check that the name matching algorithm for completion doesn't get
5140      confused with Latin1 'ÿ' / 0xff.  */
5141   {
5142     static const char str[] = "\377";
5143     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5144                  EXPECT ("\377", "\377\377123"));
5145   }
5146
5147   /* Check that the increment-last-char in the matching algorithm for
5148      completion doesn't match "t1_fund" when completing "t1_func".  */
5149   {
5150     static const char str[] = "t1_func";
5151     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5152                  EXPECT ("t1_func", "t1_func1"));
5153   }
5154
5155   /* Check that completion mode works at each prefix of the expected
5156      symbol name.  */
5157   {
5158     static const char str[] = "function(int)";
5159     size_t len = strlen (str);
5160     std::string lookup;
5161
5162     for (size_t i = 1; i < len; i++)
5163       {
5164         lookup.assign (str, i);
5165         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5166                      EXPECT ("function"));
5167       }
5168   }
5169
5170   /* While "w" is a prefix of both components, the match function
5171      should still only be called once.  */
5172   {
5173     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5174                  EXPECT ("w1::w2"));
5175     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5176                  EXPECT ("w1::w2"));
5177   }
5178
5179   /* Same, with a "complicated" symbol.  */
5180   {
5181     static const char str[] = Z_SYM_NAME;
5182     size_t len = strlen (str);
5183     std::string lookup;
5184
5185     for (size_t i = 1; i < len; i++)
5186       {
5187         lookup.assign (str, i);
5188         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5189                      EXPECT (Z_SYM_NAME));
5190       }
5191   }
5192
5193   /* In FULL mode, an incomplete symbol doesn't match.  */
5194   {
5195     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5196                  {});
5197   }
5198
5199   /* A complete symbol with parameters matches any overload, since the
5200      index has no overload info.  */
5201   {
5202     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5203                  EXPECT ("std::zfunction", "std::zfunction2"));
5204     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5205                  EXPECT ("std::zfunction", "std::zfunction2"));
5206     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5207                  EXPECT ("std::zfunction", "std::zfunction2"));
5208   }
5209
5210   /* Check that whitespace is ignored appropriately.  A symbol with a
5211      template argument list. */
5212   {
5213     static const char expected[] = "ns::foo<int>";
5214     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5215                  EXPECT (expected));
5216     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5217                  EXPECT (expected));
5218   }
5219
5220   /* Check that whitespace is ignored appropriately.  A symbol with a
5221      template argument list that includes a pointer.  */
5222   {
5223     static const char expected[] = "ns::foo<char*>";
5224     /* Try both completion and non-completion modes.  */
5225     static const bool completion_mode[2] = {false, true};
5226     for (size_t i = 0; i < 2; i++)
5227       {
5228         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5229                      completion_mode[i], EXPECT (expected));
5230         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5231                      completion_mode[i], EXPECT (expected));
5232
5233         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5234                      completion_mode[i], EXPECT (expected));
5235         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5236                      completion_mode[i], EXPECT (expected));
5237       }
5238   }
5239
5240   {
5241     /* Check method qualifiers are ignored.  */
5242     static const char expected[] = "ns::foo<char*>";
5243     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5244                  symbol_name_match_type::FULL, true, EXPECT (expected));
5245     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5246                  symbol_name_match_type::FULL, true, EXPECT (expected));
5247     CHECK_MATCH ("foo < char * >  ( int ) const",
5248                  symbol_name_match_type::WILD, true, EXPECT (expected));
5249     CHECK_MATCH ("foo < char * >  ( int ) &&",
5250                  symbol_name_match_type::WILD, true, EXPECT (expected));
5251   }
5252
5253   /* Test lookup names that don't match anything.  */
5254   {
5255     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5256                  {});
5257
5258     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5259                  {});
5260   }
5261
5262   /* Some wild matching tests, exercising "(anonymous namespace)",
5263      which should not be confused with a parameter list.  */
5264   {
5265     static const char *syms[] = {
5266       "A::B::C",
5267       "B::C",
5268       "C",
5269       "A :: B :: C ( int )",
5270       "B :: C ( int )",
5271       "C ( int )",
5272     };
5273
5274     for (const char *s : syms)
5275       {
5276         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5277                      EXPECT ("(anonymous namespace)::A::B::C"));
5278       }
5279   }
5280
5281   {
5282     static const char expected[] = "ns2::tmpl<int>::foo2";
5283     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5284                  EXPECT (expected));
5285     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5286                  EXPECT (expected));
5287   }
5288
5289   SELF_CHECK (!any_mismatch);
5290
5291 #undef EXPECT
5292 #undef CHECK_MATCH
5293 }
5294
5295 static void
5296 run_test ()
5297 {
5298   test_mapped_index_find_name_component_bounds ();
5299   test_dw2_expand_symtabs_matching_symbol ();
5300 }
5301
5302 }} // namespace selftests::dw2_expand_symtabs_matching
5303
5304 #endif /* GDB_SELF_TEST */
5305
5306 /* If FILE_MATCHER is NULL or if PER_CU has
5307    dwarf2_per_cu_quick_data::MARK set (see
5308    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5309    EXPANSION_NOTIFY on it.  */
5310
5311 static void
5312 dw2_expand_symtabs_matching_one
5313   (struct dwarf2_per_cu_data *per_cu,
5314    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5315    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5316 {
5317   if (file_matcher == NULL || per_cu->v.quick->mark)
5318     {
5319       bool symtab_was_null
5320         = (per_cu->v.quick->compunit_symtab == NULL);
5321
5322       dw2_instantiate_symtab (per_cu);
5323
5324       if (expansion_notify != NULL
5325           && symtab_was_null
5326           && per_cu->v.quick->compunit_symtab != NULL)
5327         expansion_notify (per_cu->v.quick->compunit_symtab);
5328     }
5329 }
5330
5331 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5332    matched, to expand corresponding CUs that were marked.  IDX is the
5333    index of the symbol name that matched.  */
5334
5335 static void
5336 dw2_expand_marked_cus
5337   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5338    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5339    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5340    search_domain kind)
5341 {
5342   offset_type *vec, vec_len, vec_idx;
5343   bool global_seen = false;
5344   mapped_index &index = *dwarf2_per_objfile->index_table;
5345
5346   vec = (offset_type *) (index.constant_pool
5347                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5348   vec_len = MAYBE_SWAP (vec[0]);
5349   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5350     {
5351       struct dwarf2_per_cu_data *per_cu;
5352       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5353       /* This value is only valid for index versions >= 7.  */
5354       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5355       gdb_index_symbol_kind symbol_kind =
5356         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5357       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5358       /* Only check the symbol attributes if they're present.
5359          Indices prior to version 7 don't record them,
5360          and indices >= 7 may elide them for certain symbols
5361          (gold does this).  */
5362       int attrs_valid =
5363         (index.version >= 7
5364          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5365
5366       /* Work around gold/15646.  */
5367       if (attrs_valid)
5368         {
5369           if (!is_static && global_seen)
5370             continue;
5371           if (!is_static)
5372             global_seen = true;
5373         }
5374
5375       /* Only check the symbol's kind if it has one.  */
5376       if (attrs_valid)
5377         {
5378           switch (kind)
5379             {
5380             case VARIABLES_DOMAIN:
5381               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5382                 continue;
5383               break;
5384             case FUNCTIONS_DOMAIN:
5385               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5386                 continue;
5387               break;
5388             case TYPES_DOMAIN:
5389               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5390                 continue;
5391               break;
5392             default:
5393               break;
5394             }
5395         }
5396
5397       /* Don't crash on bad data.  */
5398       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5399                        + dwarf2_per_objfile->n_type_units))
5400         {
5401           complaint (&symfile_complaints,
5402                      _(".gdb_index entry has bad CU index"
5403                        " [in module %s]"),
5404                        objfile_name (dwarf2_per_objfile->objfile));
5405           continue;
5406         }
5407
5408       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5409       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5410                                        expansion_notify);
5411     }
5412 }
5413
5414 /* If FILE_MATCHER is non-NULL, set all the
5415    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5416    that match FILE_MATCHER.  */
5417
5418 static void
5419 dw_expand_symtabs_matching_file_matcher
5420   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5421    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5422 {
5423   if (file_matcher == NULL)
5424     return;
5425
5426   objfile *const objfile = dwarf2_per_objfile->objfile;
5427
5428   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5429                                             htab_eq_pointer,
5430                                             NULL, xcalloc, xfree));
5431   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5432                                                 htab_eq_pointer,
5433                                                 NULL, xcalloc, xfree));
5434
5435   /* The rule is CUs specify all the files, including those used by
5436      any TU, so there's no need to scan TUs here.  */
5437
5438   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5439     {
5440       int j;
5441       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5442       struct quick_file_names *file_data;
5443       void **slot;
5444
5445       QUIT;
5446
5447       per_cu->v.quick->mark = 0;
5448
5449       /* We only need to look at symtabs not already expanded.  */
5450       if (per_cu->v.quick->compunit_symtab)
5451         continue;
5452
5453       file_data = dw2_get_file_names (per_cu);
5454       if (file_data == NULL)
5455         continue;
5456
5457       if (htab_find (visited_not_found.get (), file_data) != NULL)
5458         continue;
5459       else if (htab_find (visited_found.get (), file_data) != NULL)
5460         {
5461           per_cu->v.quick->mark = 1;
5462           continue;
5463         }
5464
5465       for (j = 0; j < file_data->num_file_names; ++j)
5466         {
5467           const char *this_real_name;
5468
5469           if (file_matcher (file_data->file_names[j], false))
5470             {
5471               per_cu->v.quick->mark = 1;
5472               break;
5473             }
5474
5475           /* Before we invoke realpath, which can get expensive when many
5476              files are involved, do a quick comparison of the basenames.  */
5477           if (!basenames_may_differ
5478               && !file_matcher (lbasename (file_data->file_names[j]),
5479                                 true))
5480             continue;
5481
5482           this_real_name = dw2_get_real_path (objfile, file_data, j);
5483           if (file_matcher (this_real_name, false))
5484             {
5485               per_cu->v.quick->mark = 1;
5486               break;
5487             }
5488         }
5489
5490       slot = htab_find_slot (per_cu->v.quick->mark
5491                              ? visited_found.get ()
5492                              : visited_not_found.get (),
5493                              file_data, INSERT);
5494       *slot = file_data;
5495     }
5496 }
5497
5498 static void
5499 dw2_expand_symtabs_matching
5500   (struct objfile *objfile,
5501    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5502    const lookup_name_info &lookup_name,
5503    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5504    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5505    enum search_domain kind)
5506 {
5507   struct dwarf2_per_objfile *dwarf2_per_objfile
5508     = get_dwarf2_per_objfile (objfile);
5509
5510   /* index_table is NULL if OBJF_READNOW.  */
5511   if (!dwarf2_per_objfile->index_table)
5512     return;
5513
5514   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5515
5516   mapped_index &index = *dwarf2_per_objfile->index_table;
5517
5518   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5519                                       symbol_matcher,
5520                                       kind, [&] (offset_type idx)
5521     {
5522       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5523                              expansion_notify, kind);
5524     });
5525 }
5526
5527 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5528    symtab.  */
5529
5530 static struct compunit_symtab *
5531 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5532                                           CORE_ADDR pc)
5533 {
5534   int i;
5535
5536   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5537       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5538     return cust;
5539
5540   if (cust->includes == NULL)
5541     return NULL;
5542
5543   for (i = 0; cust->includes[i]; ++i)
5544     {
5545       struct compunit_symtab *s = cust->includes[i];
5546
5547       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5548       if (s != NULL)
5549         return s;
5550     }
5551
5552   return NULL;
5553 }
5554
5555 static struct compunit_symtab *
5556 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5557                                   struct bound_minimal_symbol msymbol,
5558                                   CORE_ADDR pc,
5559                                   struct obj_section *section,
5560                                   int warn_if_readin)
5561 {
5562   struct dwarf2_per_cu_data *data;
5563   struct compunit_symtab *result;
5564
5565   if (!objfile->psymtabs_addrmap)
5566     return NULL;
5567
5568   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5569                                                      pc);
5570   if (!data)
5571     return NULL;
5572
5573   if (warn_if_readin && data->v.quick->compunit_symtab)
5574     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5575              paddress (get_objfile_arch (objfile), pc));
5576
5577   result
5578     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5579                                                 pc);
5580   gdb_assert (result != NULL);
5581   return result;
5582 }
5583
5584 static void
5585 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5586                           void *data, int need_fullname)
5587 {
5588   struct dwarf2_per_objfile *dwarf2_per_objfile
5589     = get_dwarf2_per_objfile (objfile);
5590
5591   if (!dwarf2_per_objfile->filenames_cache)
5592     {
5593       dwarf2_per_objfile->filenames_cache.emplace ();
5594
5595       htab_up visited (htab_create_alloc (10,
5596                                           htab_hash_pointer, htab_eq_pointer,
5597                                           NULL, xcalloc, xfree));
5598
5599       /* The rule is CUs specify all the files, including those used
5600          by any TU, so there's no need to scan TUs here.  We can
5601          ignore file names coming from already-expanded CUs.  */
5602
5603       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5604         {
5605           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5606
5607           if (per_cu->v.quick->compunit_symtab)
5608             {
5609               void **slot = htab_find_slot (visited.get (),
5610                                             per_cu->v.quick->file_names,
5611                                             INSERT);
5612
5613               *slot = per_cu->v.quick->file_names;
5614             }
5615         }
5616
5617       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5618         {
5619           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5620           struct quick_file_names *file_data;
5621           void **slot;
5622
5623           /* We only need to look at symtabs not already expanded.  */
5624           if (per_cu->v.quick->compunit_symtab)
5625             continue;
5626
5627           file_data = dw2_get_file_names (per_cu);
5628           if (file_data == NULL)
5629             continue;
5630
5631           slot = htab_find_slot (visited.get (), file_data, INSERT);
5632           if (*slot)
5633             {
5634               /* Already visited.  */
5635               continue;
5636             }
5637           *slot = file_data;
5638
5639           for (int j = 0; j < file_data->num_file_names; ++j)
5640             {
5641               const char *filename = file_data->file_names[j];
5642               dwarf2_per_objfile->filenames_cache->seen (filename);
5643             }
5644         }
5645     }
5646
5647   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5648     {
5649       gdb::unique_xmalloc_ptr<char> this_real_name;
5650
5651       if (need_fullname)
5652         this_real_name = gdb_realpath (filename);
5653       (*fun) (filename, this_real_name.get (), data);
5654     });
5655 }
5656
5657 static int
5658 dw2_has_symbols (struct objfile *objfile)
5659 {
5660   return 1;
5661 }
5662
5663 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5664 {
5665   dw2_has_symbols,
5666   dw2_find_last_source_symtab,
5667   dw2_forget_cached_source_info,
5668   dw2_map_symtabs_matching_filename,
5669   dw2_lookup_symbol,
5670   dw2_print_stats,
5671   dw2_dump,
5672   dw2_relocate,
5673   dw2_expand_symtabs_for_function,
5674   dw2_expand_all_symtabs,
5675   dw2_expand_symtabs_with_fullname,
5676   dw2_map_matching_symbols,
5677   dw2_expand_symtabs_matching,
5678   dw2_find_pc_sect_compunit_symtab,
5679   NULL,
5680   dw2_map_symbol_filenames
5681 };
5682
5683 /* DWARF-5 debug_names reader.  */
5684
5685 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5686 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5687
5688 /* A helper function that reads the .debug_names section in SECTION
5689    and fills in MAP.  FILENAME is the name of the file containing the
5690    section; it is used for error reporting.
5691
5692    Returns true if all went well, false otherwise.  */
5693
5694 static bool
5695 read_debug_names_from_section (struct objfile *objfile,
5696                                const char *filename,
5697                                struct dwarf2_section_info *section,
5698                                mapped_debug_names &map)
5699 {
5700   if (dwarf2_section_empty_p (section))
5701     return false;
5702
5703   /* Older elfutils strip versions could keep the section in the main
5704      executable while splitting it for the separate debug info file.  */
5705   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5706     return false;
5707
5708   dwarf2_read_section (objfile, section);
5709
5710   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5711
5712   const gdb_byte *addr = section->buffer;
5713
5714   bfd *const abfd = get_section_bfd_owner (section);
5715
5716   unsigned int bytes_read;
5717   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5718   addr += bytes_read;
5719
5720   map.dwarf5_is_dwarf64 = bytes_read != 4;
5721   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5722   if (bytes_read + length != section->size)
5723     {
5724       /* There may be multiple per-CU indices.  */
5725       warning (_("Section .debug_names in %s length %s does not match "
5726                  "section length %s, ignoring .debug_names."),
5727                filename, plongest (bytes_read + length),
5728                pulongest (section->size));
5729       return false;
5730     }
5731
5732   /* The version number.  */
5733   uint16_t version = read_2_bytes (abfd, addr);
5734   addr += 2;
5735   if (version != 5)
5736     {
5737       warning (_("Section .debug_names in %s has unsupported version %d, "
5738                  "ignoring .debug_names."),
5739                filename, version);
5740       return false;
5741     }
5742
5743   /* Padding.  */
5744   uint16_t padding = read_2_bytes (abfd, addr);
5745   addr += 2;
5746   if (padding != 0)
5747     {
5748       warning (_("Section .debug_names in %s has unsupported padding %d, "
5749                  "ignoring .debug_names."),
5750                filename, padding);
5751       return false;
5752     }
5753
5754   /* comp_unit_count - The number of CUs in the CU list.  */
5755   map.cu_count = read_4_bytes (abfd, addr);
5756   addr += 4;
5757
5758   /* local_type_unit_count - The number of TUs in the local TU
5759      list.  */
5760   map.tu_count = read_4_bytes (abfd, addr);
5761   addr += 4;
5762
5763   /* foreign_type_unit_count - The number of TUs in the foreign TU
5764      list.  */
5765   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5766   addr += 4;
5767   if (foreign_tu_count != 0)
5768     {
5769       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5770                  "ignoring .debug_names."),
5771                filename, static_cast<unsigned long> (foreign_tu_count));
5772       return false;
5773     }
5774
5775   /* bucket_count - The number of hash buckets in the hash lookup
5776      table.  */
5777   map.bucket_count = read_4_bytes (abfd, addr);
5778   addr += 4;
5779
5780   /* name_count - The number of unique names in the index.  */
5781   map.name_count = read_4_bytes (abfd, addr);
5782   addr += 4;
5783
5784   /* abbrev_table_size - The size in bytes of the abbreviations
5785      table.  */
5786   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5787   addr += 4;
5788
5789   /* augmentation_string_size - The size in bytes of the augmentation
5790      string.  This value is rounded up to a multiple of 4.  */
5791   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5792   addr += 4;
5793   map.augmentation_is_gdb = ((augmentation_string_size
5794                               == sizeof (dwarf5_augmentation))
5795                              && memcmp (addr, dwarf5_augmentation,
5796                                         sizeof (dwarf5_augmentation)) == 0);
5797   augmentation_string_size += (-augmentation_string_size) & 3;
5798   addr += augmentation_string_size;
5799
5800   /* List of CUs */
5801   map.cu_table_reordered = addr;
5802   addr += map.cu_count * map.offset_size;
5803
5804   /* List of Local TUs */
5805   map.tu_table_reordered = addr;
5806   addr += map.tu_count * map.offset_size;
5807
5808   /* Hash Lookup Table */
5809   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5810   addr += map.bucket_count * 4;
5811   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5812   addr += map.name_count * 4;
5813
5814   /* Name Table */
5815   map.name_table_string_offs_reordered = addr;
5816   addr += map.name_count * map.offset_size;
5817   map.name_table_entry_offs_reordered = addr;
5818   addr += map.name_count * map.offset_size;
5819
5820   const gdb_byte *abbrev_table_start = addr;
5821   for (;;)
5822     {
5823       unsigned int bytes_read;
5824       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5825       addr += bytes_read;
5826       if (index_num == 0)
5827         break;
5828
5829       const auto insertpair
5830         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5831       if (!insertpair.second)
5832         {
5833           warning (_("Section .debug_names in %s has duplicate index %s, "
5834                      "ignoring .debug_names."),
5835                    filename, pulongest (index_num));
5836           return false;
5837         }
5838       mapped_debug_names::index_val &indexval = insertpair.first->second;
5839       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5840       addr += bytes_read;
5841
5842       for (;;)
5843         {
5844           mapped_debug_names::index_val::attr attr;
5845           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5846           addr += bytes_read;
5847           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5848           addr += bytes_read;
5849           if (attr.form == DW_FORM_implicit_const)
5850             {
5851               attr.implicit_const = read_signed_leb128 (abfd, addr,
5852                                                         &bytes_read);
5853               addr += bytes_read;
5854             }
5855           if (attr.dw_idx == 0 && attr.form == 0)
5856             break;
5857           indexval.attr_vec.push_back (std::move (attr));
5858         }
5859     }
5860   if (addr != abbrev_table_start + abbrev_table_size)
5861     {
5862       warning (_("Section .debug_names in %s has abbreviation_table "
5863                  "of size %zu vs. written as %u, ignoring .debug_names."),
5864                filename, addr - abbrev_table_start, abbrev_table_size);
5865       return false;
5866     }
5867   map.entry_pool = addr;
5868
5869   return true;
5870 }
5871
5872 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5873    list.  */
5874
5875 static void
5876 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5877                                   const mapped_debug_names &map,
5878                                   dwarf2_section_info &section,
5879                                   bool is_dwz, int base_offset)
5880 {
5881   sect_offset sect_off_prev;
5882   for (uint32_t i = 0; i <= map.cu_count; ++i)
5883     {
5884       sect_offset sect_off_next;
5885       if (i < map.cu_count)
5886         {
5887           sect_off_next
5888             = (sect_offset) (extract_unsigned_integer
5889                              (map.cu_table_reordered + i * map.offset_size,
5890                               map.offset_size,
5891                               map.dwarf5_byte_order));
5892         }
5893       else
5894         sect_off_next = (sect_offset) section.size;
5895       if (i >= 1)
5896         {
5897           const ULONGEST length = sect_off_next - sect_off_prev;
5898           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5899             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5900                                          sect_off_prev, length);
5901         }
5902       sect_off_prev = sect_off_next;
5903     }
5904 }
5905
5906 /* Read the CU list from the mapped index, and use it to create all
5907    the CU objects for this dwarf2_per_objfile.  */
5908
5909 static void
5910 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5911                              const mapped_debug_names &map,
5912                              const mapped_debug_names &dwz_map)
5913 {
5914   struct objfile *objfile = dwarf2_per_objfile->objfile;
5915
5916   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5917   dwarf2_per_objfile->all_comp_units
5918     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5919                  dwarf2_per_objfile->n_comp_units);
5920
5921   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5922                                     dwarf2_per_objfile->info,
5923                                     false /* is_dwz */,
5924                                     0 /* base_offset */);
5925
5926   if (dwz_map.cu_count == 0)
5927     return;
5928
5929   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5930   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5931                                     true /* is_dwz */,
5932                                     map.cu_count /* base_offset */);
5933 }
5934
5935 /* Read .debug_names.  If everything went ok, initialize the "quick"
5936    elements of all the CUs and return true.  Otherwise, return false.  */
5937
5938 static bool
5939 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5940 {
5941   mapped_debug_names local_map (dwarf2_per_objfile);
5942   mapped_debug_names dwz_map (dwarf2_per_objfile);
5943   struct objfile *objfile = dwarf2_per_objfile->objfile;
5944
5945   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5946                                       &dwarf2_per_objfile->debug_names,
5947                                       local_map))
5948     return false;
5949
5950   /* Don't use the index if it's empty.  */
5951   if (local_map.name_count == 0)
5952     return false;
5953
5954   /* If there is a .dwz file, read it so we can get its CU list as
5955      well.  */
5956   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5957   if (dwz != NULL)
5958     {
5959       if (!read_debug_names_from_section (objfile,
5960                                           bfd_get_filename (dwz->dwz_bfd),
5961                                           &dwz->debug_names, dwz_map))
5962         {
5963           warning (_("could not read '.debug_names' section from %s; skipping"),
5964                    bfd_get_filename (dwz->dwz_bfd));
5965           return false;
5966         }
5967     }
5968
5969   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5970
5971   if (local_map.tu_count != 0)
5972     {
5973       /* We can only handle a single .debug_types when we have an
5974          index.  */
5975       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5976         return false;
5977
5978       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5979                                                 dwarf2_per_objfile->types, 0);
5980
5981       create_signatured_type_table_from_debug_names
5982         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5983     }
5984
5985   create_addrmap_from_aranges (dwarf2_per_objfile,
5986                                &dwarf2_per_objfile->debug_aranges);
5987
5988   dwarf2_per_objfile->debug_names_table.reset
5989     (new mapped_debug_names (dwarf2_per_objfile));
5990   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5991   dwarf2_per_objfile->using_index = 1;
5992   dwarf2_per_objfile->quick_file_names_table =
5993     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5994
5995   return true;
5996 }
5997
5998 /* Symbol name hashing function as specified by DWARF-5.  */
5999
6000 static uint32_t
6001 dwarf5_djb_hash (const char *str_)
6002 {
6003   const unsigned char *str = (const unsigned char *) str_;
6004
6005   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
6006      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6007
6008   uint32_t hash = 5381;
6009   while (int c = *str++)
6010     hash = hash * 33 + tolower (c);
6011   return hash;
6012 }
6013
6014 /* Type used to manage iterating over all CUs looking for a symbol for
6015    .debug_names.  */
6016
6017 class dw2_debug_names_iterator
6018 {
6019 public:
6020   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6021      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6022   dw2_debug_names_iterator (const mapped_debug_names &map,
6023                             bool want_specific_block,
6024                             block_enum block_index, domain_enum domain,
6025                             const char *name)
6026     : m_map (map), m_want_specific_block (want_specific_block),
6027       m_block_index (block_index), m_domain (domain),
6028       m_addr (find_vec_in_debug_names (map, name))
6029   {}
6030
6031   dw2_debug_names_iterator (const mapped_debug_names &map,
6032                             search_domain search, uint32_t namei)
6033     : m_map (map),
6034       m_search (search),
6035       m_addr (find_vec_in_debug_names (map, namei))
6036   {}
6037
6038   /* Return the next matching CU or NULL if there are no more.  */
6039   dwarf2_per_cu_data *next ();
6040
6041 private:
6042   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6043                                                   const char *name);
6044   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6045                                                   uint32_t namei);
6046
6047   /* The internalized form of .debug_names.  */
6048   const mapped_debug_names &m_map;
6049
6050   /* If true, only look for symbols that match BLOCK_INDEX.  */
6051   const bool m_want_specific_block = false;
6052
6053   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6054      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6055      value.  */
6056   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6057
6058   /* The kind of symbol we're looking for.  */
6059   const domain_enum m_domain = UNDEF_DOMAIN;
6060   const search_domain m_search = ALL_DOMAIN;
6061
6062   /* The list of CUs from the index entry of the symbol, or NULL if
6063      not found.  */
6064   const gdb_byte *m_addr;
6065 };
6066
6067 const char *
6068 mapped_debug_names::namei_to_name (uint32_t namei) const
6069 {
6070   const ULONGEST namei_string_offs
6071     = extract_unsigned_integer ((name_table_string_offs_reordered
6072                                  + namei * offset_size),
6073                                 offset_size,
6074                                 dwarf5_byte_order);
6075   return read_indirect_string_at_offset
6076     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6077 }
6078
6079 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6080    found, return pointer to its pool data.  If NAME cannot be found,
6081    return NULL.  */
6082
6083 const gdb_byte *
6084 dw2_debug_names_iterator::find_vec_in_debug_names
6085   (const mapped_debug_names &map, const char *name)
6086 {
6087   int (*cmp) (const char *, const char *);
6088
6089   if (current_language->la_language == language_cplus
6090       || current_language->la_language == language_fortran
6091       || current_language->la_language == language_d)
6092     {
6093       /* NAME is already canonical.  Drop any qualifiers as
6094          .debug_names does not contain any.  */
6095
6096       if (strchr (name, '(') != NULL)
6097         {
6098           gdb::unique_xmalloc_ptr<char> without_params
6099             = cp_remove_params (name);
6100
6101           if (without_params != NULL)
6102             {
6103               name = without_params.get();
6104             }
6105         }
6106     }
6107
6108   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6109
6110   const uint32_t full_hash = dwarf5_djb_hash (name);
6111   uint32_t namei
6112     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6113                                 (map.bucket_table_reordered
6114                                  + (full_hash % map.bucket_count)), 4,
6115                                 map.dwarf5_byte_order);
6116   if (namei == 0)
6117     return NULL;
6118   --namei;
6119   if (namei >= map.name_count)
6120     {
6121       complaint (&symfile_complaints,
6122                  _("Wrong .debug_names with name index %u but name_count=%u "
6123                    "[in module %s]"),
6124                  namei, map.name_count,
6125                  objfile_name (map.dwarf2_per_objfile->objfile));
6126       return NULL;
6127     }
6128
6129   for (;;)
6130     {
6131       const uint32_t namei_full_hash
6132         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6133                                     (map.hash_table_reordered + namei), 4,
6134                                     map.dwarf5_byte_order);
6135       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6136         return NULL;
6137
6138       if (full_hash == namei_full_hash)
6139         {
6140           const char *const namei_string = map.namei_to_name (namei);
6141
6142 #if 0 /* An expensive sanity check.  */
6143           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6144             {
6145               complaint (&symfile_complaints,
6146                          _("Wrong .debug_names hash for string at index %u "
6147                            "[in module %s]"),
6148                          namei, objfile_name (dwarf2_per_objfile->objfile));
6149               return NULL;
6150             }
6151 #endif
6152
6153           if (cmp (namei_string, name) == 0)
6154             {
6155               const ULONGEST namei_entry_offs
6156                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6157                                              + namei * map.offset_size),
6158                                             map.offset_size, map.dwarf5_byte_order);
6159               return map.entry_pool + namei_entry_offs;
6160             }
6161         }
6162
6163       ++namei;
6164       if (namei >= map.name_count)
6165         return NULL;
6166     }
6167 }
6168
6169 const gdb_byte *
6170 dw2_debug_names_iterator::find_vec_in_debug_names
6171   (const mapped_debug_names &map, uint32_t namei)
6172 {
6173   if (namei >= map.name_count)
6174     {
6175       complaint (&symfile_complaints,
6176                  _("Wrong .debug_names with name index %u but name_count=%u "
6177                    "[in module %s]"),
6178                  namei, map.name_count,
6179                  objfile_name (map.dwarf2_per_objfile->objfile));
6180       return NULL;
6181     }
6182
6183   const ULONGEST namei_entry_offs
6184     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6185                                  + namei * map.offset_size),
6186                                 map.offset_size, map.dwarf5_byte_order);
6187   return map.entry_pool + namei_entry_offs;
6188 }
6189
6190 /* See dw2_debug_names_iterator.  */
6191
6192 dwarf2_per_cu_data *
6193 dw2_debug_names_iterator::next ()
6194 {
6195   if (m_addr == NULL)
6196     return NULL;
6197
6198   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6199   struct objfile *objfile = dwarf2_per_objfile->objfile;
6200   bfd *const abfd = objfile->obfd;
6201
6202  again:
6203
6204   unsigned int bytes_read;
6205   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6206   m_addr += bytes_read;
6207   if (abbrev == 0)
6208     return NULL;
6209
6210   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6211   if (indexval_it == m_map.abbrev_map.cend ())
6212     {
6213       complaint (&symfile_complaints,
6214                  _("Wrong .debug_names undefined abbrev code %s "
6215                    "[in module %s]"),
6216                  pulongest (abbrev), objfile_name (objfile));
6217       return NULL;
6218     }
6219   const mapped_debug_names::index_val &indexval = indexval_it->second;
6220   bool have_is_static = false;
6221   bool is_static;
6222   dwarf2_per_cu_data *per_cu = NULL;
6223   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6224     {
6225       ULONGEST ull;
6226       switch (attr.form)
6227         {
6228         case DW_FORM_implicit_const:
6229           ull = attr.implicit_const;
6230           break;
6231         case DW_FORM_flag_present:
6232           ull = 1;
6233           break;
6234         case DW_FORM_udata:
6235           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6236           m_addr += bytes_read;
6237           break;
6238         default:
6239           complaint (&symfile_complaints,
6240                      _("Unsupported .debug_names form %s [in module %s]"),
6241                      dwarf_form_name (attr.form),
6242                      objfile_name (objfile));
6243           return NULL;
6244         }
6245       switch (attr.dw_idx)
6246         {
6247         case DW_IDX_compile_unit:
6248           /* Don't crash on bad data.  */
6249           if (ull >= dwarf2_per_objfile->n_comp_units)
6250             {
6251               complaint (&symfile_complaints,
6252                          _(".debug_names entry has bad CU index %s"
6253                            " [in module %s]"),
6254                          pulongest (ull),
6255                          objfile_name (dwarf2_per_objfile->objfile));
6256               continue;
6257             }
6258           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6259           break;
6260         case DW_IDX_type_unit:
6261           /* Don't crash on bad data.  */
6262           if (ull >= dwarf2_per_objfile->n_type_units)
6263             {
6264               complaint (&symfile_complaints,
6265                          _(".debug_names entry has bad TU index %s"
6266                            " [in module %s]"),
6267                          pulongest (ull),
6268                          objfile_name (dwarf2_per_objfile->objfile));
6269               continue;
6270             }
6271           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6272                                  dwarf2_per_objfile->n_comp_units + ull);
6273           break;
6274         case DW_IDX_GNU_internal:
6275           if (!m_map.augmentation_is_gdb)
6276             break;
6277           have_is_static = true;
6278           is_static = true;
6279           break;
6280         case DW_IDX_GNU_external:
6281           if (!m_map.augmentation_is_gdb)
6282             break;
6283           have_is_static = true;
6284           is_static = false;
6285           break;
6286         }
6287     }
6288
6289   /* Skip if already read in.  */
6290   if (per_cu->v.quick->compunit_symtab)
6291     goto again;
6292
6293   /* Check static vs global.  */
6294   if (have_is_static)
6295     {
6296       const bool want_static = m_block_index != GLOBAL_BLOCK;
6297       if (m_want_specific_block && want_static != is_static)
6298         goto again;
6299     }
6300
6301   /* Match dw2_symtab_iter_next, symbol_kind
6302      and debug_names::psymbol_tag.  */
6303   switch (m_domain)
6304     {
6305     case VAR_DOMAIN:
6306       switch (indexval.dwarf_tag)
6307         {
6308         case DW_TAG_variable:
6309         case DW_TAG_subprogram:
6310         /* Some types are also in VAR_DOMAIN.  */
6311         case DW_TAG_typedef:
6312         case DW_TAG_structure_type:
6313           break;
6314         default:
6315           goto again;
6316         }
6317       break;
6318     case STRUCT_DOMAIN:
6319       switch (indexval.dwarf_tag)
6320         {
6321         case DW_TAG_typedef:
6322         case DW_TAG_structure_type:
6323           break;
6324         default:
6325           goto again;
6326         }
6327       break;
6328     case LABEL_DOMAIN:
6329       switch (indexval.dwarf_tag)
6330         {
6331         case 0:
6332         case DW_TAG_variable:
6333           break;
6334         default:
6335           goto again;
6336         }
6337       break;
6338     default:
6339       break;
6340     }
6341
6342   /* Match dw2_expand_symtabs_matching, symbol_kind and
6343      debug_names::psymbol_tag.  */
6344   switch (m_search)
6345     {
6346     case VARIABLES_DOMAIN:
6347       switch (indexval.dwarf_tag)
6348         {
6349         case DW_TAG_variable:
6350           break;
6351         default:
6352           goto again;
6353         }
6354       break;
6355     case FUNCTIONS_DOMAIN:
6356       switch (indexval.dwarf_tag)
6357         {
6358         case DW_TAG_subprogram:
6359           break;
6360         default:
6361           goto again;
6362         }
6363       break;
6364     case TYPES_DOMAIN:
6365       switch (indexval.dwarf_tag)
6366         {
6367         case DW_TAG_typedef:
6368         case DW_TAG_structure_type:
6369           break;
6370         default:
6371           goto again;
6372         }
6373       break;
6374     default:
6375       break;
6376     }
6377
6378   return per_cu;
6379 }
6380
6381 static struct compunit_symtab *
6382 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6383                                const char *name, domain_enum domain)
6384 {
6385   const block_enum block_index = static_cast<block_enum> (block_index_int);
6386   struct dwarf2_per_objfile *dwarf2_per_objfile
6387     = get_dwarf2_per_objfile (objfile);
6388
6389   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6390   if (!mapp)
6391     {
6392       /* index is NULL if OBJF_READNOW.  */
6393       return NULL;
6394     }
6395   const auto &map = *mapp;
6396
6397   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6398                                  block_index, domain, name);
6399
6400   struct compunit_symtab *stab_best = NULL;
6401   struct dwarf2_per_cu_data *per_cu;
6402   while ((per_cu = iter.next ()) != NULL)
6403     {
6404       struct symbol *sym, *with_opaque = NULL;
6405       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6406       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6407       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6408
6409       sym = block_find_symbol (block, name, domain,
6410                                block_find_non_opaque_type_preferred,
6411                                &with_opaque);
6412
6413       /* Some caution must be observed with overloaded functions and
6414          methods, since the index will not contain any overload
6415          information (but NAME might contain it).  */
6416
6417       if (sym != NULL
6418           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6419         return stab;
6420       if (with_opaque != NULL
6421           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6422         stab_best = stab;
6423
6424       /* Keep looking through other CUs.  */
6425     }
6426
6427   return stab_best;
6428 }
6429
6430 /* This dumps minimal information about .debug_names.  It is called
6431    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6432    uses this to verify that .debug_names has been loaded.  */
6433
6434 static void
6435 dw2_debug_names_dump (struct objfile *objfile)
6436 {
6437   struct dwarf2_per_objfile *dwarf2_per_objfile
6438     = get_dwarf2_per_objfile (objfile);
6439
6440   gdb_assert (dwarf2_per_objfile->using_index);
6441   printf_filtered (".debug_names:");
6442   if (dwarf2_per_objfile->debug_names_table)
6443     printf_filtered (" exists\n");
6444   else
6445     printf_filtered (" faked for \"readnow\"\n");
6446   printf_filtered ("\n");
6447 }
6448
6449 static void
6450 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6451                                              const char *func_name)
6452 {
6453   struct dwarf2_per_objfile *dwarf2_per_objfile
6454     = get_dwarf2_per_objfile (objfile);
6455
6456   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6457   if (dwarf2_per_objfile->debug_names_table)
6458     {
6459       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6460
6461       /* Note: It doesn't matter what we pass for block_index here.  */
6462       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6463                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6464
6465       struct dwarf2_per_cu_data *per_cu;
6466       while ((per_cu = iter.next ()) != NULL)
6467         dw2_instantiate_symtab (per_cu);
6468     }
6469 }
6470
6471 static void
6472 dw2_debug_names_expand_symtabs_matching
6473   (struct objfile *objfile,
6474    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6475    const lookup_name_info &lookup_name,
6476    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6477    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6478    enum search_domain kind)
6479 {
6480   struct dwarf2_per_objfile *dwarf2_per_objfile
6481     = get_dwarf2_per_objfile (objfile);
6482
6483   /* debug_names_table is NULL if OBJF_READNOW.  */
6484   if (!dwarf2_per_objfile->debug_names_table)
6485     return;
6486
6487   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6488
6489   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6490
6491   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6492                                       symbol_matcher,
6493                                       kind, [&] (offset_type namei)
6494     {
6495       /* The name was matched, now expand corresponding CUs that were
6496          marked.  */
6497       dw2_debug_names_iterator iter (map, kind, namei);
6498
6499       struct dwarf2_per_cu_data *per_cu;
6500       while ((per_cu = iter.next ()) != NULL)
6501         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6502                                          expansion_notify);
6503     });
6504 }
6505
6506 const struct quick_symbol_functions dwarf2_debug_names_functions =
6507 {
6508   dw2_has_symbols,
6509   dw2_find_last_source_symtab,
6510   dw2_forget_cached_source_info,
6511   dw2_map_symtabs_matching_filename,
6512   dw2_debug_names_lookup_symbol,
6513   dw2_print_stats,
6514   dw2_debug_names_dump,
6515   dw2_relocate,
6516   dw2_debug_names_expand_symtabs_for_function,
6517   dw2_expand_all_symtabs,
6518   dw2_expand_symtabs_with_fullname,
6519   dw2_map_matching_symbols,
6520   dw2_debug_names_expand_symtabs_matching,
6521   dw2_find_pc_sect_compunit_symtab,
6522   NULL,
6523   dw2_map_symbol_filenames
6524 };
6525
6526 /* See symfile.h.  */
6527
6528 bool
6529 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6530 {
6531   struct dwarf2_per_objfile *dwarf2_per_objfile
6532     = get_dwarf2_per_objfile (objfile);
6533
6534   /* If we're about to read full symbols, don't bother with the
6535      indices.  In this case we also don't care if some other debug
6536      format is making psymtabs, because they are all about to be
6537      expanded anyway.  */
6538   if ((objfile->flags & OBJF_READNOW))
6539     {
6540       int i;
6541
6542       dwarf2_per_objfile->using_index = 1;
6543       create_all_comp_units (dwarf2_per_objfile);
6544       create_all_type_units (dwarf2_per_objfile);
6545       dwarf2_per_objfile->quick_file_names_table =
6546         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6547
6548       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6549                        + dwarf2_per_objfile->n_type_units); ++i)
6550         {
6551           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6552
6553           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6554                                             struct dwarf2_per_cu_quick_data);
6555         }
6556
6557       /* Return 1 so that gdb sees the "quick" functions.  However,
6558          these functions will be no-ops because we will have expanded
6559          all symtabs.  */
6560       *index_kind = dw_index_kind::GDB_INDEX;
6561       return true;
6562     }
6563
6564   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6565     {
6566       *index_kind = dw_index_kind::DEBUG_NAMES;
6567       return true;
6568     }
6569
6570   if (dwarf2_read_index (objfile))
6571     {
6572       *index_kind = dw_index_kind::GDB_INDEX;
6573       return true;
6574     }
6575
6576   return false;
6577 }
6578
6579 \f
6580
6581 /* Build a partial symbol table.  */
6582
6583 void
6584 dwarf2_build_psymtabs (struct objfile *objfile)
6585 {
6586   struct dwarf2_per_objfile *dwarf2_per_objfile
6587     = get_dwarf2_per_objfile (objfile);
6588
6589   if (objfile->global_psymbols.capacity () == 0
6590       && objfile->static_psymbols.capacity () == 0)
6591     init_psymbol_list (objfile, 1024);
6592
6593   TRY
6594     {
6595       /* This isn't really ideal: all the data we allocate on the
6596          objfile's obstack is still uselessly kept around.  However,
6597          freeing it seems unsafe.  */
6598       psymtab_discarder psymtabs (objfile);
6599       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6600       psymtabs.keep ();
6601     }
6602   CATCH (except, RETURN_MASK_ERROR)
6603     {
6604       exception_print (gdb_stderr, except);
6605     }
6606   END_CATCH
6607 }
6608
6609 /* Return the total length of the CU described by HEADER.  */
6610
6611 static unsigned int
6612 get_cu_length (const struct comp_unit_head *header)
6613 {
6614   return header->initial_length_size + header->length;
6615 }
6616
6617 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6618
6619 static inline bool
6620 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6621 {
6622   sect_offset bottom = cu_header->sect_off;
6623   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6624
6625   return sect_off >= bottom && sect_off < top;
6626 }
6627
6628 /* Find the base address of the compilation unit for range lists and
6629    location lists.  It will normally be specified by DW_AT_low_pc.
6630    In DWARF-3 draft 4, the base address could be overridden by
6631    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6632    compilation units with discontinuous ranges.  */
6633
6634 static void
6635 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6636 {
6637   struct attribute *attr;
6638
6639   cu->base_known = 0;
6640   cu->base_address = 0;
6641
6642   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6643   if (attr)
6644     {
6645       cu->base_address = attr_value_as_address (attr);
6646       cu->base_known = 1;
6647     }
6648   else
6649     {
6650       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6651       if (attr)
6652         {
6653           cu->base_address = attr_value_as_address (attr);
6654           cu->base_known = 1;
6655         }
6656     }
6657 }
6658
6659 /* Read in the comp unit header information from the debug_info at info_ptr.
6660    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6661    NOTE: This leaves members offset, first_die_offset to be filled in
6662    by the caller.  */
6663
6664 static const gdb_byte *
6665 read_comp_unit_head (struct comp_unit_head *cu_header,
6666                      const gdb_byte *info_ptr,
6667                      struct dwarf2_section_info *section,
6668                      rcuh_kind section_kind)
6669 {
6670   int signed_addr;
6671   unsigned int bytes_read;
6672   const char *filename = get_section_file_name (section);
6673   bfd *abfd = get_section_bfd_owner (section);
6674
6675   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6676   cu_header->initial_length_size = bytes_read;
6677   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6678   info_ptr += bytes_read;
6679   cu_header->version = read_2_bytes (abfd, info_ptr);
6680   info_ptr += 2;
6681   if (cu_header->version < 5)
6682     switch (section_kind)
6683       {
6684       case rcuh_kind::COMPILE:
6685         cu_header->unit_type = DW_UT_compile;
6686         break;
6687       case rcuh_kind::TYPE:
6688         cu_header->unit_type = DW_UT_type;
6689         break;
6690       default:
6691         internal_error (__FILE__, __LINE__,
6692                         _("read_comp_unit_head: invalid section_kind"));
6693       }
6694   else
6695     {
6696       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6697                                                  (read_1_byte (abfd, info_ptr));
6698       info_ptr += 1;
6699       switch (cu_header->unit_type)
6700         {
6701         case DW_UT_compile:
6702           if (section_kind != rcuh_kind::COMPILE)
6703             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6704                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6705                    filename);
6706           break;
6707         case DW_UT_type:
6708           section_kind = rcuh_kind::TYPE;
6709           break;
6710         default:
6711           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6712                  "(is %d, should be %d or %d) [in module %s]"),
6713                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6714         }
6715
6716       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6717       info_ptr += 1;
6718     }
6719   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6720                                                           cu_header,
6721                                                           &bytes_read);
6722   info_ptr += bytes_read;
6723   if (cu_header->version < 5)
6724     {
6725       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6726       info_ptr += 1;
6727     }
6728   signed_addr = bfd_get_sign_extend_vma (abfd);
6729   if (signed_addr < 0)
6730     internal_error (__FILE__, __LINE__,
6731                     _("read_comp_unit_head: dwarf from non elf file"));
6732   cu_header->signed_addr_p = signed_addr;
6733
6734   if (section_kind == rcuh_kind::TYPE)
6735     {
6736       LONGEST type_offset;
6737
6738       cu_header->signature = read_8_bytes (abfd, info_ptr);
6739       info_ptr += 8;
6740
6741       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6742       info_ptr += bytes_read;
6743       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6744       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6745         error (_("Dwarf Error: Too big type_offset in compilation unit "
6746                "header (is %s) [in module %s]"), plongest (type_offset),
6747                filename);
6748     }
6749
6750   return info_ptr;
6751 }
6752
6753 /* Helper function that returns the proper abbrev section for
6754    THIS_CU.  */
6755
6756 static struct dwarf2_section_info *
6757 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6758 {
6759   struct dwarf2_section_info *abbrev;
6760   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6761
6762   if (this_cu->is_dwz)
6763     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6764   else
6765     abbrev = &dwarf2_per_objfile->abbrev;
6766
6767   return abbrev;
6768 }
6769
6770 /* Subroutine of read_and_check_comp_unit_head and
6771    read_and_check_type_unit_head to simplify them.
6772    Perform various error checking on the header.  */
6773
6774 static void
6775 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6776                             struct comp_unit_head *header,
6777                             struct dwarf2_section_info *section,
6778                             struct dwarf2_section_info *abbrev_section)
6779 {
6780   const char *filename = get_section_file_name (section);
6781
6782   if (header->version < 2 || header->version > 5)
6783     error (_("Dwarf Error: wrong version in compilation unit header "
6784            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6785            filename);
6786
6787   if (to_underlying (header->abbrev_sect_off)
6788       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6789     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6790            "(offset 0x%x + 6) [in module %s]"),
6791            to_underlying (header->abbrev_sect_off),
6792            to_underlying (header->sect_off),
6793            filename);
6794
6795   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6796      avoid potential 32-bit overflow.  */
6797   if (((ULONGEST) header->sect_off + get_cu_length (header))
6798       > section->size)
6799     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6800            "(offset 0x%x + 0) [in module %s]"),
6801            header->length, to_underlying (header->sect_off),
6802            filename);
6803 }
6804
6805 /* Read in a CU/TU header and perform some basic error checking.
6806    The contents of the header are stored in HEADER.
6807    The result is a pointer to the start of the first DIE.  */
6808
6809 static const gdb_byte *
6810 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6811                                struct comp_unit_head *header,
6812                                struct dwarf2_section_info *section,
6813                                struct dwarf2_section_info *abbrev_section,
6814                                const gdb_byte *info_ptr,
6815                                rcuh_kind section_kind)
6816 {
6817   const gdb_byte *beg_of_comp_unit = info_ptr;
6818
6819   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6820
6821   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6822
6823   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6824
6825   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6826                               abbrev_section);
6827
6828   return info_ptr;
6829 }
6830
6831 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6832
6833 static sect_offset
6834 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6835                     struct dwarf2_section_info *section,
6836                     sect_offset sect_off)
6837 {
6838   bfd *abfd = get_section_bfd_owner (section);
6839   const gdb_byte *info_ptr;
6840   unsigned int initial_length_size, offset_size;
6841   uint16_t version;
6842
6843   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6844   info_ptr = section->buffer + to_underlying (sect_off);
6845   read_initial_length (abfd, info_ptr, &initial_length_size);
6846   offset_size = initial_length_size == 4 ? 4 : 8;
6847   info_ptr += initial_length_size;
6848
6849   version = read_2_bytes (abfd, info_ptr);
6850   info_ptr += 2;
6851   if (version >= 5)
6852     {
6853       /* Skip unit type and address size.  */
6854       info_ptr += 2;
6855     }
6856
6857   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6858 }
6859
6860 /* Allocate a new partial symtab for file named NAME and mark this new
6861    partial symtab as being an include of PST.  */
6862
6863 static void
6864 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6865                                struct objfile *objfile)
6866 {
6867   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6868
6869   if (!IS_ABSOLUTE_PATH (subpst->filename))
6870     {
6871       /* It shares objfile->objfile_obstack.  */
6872       subpst->dirname = pst->dirname;
6873     }
6874
6875   subpst->textlow = 0;
6876   subpst->texthigh = 0;
6877
6878   subpst->dependencies
6879     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6880   subpst->dependencies[0] = pst;
6881   subpst->number_of_dependencies = 1;
6882
6883   subpst->globals_offset = 0;
6884   subpst->n_global_syms = 0;
6885   subpst->statics_offset = 0;
6886   subpst->n_static_syms = 0;
6887   subpst->compunit_symtab = NULL;
6888   subpst->read_symtab = pst->read_symtab;
6889   subpst->readin = 0;
6890
6891   /* No private part is necessary for include psymtabs.  This property
6892      can be used to differentiate between such include psymtabs and
6893      the regular ones.  */
6894   subpst->read_symtab_private = NULL;
6895 }
6896
6897 /* Read the Line Number Program data and extract the list of files
6898    included by the source file represented by PST.  Build an include
6899    partial symtab for each of these included files.  */
6900
6901 static void
6902 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6903                                struct die_info *die,
6904                                struct partial_symtab *pst)
6905 {
6906   line_header_up lh;
6907   struct attribute *attr;
6908
6909   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6910   if (attr)
6911     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6912   if (lh == NULL)
6913     return;  /* No linetable, so no includes.  */
6914
6915   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6916   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6917 }
6918
6919 static hashval_t
6920 hash_signatured_type (const void *item)
6921 {
6922   const struct signatured_type *sig_type
6923     = (const struct signatured_type *) item;
6924
6925   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6926   return sig_type->signature;
6927 }
6928
6929 static int
6930 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6931 {
6932   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6933   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6934
6935   return lhs->signature == rhs->signature;
6936 }
6937
6938 /* Allocate a hash table for signatured types.  */
6939
6940 static htab_t
6941 allocate_signatured_type_table (struct objfile *objfile)
6942 {
6943   return htab_create_alloc_ex (41,
6944                                hash_signatured_type,
6945                                eq_signatured_type,
6946                                NULL,
6947                                &objfile->objfile_obstack,
6948                                hashtab_obstack_allocate,
6949                                dummy_obstack_deallocate);
6950 }
6951
6952 /* A helper function to add a signatured type CU to a table.  */
6953
6954 static int
6955 add_signatured_type_cu_to_table (void **slot, void *datum)
6956 {
6957   struct signatured_type *sigt = (struct signatured_type *) *slot;
6958   struct signatured_type ***datap = (struct signatured_type ***) datum;
6959
6960   **datap = sigt;
6961   ++*datap;
6962
6963   return 1;
6964 }
6965
6966 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6967    and fill them into TYPES_HTAB.  It will process only type units,
6968    therefore DW_UT_type.  */
6969
6970 static void
6971 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6972                               struct dwo_file *dwo_file,
6973                               dwarf2_section_info *section, htab_t &types_htab,
6974                               rcuh_kind section_kind)
6975 {
6976   struct objfile *objfile = dwarf2_per_objfile->objfile;
6977   struct dwarf2_section_info *abbrev_section;
6978   bfd *abfd;
6979   const gdb_byte *info_ptr, *end_ptr;
6980
6981   abbrev_section = (dwo_file != NULL
6982                     ? &dwo_file->sections.abbrev
6983                     : &dwarf2_per_objfile->abbrev);
6984
6985   if (dwarf_read_debug)
6986     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6987                         get_section_name (section),
6988                         get_section_file_name (abbrev_section));
6989
6990   dwarf2_read_section (objfile, section);
6991   info_ptr = section->buffer;
6992
6993   if (info_ptr == NULL)
6994     return;
6995
6996   /* We can't set abfd until now because the section may be empty or
6997      not present, in which case the bfd is unknown.  */
6998   abfd = get_section_bfd_owner (section);
6999
7000   /* We don't use init_cutu_and_read_dies_simple, or some such, here
7001      because we don't need to read any dies: the signature is in the
7002      header.  */
7003
7004   end_ptr = info_ptr + section->size;
7005   while (info_ptr < end_ptr)
7006     {
7007       struct signatured_type *sig_type;
7008       struct dwo_unit *dwo_tu;
7009       void **slot;
7010       const gdb_byte *ptr = info_ptr;
7011       struct comp_unit_head header;
7012       unsigned int length;
7013
7014       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7015
7016       /* Initialize it due to a false compiler warning.  */
7017       header.signature = -1;
7018       header.type_cu_offset_in_tu = (cu_offset) -1;
7019
7020       /* We need to read the type's signature in order to build the hash
7021          table, but we don't need anything else just yet.  */
7022
7023       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7024                                            abbrev_section, ptr, section_kind);
7025
7026       length = get_cu_length (&header);
7027
7028       /* Skip dummy type units.  */
7029       if (ptr >= info_ptr + length
7030           || peek_abbrev_code (abfd, ptr) == 0
7031           || header.unit_type != DW_UT_type)
7032         {
7033           info_ptr += length;
7034           continue;
7035         }
7036
7037       if (types_htab == NULL)
7038         {
7039           if (dwo_file)
7040             types_htab = allocate_dwo_unit_table (objfile);
7041           else
7042             types_htab = allocate_signatured_type_table (objfile);
7043         }
7044
7045       if (dwo_file)
7046         {
7047           sig_type = NULL;
7048           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7049                                    struct dwo_unit);
7050           dwo_tu->dwo_file = dwo_file;
7051           dwo_tu->signature = header.signature;
7052           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7053           dwo_tu->section = section;
7054           dwo_tu->sect_off = sect_off;
7055           dwo_tu->length = length;
7056         }
7057       else
7058         {
7059           /* N.B.: type_offset is not usable if this type uses a DWO file.
7060              The real type_offset is in the DWO file.  */
7061           dwo_tu = NULL;
7062           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7063                                      struct signatured_type);
7064           sig_type->signature = header.signature;
7065           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7066           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7067           sig_type->per_cu.is_debug_types = 1;
7068           sig_type->per_cu.section = section;
7069           sig_type->per_cu.sect_off = sect_off;
7070           sig_type->per_cu.length = length;
7071         }
7072
7073       slot = htab_find_slot (types_htab,
7074                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7075                              INSERT);
7076       gdb_assert (slot != NULL);
7077       if (*slot != NULL)
7078         {
7079           sect_offset dup_sect_off;
7080
7081           if (dwo_file)
7082             {
7083               const struct dwo_unit *dup_tu
7084                 = (const struct dwo_unit *) *slot;
7085
7086               dup_sect_off = dup_tu->sect_off;
7087             }
7088           else
7089             {
7090               const struct signatured_type *dup_tu
7091                 = (const struct signatured_type *) *slot;
7092
7093               dup_sect_off = dup_tu->per_cu.sect_off;
7094             }
7095
7096           complaint (&symfile_complaints,
7097                      _("debug type entry at offset 0x%x is duplicate to"
7098                        " the entry at offset 0x%x, signature %s"),
7099                      to_underlying (sect_off), to_underlying (dup_sect_off),
7100                      hex_string (header.signature));
7101         }
7102       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7103
7104       if (dwarf_read_debug > 1)
7105         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7106                             to_underlying (sect_off),
7107                             hex_string (header.signature));
7108
7109       info_ptr += length;
7110     }
7111 }
7112
7113 /* Create the hash table of all entries in the .debug_types
7114    (or .debug_types.dwo) section(s).
7115    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7116    otherwise it is NULL.
7117
7118    The result is a pointer to the hash table or NULL if there are no types.
7119
7120    Note: This function processes DWO files only, not DWP files.  */
7121
7122 static void
7123 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7124                                struct dwo_file *dwo_file,
7125                                VEC (dwarf2_section_info_def) *types,
7126                                htab_t &types_htab)
7127 {
7128   int ix;
7129   struct dwarf2_section_info *section;
7130
7131   if (VEC_empty (dwarf2_section_info_def, types))
7132     return;
7133
7134   for (ix = 0;
7135        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7136        ++ix)
7137     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7138                                   types_htab, rcuh_kind::TYPE);
7139 }
7140
7141 /* Create the hash table of all entries in the .debug_types section,
7142    and initialize all_type_units.
7143    The result is zero if there is an error (e.g. missing .debug_types section),
7144    otherwise non-zero.  */
7145
7146 static int
7147 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7148 {
7149   htab_t types_htab = NULL;
7150   struct signatured_type **iter;
7151
7152   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7153                                 &dwarf2_per_objfile->info, types_htab,
7154                                 rcuh_kind::COMPILE);
7155   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7156                                  dwarf2_per_objfile->types, types_htab);
7157   if (types_htab == NULL)
7158     {
7159       dwarf2_per_objfile->signatured_types = NULL;
7160       return 0;
7161     }
7162
7163   dwarf2_per_objfile->signatured_types = types_htab;
7164
7165   dwarf2_per_objfile->n_type_units
7166     = dwarf2_per_objfile->n_allocated_type_units
7167     = htab_elements (types_htab);
7168   dwarf2_per_objfile->all_type_units =
7169     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7170   iter = &dwarf2_per_objfile->all_type_units[0];
7171   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7172   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7173               == dwarf2_per_objfile->n_type_units);
7174
7175   return 1;
7176 }
7177
7178 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7179    If SLOT is non-NULL, it is the entry to use in the hash table.
7180    Otherwise we find one.  */
7181
7182 static struct signatured_type *
7183 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7184                void **slot)
7185 {
7186   struct objfile *objfile = dwarf2_per_objfile->objfile;
7187   int n_type_units = dwarf2_per_objfile->n_type_units;
7188   struct signatured_type *sig_type;
7189
7190   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7191   ++n_type_units;
7192   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7193     {
7194       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7195         dwarf2_per_objfile->n_allocated_type_units = 1;
7196       dwarf2_per_objfile->n_allocated_type_units *= 2;
7197       dwarf2_per_objfile->all_type_units
7198         = XRESIZEVEC (struct signatured_type *,
7199                       dwarf2_per_objfile->all_type_units,
7200                       dwarf2_per_objfile->n_allocated_type_units);
7201       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7202     }
7203   dwarf2_per_objfile->n_type_units = n_type_units;
7204
7205   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7206                              struct signatured_type);
7207   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7208   sig_type->signature = sig;
7209   sig_type->per_cu.is_debug_types = 1;
7210   if (dwarf2_per_objfile->using_index)
7211     {
7212       sig_type->per_cu.v.quick =
7213         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7214                         struct dwarf2_per_cu_quick_data);
7215     }
7216
7217   if (slot == NULL)
7218     {
7219       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7220                              sig_type, INSERT);
7221     }
7222   gdb_assert (*slot == NULL);
7223   *slot = sig_type;
7224   /* The rest of sig_type must be filled in by the caller.  */
7225   return sig_type;
7226 }
7227
7228 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7229    Fill in SIG_ENTRY with DWO_ENTRY.  */
7230
7231 static void
7232 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7233                                   struct signatured_type *sig_entry,
7234                                   struct dwo_unit *dwo_entry)
7235 {
7236   /* Make sure we're not clobbering something we don't expect to.  */
7237   gdb_assert (! sig_entry->per_cu.queued);
7238   gdb_assert (sig_entry->per_cu.cu == NULL);
7239   if (dwarf2_per_objfile->using_index)
7240     {
7241       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7242       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7243     }
7244   else
7245       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7246   gdb_assert (sig_entry->signature == dwo_entry->signature);
7247   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7248   gdb_assert (sig_entry->type_unit_group == NULL);
7249   gdb_assert (sig_entry->dwo_unit == NULL);
7250
7251   sig_entry->per_cu.section = dwo_entry->section;
7252   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7253   sig_entry->per_cu.length = dwo_entry->length;
7254   sig_entry->per_cu.reading_dwo_directly = 1;
7255   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7256   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7257   sig_entry->dwo_unit = dwo_entry;
7258 }
7259
7260 /* Subroutine of lookup_signatured_type.
7261    If we haven't read the TU yet, create the signatured_type data structure
7262    for a TU to be read in directly from a DWO file, bypassing the stub.
7263    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7264    using .gdb_index, then when reading a CU we want to stay in the DWO file
7265    containing that CU.  Otherwise we could end up reading several other DWO
7266    files (due to comdat folding) to process the transitive closure of all the
7267    mentioned TUs, and that can be slow.  The current DWO file will have every
7268    type signature that it needs.
7269    We only do this for .gdb_index because in the psymtab case we already have
7270    to read all the DWOs to build the type unit groups.  */
7271
7272 static struct signatured_type *
7273 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7274 {
7275   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
7276   struct objfile *objfile = dwarf2_per_objfile->objfile;
7277   struct dwo_file *dwo_file;
7278   struct dwo_unit find_dwo_entry, *dwo_entry;
7279   struct signatured_type find_sig_entry, *sig_entry;
7280   void **slot;
7281
7282   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7283
7284   /* If TU skeletons have been removed then we may not have read in any
7285      TUs yet.  */
7286   if (dwarf2_per_objfile->signatured_types == NULL)
7287     {
7288       dwarf2_per_objfile->signatured_types
7289         = allocate_signatured_type_table (objfile);
7290     }
7291
7292   /* We only ever need to read in one copy of a signatured type.
7293      Use the global signatured_types array to do our own comdat-folding
7294      of types.  If this is the first time we're reading this TU, and
7295      the TU has an entry in .gdb_index, replace the recorded data from
7296      .gdb_index with this TU.  */
7297
7298   find_sig_entry.signature = sig;
7299   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7300                          &find_sig_entry, INSERT);
7301   sig_entry = (struct signatured_type *) *slot;
7302
7303   /* We can get here with the TU already read, *or* in the process of being
7304      read.  Don't reassign the global entry to point to this DWO if that's
7305      the case.  Also note that if the TU is already being read, it may not
7306      have come from a DWO, the program may be a mix of Fission-compiled
7307      code and non-Fission-compiled code.  */
7308
7309   /* Have we already tried to read this TU?
7310      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7311      needn't exist in the global table yet).  */
7312   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7313     return sig_entry;
7314
7315   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7316      dwo_unit of the TU itself.  */
7317   dwo_file = cu->dwo_unit->dwo_file;
7318
7319   /* Ok, this is the first time we're reading this TU.  */
7320   if (dwo_file->tus == NULL)
7321     return NULL;
7322   find_dwo_entry.signature = sig;
7323   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7324   if (dwo_entry == NULL)
7325     return NULL;
7326
7327   /* If the global table doesn't have an entry for this TU, add one.  */
7328   if (sig_entry == NULL)
7329     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7330
7331   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7332   sig_entry->per_cu.tu_read = 1;
7333   return sig_entry;
7334 }
7335
7336 /* Subroutine of lookup_signatured_type.
7337    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7338    then try the DWP file.  If the TU stub (skeleton) has been removed then
7339    it won't be in .gdb_index.  */
7340
7341 static struct signatured_type *
7342 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7343 {
7344   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
7345   struct objfile *objfile = dwarf2_per_objfile->objfile;
7346   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7347   struct dwo_unit *dwo_entry;
7348   struct signatured_type find_sig_entry, *sig_entry;
7349   void **slot;
7350
7351   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7352   gdb_assert (dwp_file != NULL);
7353
7354   /* If TU skeletons have been removed then we may not have read in any
7355      TUs yet.  */
7356   if (dwarf2_per_objfile->signatured_types == NULL)
7357     {
7358       dwarf2_per_objfile->signatured_types
7359         = allocate_signatured_type_table (objfile);
7360     }
7361
7362   find_sig_entry.signature = sig;
7363   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7364                          &find_sig_entry, INSERT);
7365   sig_entry = (struct signatured_type *) *slot;
7366
7367   /* Have we already tried to read this TU?
7368      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7369      needn't exist in the global table yet).  */
7370   if (sig_entry != NULL)
7371     return sig_entry;
7372
7373   if (dwp_file->tus == NULL)
7374     return NULL;
7375   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7376                                       sig, 1 /* is_debug_types */);
7377   if (dwo_entry == NULL)
7378     return NULL;
7379
7380   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7381   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7382
7383   return sig_entry;
7384 }
7385
7386 /* Lookup a signature based type for DW_FORM_ref_sig8.
7387    Returns NULL if signature SIG is not present in the table.
7388    It is up to the caller to complain about this.  */
7389
7390 static struct signatured_type *
7391 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7392 {
7393   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
7394
7395   if (cu->dwo_unit
7396       && dwarf2_per_objfile->using_index)
7397     {
7398       /* We're in a DWO/DWP file, and we're using .gdb_index.
7399          These cases require special processing.  */
7400       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7401         return lookup_dwo_signatured_type (cu, sig);
7402       else
7403         return lookup_dwp_signatured_type (cu, sig);
7404     }
7405   else
7406     {
7407       struct signatured_type find_entry, *entry;
7408
7409       if (dwarf2_per_objfile->signatured_types == NULL)
7410         return NULL;
7411       find_entry.signature = sig;
7412       entry = ((struct signatured_type *)
7413                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7414       return entry;
7415     }
7416 }
7417 \f
7418 /* Low level DIE reading support.  */
7419
7420 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7421
7422 static void
7423 init_cu_die_reader (struct die_reader_specs *reader,
7424                     struct dwarf2_cu *cu,
7425                     struct dwarf2_section_info *section,
7426                     struct dwo_file *dwo_file)
7427 {
7428   gdb_assert (section->readin && section->buffer != NULL);
7429   reader->abfd = get_section_bfd_owner (section);
7430   reader->cu = cu;
7431   reader->dwo_file = dwo_file;
7432   reader->die_section = section;
7433   reader->buffer = section->buffer;
7434   reader->buffer_end = section->buffer + section->size;
7435   reader->comp_dir = NULL;
7436 }
7437
7438 /* Subroutine of init_cutu_and_read_dies to simplify it.
7439    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7440    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7441    already.
7442
7443    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7444    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7445    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7446    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7447    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7448    STUB_COMP_DIR may be non-NULL.
7449    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7450    are filled in with the info of the DIE from the DWO file.
7451    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
7452    provided an abbrev table to use.
7453    The result is non-zero if a valid (non-dummy) DIE was found.  */
7454
7455 static int
7456 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7457                         struct dwo_unit *dwo_unit,
7458                         int abbrev_table_provided,
7459                         struct die_info *stub_comp_unit_die,
7460                         const char *stub_comp_dir,
7461                         struct die_reader_specs *result_reader,
7462                         const gdb_byte **result_info_ptr,
7463                         struct die_info **result_comp_unit_die,
7464                         int *result_has_children)
7465 {
7466   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7467   struct objfile *objfile = dwarf2_per_objfile->objfile;
7468   struct dwarf2_cu *cu = this_cu->cu;
7469   struct dwarf2_section_info *section;
7470   bfd *abfd;
7471   const gdb_byte *begin_info_ptr, *info_ptr;
7472   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7473   int i,num_extra_attrs;
7474   struct dwarf2_section_info *dwo_abbrev_section;
7475   struct attribute *attr;
7476   struct die_info *comp_unit_die;
7477
7478   /* At most one of these may be provided.  */
7479   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7480
7481   /* These attributes aren't processed until later:
7482      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7483      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7484      referenced later.  However, these attributes are found in the stub
7485      which we won't have later.  In order to not impose this complication
7486      on the rest of the code, we read them here and copy them to the
7487      DWO CU/TU die.  */
7488
7489   stmt_list = NULL;
7490   low_pc = NULL;
7491   high_pc = NULL;
7492   ranges = NULL;
7493   comp_dir = NULL;
7494
7495   if (stub_comp_unit_die != NULL)
7496     {
7497       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7498          DWO file.  */
7499       if (! this_cu->is_debug_types)
7500         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7501       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7502       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7503       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7504       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7505
7506       /* There should be a DW_AT_addr_base attribute here (if needed).
7507          We need the value before we can process DW_FORM_GNU_addr_index.  */
7508       cu->addr_base = 0;
7509       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7510       if (attr)
7511         cu->addr_base = DW_UNSND (attr);
7512
7513       /* There should be a DW_AT_ranges_base attribute here (if needed).
7514          We need the value before we can process DW_AT_ranges.  */
7515       cu->ranges_base = 0;
7516       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7517       if (attr)
7518         cu->ranges_base = DW_UNSND (attr);
7519     }
7520   else if (stub_comp_dir != NULL)
7521     {
7522       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7523       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7524       comp_dir->name = DW_AT_comp_dir;
7525       comp_dir->form = DW_FORM_string;
7526       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7527       DW_STRING (comp_dir) = stub_comp_dir;
7528     }
7529
7530   /* Set up for reading the DWO CU/TU.  */
7531   cu->dwo_unit = dwo_unit;
7532   section = dwo_unit->section;
7533   dwarf2_read_section (objfile, section);
7534   abfd = get_section_bfd_owner (section);
7535   begin_info_ptr = info_ptr = (section->buffer
7536                                + to_underlying (dwo_unit->sect_off));
7537   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7538   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
7539
7540   if (this_cu->is_debug_types)
7541     {
7542       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7543
7544       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7545                                                 &cu->header, section,
7546                                                 dwo_abbrev_section,
7547                                                 info_ptr, rcuh_kind::TYPE);
7548       /* This is not an assert because it can be caused by bad debug info.  */
7549       if (sig_type->signature != cu->header.signature)
7550         {
7551           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7552                    " TU at offset 0x%x [in module %s]"),
7553                  hex_string (sig_type->signature),
7554                  hex_string (cu->header.signature),
7555                  to_underlying (dwo_unit->sect_off),
7556                  bfd_get_filename (abfd));
7557         }
7558       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7559       /* For DWOs coming from DWP files, we don't know the CU length
7560          nor the type's offset in the TU until now.  */
7561       dwo_unit->length = get_cu_length (&cu->header);
7562       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7563
7564       /* Establish the type offset that can be used to lookup the type.
7565          For DWO files, we don't know it until now.  */
7566       sig_type->type_offset_in_section
7567         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7568     }
7569   else
7570     {
7571       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7572                                                 &cu->header, section,
7573                                                 dwo_abbrev_section,
7574                                                 info_ptr, rcuh_kind::COMPILE);
7575       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7576       /* For DWOs coming from DWP files, we don't know the CU length
7577          until now.  */
7578       dwo_unit->length = get_cu_length (&cu->header);
7579     }
7580
7581   /* Replace the CU's original abbrev table with the DWO's.
7582      Reminder: We can't read the abbrev table until we've read the header.  */
7583   if (abbrev_table_provided)
7584     {
7585       /* Don't free the provided abbrev table, the caller of
7586          init_cutu_and_read_dies owns it.  */
7587       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7588       /* Ensure the DWO abbrev table gets freed.  */
7589       make_cleanup (dwarf2_free_abbrev_table, cu);
7590     }
7591   else
7592     {
7593       dwarf2_free_abbrev_table (cu);
7594       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7595       /* Leave any existing abbrev table cleanup as is.  */
7596     }
7597
7598   /* Read in the die, but leave space to copy over the attributes
7599      from the stub.  This has the benefit of simplifying the rest of
7600      the code - all the work to maintain the illusion of a single
7601      DW_TAG_{compile,type}_unit DIE is done here.  */
7602   num_extra_attrs = ((stmt_list != NULL)
7603                      + (low_pc != NULL)
7604                      + (high_pc != NULL)
7605                      + (ranges != NULL)
7606                      + (comp_dir != NULL));
7607   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7608                               result_has_children, num_extra_attrs);
7609
7610   /* Copy over the attributes from the stub to the DIE we just read in.  */
7611   comp_unit_die = *result_comp_unit_die;
7612   i = comp_unit_die->num_attrs;
7613   if (stmt_list != NULL)
7614     comp_unit_die->attrs[i++] = *stmt_list;
7615   if (low_pc != NULL)
7616     comp_unit_die->attrs[i++] = *low_pc;
7617   if (high_pc != NULL)
7618     comp_unit_die->attrs[i++] = *high_pc;
7619   if (ranges != NULL)
7620     comp_unit_die->attrs[i++] = *ranges;
7621   if (comp_dir != NULL)
7622     comp_unit_die->attrs[i++] = *comp_dir;
7623   comp_unit_die->num_attrs += num_extra_attrs;
7624
7625   if (dwarf_die_debug)
7626     {
7627       fprintf_unfiltered (gdb_stdlog,
7628                           "Read die from %s@0x%x of %s:\n",
7629                           get_section_name (section),
7630                           (unsigned) (begin_info_ptr - section->buffer),
7631                           bfd_get_filename (abfd));
7632       dump_die (comp_unit_die, dwarf_die_debug);
7633     }
7634
7635   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7636      TUs by skipping the stub and going directly to the entry in the DWO file.
7637      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7638      to get it via circuitous means.  Blech.  */
7639   if (comp_dir != NULL)
7640     result_reader->comp_dir = DW_STRING (comp_dir);
7641
7642   /* Skip dummy compilation units.  */
7643   if (info_ptr >= begin_info_ptr + dwo_unit->length
7644       || peek_abbrev_code (abfd, info_ptr) == 0)
7645     return 0;
7646
7647   *result_info_ptr = info_ptr;
7648   return 1;
7649 }
7650
7651 /* Subroutine of init_cutu_and_read_dies to simplify it.
7652    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7653    Returns NULL if the specified DWO unit cannot be found.  */
7654
7655 static struct dwo_unit *
7656 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7657                  struct die_info *comp_unit_die)
7658 {
7659   struct dwarf2_cu *cu = this_cu->cu;
7660   ULONGEST signature;
7661   struct dwo_unit *dwo_unit;
7662   const char *comp_dir, *dwo_name;
7663
7664   gdb_assert (cu != NULL);
7665
7666   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7667   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7668   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7669
7670   if (this_cu->is_debug_types)
7671     {
7672       struct signatured_type *sig_type;
7673
7674       /* Since this_cu is the first member of struct signatured_type,
7675          we can go from a pointer to one to a pointer to the other.  */
7676       sig_type = (struct signatured_type *) this_cu;
7677       signature = sig_type->signature;
7678       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7679     }
7680   else
7681     {
7682       struct attribute *attr;
7683
7684       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7685       if (! attr)
7686         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7687                  " [in module %s]"),
7688                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7689       signature = DW_UNSND (attr);
7690       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7691                                        signature);
7692     }
7693
7694   return dwo_unit;
7695 }
7696
7697 /* Subroutine of init_cutu_and_read_dies to simplify it.
7698    See it for a description of the parameters.
7699    Read a TU directly from a DWO file, bypassing the stub.
7700
7701    Note: This function could be a little bit simpler if we shared cleanups
7702    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7703    to do, so we keep this function self-contained.  Or we could move this
7704    into our caller, but it's complex enough already.  */
7705
7706 static void
7707 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7708                            int use_existing_cu, int keep,
7709                            die_reader_func_ftype *die_reader_func,
7710                            void *data)
7711 {
7712   struct dwarf2_cu *cu;
7713   struct signatured_type *sig_type;
7714   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7715   struct die_reader_specs reader;
7716   const gdb_byte *info_ptr;
7717   struct die_info *comp_unit_die;
7718   int has_children;
7719   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7720
7721   /* Verify we can do the following downcast, and that we have the
7722      data we need.  */
7723   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7724   sig_type = (struct signatured_type *) this_cu;
7725   gdb_assert (sig_type->dwo_unit != NULL);
7726
7727   cleanups = make_cleanup (null_cleanup, NULL);
7728
7729   if (use_existing_cu && this_cu->cu != NULL)
7730     {
7731       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7732       cu = this_cu->cu;
7733       /* There's no need to do the rereading_dwo_cu handling that
7734          init_cutu_and_read_dies does since we don't read the stub.  */
7735     }
7736   else
7737     {
7738       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7739       gdb_assert (this_cu->cu == NULL);
7740       cu = XNEW (struct dwarf2_cu);
7741       init_one_comp_unit (cu, this_cu);
7742       /* If an error occurs while loading, release our storage.  */
7743       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7744     }
7745
7746   /* A future optimization, if needed, would be to use an existing
7747      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7748      could share abbrev tables.  */
7749
7750   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7751                               0 /* abbrev_table_provided */,
7752                               NULL /* stub_comp_unit_die */,
7753                               sig_type->dwo_unit->dwo_file->comp_dir,
7754                               &reader, &info_ptr,
7755                               &comp_unit_die, &has_children) == 0)
7756     {
7757       /* Dummy die.  */
7758       do_cleanups (cleanups);
7759       return;
7760     }
7761
7762   /* All the "real" work is done here.  */
7763   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7764
7765   /* This duplicates the code in init_cutu_and_read_dies,
7766      but the alternative is making the latter more complex.
7767      This function is only for the special case of using DWO files directly:
7768      no point in overly complicating the general case just to handle this.  */
7769   if (free_cu_cleanup != NULL)
7770     {
7771       if (keep)
7772         {
7773           /* We've successfully allocated this compilation unit.  Let our
7774              caller clean it up when finished with it.  */
7775           discard_cleanups (free_cu_cleanup);
7776
7777           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7778              So we have to manually free the abbrev table.  */
7779           dwarf2_free_abbrev_table (cu);
7780
7781           /* Link this CU into read_in_chain.  */
7782           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7783           dwarf2_per_objfile->read_in_chain = this_cu;
7784         }
7785       else
7786         do_cleanups (free_cu_cleanup);
7787     }
7788
7789   do_cleanups (cleanups);
7790 }
7791
7792 /* Initialize a CU (or TU) and read its DIEs.
7793    If the CU defers to a DWO file, read the DWO file as well.
7794
7795    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7796    Otherwise the table specified in the comp unit header is read in and used.
7797    This is an optimization for when we already have the abbrev table.
7798
7799    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7800    Otherwise, a new CU is allocated with xmalloc.
7801
7802    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7803    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7804
7805    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7806    linker) then DIE_READER_FUNC will not get called.  */
7807
7808 static void
7809 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7810                          struct abbrev_table *abbrev_table,
7811                          int use_existing_cu, int keep,
7812                          die_reader_func_ftype *die_reader_func,
7813                          void *data)
7814 {
7815   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7816   struct objfile *objfile = dwarf2_per_objfile->objfile;
7817   struct dwarf2_section_info *section = this_cu->section;
7818   bfd *abfd = get_section_bfd_owner (section);
7819   struct dwarf2_cu *cu;
7820   const gdb_byte *begin_info_ptr, *info_ptr;
7821   struct die_reader_specs reader;
7822   struct die_info *comp_unit_die;
7823   int has_children;
7824   struct attribute *attr;
7825   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7826   struct signatured_type *sig_type = NULL;
7827   struct dwarf2_section_info *abbrev_section;
7828   /* Non-zero if CU currently points to a DWO file and we need to
7829      reread it.  When this happens we need to reread the skeleton die
7830      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7831   int rereading_dwo_cu = 0;
7832
7833   if (dwarf_die_debug)
7834     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7835                         this_cu->is_debug_types ? "type" : "comp",
7836                         to_underlying (this_cu->sect_off));
7837
7838   if (use_existing_cu)
7839     gdb_assert (keep);
7840
7841   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7842      file (instead of going through the stub), short-circuit all of this.  */
7843   if (this_cu->reading_dwo_directly)
7844     {
7845       /* Narrow down the scope of possibilities to have to understand.  */
7846       gdb_assert (this_cu->is_debug_types);
7847       gdb_assert (abbrev_table == NULL);
7848       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7849                                  die_reader_func, data);
7850       return;
7851     }
7852
7853   cleanups = make_cleanup (null_cleanup, NULL);
7854
7855   /* This is cheap if the section is already read in.  */
7856   dwarf2_read_section (objfile, section);
7857
7858   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7859
7860   abbrev_section = get_abbrev_section_for_cu (this_cu);
7861
7862   if (use_existing_cu && this_cu->cu != NULL)
7863     {
7864       cu = this_cu->cu;
7865       /* If this CU is from a DWO file we need to start over, we need to
7866          refetch the attributes from the skeleton CU.
7867          This could be optimized by retrieving those attributes from when we
7868          were here the first time: the previous comp_unit_die was stored in
7869          comp_unit_obstack.  But there's no data yet that we need this
7870          optimization.  */
7871       if (cu->dwo_unit != NULL)
7872         rereading_dwo_cu = 1;
7873     }
7874   else
7875     {
7876       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7877       gdb_assert (this_cu->cu == NULL);
7878       cu = XNEW (struct dwarf2_cu);
7879       init_one_comp_unit (cu, this_cu);
7880       /* If an error occurs while loading, release our storage.  */
7881       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7882     }
7883
7884   /* Get the header.  */
7885   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7886     {
7887       /* We already have the header, there's no need to read it in again.  */
7888       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7889     }
7890   else
7891     {
7892       if (this_cu->is_debug_types)
7893         {
7894           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7895                                                     &cu->header, section,
7896                                                     abbrev_section, info_ptr,
7897                                                     rcuh_kind::TYPE);
7898
7899           /* Since per_cu is the first member of struct signatured_type,
7900              we can go from a pointer to one to a pointer to the other.  */
7901           sig_type = (struct signatured_type *) this_cu;
7902           gdb_assert (sig_type->signature == cu->header.signature);
7903           gdb_assert (sig_type->type_offset_in_tu
7904                       == cu->header.type_cu_offset_in_tu);
7905           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7906
7907           /* LENGTH has not been set yet for type units if we're
7908              using .gdb_index.  */
7909           this_cu->length = get_cu_length (&cu->header);
7910
7911           /* Establish the type offset that can be used to lookup the type.  */
7912           sig_type->type_offset_in_section =
7913             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7914
7915           this_cu->dwarf_version = cu->header.version;
7916         }
7917       else
7918         {
7919           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7920                                                     &cu->header, section,
7921                                                     abbrev_section,
7922                                                     info_ptr,
7923                                                     rcuh_kind::COMPILE);
7924
7925           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7926           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7927           this_cu->dwarf_version = cu->header.version;
7928         }
7929     }
7930
7931   /* Skip dummy compilation units.  */
7932   if (info_ptr >= begin_info_ptr + this_cu->length
7933       || peek_abbrev_code (abfd, info_ptr) == 0)
7934     {
7935       do_cleanups (cleanups);
7936       return;
7937     }
7938
7939   /* If we don't have them yet, read the abbrevs for this compilation unit.
7940      And if we need to read them now, make sure they're freed when we're
7941      done.  Note that it's important that if the CU had an abbrev table
7942      on entry we don't free it when we're done: Somewhere up the call stack
7943      it may be in use.  */
7944   if (abbrev_table != NULL)
7945     {
7946       gdb_assert (cu->abbrev_table == NULL);
7947       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7948       cu->abbrev_table = abbrev_table;
7949     }
7950   else if (cu->abbrev_table == NULL)
7951     {
7952       dwarf2_read_abbrevs (cu, abbrev_section);
7953       make_cleanup (dwarf2_free_abbrev_table, cu);
7954     }
7955   else if (rereading_dwo_cu)
7956     {
7957       dwarf2_free_abbrev_table (cu);
7958       dwarf2_read_abbrevs (cu, abbrev_section);
7959     }
7960
7961   /* Read the top level CU/TU die.  */
7962   init_cu_die_reader (&reader, cu, section, NULL);
7963   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7964
7965   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7966      from the DWO file.
7967      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7968      DWO CU, that this test will fail (the attribute will not be present).  */
7969   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7970   if (attr)
7971     {
7972       struct dwo_unit *dwo_unit;
7973       struct die_info *dwo_comp_unit_die;
7974
7975       if (has_children)
7976         {
7977           complaint (&symfile_complaints,
7978                      _("compilation unit with DW_AT_GNU_dwo_name"
7979                        " has children (offset 0x%x) [in module %s]"),
7980                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7981         }
7982       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7983       if (dwo_unit != NULL)
7984         {
7985           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7986                                       abbrev_table != NULL,
7987                                       comp_unit_die, NULL,
7988                                       &reader, &info_ptr,
7989                                       &dwo_comp_unit_die, &has_children) == 0)
7990             {
7991               /* Dummy die.  */
7992               do_cleanups (cleanups);
7993               return;
7994             }
7995           comp_unit_die = dwo_comp_unit_die;
7996         }
7997       else
7998         {
7999           /* Yikes, we couldn't find the rest of the DIE, we only have
8000              the stub.  A complaint has already been logged.  There's
8001              not much more we can do except pass on the stub DIE to
8002              die_reader_func.  We don't want to throw an error on bad
8003              debug info.  */
8004         }
8005     }
8006
8007   /* All of the above is setup for this call.  Yikes.  */
8008   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8009
8010   /* Done, clean up.  */
8011   if (free_cu_cleanup != NULL)
8012     {
8013       if (keep)
8014         {
8015           /* We've successfully allocated this compilation unit.  Let our
8016              caller clean it up when finished with it.  */
8017           discard_cleanups (free_cu_cleanup);
8018
8019           /* We can only discard free_cu_cleanup and all subsequent cleanups.
8020              So we have to manually free the abbrev table.  */
8021           dwarf2_free_abbrev_table (cu);
8022
8023           /* Link this CU into read_in_chain.  */
8024           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8025           dwarf2_per_objfile->read_in_chain = this_cu;
8026         }
8027       else
8028         do_cleanups (free_cu_cleanup);
8029     }
8030
8031   do_cleanups (cleanups);
8032 }
8033
8034 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8035    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8036    to have already done the lookup to find the DWO file).
8037
8038    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8039    THIS_CU->is_debug_types, but nothing else.
8040
8041    We fill in THIS_CU->length.
8042
8043    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8044    linker) then DIE_READER_FUNC will not get called.
8045
8046    THIS_CU->cu is always freed when done.
8047    This is done in order to not leave THIS_CU->cu in a state where we have
8048    to care whether it refers to the "main" CU or the DWO CU.  */
8049
8050 static void
8051 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8052                                    struct dwo_file *dwo_file,
8053                                    die_reader_func_ftype *die_reader_func,
8054                                    void *data)
8055 {
8056   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8057   struct objfile *objfile = dwarf2_per_objfile->objfile;
8058   struct dwarf2_section_info *section = this_cu->section;
8059   bfd *abfd = get_section_bfd_owner (section);
8060   struct dwarf2_section_info *abbrev_section;
8061   struct dwarf2_cu cu;
8062   const gdb_byte *begin_info_ptr, *info_ptr;
8063   struct die_reader_specs reader;
8064   struct cleanup *cleanups;
8065   struct die_info *comp_unit_die;
8066   int has_children;
8067
8068   if (dwarf_die_debug)
8069     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
8070                         this_cu->is_debug_types ? "type" : "comp",
8071                         to_underlying (this_cu->sect_off));
8072
8073   gdb_assert (this_cu->cu == NULL);
8074
8075   abbrev_section = (dwo_file != NULL
8076                     ? &dwo_file->sections.abbrev
8077                     : get_abbrev_section_for_cu (this_cu));
8078
8079   /* This is cheap if the section is already read in.  */
8080   dwarf2_read_section (objfile, section);
8081
8082   init_one_comp_unit (&cu, this_cu);
8083
8084   cleanups = make_cleanup (free_stack_comp_unit, &cu);
8085
8086   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8087   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8088                                             &cu.header, section,
8089                                             abbrev_section, info_ptr,
8090                                             (this_cu->is_debug_types
8091                                              ? rcuh_kind::TYPE
8092                                              : rcuh_kind::COMPILE));
8093
8094   this_cu->length = get_cu_length (&cu.header);
8095
8096   /* Skip dummy compilation units.  */
8097   if (info_ptr >= begin_info_ptr + this_cu->length
8098       || peek_abbrev_code (abfd, info_ptr) == 0)
8099     {
8100       do_cleanups (cleanups);
8101       return;
8102     }
8103
8104   dwarf2_read_abbrevs (&cu, abbrev_section);
8105   make_cleanup (dwarf2_free_abbrev_table, &cu);
8106
8107   init_cu_die_reader (&reader, &cu, section, dwo_file);
8108   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8109
8110   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8111
8112   do_cleanups (cleanups);
8113 }
8114
8115 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8116    does not lookup the specified DWO file.
8117    This cannot be used to read DWO files.
8118
8119    THIS_CU->cu is always freed when done.
8120    This is done in order to not leave THIS_CU->cu in a state where we have
8121    to care whether it refers to the "main" CU or the DWO CU.
8122    We can revisit this if the data shows there's a performance issue.  */
8123
8124 static void
8125 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8126                                 die_reader_func_ftype *die_reader_func,
8127                                 void *data)
8128 {
8129   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8130 }
8131 \f
8132 /* Type Unit Groups.
8133
8134    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8135    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8136    so that all types coming from the same compilation (.o file) are grouped
8137    together.  A future step could be to put the types in the same symtab as
8138    the CU the types ultimately came from.  */
8139
8140 static hashval_t
8141 hash_type_unit_group (const void *item)
8142 {
8143   const struct type_unit_group *tu_group
8144     = (const struct type_unit_group *) item;
8145
8146   return hash_stmt_list_entry (&tu_group->hash);
8147 }
8148
8149 static int
8150 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8151 {
8152   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8153   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8154
8155   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8156 }
8157
8158 /* Allocate a hash table for type unit groups.  */
8159
8160 static htab_t
8161 allocate_type_unit_groups_table (struct objfile *objfile)
8162 {
8163   return htab_create_alloc_ex (3,
8164                                hash_type_unit_group,
8165                                eq_type_unit_group,
8166                                NULL,
8167                                &objfile->objfile_obstack,
8168                                hashtab_obstack_allocate,
8169                                dummy_obstack_deallocate);
8170 }
8171
8172 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8173    partial symtabs.  We combine several TUs per psymtab to not let the size
8174    of any one psymtab grow too big.  */
8175 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8176 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8177
8178 /* Helper routine for get_type_unit_group.
8179    Create the type_unit_group object used to hold one or more TUs.  */
8180
8181 static struct type_unit_group *
8182 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8183 {
8184   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
8185   struct objfile *objfile = dwarf2_per_objfile->objfile;
8186   struct dwarf2_per_cu_data *per_cu;
8187   struct type_unit_group *tu_group;
8188
8189   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8190                              struct type_unit_group);
8191   per_cu = &tu_group->per_cu;
8192   per_cu->dwarf2_per_objfile = cu->dwarf2_per_objfile;
8193
8194   if (dwarf2_per_objfile->using_index)
8195     {
8196       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8197                                         struct dwarf2_per_cu_quick_data);
8198     }
8199   else
8200     {
8201       unsigned int line_offset = to_underlying (line_offset_struct);
8202       struct partial_symtab *pst;
8203       char *name;
8204
8205       /* Give the symtab a useful name for debug purposes.  */
8206       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8207         name = xstrprintf ("<type_units_%d>",
8208                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8209       else
8210         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8211
8212       pst = create_partial_symtab (per_cu, name);
8213       pst->anonymous = 1;
8214
8215       xfree (name);
8216     }
8217
8218   tu_group->hash.dwo_unit = cu->dwo_unit;
8219   tu_group->hash.line_sect_off = line_offset_struct;
8220
8221   return tu_group;
8222 }
8223
8224 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8225    STMT_LIST is a DW_AT_stmt_list attribute.  */
8226
8227 static struct type_unit_group *
8228 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8229 {
8230   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
8231   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8232   struct type_unit_group *tu_group;
8233   void **slot;
8234   unsigned int line_offset;
8235   struct type_unit_group type_unit_group_for_lookup;
8236
8237   if (dwarf2_per_objfile->type_unit_groups == NULL)
8238     {
8239       dwarf2_per_objfile->type_unit_groups =
8240         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8241     }
8242
8243   /* Do we need to create a new group, or can we use an existing one?  */
8244
8245   if (stmt_list)
8246     {
8247       line_offset = DW_UNSND (stmt_list);
8248       ++tu_stats->nr_symtab_sharers;
8249     }
8250   else
8251     {
8252       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8253          We can do various things here like create one group per TU or
8254          spread them over multiple groups to split up the expansion work.
8255          To avoid worst case scenarios (too many groups or too large groups)
8256          we, umm, group them in bunches.  */
8257       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8258                      | (tu_stats->nr_stmt_less_type_units
8259                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8260       ++tu_stats->nr_stmt_less_type_units;
8261     }
8262
8263   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8264   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8265   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8266                          &type_unit_group_for_lookup, INSERT);
8267   if (*slot != NULL)
8268     {
8269       tu_group = (struct type_unit_group *) *slot;
8270       gdb_assert (tu_group != NULL);
8271     }
8272   else
8273     {
8274       sect_offset line_offset_struct = (sect_offset) line_offset;
8275       tu_group = create_type_unit_group (cu, line_offset_struct);
8276       *slot = tu_group;
8277       ++tu_stats->nr_symtabs;
8278     }
8279
8280   return tu_group;
8281 }
8282 \f
8283 /* Partial symbol tables.  */
8284
8285 /* Create a psymtab named NAME and assign it to PER_CU.
8286
8287    The caller must fill in the following details:
8288    dirname, textlow, texthigh.  */
8289
8290 static struct partial_symtab *
8291 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8292 {
8293   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8294   struct partial_symtab *pst;
8295
8296   pst = start_psymtab_common (objfile, name, 0,
8297                               objfile->global_psymbols,
8298                               objfile->static_psymbols);
8299
8300   pst->psymtabs_addrmap_supported = 1;
8301
8302   /* This is the glue that links PST into GDB's symbol API.  */
8303   pst->read_symtab_private = per_cu;
8304   pst->read_symtab = dwarf2_read_symtab;
8305   per_cu->v.psymtab = pst;
8306
8307   return pst;
8308 }
8309
8310 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8311    type.  */
8312
8313 struct process_psymtab_comp_unit_data
8314 {
8315   /* True if we are reading a DW_TAG_partial_unit.  */
8316
8317   int want_partial_unit;
8318
8319   /* The "pretend" language that is used if the CU doesn't declare a
8320      language.  */
8321
8322   enum language pretend_language;
8323 };
8324
8325 /* die_reader_func for process_psymtab_comp_unit.  */
8326
8327 static void
8328 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8329                                   const gdb_byte *info_ptr,
8330                                   struct die_info *comp_unit_die,
8331                                   int has_children,
8332                                   void *data)
8333 {
8334   struct dwarf2_cu *cu = reader->cu;
8335   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
8336   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8337   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8338   CORE_ADDR baseaddr;
8339   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8340   struct partial_symtab *pst;
8341   enum pc_bounds_kind cu_bounds_kind;
8342   const char *filename;
8343   struct process_psymtab_comp_unit_data *info
8344     = (struct process_psymtab_comp_unit_data *) data;
8345
8346   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8347     return;
8348
8349   gdb_assert (! per_cu->is_debug_types);
8350
8351   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8352
8353   cu->list_in_scope = &file_symbols;
8354
8355   /* Allocate a new partial symbol table structure.  */
8356   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8357   if (filename == NULL)
8358     filename = "";
8359
8360   pst = create_partial_symtab (per_cu, filename);
8361
8362   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8363   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8364
8365   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8366
8367   dwarf2_find_base_address (comp_unit_die, cu);
8368
8369   /* Possibly set the default values of LOWPC and HIGHPC from
8370      `DW_AT_ranges'.  */
8371   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8372                                          &best_highpc, cu, pst);
8373   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8374     /* Store the contiguous range if it is not empty; it can be empty for
8375        CUs with no code.  */
8376     addrmap_set_empty (objfile->psymtabs_addrmap,
8377                        gdbarch_adjust_dwarf2_addr (gdbarch,
8378                                                    best_lowpc + baseaddr),
8379                        gdbarch_adjust_dwarf2_addr (gdbarch,
8380                                                    best_highpc + baseaddr) - 1,
8381                        pst);
8382
8383   /* Check if comp unit has_children.
8384      If so, read the rest of the partial symbols from this comp unit.
8385      If not, there's no more debug_info for this comp unit.  */
8386   if (has_children)
8387     {
8388       struct partial_die_info *first_die;
8389       CORE_ADDR lowpc, highpc;
8390
8391       lowpc = ((CORE_ADDR) -1);
8392       highpc = ((CORE_ADDR) 0);
8393
8394       first_die = load_partial_dies (reader, info_ptr, 1);
8395
8396       scan_partial_symbols (first_die, &lowpc, &highpc,
8397                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8398
8399       /* If we didn't find a lowpc, set it to highpc to avoid
8400          complaints from `maint check'.  */
8401       if (lowpc == ((CORE_ADDR) -1))
8402         lowpc = highpc;
8403
8404       /* If the compilation unit didn't have an explicit address range,
8405          then use the information extracted from its child dies.  */
8406       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8407         {
8408           best_lowpc = lowpc;
8409           best_highpc = highpc;
8410         }
8411     }
8412   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8413   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8414
8415   end_psymtab_common (objfile, pst);
8416
8417   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8418     {
8419       int i;
8420       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8421       struct dwarf2_per_cu_data *iter;
8422
8423       /* Fill in 'dependencies' here; we fill in 'users' in a
8424          post-pass.  */
8425       pst->number_of_dependencies = len;
8426       pst->dependencies =
8427         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8428       for (i = 0;
8429            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8430                         i, iter);
8431            ++i)
8432         pst->dependencies[i] = iter->v.psymtab;
8433
8434       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8435     }
8436
8437   /* Get the list of files included in the current compilation unit,
8438      and build a psymtab for each of them.  */
8439   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8440
8441   if (dwarf_read_debug)
8442     {
8443       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8444
8445       fprintf_unfiltered (gdb_stdlog,
8446                           "Psymtab for %s unit @0x%x: %s - %s"
8447                           ", %d global, %d static syms\n",
8448                           per_cu->is_debug_types ? "type" : "comp",
8449                           to_underlying (per_cu->sect_off),
8450                           paddress (gdbarch, pst->textlow),
8451                           paddress (gdbarch, pst->texthigh),
8452                           pst->n_global_syms, pst->n_static_syms);
8453     }
8454 }
8455
8456 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8457    Process compilation unit THIS_CU for a psymtab.  */
8458
8459 static void
8460 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8461                            int want_partial_unit,
8462                            enum language pretend_language)
8463 {
8464   /* If this compilation unit was already read in, free the
8465      cached copy in order to read it in again.  This is
8466      necessary because we skipped some symbols when we first
8467      read in the compilation unit (see load_partial_dies).
8468      This problem could be avoided, but the benefit is unclear.  */
8469   if (this_cu->cu != NULL)
8470     free_one_cached_comp_unit (this_cu);
8471
8472   if (this_cu->is_debug_types)
8473     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8474                              NULL);
8475   else
8476     {
8477       process_psymtab_comp_unit_data info;
8478       info.want_partial_unit = want_partial_unit;
8479       info.pretend_language = pretend_language;
8480       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8481                                process_psymtab_comp_unit_reader, &info);
8482     }
8483
8484   /* Age out any secondary CUs.  */
8485   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8486 }
8487
8488 /* Reader function for build_type_psymtabs.  */
8489
8490 static void
8491 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8492                             const gdb_byte *info_ptr,
8493                             struct die_info *type_unit_die,
8494                             int has_children,
8495                             void *data)
8496 {
8497   struct dwarf2_per_objfile *dwarf2_per_objfile
8498     = reader->cu->dwarf2_per_objfile;
8499   struct objfile *objfile = dwarf2_per_objfile->objfile;
8500   struct dwarf2_cu *cu = reader->cu;
8501   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8502   struct signatured_type *sig_type;
8503   struct type_unit_group *tu_group;
8504   struct attribute *attr;
8505   struct partial_die_info *first_die;
8506   CORE_ADDR lowpc, highpc;
8507   struct partial_symtab *pst;
8508
8509   gdb_assert (data == NULL);
8510   gdb_assert (per_cu->is_debug_types);
8511   sig_type = (struct signatured_type *) per_cu;
8512
8513   if (! has_children)
8514     return;
8515
8516   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8517   tu_group = get_type_unit_group (cu, attr);
8518
8519   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8520
8521   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8522   cu->list_in_scope = &file_symbols;
8523   pst = create_partial_symtab (per_cu, "");
8524   pst->anonymous = 1;
8525
8526   first_die = load_partial_dies (reader, info_ptr, 1);
8527
8528   lowpc = (CORE_ADDR) -1;
8529   highpc = (CORE_ADDR) 0;
8530   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8531
8532   end_psymtab_common (objfile, pst);
8533 }
8534
8535 /* Struct used to sort TUs by their abbreviation table offset.  */
8536
8537 struct tu_abbrev_offset
8538 {
8539   struct signatured_type *sig_type;
8540   sect_offset abbrev_offset;
8541 };
8542
8543 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8544
8545 static int
8546 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8547 {
8548   const struct tu_abbrev_offset * const *a
8549     = (const struct tu_abbrev_offset * const*) ap;
8550   const struct tu_abbrev_offset * const *b
8551     = (const struct tu_abbrev_offset * const*) bp;
8552   sect_offset aoff = (*a)->abbrev_offset;
8553   sect_offset boff = (*b)->abbrev_offset;
8554
8555   return (aoff > boff) - (aoff < boff);
8556 }
8557
8558 /* Efficiently read all the type units.
8559    This does the bulk of the work for build_type_psymtabs.
8560
8561    The efficiency is because we sort TUs by the abbrev table they use and
8562    only read each abbrev table once.  In one program there are 200K TUs
8563    sharing 8K abbrev tables.
8564
8565    The main purpose of this function is to support building the
8566    dwarf2_per_objfile->type_unit_groups table.
8567    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8568    can collapse the search space by grouping them by stmt_list.
8569    The savings can be significant, in the same program from above the 200K TUs
8570    share 8K stmt_list tables.
8571
8572    FUNC is expected to call get_type_unit_group, which will create the
8573    struct type_unit_group if necessary and add it to
8574    dwarf2_per_objfile->type_unit_groups.  */
8575
8576 static void
8577 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8578 {
8579   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8580   struct cleanup *cleanups;
8581   struct abbrev_table *abbrev_table;
8582   sect_offset abbrev_offset;
8583   struct tu_abbrev_offset *sorted_by_abbrev;
8584   int i;
8585
8586   /* It's up to the caller to not call us multiple times.  */
8587   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8588
8589   if (dwarf2_per_objfile->n_type_units == 0)
8590     return;
8591
8592   /* TUs typically share abbrev tables, and there can be way more TUs than
8593      abbrev tables.  Sort by abbrev table to reduce the number of times we
8594      read each abbrev table in.
8595      Alternatives are to punt or to maintain a cache of abbrev tables.
8596      This is simpler and efficient enough for now.
8597
8598      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8599      symtab to use).  Typically TUs with the same abbrev offset have the same
8600      stmt_list value too so in practice this should work well.
8601
8602      The basic algorithm here is:
8603
8604       sort TUs by abbrev table
8605       for each TU with same abbrev table:
8606         read abbrev table if first user
8607         read TU top level DIE
8608           [IWBN if DWO skeletons had DW_AT_stmt_list]
8609         call FUNC  */
8610
8611   if (dwarf_read_debug)
8612     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8613
8614   /* Sort in a separate table to maintain the order of all_type_units
8615      for .gdb_index: TU indices directly index all_type_units.  */
8616   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8617                               dwarf2_per_objfile->n_type_units);
8618   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8619     {
8620       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8621
8622       sorted_by_abbrev[i].sig_type = sig_type;
8623       sorted_by_abbrev[i].abbrev_offset =
8624         read_abbrev_offset (dwarf2_per_objfile,
8625                             sig_type->per_cu.section,
8626                             sig_type->per_cu.sect_off);
8627     }
8628   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8629   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8630          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8631
8632   abbrev_offset = (sect_offset) ~(unsigned) 0;
8633   abbrev_table = NULL;
8634   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
8635
8636   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8637     {
8638       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8639
8640       /* Switch to the next abbrev table if necessary.  */
8641       if (abbrev_table == NULL
8642           || tu->abbrev_offset != abbrev_offset)
8643         {
8644           if (abbrev_table != NULL)
8645             {
8646               abbrev_table_free (abbrev_table);
8647               /* Reset to NULL in case abbrev_table_read_table throws
8648                  an error: abbrev_table_free_cleanup will get called.  */
8649               abbrev_table = NULL;
8650             }
8651           abbrev_offset = tu->abbrev_offset;
8652           abbrev_table =
8653             abbrev_table_read_table (dwarf2_per_objfile,
8654                                      &dwarf2_per_objfile->abbrev,
8655                                      abbrev_offset);
8656           ++tu_stats->nr_uniq_abbrev_tables;
8657         }
8658
8659       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
8660                                build_type_psymtabs_reader, NULL);
8661     }
8662
8663   do_cleanups (cleanups);
8664 }
8665
8666 /* Print collected type unit statistics.  */
8667
8668 static void
8669 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8670 {
8671   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8672
8673   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8674   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8675                       dwarf2_per_objfile->n_type_units);
8676   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8677                       tu_stats->nr_uniq_abbrev_tables);
8678   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8679                       tu_stats->nr_symtabs);
8680   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8681                       tu_stats->nr_symtab_sharers);
8682   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8683                       tu_stats->nr_stmt_less_type_units);
8684   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8685                       tu_stats->nr_all_type_units_reallocs);
8686 }
8687
8688 /* Traversal function for build_type_psymtabs.  */
8689
8690 static int
8691 build_type_psymtab_dependencies (void **slot, void *info)
8692 {
8693   struct dwarf2_per_objfile *dwarf2_per_objfile
8694     = (struct dwarf2_per_objfile *) info;
8695   struct objfile *objfile = dwarf2_per_objfile->objfile;
8696   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8697   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8698   struct partial_symtab *pst = per_cu->v.psymtab;
8699   int len = VEC_length (sig_type_ptr, tu_group->tus);
8700   struct signatured_type *iter;
8701   int i;
8702
8703   gdb_assert (len > 0);
8704   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8705
8706   pst->number_of_dependencies = len;
8707   pst->dependencies =
8708     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8709   for (i = 0;
8710        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8711        ++i)
8712     {
8713       gdb_assert (iter->per_cu.is_debug_types);
8714       pst->dependencies[i] = iter->per_cu.v.psymtab;
8715       iter->type_unit_group = tu_group;
8716     }
8717
8718   VEC_free (sig_type_ptr, tu_group->tus);
8719
8720   return 1;
8721 }
8722
8723 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8724    Build partial symbol tables for the .debug_types comp-units.  */
8725
8726 static void
8727 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8728 {
8729   if (! create_all_type_units (dwarf2_per_objfile))
8730     return;
8731
8732   build_type_psymtabs_1 (dwarf2_per_objfile);
8733 }
8734
8735 /* Traversal function for process_skeletonless_type_unit.
8736    Read a TU in a DWO file and build partial symbols for it.  */
8737
8738 static int
8739 process_skeletonless_type_unit (void **slot, void *info)
8740 {
8741   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8742   struct dwarf2_per_objfile *dwarf2_per_objfile
8743     = (struct dwarf2_per_objfile *) info;
8744   struct signatured_type find_entry, *entry;
8745
8746   /* If this TU doesn't exist in the global table, add it and read it in.  */
8747
8748   if (dwarf2_per_objfile->signatured_types == NULL)
8749     {
8750       dwarf2_per_objfile->signatured_types
8751         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8752     }
8753
8754   find_entry.signature = dwo_unit->signature;
8755   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8756                          INSERT);
8757   /* If we've already seen this type there's nothing to do.  What's happening
8758      is we're doing our own version of comdat-folding here.  */
8759   if (*slot != NULL)
8760     return 1;
8761
8762   /* This does the job that create_all_type_units would have done for
8763      this TU.  */
8764   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8765   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8766   *slot = entry;
8767
8768   /* This does the job that build_type_psymtabs_1 would have done.  */
8769   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8770                            build_type_psymtabs_reader, NULL);
8771
8772   return 1;
8773 }
8774
8775 /* Traversal function for process_skeletonless_type_units.  */
8776
8777 static int
8778 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8779 {
8780   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8781
8782   if (dwo_file->tus != NULL)
8783     {
8784       htab_traverse_noresize (dwo_file->tus,
8785                               process_skeletonless_type_unit, info);
8786     }
8787
8788   return 1;
8789 }
8790
8791 /* Scan all TUs of DWO files, verifying we've processed them.
8792    This is needed in case a TU was emitted without its skeleton.
8793    Note: This can't be done until we know what all the DWO files are.  */
8794
8795 static void
8796 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8797 {
8798   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8799   if (get_dwp_file (dwarf2_per_objfile) == NULL
8800       && dwarf2_per_objfile->dwo_files != NULL)
8801     {
8802       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8803                               process_dwo_file_for_skeletonless_type_units,
8804                               dwarf2_per_objfile);
8805     }
8806 }
8807
8808 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8809
8810 static void
8811 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8812 {
8813   int i;
8814
8815   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8816     {
8817       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8818       struct partial_symtab *pst = per_cu->v.psymtab;
8819       int j;
8820
8821       if (pst == NULL)
8822         continue;
8823
8824       for (j = 0; j < pst->number_of_dependencies; ++j)
8825         {
8826           /* Set the 'user' field only if it is not already set.  */
8827           if (pst->dependencies[j]->user == NULL)
8828             pst->dependencies[j]->user = pst;
8829         }
8830     }
8831 }
8832
8833 /* Build the partial symbol table by doing a quick pass through the
8834    .debug_info and .debug_abbrev sections.  */
8835
8836 static void
8837 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8838 {
8839   struct cleanup *back_to;
8840   int i;
8841   struct objfile *objfile = dwarf2_per_objfile->objfile;
8842
8843   if (dwarf_read_debug)
8844     {
8845       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8846                           objfile_name (objfile));
8847     }
8848
8849   dwarf2_per_objfile->reading_partial_symbols = 1;
8850
8851   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8852
8853   /* Any cached compilation units will be linked by the per-objfile
8854      read_in_chain.  Make sure to free them when we're done.  */
8855   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8856
8857   build_type_psymtabs (dwarf2_per_objfile);
8858
8859   create_all_comp_units (dwarf2_per_objfile);
8860
8861   /* Create a temporary address map on a temporary obstack.  We later
8862      copy this to the final obstack.  */
8863   auto_obstack temp_obstack;
8864
8865   scoped_restore save_psymtabs_addrmap
8866     = make_scoped_restore (&objfile->psymtabs_addrmap,
8867                            addrmap_create_mutable (&temp_obstack));
8868
8869   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8870     {
8871       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8872
8873       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8874     }
8875
8876   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8877   process_skeletonless_type_units (dwarf2_per_objfile);
8878
8879   /* Now that all TUs have been processed we can fill in the dependencies.  */
8880   if (dwarf2_per_objfile->type_unit_groups != NULL)
8881     {
8882       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8883                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8884     }
8885
8886   if (dwarf_read_debug)
8887     print_tu_stats (dwarf2_per_objfile);
8888
8889   set_partial_user (dwarf2_per_objfile);
8890
8891   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8892                                                     &objfile->objfile_obstack);
8893   /* At this point we want to keep the address map.  */
8894   save_psymtabs_addrmap.release ();
8895
8896   do_cleanups (back_to);
8897
8898   if (dwarf_read_debug)
8899     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8900                         objfile_name (objfile));
8901 }
8902
8903 /* die_reader_func for load_partial_comp_unit.  */
8904
8905 static void
8906 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8907                                const gdb_byte *info_ptr,
8908                                struct die_info *comp_unit_die,
8909                                int has_children,
8910                                void *data)
8911 {
8912   struct dwarf2_cu *cu = reader->cu;
8913
8914   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8915
8916   /* Check if comp unit has_children.
8917      If so, read the rest of the partial symbols from this comp unit.
8918      If not, there's no more debug_info for this comp unit.  */
8919   if (has_children)
8920     load_partial_dies (reader, info_ptr, 0);
8921 }
8922
8923 /* Load the partial DIEs for a secondary CU into memory.
8924    This is also used when rereading a primary CU with load_all_dies.  */
8925
8926 static void
8927 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8928 {
8929   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8930                            load_partial_comp_unit_reader, NULL);
8931 }
8932
8933 static void
8934 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8935                               struct dwarf2_section_info *section,
8936                               struct dwarf2_section_info *abbrev_section,
8937                               unsigned int is_dwz,
8938                               int *n_allocated,
8939                               int *n_comp_units,
8940                               struct dwarf2_per_cu_data ***all_comp_units)
8941 {
8942   const gdb_byte *info_ptr;
8943   struct objfile *objfile = dwarf2_per_objfile->objfile;
8944
8945   if (dwarf_read_debug)
8946     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8947                         get_section_name (section),
8948                         get_section_file_name (section));
8949
8950   dwarf2_read_section (objfile, section);
8951
8952   info_ptr = section->buffer;
8953
8954   while (info_ptr < section->buffer + section->size)
8955     {
8956       struct dwarf2_per_cu_data *this_cu;
8957
8958       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8959
8960       comp_unit_head cu_header;
8961       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8962                                      abbrev_section, info_ptr,
8963                                      rcuh_kind::COMPILE);
8964
8965       /* Save the compilation unit for later lookup.  */
8966       if (cu_header.unit_type != DW_UT_type)
8967         {
8968           this_cu = XOBNEW (&objfile->objfile_obstack,
8969                             struct dwarf2_per_cu_data);
8970           memset (this_cu, 0, sizeof (*this_cu));
8971         }
8972       else
8973         {
8974           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8975                                   struct signatured_type);
8976           memset (sig_type, 0, sizeof (*sig_type));
8977           sig_type->signature = cu_header.signature;
8978           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8979           this_cu = &sig_type->per_cu;
8980         }
8981       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8982       this_cu->sect_off = sect_off;
8983       this_cu->length = cu_header.length + cu_header.initial_length_size;
8984       this_cu->is_dwz = is_dwz;
8985       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8986       this_cu->section = section;
8987
8988       if (*n_comp_units == *n_allocated)
8989         {
8990           *n_allocated *= 2;
8991           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8992                                         *all_comp_units, *n_allocated);
8993         }
8994       (*all_comp_units)[*n_comp_units] = this_cu;
8995       ++*n_comp_units;
8996
8997       info_ptr = info_ptr + this_cu->length;
8998     }
8999 }
9000
9001 /* Create a list of all compilation units in OBJFILE.
9002    This is only done for -readnow and building partial symtabs.  */
9003
9004 static void
9005 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
9006 {
9007   int n_allocated;
9008   int n_comp_units;
9009   struct dwarf2_per_cu_data **all_comp_units;
9010   struct dwz_file *dwz;
9011   struct objfile *objfile = dwarf2_per_objfile->objfile;
9012
9013   n_comp_units = 0;
9014   n_allocated = 10;
9015   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9016
9017   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9018                                 &dwarf2_per_objfile->abbrev, 0,
9019                                 &n_allocated, &n_comp_units, &all_comp_units);
9020
9021   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9022   if (dwz != NULL)
9023     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9024                                   1, &n_allocated, &n_comp_units,
9025                                   &all_comp_units);
9026
9027   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9028                                                   struct dwarf2_per_cu_data *,
9029                                                   n_comp_units);
9030   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9031           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9032   xfree (all_comp_units);
9033   dwarf2_per_objfile->n_comp_units = n_comp_units;
9034 }
9035
9036 /* Process all loaded DIEs for compilation unit CU, starting at
9037    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9038    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9039    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9040    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9041
9042 static void
9043 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9044                       CORE_ADDR *highpc, int set_addrmap,
9045                       struct dwarf2_cu *cu)
9046 {
9047   struct partial_die_info *pdi;
9048
9049   /* Now, march along the PDI's, descending into ones which have
9050      interesting children but skipping the children of the other ones,
9051      until we reach the end of the compilation unit.  */
9052
9053   pdi = first_die;
9054
9055   while (pdi != NULL)
9056     {
9057       fixup_partial_die (pdi, cu);
9058
9059       /* Anonymous namespaces or modules have no name but have interesting
9060          children, so we need to look at them.  Ditto for anonymous
9061          enums.  */
9062
9063       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9064           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9065           || pdi->tag == DW_TAG_imported_unit)
9066         {
9067           switch (pdi->tag)
9068             {
9069             case DW_TAG_subprogram:
9070               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9071               break;
9072             case DW_TAG_constant:
9073             case DW_TAG_variable:
9074             case DW_TAG_typedef:
9075             case DW_TAG_union_type:
9076               if (!pdi->is_declaration)
9077                 {
9078                   add_partial_symbol (pdi, cu);
9079                 }
9080               break;
9081             case DW_TAG_class_type:
9082             case DW_TAG_interface_type:
9083             case DW_TAG_structure_type:
9084               if (!pdi->is_declaration)
9085                 {
9086                   add_partial_symbol (pdi, cu);
9087                 }
9088               if (cu->language == language_rust && pdi->has_children)
9089                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
9090                                       set_addrmap, cu);
9091               break;
9092             case DW_TAG_enumeration_type:
9093               if (!pdi->is_declaration)
9094                 add_partial_enumeration (pdi, cu);
9095               break;
9096             case DW_TAG_base_type:
9097             case DW_TAG_subrange_type:
9098               /* File scope base type definitions are added to the partial
9099                  symbol table.  */
9100               add_partial_symbol (pdi, cu);
9101               break;
9102             case DW_TAG_namespace:
9103               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
9104               break;
9105             case DW_TAG_module:
9106               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
9107               break;
9108             case DW_TAG_imported_unit:
9109               {
9110                 struct dwarf2_per_cu_data *per_cu;
9111
9112                 /* For now we don't handle imported units in type units.  */
9113                 if (cu->per_cu->is_debug_types)
9114                   {
9115                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
9116                              " supported in type units [in module %s]"),
9117                            objfile_name (cu->dwarf2_per_objfile->objfile));
9118                   }
9119
9120                 per_cu = dwarf2_find_containing_comp_unit
9121                            (pdi->d.sect_off, pdi->is_dwz,
9122                             cu->dwarf2_per_objfile);
9123
9124                 /* Go read the partial unit, if needed.  */
9125                 if (per_cu->v.psymtab == NULL)
9126                   process_psymtab_comp_unit (per_cu, 1, cu->language);
9127
9128                 VEC_safe_push (dwarf2_per_cu_ptr,
9129                                cu->per_cu->imported_symtabs, per_cu);
9130               }
9131               break;
9132             case DW_TAG_imported_declaration:
9133               add_partial_symbol (pdi, cu);
9134               break;
9135             default:
9136               break;
9137             }
9138         }
9139
9140       /* If the die has a sibling, skip to the sibling.  */
9141
9142       pdi = pdi->die_sibling;
9143     }
9144 }
9145
9146 /* Functions used to compute the fully scoped name of a partial DIE.
9147
9148    Normally, this is simple.  For C++, the parent DIE's fully scoped
9149    name is concatenated with "::" and the partial DIE's name.
9150    Enumerators are an exception; they use the scope of their parent
9151    enumeration type, i.e. the name of the enumeration type is not
9152    prepended to the enumerator.
9153
9154    There are two complexities.  One is DW_AT_specification; in this
9155    case "parent" means the parent of the target of the specification,
9156    instead of the direct parent of the DIE.  The other is compilers
9157    which do not emit DW_TAG_namespace; in this case we try to guess
9158    the fully qualified name of structure types from their members'
9159    linkage names.  This must be done using the DIE's children rather
9160    than the children of any DW_AT_specification target.  We only need
9161    to do this for structures at the top level, i.e. if the target of
9162    any DW_AT_specification (if any; otherwise the DIE itself) does not
9163    have a parent.  */
9164
9165 /* Compute the scope prefix associated with PDI's parent, in
9166    compilation unit CU.  The result will be allocated on CU's
9167    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9168    field.  NULL is returned if no prefix is necessary.  */
9169 static const char *
9170 partial_die_parent_scope (struct partial_die_info *pdi,
9171                           struct dwarf2_cu *cu)
9172 {
9173   const char *grandparent_scope;
9174   struct partial_die_info *parent, *real_pdi;
9175
9176   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9177      then this means the parent of the specification DIE.  */
9178
9179   real_pdi = pdi;
9180   while (real_pdi->has_specification)
9181     real_pdi = find_partial_die (real_pdi->spec_offset,
9182                                  real_pdi->spec_is_dwz, cu);
9183
9184   parent = real_pdi->die_parent;
9185   if (parent == NULL)
9186     return NULL;
9187
9188   if (parent->scope_set)
9189     return parent->scope;
9190
9191   fixup_partial_die (parent, cu);
9192
9193   grandparent_scope = partial_die_parent_scope (parent, cu);
9194
9195   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9196      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9197      Work around this problem here.  */
9198   if (cu->language == language_cplus
9199       && parent->tag == DW_TAG_namespace
9200       && strcmp (parent->name, "::") == 0
9201       && grandparent_scope == NULL)
9202     {
9203       parent->scope = NULL;
9204       parent->scope_set = 1;
9205       return NULL;
9206     }
9207
9208   if (pdi->tag == DW_TAG_enumerator)
9209     /* Enumerators should not get the name of the enumeration as a prefix.  */
9210     parent->scope = grandparent_scope;
9211   else if (parent->tag == DW_TAG_namespace
9212       || parent->tag == DW_TAG_module
9213       || parent->tag == DW_TAG_structure_type
9214       || parent->tag == DW_TAG_class_type
9215       || parent->tag == DW_TAG_interface_type
9216       || parent->tag == DW_TAG_union_type
9217       || parent->tag == DW_TAG_enumeration_type)
9218     {
9219       if (grandparent_scope == NULL)
9220         parent->scope = parent->name;
9221       else
9222         parent->scope = typename_concat (&cu->comp_unit_obstack,
9223                                          grandparent_scope,
9224                                          parent->name, 0, cu);
9225     }
9226   else
9227     {
9228       /* FIXME drow/2004-04-01: What should we be doing with
9229          function-local names?  For partial symbols, we should probably be
9230          ignoring them.  */
9231       complaint (&symfile_complaints,
9232                  _("unhandled containing DIE tag %d for DIE at %d"),
9233                  parent->tag, to_underlying (pdi->sect_off));
9234       parent->scope = grandparent_scope;
9235     }
9236
9237   parent->scope_set = 1;
9238   return parent->scope;
9239 }
9240
9241 /* Return the fully scoped name associated with PDI, from compilation unit
9242    CU.  The result will be allocated with malloc.  */
9243
9244 static char *
9245 partial_die_full_name (struct partial_die_info *pdi,
9246                        struct dwarf2_cu *cu)
9247 {
9248   const char *parent_scope;
9249
9250   /* If this is a template instantiation, we can not work out the
9251      template arguments from partial DIEs.  So, unfortunately, we have
9252      to go through the full DIEs.  At least any work we do building
9253      types here will be reused if full symbols are loaded later.  */
9254   if (pdi->has_template_arguments)
9255     {
9256       fixup_partial_die (pdi, cu);
9257
9258       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9259         {
9260           struct die_info *die;
9261           struct attribute attr;
9262           struct dwarf2_cu *ref_cu = cu;
9263
9264           /* DW_FORM_ref_addr is using section offset.  */
9265           attr.name = (enum dwarf_attribute) 0;
9266           attr.form = DW_FORM_ref_addr;
9267           attr.u.unsnd = to_underlying (pdi->sect_off);
9268           die = follow_die_ref (NULL, &attr, &ref_cu);
9269
9270           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9271         }
9272     }
9273
9274   parent_scope = partial_die_parent_scope (pdi, cu);
9275   if (parent_scope == NULL)
9276     return NULL;
9277   else
9278     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9279 }
9280
9281 static void
9282 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9283 {
9284   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
9285   struct objfile *objfile = dwarf2_per_objfile->objfile;
9286   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9287   CORE_ADDR addr = 0;
9288   const char *actual_name = NULL;
9289   CORE_ADDR baseaddr;
9290   char *built_actual_name;
9291
9292   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9293
9294   built_actual_name = partial_die_full_name (pdi, cu);
9295   if (built_actual_name != NULL)
9296     actual_name = built_actual_name;
9297
9298   if (actual_name == NULL)
9299     actual_name = pdi->name;
9300
9301   switch (pdi->tag)
9302     {
9303     case DW_TAG_subprogram:
9304       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9305       if (pdi->is_external || cu->language == language_ada)
9306         {
9307           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9308              of the global scope.  But in Ada, we want to be able to access
9309              nested procedures globally.  So all Ada subprograms are stored
9310              in the global scope.  */
9311           add_psymbol_to_list (actual_name, strlen (actual_name),
9312                                built_actual_name != NULL,
9313                                VAR_DOMAIN, LOC_BLOCK,
9314                                &objfile->global_psymbols,
9315                                addr, cu->language, objfile);
9316         }
9317       else
9318         {
9319           add_psymbol_to_list (actual_name, strlen (actual_name),
9320                                built_actual_name != NULL,
9321                                VAR_DOMAIN, LOC_BLOCK,
9322                                &objfile->static_psymbols,
9323                                addr, cu->language, objfile);
9324         }
9325
9326       if (pdi->main_subprogram && actual_name != NULL)
9327         set_objfile_main_name (objfile, actual_name, cu->language);
9328       break;
9329     case DW_TAG_constant:
9330       {
9331         std::vector<partial_symbol *> *list;
9332
9333         if (pdi->is_external)
9334           list = &objfile->global_psymbols;
9335         else
9336           list = &objfile->static_psymbols;
9337         add_psymbol_to_list (actual_name, strlen (actual_name),
9338                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9339                              list, 0, cu->language, objfile);
9340       }
9341       break;
9342     case DW_TAG_variable:
9343       if (pdi->d.locdesc)
9344         addr = decode_locdesc (pdi->d.locdesc, cu);
9345
9346       if (pdi->d.locdesc
9347           && addr == 0
9348           && !dwarf2_per_objfile->has_section_at_zero)
9349         {
9350           /* A global or static variable may also have been stripped
9351              out by the linker if unused, in which case its address
9352              will be nullified; do not add such variables into partial
9353              symbol table then.  */
9354         }
9355       else if (pdi->is_external)
9356         {
9357           /* Global Variable.
9358              Don't enter into the minimal symbol tables as there is
9359              a minimal symbol table entry from the ELF symbols already.
9360              Enter into partial symbol table if it has a location
9361              descriptor or a type.
9362              If the location descriptor is missing, new_symbol will create
9363              a LOC_UNRESOLVED symbol, the address of the variable will then
9364              be determined from the minimal symbol table whenever the variable
9365              is referenced.
9366              The address for the partial symbol table entry is not
9367              used by GDB, but it comes in handy for debugging partial symbol
9368              table building.  */
9369
9370           if (pdi->d.locdesc || pdi->has_type)
9371             add_psymbol_to_list (actual_name, strlen (actual_name),
9372                                  built_actual_name != NULL,
9373                                  VAR_DOMAIN, LOC_STATIC,
9374                                  &objfile->global_psymbols,
9375                                  addr + baseaddr,
9376                                  cu->language, objfile);
9377         }
9378       else
9379         {
9380           int has_loc = pdi->d.locdesc != NULL;
9381
9382           /* Static Variable.  Skip symbols whose value we cannot know (those
9383              without location descriptors or constant values).  */
9384           if (!has_loc && !pdi->has_const_value)
9385             {
9386               xfree (built_actual_name);
9387               return;
9388             }
9389
9390           add_psymbol_to_list (actual_name, strlen (actual_name),
9391                                built_actual_name != NULL,
9392                                VAR_DOMAIN, LOC_STATIC,
9393                                &objfile->static_psymbols,
9394                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9395                                cu->language, objfile);
9396         }
9397       break;
9398     case DW_TAG_typedef:
9399     case DW_TAG_base_type:
9400     case DW_TAG_subrange_type:
9401       add_psymbol_to_list (actual_name, strlen (actual_name),
9402                            built_actual_name != NULL,
9403                            VAR_DOMAIN, LOC_TYPEDEF,
9404                            &objfile->static_psymbols,
9405                            0, cu->language, objfile);
9406       break;
9407     case DW_TAG_imported_declaration:
9408     case DW_TAG_namespace:
9409       add_psymbol_to_list (actual_name, strlen (actual_name),
9410                            built_actual_name != NULL,
9411                            VAR_DOMAIN, LOC_TYPEDEF,
9412                            &objfile->global_psymbols,
9413                            0, cu->language, objfile);
9414       break;
9415     case DW_TAG_module:
9416       add_psymbol_to_list (actual_name, strlen (actual_name),
9417                            built_actual_name != NULL,
9418                            MODULE_DOMAIN, LOC_TYPEDEF,
9419                            &objfile->global_psymbols,
9420                            0, cu->language, objfile);
9421       break;
9422     case DW_TAG_class_type:
9423     case DW_TAG_interface_type:
9424     case DW_TAG_structure_type:
9425     case DW_TAG_union_type:
9426     case DW_TAG_enumeration_type:
9427       /* Skip external references.  The DWARF standard says in the section
9428          about "Structure, Union, and Class Type Entries": "An incomplete
9429          structure, union or class type is represented by a structure,
9430          union or class entry that does not have a byte size attribute
9431          and that has a DW_AT_declaration attribute."  */
9432       if (!pdi->has_byte_size && pdi->is_declaration)
9433         {
9434           xfree (built_actual_name);
9435           return;
9436         }
9437
9438       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9439          static vs. global.  */
9440       add_psymbol_to_list (actual_name, strlen (actual_name),
9441                            built_actual_name != NULL,
9442                            STRUCT_DOMAIN, LOC_TYPEDEF,
9443                            cu->language == language_cplus
9444                            ? &objfile->global_psymbols
9445                            : &objfile->static_psymbols,
9446                            0, cu->language, objfile);
9447
9448       break;
9449     case DW_TAG_enumerator:
9450       add_psymbol_to_list (actual_name, strlen (actual_name),
9451                            built_actual_name != NULL,
9452                            VAR_DOMAIN, LOC_CONST,
9453                            cu->language == language_cplus
9454                            ? &objfile->global_psymbols
9455                            : &objfile->static_psymbols,
9456                            0, cu->language, objfile);
9457       break;
9458     default:
9459       break;
9460     }
9461
9462   xfree (built_actual_name);
9463 }
9464
9465 /* Read a partial die corresponding to a namespace; also, add a symbol
9466    corresponding to that namespace to the symbol table.  NAMESPACE is
9467    the name of the enclosing namespace.  */
9468
9469 static void
9470 add_partial_namespace (struct partial_die_info *pdi,
9471                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9472                        int set_addrmap, struct dwarf2_cu *cu)
9473 {
9474   /* Add a symbol for the namespace.  */
9475
9476   add_partial_symbol (pdi, cu);
9477
9478   /* Now scan partial symbols in that namespace.  */
9479
9480   if (pdi->has_children)
9481     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9482 }
9483
9484 /* Read a partial die corresponding to a Fortran module.  */
9485
9486 static void
9487 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9488                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9489 {
9490   /* Add a symbol for the namespace.  */
9491
9492   add_partial_symbol (pdi, cu);
9493
9494   /* Now scan partial symbols in that module.  */
9495
9496   if (pdi->has_children)
9497     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9498 }
9499
9500 /* Read a partial die corresponding to a subprogram and create a partial
9501    symbol for that subprogram.  When the CU language allows it, this
9502    routine also defines a partial symbol for each nested subprogram
9503    that this subprogram contains.  If SET_ADDRMAP is true, record the
9504    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
9505    and highest PC values found in PDI.
9506
9507    PDI may also be a lexical block, in which case we simply search
9508    recursively for subprograms defined inside that lexical block.
9509    Again, this is only performed when the CU language allows this
9510    type of definitions.  */
9511
9512 static void
9513 add_partial_subprogram (struct partial_die_info *pdi,
9514                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9515                         int set_addrmap, struct dwarf2_cu *cu)
9516 {
9517   if (pdi->tag == DW_TAG_subprogram)
9518     {
9519       if (pdi->has_pc_info)
9520         {
9521           if (pdi->lowpc < *lowpc)
9522             *lowpc = pdi->lowpc;
9523           if (pdi->highpc > *highpc)
9524             *highpc = pdi->highpc;
9525           if (set_addrmap)
9526             {
9527               struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
9528               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9529               CORE_ADDR baseaddr;
9530               CORE_ADDR highpc;
9531               CORE_ADDR lowpc;
9532
9533               baseaddr = ANOFFSET (objfile->section_offsets,
9534                                    SECT_OFF_TEXT (objfile));
9535               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9536                                                   pdi->lowpc + baseaddr);
9537               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9538                                                    pdi->highpc + baseaddr);
9539               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9540                                  cu->per_cu->v.psymtab);
9541             }
9542         }
9543
9544       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9545         {
9546           if (!pdi->is_declaration)
9547             /* Ignore subprogram DIEs that do not have a name, they are
9548                illegal.  Do not emit a complaint at this point, we will
9549                do so when we convert this psymtab into a symtab.  */
9550             if (pdi->name)
9551               add_partial_symbol (pdi, cu);
9552         }
9553     }
9554
9555   if (! pdi->has_children)
9556     return;
9557
9558   if (cu->language == language_ada)
9559     {
9560       pdi = pdi->die_child;
9561       while (pdi != NULL)
9562         {
9563           fixup_partial_die (pdi, cu);
9564           if (pdi->tag == DW_TAG_subprogram
9565               || pdi->tag == DW_TAG_lexical_block)
9566             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9567           pdi = pdi->die_sibling;
9568         }
9569     }
9570 }
9571
9572 /* Read a partial die corresponding to an enumeration type.  */
9573
9574 static void
9575 add_partial_enumeration (struct partial_die_info *enum_pdi,
9576                          struct dwarf2_cu *cu)
9577 {
9578   struct partial_die_info *pdi;
9579
9580   if (enum_pdi->name != NULL)
9581     add_partial_symbol (enum_pdi, cu);
9582
9583   pdi = enum_pdi->die_child;
9584   while (pdi)
9585     {
9586       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9587         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9588       else
9589         add_partial_symbol (pdi, cu);
9590       pdi = pdi->die_sibling;
9591     }
9592 }
9593
9594 /* Return the initial uleb128 in the die at INFO_PTR.  */
9595
9596 static unsigned int
9597 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9598 {
9599   unsigned int bytes_read;
9600
9601   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9602 }
9603
9604 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
9605    Return the corresponding abbrev, or NULL if the number is zero (indicating
9606    an empty DIE).  In either case *BYTES_READ will be set to the length of
9607    the initial number.  */
9608
9609 static struct abbrev_info *
9610 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
9611                  struct dwarf2_cu *cu)
9612 {
9613   bfd *abfd = cu->dwarf2_per_objfile->objfile->obfd;
9614   unsigned int abbrev_number;
9615   struct abbrev_info *abbrev;
9616
9617   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9618
9619   if (abbrev_number == 0)
9620     return NULL;
9621
9622   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
9623   if (!abbrev)
9624     {
9625       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9626                " at offset 0x%x [in module %s]"),
9627              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9628              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9629     }
9630
9631   return abbrev;
9632 }
9633
9634 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9635    Returns a pointer to the end of a series of DIEs, terminated by an empty
9636    DIE.  Any children of the skipped DIEs will also be skipped.  */
9637
9638 static const gdb_byte *
9639 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9640 {
9641   struct dwarf2_cu *cu = reader->cu;
9642   struct abbrev_info *abbrev;
9643   unsigned int bytes_read;
9644
9645   while (1)
9646     {
9647       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
9648       if (abbrev == NULL)
9649         return info_ptr + bytes_read;
9650       else
9651         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9652     }
9653 }
9654
9655 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9656    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9657    abbrev corresponding to that skipped uleb128 should be passed in
9658    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9659    children.  */
9660
9661 static const gdb_byte *
9662 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9663               struct abbrev_info *abbrev)
9664 {
9665   unsigned int bytes_read;
9666   struct attribute attr;
9667   bfd *abfd = reader->abfd;
9668   struct dwarf2_cu *cu = reader->cu;
9669   const gdb_byte *buffer = reader->buffer;
9670   const gdb_byte *buffer_end = reader->buffer_end;
9671   unsigned int form, i;
9672
9673   for (i = 0; i < abbrev->num_attrs; i++)
9674     {
9675       /* The only abbrev we care about is DW_AT_sibling.  */
9676       if (abbrev->attrs[i].name == DW_AT_sibling)
9677         {
9678           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9679           if (attr.form == DW_FORM_ref_addr)
9680             complaint (&symfile_complaints,
9681                        _("ignoring absolute DW_AT_sibling"));
9682           else
9683             {
9684               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9685               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9686
9687               if (sibling_ptr < info_ptr)
9688                 complaint (&symfile_complaints,
9689                            _("DW_AT_sibling points backwards"));
9690               else if (sibling_ptr > reader->buffer_end)
9691                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9692               else
9693                 return sibling_ptr;
9694             }
9695         }
9696
9697       /* If it isn't DW_AT_sibling, skip this attribute.  */
9698       form = abbrev->attrs[i].form;
9699     skip_attribute:
9700       switch (form)
9701         {
9702         case DW_FORM_ref_addr:
9703           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9704              and later it is offset sized.  */
9705           if (cu->header.version == 2)
9706             info_ptr += cu->header.addr_size;
9707           else
9708             info_ptr += cu->header.offset_size;
9709           break;
9710         case DW_FORM_GNU_ref_alt:
9711           info_ptr += cu->header.offset_size;
9712           break;
9713         case DW_FORM_addr:
9714           info_ptr += cu->header.addr_size;
9715           break;
9716         case DW_FORM_data1:
9717         case DW_FORM_ref1:
9718         case DW_FORM_flag:
9719           info_ptr += 1;
9720           break;
9721         case DW_FORM_flag_present:
9722         case DW_FORM_implicit_const:
9723           break;
9724         case DW_FORM_data2:
9725         case DW_FORM_ref2:
9726           info_ptr += 2;
9727           break;
9728         case DW_FORM_data4:
9729         case DW_FORM_ref4:
9730           info_ptr += 4;
9731           break;
9732         case DW_FORM_data8:
9733         case DW_FORM_ref8:
9734         case DW_FORM_ref_sig8:
9735           info_ptr += 8;
9736           break;
9737         case DW_FORM_data16:
9738           info_ptr += 16;
9739           break;
9740         case DW_FORM_string:
9741           read_direct_string (abfd, info_ptr, &bytes_read);
9742           info_ptr += bytes_read;
9743           break;
9744         case DW_FORM_sec_offset:
9745         case DW_FORM_strp:
9746         case DW_FORM_GNU_strp_alt:
9747           info_ptr += cu->header.offset_size;
9748           break;
9749         case DW_FORM_exprloc:
9750         case DW_FORM_block:
9751           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9752           info_ptr += bytes_read;
9753           break;
9754         case DW_FORM_block1:
9755           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9756           break;
9757         case DW_FORM_block2:
9758           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9759           break;
9760         case DW_FORM_block4:
9761           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9762           break;
9763         case DW_FORM_sdata:
9764         case DW_FORM_udata:
9765         case DW_FORM_ref_udata:
9766         case DW_FORM_GNU_addr_index:
9767         case DW_FORM_GNU_str_index:
9768           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9769           break;
9770         case DW_FORM_indirect:
9771           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9772           info_ptr += bytes_read;
9773           /* We need to continue parsing from here, so just go back to
9774              the top.  */
9775           goto skip_attribute;
9776
9777         default:
9778           error (_("Dwarf Error: Cannot handle %s "
9779                    "in DWARF reader [in module %s]"),
9780                  dwarf_form_name (form),
9781                  bfd_get_filename (abfd));
9782         }
9783     }
9784
9785   if (abbrev->has_children)
9786     return skip_children (reader, info_ptr);
9787   else
9788     return info_ptr;
9789 }
9790
9791 /* Locate ORIG_PDI's sibling.
9792    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9793
9794 static const gdb_byte *
9795 locate_pdi_sibling (const struct die_reader_specs *reader,
9796                     struct partial_die_info *orig_pdi,
9797                     const gdb_byte *info_ptr)
9798 {
9799   /* Do we know the sibling already?  */
9800
9801   if (orig_pdi->sibling)
9802     return orig_pdi->sibling;
9803
9804   /* Are there any children to deal with?  */
9805
9806   if (!orig_pdi->has_children)
9807     return info_ptr;
9808
9809   /* Skip the children the long way.  */
9810
9811   return skip_children (reader, info_ptr);
9812 }
9813
9814 /* Expand this partial symbol table into a full symbol table.  SELF is
9815    not NULL.  */
9816
9817 static void
9818 dwarf2_read_symtab (struct partial_symtab *self,
9819                     struct objfile *objfile)
9820 {
9821   struct dwarf2_per_objfile *dwarf2_per_objfile
9822     = get_dwarf2_per_objfile (objfile);
9823
9824   if (self->readin)
9825     {
9826       warning (_("bug: psymtab for %s is already read in."),
9827                self->filename);
9828     }
9829   else
9830     {
9831       if (info_verbose)
9832         {
9833           printf_filtered (_("Reading in symbols for %s..."),
9834                            self->filename);
9835           gdb_flush (gdb_stdout);
9836         }
9837
9838       /* If this psymtab is constructed from a debug-only objfile, the
9839          has_section_at_zero flag will not necessarily be correct.  We
9840          can get the correct value for this flag by looking at the data
9841          associated with the (presumably stripped) associated objfile.  */
9842       if (objfile->separate_debug_objfile_backlink)
9843         {
9844           struct dwarf2_per_objfile *dpo_backlink
9845             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9846
9847           dwarf2_per_objfile->has_section_at_zero
9848             = dpo_backlink->has_section_at_zero;
9849         }
9850
9851       dwarf2_per_objfile->reading_partial_symbols = 0;
9852
9853       psymtab_to_symtab_1 (self);
9854
9855       /* Finish up the debug error message.  */
9856       if (info_verbose)
9857         printf_filtered (_("done.\n"));
9858     }
9859
9860   process_cu_includes (dwarf2_per_objfile);
9861 }
9862 \f
9863 /* Reading in full CUs.  */
9864
9865 /* Add PER_CU to the queue.  */
9866
9867 static void
9868 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9869                  enum language pretend_language)
9870 {
9871   struct dwarf2_queue_item *item;
9872
9873   per_cu->queued = 1;
9874   item = XNEW (struct dwarf2_queue_item);
9875   item->per_cu = per_cu;
9876   item->pretend_language = pretend_language;
9877   item->next = NULL;
9878
9879   if (dwarf2_queue == NULL)
9880     dwarf2_queue = item;
9881   else
9882     dwarf2_queue_tail->next = item;
9883
9884   dwarf2_queue_tail = item;
9885 }
9886
9887 /* If PER_CU is not yet queued, add it to the queue.
9888    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9889    dependency.
9890    The result is non-zero if PER_CU was queued, otherwise the result is zero
9891    meaning either PER_CU is already queued or it is already loaded.
9892
9893    N.B. There is an invariant here that if a CU is queued then it is loaded.
9894    The caller is required to load PER_CU if we return non-zero.  */
9895
9896 static int
9897 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9898                        struct dwarf2_per_cu_data *per_cu,
9899                        enum language pretend_language)
9900 {
9901   /* We may arrive here during partial symbol reading, if we need full
9902      DIEs to process an unusual case (e.g. template arguments).  Do
9903      not queue PER_CU, just tell our caller to load its DIEs.  */
9904   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9905     {
9906       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9907         return 1;
9908       return 0;
9909     }
9910
9911   /* Mark the dependence relation so that we don't flush PER_CU
9912      too early.  */
9913   if (dependent_cu != NULL)
9914     dwarf2_add_dependence (dependent_cu, per_cu);
9915
9916   /* If it's already on the queue, we have nothing to do.  */
9917   if (per_cu->queued)
9918     return 0;
9919
9920   /* If the compilation unit is already loaded, just mark it as
9921      used.  */
9922   if (per_cu->cu != NULL)
9923     {
9924       per_cu->cu->last_used = 0;
9925       return 0;
9926     }
9927
9928   /* Add it to the queue.  */
9929   queue_comp_unit (per_cu, pretend_language);
9930
9931   return 1;
9932 }
9933
9934 /* Process the queue.  */
9935
9936 static void
9937 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9938 {
9939   struct dwarf2_queue_item *item, *next_item;
9940
9941   if (dwarf_read_debug)
9942     {
9943       fprintf_unfiltered (gdb_stdlog,
9944                           "Expanding one or more symtabs of objfile %s ...\n",
9945                           objfile_name (dwarf2_per_objfile->objfile));
9946     }
9947
9948   /* The queue starts out with one item, but following a DIE reference
9949      may load a new CU, adding it to the end of the queue.  */
9950   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9951     {
9952       if ((dwarf2_per_objfile->using_index
9953            ? !item->per_cu->v.quick->compunit_symtab
9954            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9955           /* Skip dummy CUs.  */
9956           && item->per_cu->cu != NULL)
9957         {
9958           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9959           unsigned int debug_print_threshold;
9960           char buf[100];
9961
9962           if (per_cu->is_debug_types)
9963             {
9964               struct signatured_type *sig_type =
9965                 (struct signatured_type *) per_cu;
9966
9967               sprintf (buf, "TU %s at offset 0x%x",
9968                        hex_string (sig_type->signature),
9969                        to_underlying (per_cu->sect_off));
9970               /* There can be 100s of TUs.
9971                  Only print them in verbose mode.  */
9972               debug_print_threshold = 2;
9973             }
9974           else
9975             {
9976               sprintf (buf, "CU at offset 0x%x",
9977                        to_underlying (per_cu->sect_off));
9978               debug_print_threshold = 1;
9979             }
9980
9981           if (dwarf_read_debug >= debug_print_threshold)
9982             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9983
9984           if (per_cu->is_debug_types)
9985             process_full_type_unit (per_cu, item->pretend_language);
9986           else
9987             process_full_comp_unit (per_cu, item->pretend_language);
9988
9989           if (dwarf_read_debug >= debug_print_threshold)
9990             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9991         }
9992
9993       item->per_cu->queued = 0;
9994       next_item = item->next;
9995       xfree (item);
9996     }
9997
9998   dwarf2_queue_tail = NULL;
9999
10000   if (dwarf_read_debug)
10001     {
10002       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
10003                           objfile_name (dwarf2_per_objfile->objfile));
10004     }
10005 }
10006
10007 /* Free all allocated queue entries.  This function only releases anything if
10008    an error was thrown; if the queue was processed then it would have been
10009    freed as we went along.  */
10010
10011 static void
10012 dwarf2_release_queue (void *dummy)
10013 {
10014   struct dwarf2_queue_item *item, *last;
10015
10016   item = dwarf2_queue;
10017   while (item)
10018     {
10019       /* Anything still marked queued is likely to be in an
10020          inconsistent state, so discard it.  */
10021       if (item->per_cu->queued)
10022         {
10023           if (item->per_cu->cu != NULL)
10024             free_one_cached_comp_unit (item->per_cu);
10025           item->per_cu->queued = 0;
10026         }
10027
10028       last = item;
10029       item = item->next;
10030       xfree (last);
10031     }
10032
10033   dwarf2_queue = dwarf2_queue_tail = NULL;
10034 }
10035
10036 /* Read in full symbols for PST, and anything it depends on.  */
10037
10038 static void
10039 psymtab_to_symtab_1 (struct partial_symtab *pst)
10040 {
10041   struct dwarf2_per_cu_data *per_cu;
10042   int i;
10043
10044   if (pst->readin)
10045     return;
10046
10047   for (i = 0; i < pst->number_of_dependencies; i++)
10048     if (!pst->dependencies[i]->readin
10049         && pst->dependencies[i]->user == NULL)
10050       {
10051         /* Inform about additional files that need to be read in.  */
10052         if (info_verbose)
10053           {
10054             /* FIXME: i18n: Need to make this a single string.  */
10055             fputs_filtered (" ", gdb_stdout);
10056             wrap_here ("");
10057             fputs_filtered ("and ", gdb_stdout);
10058             wrap_here ("");
10059             printf_filtered ("%s...", pst->dependencies[i]->filename);
10060             wrap_here ("");     /* Flush output.  */
10061             gdb_flush (gdb_stdout);
10062           }
10063         psymtab_to_symtab_1 (pst->dependencies[i]);
10064       }
10065
10066   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10067
10068   if (per_cu == NULL)
10069     {
10070       /* It's an include file, no symbols to read for it.
10071          Everything is in the parent symtab.  */
10072       pst->readin = 1;
10073       return;
10074     }
10075
10076   dw2_do_instantiate_symtab (per_cu);
10077 }
10078
10079 /* Trivial hash function for die_info: the hash value of a DIE
10080    is its offset in .debug_info for this objfile.  */
10081
10082 static hashval_t
10083 die_hash (const void *item)
10084 {
10085   const struct die_info *die = (const struct die_info *) item;
10086
10087   return to_underlying (die->sect_off);
10088 }
10089
10090 /* Trivial comparison function for die_info structures: two DIEs
10091    are equal if they have the same offset.  */
10092
10093 static int
10094 die_eq (const void *item_lhs, const void *item_rhs)
10095 {
10096   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10097   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10098
10099   return die_lhs->sect_off == die_rhs->sect_off;
10100 }
10101
10102 /* die_reader_func for load_full_comp_unit.
10103    This is identical to read_signatured_type_reader,
10104    but is kept separate for now.  */
10105
10106 static void
10107 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10108                             const gdb_byte *info_ptr,
10109                             struct die_info *comp_unit_die,
10110                             int has_children,
10111                             void *data)
10112 {
10113   struct dwarf2_cu *cu = reader->cu;
10114   enum language *language_ptr = (enum language *) data;
10115
10116   gdb_assert (cu->die_hash == NULL);
10117   cu->die_hash =
10118     htab_create_alloc_ex (cu->header.length / 12,
10119                           die_hash,
10120                           die_eq,
10121                           NULL,
10122                           &cu->comp_unit_obstack,
10123                           hashtab_obstack_allocate,
10124                           dummy_obstack_deallocate);
10125
10126   if (has_children)
10127     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10128                                                   &info_ptr, comp_unit_die);
10129   cu->dies = comp_unit_die;
10130   /* comp_unit_die is not stored in die_hash, no need.  */
10131
10132   /* We try not to read any attributes in this function, because not
10133      all CUs needed for references have been loaded yet, and symbol
10134      table processing isn't initialized.  But we have to set the CU language,
10135      or we won't be able to build types correctly.
10136      Similarly, if we do not read the producer, we can not apply
10137      producer-specific interpretation.  */
10138   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10139 }
10140
10141 /* Load the DIEs associated with PER_CU into memory.  */
10142
10143 static void
10144 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10145                      enum language pretend_language)
10146 {
10147   gdb_assert (! this_cu->is_debug_types);
10148
10149   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10150                            load_full_comp_unit_reader, &pretend_language);
10151 }
10152
10153 /* Add a DIE to the delayed physname list.  */
10154
10155 static void
10156 add_to_method_list (struct type *type, int fnfield_index, int index,
10157                     const char *name, struct die_info *die,
10158                     struct dwarf2_cu *cu)
10159 {
10160   struct delayed_method_info mi;
10161   mi.type = type;
10162   mi.fnfield_index = fnfield_index;
10163   mi.index = index;
10164   mi.name = name;
10165   mi.die = die;
10166   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10167 }
10168
10169 /* A cleanup for freeing the delayed method list.  */
10170
10171 static void
10172 free_delayed_list (void *ptr)
10173 {
10174   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10175   if (cu->method_list != NULL)
10176     {
10177       VEC_free (delayed_method_info, cu->method_list);
10178       cu->method_list = NULL;
10179     }
10180 }
10181
10182 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10183    "const" / "volatile".  If so, decrements LEN by the length of the
10184    modifier and return true.  Otherwise return false.  */
10185
10186 template<size_t N>
10187 static bool
10188 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10189 {
10190   size_t mod_len = sizeof (mod) - 1;
10191   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10192     {
10193       len -= mod_len;
10194       return true;
10195     }
10196   return false;
10197 }
10198
10199 /* Compute the physnames of any methods on the CU's method list.
10200
10201    The computation of method physnames is delayed in order to avoid the
10202    (bad) condition that one of the method's formal parameters is of an as yet
10203    incomplete type.  */
10204
10205 static void
10206 compute_delayed_physnames (struct dwarf2_cu *cu)
10207 {
10208   int i;
10209   struct delayed_method_info *mi;
10210
10211   /* Only C++ delays computing physnames.  */
10212   if (VEC_empty (delayed_method_info, cu->method_list))
10213     return;
10214   gdb_assert (cu->language == language_cplus);
10215
10216   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10217     {
10218       const char *physname;
10219       struct fn_fieldlist *fn_flp
10220         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10221       physname = dwarf2_physname (mi->name, mi->die, cu);
10222       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10223         = physname ? physname : "";
10224
10225       /* Since there's no tag to indicate whether a method is a
10226          const/volatile overload, extract that information out of the
10227          demangled name.  */
10228       if (physname != NULL)
10229         {
10230           size_t len = strlen (physname);
10231
10232           while (1)
10233             {
10234               if (physname[len] == ')') /* shortcut */
10235                 break;
10236               else if (check_modifier (physname, len, " const"))
10237                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10238               else if (check_modifier (physname, len, " volatile"))
10239                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10240               else
10241                 break;
10242             }
10243         }
10244     }
10245 }
10246
10247 /* Go objects should be embedded in a DW_TAG_module DIE,
10248    and it's not clear if/how imported objects will appear.
10249    To keep Go support simple until that's worked out,
10250    go back through what we've read and create something usable.
10251    We could do this while processing each DIE, and feels kinda cleaner,
10252    but that way is more invasive.
10253    This is to, for example, allow the user to type "p var" or "b main"
10254    without having to specify the package name, and allow lookups
10255    of module.object to work in contexts that use the expression
10256    parser.  */
10257
10258 static void
10259 fixup_go_packaging (struct dwarf2_cu *cu)
10260 {
10261   char *package_name = NULL;
10262   struct pending *list;
10263   int i;
10264
10265   for (list = global_symbols; list != NULL; list = list->next)
10266     {
10267       for (i = 0; i < list->nsyms; ++i)
10268         {
10269           struct symbol *sym = list->symbol[i];
10270
10271           if (SYMBOL_LANGUAGE (sym) == language_go
10272               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10273             {
10274               char *this_package_name = go_symbol_package_name (sym);
10275
10276               if (this_package_name == NULL)
10277                 continue;
10278               if (package_name == NULL)
10279                 package_name = this_package_name;
10280               else
10281                 {
10282                   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
10283                   if (strcmp (package_name, this_package_name) != 0)
10284                     complaint (&symfile_complaints,
10285                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10286                                (symbol_symtab (sym) != NULL
10287                                 ? symtab_to_filename_for_display
10288                                     (symbol_symtab (sym))
10289                                 : objfile_name (objfile)),
10290                                this_package_name, package_name);
10291                   xfree (this_package_name);
10292                 }
10293             }
10294         }
10295     }
10296
10297   if (package_name != NULL)
10298     {
10299       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
10300       const char *saved_package_name
10301         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10302                                         package_name,
10303                                         strlen (package_name));
10304       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10305                                      saved_package_name);
10306       struct symbol *sym;
10307
10308       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10309
10310       sym = allocate_symbol (objfile);
10311       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10312       SYMBOL_SET_NAMES (sym, saved_package_name,
10313                         strlen (saved_package_name), 0, objfile);
10314       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10315          e.g., "main" finds the "main" module and not C's main().  */
10316       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10317       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10318       SYMBOL_TYPE (sym) = type;
10319
10320       add_symbol_to_list (sym, &global_symbols);
10321
10322       xfree (package_name);
10323     }
10324 }
10325
10326 /* Return the symtab for PER_CU.  This works properly regardless of
10327    whether we're using the index or psymtabs.  */
10328
10329 static struct compunit_symtab *
10330 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10331 {
10332   return (per_cu->dwarf2_per_objfile->using_index
10333           ? per_cu->v.quick->compunit_symtab
10334           : per_cu->v.psymtab->compunit_symtab);
10335 }
10336
10337 /* A helper function for computing the list of all symbol tables
10338    included by PER_CU.  */
10339
10340 static void
10341 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10342                                 htab_t all_children, htab_t all_type_symtabs,
10343                                 struct dwarf2_per_cu_data *per_cu,
10344                                 struct compunit_symtab *immediate_parent)
10345 {
10346   void **slot;
10347   int ix;
10348   struct compunit_symtab *cust;
10349   struct dwarf2_per_cu_data *iter;
10350
10351   slot = htab_find_slot (all_children, per_cu, INSERT);
10352   if (*slot != NULL)
10353     {
10354       /* This inclusion and its children have been processed.  */
10355       return;
10356     }
10357
10358   *slot = per_cu;
10359   /* Only add a CU if it has a symbol table.  */
10360   cust = get_compunit_symtab (per_cu);
10361   if (cust != NULL)
10362     {
10363       /* If this is a type unit only add its symbol table if we haven't
10364          seen it yet (type unit per_cu's can share symtabs).  */
10365       if (per_cu->is_debug_types)
10366         {
10367           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10368           if (*slot == NULL)
10369             {
10370               *slot = cust;
10371               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10372               if (cust->user == NULL)
10373                 cust->user = immediate_parent;
10374             }
10375         }
10376       else
10377         {
10378           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10379           if (cust->user == NULL)
10380             cust->user = immediate_parent;
10381         }
10382     }
10383
10384   for (ix = 0;
10385        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10386        ++ix)
10387     {
10388       recursively_compute_inclusions (result, all_children,
10389                                       all_type_symtabs, iter, cust);
10390     }
10391 }
10392
10393 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10394    PER_CU.  */
10395
10396 static void
10397 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10398 {
10399   gdb_assert (! per_cu->is_debug_types);
10400
10401   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10402     {
10403       int ix, len;
10404       struct dwarf2_per_cu_data *per_cu_iter;
10405       struct compunit_symtab *compunit_symtab_iter;
10406       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10407       htab_t all_children, all_type_symtabs;
10408       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10409
10410       /* If we don't have a symtab, we can just skip this case.  */
10411       if (cust == NULL)
10412         return;
10413
10414       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10415                                         NULL, xcalloc, xfree);
10416       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10417                                             NULL, xcalloc, xfree);
10418
10419       for (ix = 0;
10420            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10421                         ix, per_cu_iter);
10422            ++ix)
10423         {
10424           recursively_compute_inclusions (&result_symtabs, all_children,
10425                                           all_type_symtabs, per_cu_iter,
10426                                           cust);
10427         }
10428
10429       /* Now we have a transitive closure of all the included symtabs.  */
10430       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10431       cust->includes
10432         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10433                      struct compunit_symtab *, len + 1);
10434       for (ix = 0;
10435            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10436                         compunit_symtab_iter);
10437            ++ix)
10438         cust->includes[ix] = compunit_symtab_iter;
10439       cust->includes[len] = NULL;
10440
10441       VEC_free (compunit_symtab_ptr, result_symtabs);
10442       htab_delete (all_children);
10443       htab_delete (all_type_symtabs);
10444     }
10445 }
10446
10447 /* Compute the 'includes' field for the symtabs of all the CUs we just
10448    read.  */
10449
10450 static void
10451 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10452 {
10453   int ix;
10454   struct dwarf2_per_cu_data *iter;
10455
10456   for (ix = 0;
10457        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10458                     ix, iter);
10459        ++ix)
10460     {
10461       if (! iter->is_debug_types)
10462         compute_compunit_symtab_includes (iter);
10463     }
10464
10465   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10466 }
10467
10468 /* Generate full symbol information for PER_CU, whose DIEs have
10469    already been loaded into memory.  */
10470
10471 static void
10472 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10473                         enum language pretend_language)
10474 {
10475   struct dwarf2_cu *cu = per_cu->cu;
10476   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10477   struct objfile *objfile = dwarf2_per_objfile->objfile;
10478   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10479   CORE_ADDR lowpc, highpc;
10480   struct compunit_symtab *cust;
10481   struct cleanup *delayed_list_cleanup;
10482   CORE_ADDR baseaddr;
10483   struct block *static_block;
10484   CORE_ADDR addr;
10485
10486   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10487
10488   buildsym_init ();
10489   scoped_free_pendings free_pending;
10490   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10491
10492   cu->list_in_scope = &file_symbols;
10493
10494   cu->language = pretend_language;
10495   cu->language_defn = language_def (cu->language);
10496
10497   /* Do line number decoding in read_file_scope () */
10498   process_die (cu->dies, cu);
10499
10500   /* For now fudge the Go package.  */
10501   if (cu->language == language_go)
10502     fixup_go_packaging (cu);
10503
10504   /* Now that we have processed all the DIEs in the CU, all the types 
10505      should be complete, and it should now be safe to compute all of the
10506      physnames.  */
10507   compute_delayed_physnames (cu);
10508   do_cleanups (delayed_list_cleanup);
10509
10510   /* Some compilers don't define a DW_AT_high_pc attribute for the
10511      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10512      it, by scanning the DIE's below the compilation unit.  */
10513   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10514
10515   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10516   static_block = end_symtab_get_static_block (addr, 0, 1);
10517
10518   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10519      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10520      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10521      addrmap to help ensure it has an accurate map of pc values belonging to
10522      this comp unit.  */
10523   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10524
10525   cust = end_symtab_from_static_block (static_block,
10526                                        SECT_OFF_TEXT (objfile), 0);
10527
10528   if (cust != NULL)
10529     {
10530       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10531
10532       /* Set symtab language to language from DW_AT_language.  If the
10533          compilation is from a C file generated by language preprocessors, do
10534          not set the language if it was already deduced by start_subfile.  */
10535       if (!(cu->language == language_c
10536             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10537         COMPUNIT_FILETABS (cust)->language = cu->language;
10538
10539       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10540          produce DW_AT_location with location lists but it can be possibly
10541          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10542          there were bugs in prologue debug info, fixed later in GCC-4.5
10543          by "unwind info for epilogues" patch (which is not directly related).
10544
10545          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10546          needed, it would be wrong due to missing DW_AT_producer there.
10547
10548          Still one can confuse GDB by using non-standard GCC compilation
10549          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10550          */ 
10551       if (cu->has_loclist && gcc_4_minor >= 5)
10552         cust->locations_valid = 1;
10553
10554       if (gcc_4_minor >= 5)
10555         cust->epilogue_unwind_valid = 1;
10556
10557       cust->call_site_htab = cu->call_site_htab;
10558     }
10559
10560   if (dwarf2_per_objfile->using_index)
10561     per_cu->v.quick->compunit_symtab = cust;
10562   else
10563     {
10564       struct partial_symtab *pst = per_cu->v.psymtab;
10565       pst->compunit_symtab = cust;
10566       pst->readin = 1;
10567     }
10568
10569   /* Push it for inclusion processing later.  */
10570   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10571 }
10572
10573 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10574    already been loaded into memory.  */
10575
10576 static void
10577 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10578                         enum language pretend_language)
10579 {
10580   struct dwarf2_cu *cu = per_cu->cu;
10581   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10582   struct objfile *objfile = dwarf2_per_objfile->objfile;
10583   struct compunit_symtab *cust;
10584   struct cleanup *delayed_list_cleanup;
10585   struct signatured_type *sig_type;
10586
10587   gdb_assert (per_cu->is_debug_types);
10588   sig_type = (struct signatured_type *) per_cu;
10589
10590   buildsym_init ();
10591   scoped_free_pendings free_pending;
10592   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10593
10594   cu->list_in_scope = &file_symbols;
10595
10596   cu->language = pretend_language;
10597   cu->language_defn = language_def (cu->language);
10598
10599   /* The symbol tables are set up in read_type_unit_scope.  */
10600   process_die (cu->dies, cu);
10601
10602   /* For now fudge the Go package.  */
10603   if (cu->language == language_go)
10604     fixup_go_packaging (cu);
10605
10606   /* Now that we have processed all the DIEs in the CU, all the types 
10607      should be complete, and it should now be safe to compute all of the
10608      physnames.  */
10609   compute_delayed_physnames (cu);
10610   do_cleanups (delayed_list_cleanup);
10611
10612   /* TUs share symbol tables.
10613      If this is the first TU to use this symtab, complete the construction
10614      of it with end_expandable_symtab.  Otherwise, complete the addition of
10615      this TU's symbols to the existing symtab.  */
10616   if (sig_type->type_unit_group->compunit_symtab == NULL)
10617     {
10618       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10619       sig_type->type_unit_group->compunit_symtab = cust;
10620
10621       if (cust != NULL)
10622         {
10623           /* Set symtab language to language from DW_AT_language.  If the
10624              compilation is from a C file generated by language preprocessors,
10625              do not set the language if it was already deduced by
10626              start_subfile.  */
10627           if (!(cu->language == language_c
10628                 && COMPUNIT_FILETABS (cust)->language != language_c))
10629             COMPUNIT_FILETABS (cust)->language = cu->language;
10630         }
10631     }
10632   else
10633     {
10634       augment_type_symtab ();
10635       cust = sig_type->type_unit_group->compunit_symtab;
10636     }
10637
10638   if (dwarf2_per_objfile->using_index)
10639     per_cu->v.quick->compunit_symtab = cust;
10640   else
10641     {
10642       struct partial_symtab *pst = per_cu->v.psymtab;
10643       pst->compunit_symtab = cust;
10644       pst->readin = 1;
10645     }
10646 }
10647
10648 /* Process an imported unit DIE.  */
10649
10650 static void
10651 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10652 {
10653   struct attribute *attr;
10654
10655   /* For now we don't handle imported units in type units.  */
10656   if (cu->per_cu->is_debug_types)
10657     {
10658       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10659                " supported in type units [in module %s]"),
10660              objfile_name (cu->dwarf2_per_objfile->objfile));
10661     }
10662
10663   attr = dwarf2_attr (die, DW_AT_import, cu);
10664   if (attr != NULL)
10665     {
10666       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10667       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10668       dwarf2_per_cu_data *per_cu
10669         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10670                                             cu->dwarf2_per_objfile);
10671
10672       /* If necessary, add it to the queue and load its DIEs.  */
10673       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10674         load_full_comp_unit (per_cu, cu->language);
10675
10676       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10677                      per_cu);
10678     }
10679 }
10680
10681 /* RAII object that represents a process_die scope: i.e.,
10682    starts/finishes processing a DIE.  */
10683 class process_die_scope
10684 {
10685 public:
10686   process_die_scope (die_info *die, dwarf2_cu *cu)
10687     : m_die (die), m_cu (cu)
10688   {
10689     /* We should only be processing DIEs not already in process.  */
10690     gdb_assert (!m_die->in_process);
10691     m_die->in_process = true;
10692   }
10693
10694   ~process_die_scope ()
10695   {
10696     m_die->in_process = false;
10697
10698     /* If we're done processing the DIE for the CU that owns the line
10699        header, we don't need the line header anymore.  */
10700     if (m_cu->line_header_die_owner == m_die)
10701       {
10702         delete m_cu->line_header;
10703         m_cu->line_header = NULL;
10704         m_cu->line_header_die_owner = NULL;
10705       }
10706   }
10707
10708 private:
10709   die_info *m_die;
10710   dwarf2_cu *m_cu;
10711 };
10712
10713 /* Process a die and its children.  */
10714
10715 static void
10716 process_die (struct die_info *die, struct dwarf2_cu *cu)
10717 {
10718   process_die_scope scope (die, cu);
10719
10720   switch (die->tag)
10721     {
10722     case DW_TAG_padding:
10723       break;
10724     case DW_TAG_compile_unit:
10725     case DW_TAG_partial_unit:
10726       read_file_scope (die, cu);
10727       break;
10728     case DW_TAG_type_unit:
10729       read_type_unit_scope (die, cu);
10730       break;
10731     case DW_TAG_subprogram:
10732     case DW_TAG_inlined_subroutine:
10733       read_func_scope (die, cu);
10734       break;
10735     case DW_TAG_lexical_block:
10736     case DW_TAG_try_block:
10737     case DW_TAG_catch_block:
10738       read_lexical_block_scope (die, cu);
10739       break;
10740     case DW_TAG_call_site:
10741     case DW_TAG_GNU_call_site:
10742       read_call_site_scope (die, cu);
10743       break;
10744     case DW_TAG_class_type:
10745     case DW_TAG_interface_type:
10746     case DW_TAG_structure_type:
10747     case DW_TAG_union_type:
10748       process_structure_scope (die, cu);
10749       break;
10750     case DW_TAG_enumeration_type:
10751       process_enumeration_scope (die, cu);
10752       break;
10753
10754     /* These dies have a type, but processing them does not create
10755        a symbol or recurse to process the children.  Therefore we can
10756        read them on-demand through read_type_die.  */
10757     case DW_TAG_subroutine_type:
10758     case DW_TAG_set_type:
10759     case DW_TAG_array_type:
10760     case DW_TAG_pointer_type:
10761     case DW_TAG_ptr_to_member_type:
10762     case DW_TAG_reference_type:
10763     case DW_TAG_rvalue_reference_type:
10764     case DW_TAG_string_type:
10765       break;
10766
10767     case DW_TAG_base_type:
10768     case DW_TAG_subrange_type:
10769     case DW_TAG_typedef:
10770       /* Add a typedef symbol for the type definition, if it has a
10771          DW_AT_name.  */
10772       new_symbol (die, read_type_die (die, cu), cu);
10773       break;
10774     case DW_TAG_common_block:
10775       read_common_block (die, cu);
10776       break;
10777     case DW_TAG_common_inclusion:
10778       break;
10779     case DW_TAG_namespace:
10780       cu->processing_has_namespace_info = 1;
10781       read_namespace (die, cu);
10782       break;
10783     case DW_TAG_module:
10784       cu->processing_has_namespace_info = 1;
10785       read_module (die, cu);
10786       break;
10787     case DW_TAG_imported_declaration:
10788       cu->processing_has_namespace_info = 1;
10789       if (read_namespace_alias (die, cu))
10790         break;
10791       /* The declaration is not a global namespace alias: fall through.  */
10792     case DW_TAG_imported_module:
10793       cu->processing_has_namespace_info = 1;
10794       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10795                                  || cu->language != language_fortran))
10796         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10797                    dwarf_tag_name (die->tag));
10798       read_import_statement (die, cu);
10799       break;
10800
10801     case DW_TAG_imported_unit:
10802       process_imported_unit_die (die, cu);
10803       break;
10804
10805     case DW_TAG_variable:
10806       read_variable (die, cu);
10807       break;
10808
10809     default:
10810       new_symbol (die, NULL, cu);
10811       break;
10812     }
10813 }
10814 \f
10815 /* DWARF name computation.  */
10816
10817 /* A helper function for dwarf2_compute_name which determines whether DIE
10818    needs to have the name of the scope prepended to the name listed in the
10819    die.  */
10820
10821 static int
10822 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10823 {
10824   struct attribute *attr;
10825
10826   switch (die->tag)
10827     {
10828     case DW_TAG_namespace:
10829     case DW_TAG_typedef:
10830     case DW_TAG_class_type:
10831     case DW_TAG_interface_type:
10832     case DW_TAG_structure_type:
10833     case DW_TAG_union_type:
10834     case DW_TAG_enumeration_type:
10835     case DW_TAG_enumerator:
10836     case DW_TAG_subprogram:
10837     case DW_TAG_inlined_subroutine:
10838     case DW_TAG_member:
10839     case DW_TAG_imported_declaration:
10840       return 1;
10841
10842     case DW_TAG_variable:
10843     case DW_TAG_constant:
10844       /* We only need to prefix "globally" visible variables.  These include
10845          any variable marked with DW_AT_external or any variable that
10846          lives in a namespace.  [Variables in anonymous namespaces
10847          require prefixing, but they are not DW_AT_external.]  */
10848
10849       if (dwarf2_attr (die, DW_AT_specification, cu))
10850         {
10851           struct dwarf2_cu *spec_cu = cu;
10852
10853           return die_needs_namespace (die_specification (die, &spec_cu),
10854                                       spec_cu);
10855         }
10856
10857       attr = dwarf2_attr (die, DW_AT_external, cu);
10858       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10859           && die->parent->tag != DW_TAG_module)
10860         return 0;
10861       /* A variable in a lexical block of some kind does not need a
10862          namespace, even though in C++ such variables may be external
10863          and have a mangled name.  */
10864       if (die->parent->tag ==  DW_TAG_lexical_block
10865           || die->parent->tag ==  DW_TAG_try_block
10866           || die->parent->tag ==  DW_TAG_catch_block
10867           || die->parent->tag == DW_TAG_subprogram)
10868         return 0;
10869       return 1;
10870
10871     default:
10872       return 0;
10873     }
10874 }
10875
10876 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10877    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10878    defined for the given DIE.  */
10879
10880 static struct attribute *
10881 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10882 {
10883   struct attribute *attr;
10884
10885   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10886   if (attr == NULL)
10887     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10888
10889   return attr;
10890 }
10891
10892 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10893    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10894    defined for the given DIE.  */
10895
10896 static const char *
10897 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10898 {
10899   const char *linkage_name;
10900
10901   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10902   if (linkage_name == NULL)
10903     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10904
10905   return linkage_name;
10906 }
10907
10908 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10909    compute the physname for the object, which include a method's:
10910    - formal parameters (C++),
10911    - receiver type (Go),
10912
10913    The term "physname" is a bit confusing.
10914    For C++, for example, it is the demangled name.
10915    For Go, for example, it's the mangled name.
10916
10917    For Ada, return the DIE's linkage name rather than the fully qualified
10918    name.  PHYSNAME is ignored..
10919
10920    The result is allocated on the objfile_obstack and canonicalized.  */
10921
10922 static const char *
10923 dwarf2_compute_name (const char *name,
10924                      struct die_info *die, struct dwarf2_cu *cu,
10925                      int physname)
10926 {
10927   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
10928
10929   if (name == NULL)
10930     name = dwarf2_name (die, cu);
10931
10932   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10933      but otherwise compute it by typename_concat inside GDB.
10934      FIXME: Actually this is not really true, or at least not always true.
10935      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10936      Fortran names because there is no mangling standard.  So new_symbol_full
10937      will set the demangled name to the result of dwarf2_full_name, and it is
10938      the demangled name that GDB uses if it exists.  */
10939   if (cu->language == language_ada
10940       || (cu->language == language_fortran && physname))
10941     {
10942       /* For Ada unit, we prefer the linkage name over the name, as
10943          the former contains the exported name, which the user expects
10944          to be able to reference.  Ideally, we want the user to be able
10945          to reference this entity using either natural or linkage name,
10946          but we haven't started looking at this enhancement yet.  */
10947       const char *linkage_name = dw2_linkage_name (die, cu);
10948
10949       if (linkage_name != NULL)
10950         return linkage_name;
10951     }
10952
10953   /* These are the only languages we know how to qualify names in.  */
10954   if (name != NULL
10955       && (cu->language == language_cplus
10956           || cu->language == language_fortran || cu->language == language_d
10957           || cu->language == language_rust))
10958     {
10959       if (die_needs_namespace (die, cu))
10960         {
10961           const char *prefix;
10962           const char *canonical_name = NULL;
10963
10964           string_file buf;
10965
10966           prefix = determine_prefix (die, cu);
10967           if (*prefix != '\0')
10968             {
10969               char *prefixed_name = typename_concat (NULL, prefix, name,
10970                                                      physname, cu);
10971
10972               buf.puts (prefixed_name);
10973               xfree (prefixed_name);
10974             }
10975           else
10976             buf.puts (name);
10977
10978           /* Template parameters may be specified in the DIE's DW_AT_name, or
10979              as children with DW_TAG_template_type_param or
10980              DW_TAG_value_type_param.  If the latter, add them to the name
10981              here.  If the name already has template parameters, then
10982              skip this step; some versions of GCC emit both, and
10983              it is more efficient to use the pre-computed name.
10984
10985              Something to keep in mind about this process: it is very
10986              unlikely, or in some cases downright impossible, to produce
10987              something that will match the mangled name of a function.
10988              If the definition of the function has the same debug info,
10989              we should be able to match up with it anyway.  But fallbacks
10990              using the minimal symbol, for instance to find a method
10991              implemented in a stripped copy of libstdc++, will not work.
10992              If we do not have debug info for the definition, we will have to
10993              match them up some other way.
10994
10995              When we do name matching there is a related problem with function
10996              templates; two instantiated function templates are allowed to
10997              differ only by their return types, which we do not add here.  */
10998
10999           if (cu->language == language_cplus && strchr (name, '<') == NULL)
11000             {
11001               struct attribute *attr;
11002               struct die_info *child;
11003               int first = 1;
11004
11005               die->building_fullname = 1;
11006
11007               for (child = die->child; child != NULL; child = child->sibling)
11008                 {
11009                   struct type *type;
11010                   LONGEST value;
11011                   const gdb_byte *bytes;
11012                   struct dwarf2_locexpr_baton *baton;
11013                   struct value *v;
11014
11015                   if (child->tag != DW_TAG_template_type_param
11016                       && child->tag != DW_TAG_template_value_param)
11017                     continue;
11018
11019                   if (first)
11020                     {
11021                       buf.puts ("<");
11022                       first = 0;
11023                     }
11024                   else
11025                     buf.puts (", ");
11026
11027                   attr = dwarf2_attr (child, DW_AT_type, cu);
11028                   if (attr == NULL)
11029                     {
11030                       complaint (&symfile_complaints,
11031                                  _("template parameter missing DW_AT_type"));
11032                       buf.puts ("UNKNOWN_TYPE");
11033                       continue;
11034                     }
11035                   type = die_type (child, cu);
11036
11037                   if (child->tag == DW_TAG_template_type_param)
11038                     {
11039                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11040                       continue;
11041                     }
11042
11043                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11044                   if (attr == NULL)
11045                     {
11046                       complaint (&symfile_complaints,
11047                                  _("template parameter missing "
11048                                    "DW_AT_const_value"));
11049                       buf.puts ("UNKNOWN_VALUE");
11050                       continue;
11051                     }
11052
11053                   dwarf2_const_value_attr (attr, type, name,
11054                                            &cu->comp_unit_obstack, cu,
11055                                            &value, &bytes, &baton);
11056
11057                   if (TYPE_NOSIGN (type))
11058                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11059                        changed, this can use value_print instead.  */
11060                     c_printchar (value, type, &buf);
11061                   else
11062                     {
11063                       struct value_print_options opts;
11064
11065                       if (baton != NULL)
11066                         v = dwarf2_evaluate_loc_desc (type, NULL,
11067                                                       baton->data,
11068                                                       baton->size,
11069                                                       baton->per_cu);
11070                       else if (bytes != NULL)
11071                         {
11072                           v = allocate_value (type);
11073                           memcpy (value_contents_writeable (v), bytes,
11074                                   TYPE_LENGTH (type));
11075                         }
11076                       else
11077                         v = value_from_longest (type, value);
11078
11079                       /* Specify decimal so that we do not depend on
11080                          the radix.  */
11081                       get_formatted_print_options (&opts, 'd');
11082                       opts.raw = 1;
11083                       value_print (v, &buf, &opts);
11084                       release_value (v);
11085                       value_free (v);
11086                     }
11087                 }
11088
11089               die->building_fullname = 0;
11090
11091               if (!first)
11092                 {
11093                   /* Close the argument list, with a space if necessary
11094                      (nested templates).  */
11095                   if (!buf.empty () && buf.string ().back () == '>')
11096                     buf.puts (" >");
11097                   else
11098                     buf.puts (">");
11099                 }
11100             }
11101
11102           /* For C++ methods, append formal parameter type
11103              information, if PHYSNAME.  */
11104
11105           if (physname && die->tag == DW_TAG_subprogram
11106               && cu->language == language_cplus)
11107             {
11108               struct type *type = read_type_die (die, cu);
11109
11110               c_type_print_args (type, &buf, 1, cu->language,
11111                                  &type_print_raw_options);
11112
11113               if (cu->language == language_cplus)
11114                 {
11115                   /* Assume that an artificial first parameter is
11116                      "this", but do not crash if it is not.  RealView
11117                      marks unnamed (and thus unused) parameters as
11118                      artificial; there is no way to differentiate
11119                      the two cases.  */
11120                   if (TYPE_NFIELDS (type) > 0
11121                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11122                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11123                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11124                                                                         0))))
11125                     buf.puts (" const");
11126                 }
11127             }
11128
11129           const std::string &intermediate_name = buf.string ();
11130
11131           if (cu->language == language_cplus)
11132             canonical_name
11133               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11134                                           &objfile->per_bfd->storage_obstack);
11135
11136           /* If we only computed INTERMEDIATE_NAME, or if
11137              INTERMEDIATE_NAME is already canonical, then we need to
11138              copy it to the appropriate obstack.  */
11139           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11140             name = ((const char *)
11141                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11142                                    intermediate_name.c_str (),
11143                                    intermediate_name.length ()));
11144           else
11145             name = canonical_name;
11146         }
11147     }
11148
11149   return name;
11150 }
11151
11152 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11153    If scope qualifiers are appropriate they will be added.  The result
11154    will be allocated on the storage_obstack, or NULL if the DIE does
11155    not have a name.  NAME may either be from a previous call to
11156    dwarf2_name or NULL.
11157
11158    The output string will be canonicalized (if C++).  */
11159
11160 static const char *
11161 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11162 {
11163   return dwarf2_compute_name (name, die, cu, 0);
11164 }
11165
11166 /* Construct a physname for the given DIE in CU.  NAME may either be
11167    from a previous call to dwarf2_name or NULL.  The result will be
11168    allocated on the objfile_objstack or NULL if the DIE does not have a
11169    name.
11170
11171    The output string will be canonicalized (if C++).  */
11172
11173 static const char *
11174 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11175 {
11176   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
11177   const char *retval, *mangled = NULL, *canon = NULL;
11178   int need_copy = 1;
11179
11180   /* In this case dwarf2_compute_name is just a shortcut not building anything
11181      on its own.  */
11182   if (!die_needs_namespace (die, cu))
11183     return dwarf2_compute_name (name, die, cu, 1);
11184
11185   mangled = dw2_linkage_name (die, cu);
11186
11187   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11188      See https://github.com/rust-lang/rust/issues/32925.  */
11189   if (cu->language == language_rust && mangled != NULL
11190       && strchr (mangled, '{') != NULL)
11191     mangled = NULL;
11192
11193   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11194      has computed.  */
11195   gdb::unique_xmalloc_ptr<char> demangled;
11196   if (mangled != NULL)
11197     {
11198       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11199          type.  It is easier for GDB users to search for such functions as
11200          `name(params)' than `long name(params)'.  In such case the minimal
11201          symbol names do not match the full symbol names but for template
11202          functions there is never a need to look up their definition from their
11203          declaration so the only disadvantage remains the minimal symbol
11204          variant `long name(params)' does not have the proper inferior type.
11205          */
11206
11207       if (cu->language == language_go)
11208         {
11209           /* This is a lie, but we already lie to the caller new_symbol_full.
11210              new_symbol_full assumes we return the mangled name.
11211              This just undoes that lie until things are cleaned up.  */
11212         }
11213       else
11214         {
11215           demangled.reset (gdb_demangle (mangled,
11216                                          (DMGL_PARAMS | DMGL_ANSI
11217                                           | DMGL_RET_DROP)));
11218         }
11219       if (demangled)
11220         canon = demangled.get ();
11221       else
11222         {
11223           canon = mangled;
11224           need_copy = 0;
11225         }
11226     }
11227
11228   if (canon == NULL || check_physname)
11229     {
11230       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11231
11232       if (canon != NULL && strcmp (physname, canon) != 0)
11233         {
11234           /* It may not mean a bug in GDB.  The compiler could also
11235              compute DW_AT_linkage_name incorrectly.  But in such case
11236              GDB would need to be bug-to-bug compatible.  */
11237
11238           complaint (&symfile_complaints,
11239                      _("Computed physname <%s> does not match demangled <%s> "
11240                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11241                      physname, canon, mangled, to_underlying (die->sect_off),
11242                      objfile_name (objfile));
11243
11244           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11245              is available here - over computed PHYSNAME.  It is safer
11246              against both buggy GDB and buggy compilers.  */
11247
11248           retval = canon;
11249         }
11250       else
11251         {
11252           retval = physname;
11253           need_copy = 0;
11254         }
11255     }
11256   else
11257     retval = canon;
11258
11259   if (need_copy)
11260     retval = ((const char *)
11261               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11262                              retval, strlen (retval)));
11263
11264   return retval;
11265 }
11266
11267 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11268    a new symbol for it.
11269
11270    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11271
11272 static int
11273 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11274 {
11275   struct attribute *attr;
11276
11277   /* If the die does not have a name, this is not a namespace
11278      alias.  */
11279   attr = dwarf2_attr (die, DW_AT_name, cu);
11280   if (attr != NULL)
11281     {
11282       int num;
11283       struct die_info *d = die;
11284       struct dwarf2_cu *imported_cu = cu;
11285
11286       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11287          keep inspecting DIEs until we hit the underlying import.  */
11288 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11289       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11290         {
11291           attr = dwarf2_attr (d, DW_AT_import, cu);
11292           if (attr == NULL)
11293             break;
11294
11295           d = follow_die_ref (d, attr, &imported_cu);
11296           if (d->tag != DW_TAG_imported_declaration)
11297             break;
11298         }
11299
11300       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11301         {
11302           complaint (&symfile_complaints,
11303                      _("DIE at 0x%x has too many recursively imported "
11304                        "declarations"), to_underlying (d->sect_off));
11305           return 0;
11306         }
11307
11308       if (attr != NULL)
11309         {
11310           struct type *type;
11311           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11312
11313           type = get_die_type_at_offset (sect_off, cu->per_cu);
11314           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11315             {
11316               /* This declaration is a global namespace alias.  Add
11317                  a symbol for it whose type is the aliased namespace.  */
11318               new_symbol (die, type, cu);
11319               return 1;
11320             }
11321         }
11322     }
11323
11324   return 0;
11325 }
11326
11327 /* Return the using directives repository (global or local?) to use in the
11328    current context for LANGUAGE.
11329
11330    For Ada, imported declarations can materialize renamings, which *may* be
11331    global.  However it is impossible (for now?) in DWARF to distinguish
11332    "external" imported declarations and "static" ones.  As all imported
11333    declarations seem to be static in all other languages, make them all CU-wide
11334    global only in Ada.  */
11335
11336 static struct using_direct **
11337 using_directives (enum language language)
11338 {
11339   if (language == language_ada && context_stack_depth == 0)
11340     return &global_using_directives;
11341   else
11342     return &local_using_directives;
11343 }
11344
11345 /* Read the import statement specified by the given die and record it.  */
11346
11347 static void
11348 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11349 {
11350   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
11351   struct attribute *import_attr;
11352   struct die_info *imported_die, *child_die;
11353   struct dwarf2_cu *imported_cu;
11354   const char *imported_name;
11355   const char *imported_name_prefix;
11356   const char *canonical_name;
11357   const char *import_alias;
11358   const char *imported_declaration = NULL;
11359   const char *import_prefix;
11360   std::vector<const char *> excludes;
11361
11362   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11363   if (import_attr == NULL)
11364     {
11365       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11366                  dwarf_tag_name (die->tag));
11367       return;
11368     }
11369
11370   imported_cu = cu;
11371   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11372   imported_name = dwarf2_name (imported_die, imported_cu);
11373   if (imported_name == NULL)
11374     {
11375       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11376
11377         The import in the following code:
11378         namespace A
11379           {
11380             typedef int B;
11381           }
11382
11383         int main ()
11384           {
11385             using A::B;
11386             B b;
11387             return b;
11388           }
11389
11390         ...
11391          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11392             <52>   DW_AT_decl_file   : 1
11393             <53>   DW_AT_decl_line   : 6
11394             <54>   DW_AT_import      : <0x75>
11395          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11396             <59>   DW_AT_name        : B
11397             <5b>   DW_AT_decl_file   : 1
11398             <5c>   DW_AT_decl_line   : 2
11399             <5d>   DW_AT_type        : <0x6e>
11400         ...
11401          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11402             <76>   DW_AT_byte_size   : 4
11403             <77>   DW_AT_encoding    : 5        (signed)
11404
11405         imports the wrong die ( 0x75 instead of 0x58 ).
11406         This case will be ignored until the gcc bug is fixed.  */
11407       return;
11408     }
11409
11410   /* Figure out the local name after import.  */
11411   import_alias = dwarf2_name (die, cu);
11412
11413   /* Figure out where the statement is being imported to.  */
11414   import_prefix = determine_prefix (die, cu);
11415
11416   /* Figure out what the scope of the imported die is and prepend it
11417      to the name of the imported die.  */
11418   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11419
11420   if (imported_die->tag != DW_TAG_namespace
11421       && imported_die->tag != DW_TAG_module)
11422     {
11423       imported_declaration = imported_name;
11424       canonical_name = imported_name_prefix;
11425     }
11426   else if (strlen (imported_name_prefix) > 0)
11427     canonical_name = obconcat (&objfile->objfile_obstack,
11428                                imported_name_prefix,
11429                                (cu->language == language_d ? "." : "::"),
11430                                imported_name, (char *) NULL);
11431   else
11432     canonical_name = imported_name;
11433
11434   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11435     for (child_die = die->child; child_die && child_die->tag;
11436          child_die = sibling_die (child_die))
11437       {
11438         /* DWARF-4: A Fortran use statement with a “rename list” may be
11439            represented by an imported module entry with an import attribute
11440            referring to the module and owned entries corresponding to those
11441            entities that are renamed as part of being imported.  */
11442
11443         if (child_die->tag != DW_TAG_imported_declaration)
11444           {
11445             complaint (&symfile_complaints,
11446                        _("child DW_TAG_imported_declaration expected "
11447                          "- DIE at 0x%x [in module %s]"),
11448                        to_underlying (child_die->sect_off), objfile_name (objfile));
11449             continue;
11450           }
11451
11452         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11453         if (import_attr == NULL)
11454           {
11455             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11456                        dwarf_tag_name (child_die->tag));
11457             continue;
11458           }
11459
11460         imported_cu = cu;
11461         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11462                                               &imported_cu);
11463         imported_name = dwarf2_name (imported_die, imported_cu);
11464         if (imported_name == NULL)
11465           {
11466             complaint (&symfile_complaints,
11467                        _("child DW_TAG_imported_declaration has unknown "
11468                          "imported name - DIE at 0x%x [in module %s]"),
11469                        to_underlying (child_die->sect_off), objfile_name (objfile));
11470             continue;
11471           }
11472
11473         excludes.push_back (imported_name);
11474
11475         process_die (child_die, cu);
11476       }
11477
11478   add_using_directive (using_directives (cu->language),
11479                        import_prefix,
11480                        canonical_name,
11481                        import_alias,
11482                        imported_declaration,
11483                        excludes,
11484                        0,
11485                        &objfile->objfile_obstack);
11486 }
11487
11488 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11489    types, but gives them a size of zero.  Starting with version 14,
11490    ICC is compatible with GCC.  */
11491
11492 static int
11493 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11494 {
11495   if (!cu->checked_producer)
11496     check_producer (cu);
11497
11498   return cu->producer_is_icc_lt_14;
11499 }
11500
11501 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11502    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11503    this, it was first present in GCC release 4.3.0.  */
11504
11505 static int
11506 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11507 {
11508   if (!cu->checked_producer)
11509     check_producer (cu);
11510
11511   return cu->producer_is_gcc_lt_4_3;
11512 }
11513
11514 static file_and_directory
11515 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11516 {
11517   file_and_directory res;
11518
11519   /* Find the filename.  Do not use dwarf2_name here, since the filename
11520      is not a source language identifier.  */
11521   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11522   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11523
11524   if (res.comp_dir == NULL
11525       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11526       && IS_ABSOLUTE_PATH (res.name))
11527     {
11528       res.comp_dir_storage = ldirname (res.name);
11529       if (!res.comp_dir_storage.empty ())
11530         res.comp_dir = res.comp_dir_storage.c_str ();
11531     }
11532   if (res.comp_dir != NULL)
11533     {
11534       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11535          directory, get rid of it.  */
11536       const char *cp = strchr (res.comp_dir, ':');
11537
11538       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11539         res.comp_dir = cp + 1;
11540     }
11541
11542   if (res.name == NULL)
11543     res.name = "<unknown>";
11544
11545   return res;
11546 }
11547
11548 /* Handle DW_AT_stmt_list for a compilation unit.
11549    DIE is the DW_TAG_compile_unit die for CU.
11550    COMP_DIR is the compilation directory.  LOWPC is passed to
11551    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11552
11553 static void
11554 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11555                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11556 {
11557   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
11558   struct objfile *objfile = dwarf2_per_objfile->objfile;
11559   struct attribute *attr;
11560   struct line_header line_header_local;
11561   hashval_t line_header_local_hash;
11562   void **slot;
11563   int decode_mapping;
11564
11565   gdb_assert (! cu->per_cu->is_debug_types);
11566
11567   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11568   if (attr == NULL)
11569     return;
11570
11571   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11572
11573   /* The line header hash table is only created if needed (it exists to
11574      prevent redundant reading of the line table for partial_units).
11575      If we're given a partial_unit, we'll need it.  If we're given a
11576      compile_unit, then use the line header hash table if it's already
11577      created, but don't create one just yet.  */
11578
11579   if (dwarf2_per_objfile->line_header_hash == NULL
11580       && die->tag == DW_TAG_partial_unit)
11581     {
11582       dwarf2_per_objfile->line_header_hash
11583         = htab_create_alloc_ex (127, line_header_hash_voidp,
11584                                 line_header_eq_voidp,
11585                                 free_line_header_voidp,
11586                                 &objfile->objfile_obstack,
11587                                 hashtab_obstack_allocate,
11588                                 dummy_obstack_deallocate);
11589     }
11590
11591   line_header_local.sect_off = line_offset;
11592   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11593   line_header_local_hash = line_header_hash (&line_header_local);
11594   if (dwarf2_per_objfile->line_header_hash != NULL)
11595     {
11596       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11597                                        &line_header_local,
11598                                        line_header_local_hash, NO_INSERT);
11599
11600       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11601          is not present in *SLOT (since if there is something in *SLOT then
11602          it will be for a partial_unit).  */
11603       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11604         {
11605           gdb_assert (*slot != NULL);
11606           cu->line_header = (struct line_header *) *slot;
11607           return;
11608         }
11609     }
11610
11611   /* dwarf_decode_line_header does not yet provide sufficient information.
11612      We always have to call also dwarf_decode_lines for it.  */
11613   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11614   if (lh == NULL)
11615     return;
11616
11617   cu->line_header = lh.release ();
11618   cu->line_header_die_owner = die;
11619
11620   if (dwarf2_per_objfile->line_header_hash == NULL)
11621     slot = NULL;
11622   else
11623     {
11624       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11625                                        &line_header_local,
11626                                        line_header_local_hash, INSERT);
11627       gdb_assert (slot != NULL);
11628     }
11629   if (slot != NULL && *slot == NULL)
11630     {
11631       /* This newly decoded line number information unit will be owned
11632          by line_header_hash hash table.  */
11633       *slot = cu->line_header;
11634       cu->line_header_die_owner = NULL;
11635     }
11636   else
11637     {
11638       /* We cannot free any current entry in (*slot) as that struct line_header
11639          may be already used by multiple CUs.  Create only temporary decoded
11640          line_header for this CU - it may happen at most once for each line
11641          number information unit.  And if we're not using line_header_hash
11642          then this is what we want as well.  */
11643       gdb_assert (die->tag != DW_TAG_partial_unit);
11644     }
11645   decode_mapping = (die->tag != DW_TAG_partial_unit);
11646   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11647                       decode_mapping);
11648
11649 }
11650
11651 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11652
11653 static void
11654 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11655 {
11656   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
11657   struct objfile *objfile = dwarf2_per_objfile->objfile;
11658   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11659   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11660   CORE_ADDR highpc = ((CORE_ADDR) 0);
11661   struct attribute *attr;
11662   struct die_info *child_die;
11663   CORE_ADDR baseaddr;
11664
11665   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11666
11667   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11668
11669   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11670      from finish_block.  */
11671   if (lowpc == ((CORE_ADDR) -1))
11672     lowpc = highpc;
11673   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11674
11675   file_and_directory fnd = find_file_and_directory (die, cu);
11676
11677   prepare_one_comp_unit (cu, die, cu->language);
11678
11679   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11680      standardised yet.  As a workaround for the language detection we fall
11681      back to the DW_AT_producer string.  */
11682   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11683     cu->language = language_opencl;
11684
11685   /* Similar hack for Go.  */
11686   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11687     set_cu_language (DW_LANG_Go, cu);
11688
11689   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11690
11691   /* Decode line number information if present.  We do this before
11692      processing child DIEs, so that the line header table is available
11693      for DW_AT_decl_file.  */
11694   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11695
11696   /* Process all dies in compilation unit.  */
11697   if (die->child != NULL)
11698     {
11699       child_die = die->child;
11700       while (child_die && child_die->tag)
11701         {
11702           process_die (child_die, cu);
11703           child_die = sibling_die (child_die);
11704         }
11705     }
11706
11707   /* Decode macro information, if present.  Dwarf 2 macro information
11708      refers to information in the line number info statement program
11709      header, so we can only read it if we've read the header
11710      successfully.  */
11711   attr = dwarf2_attr (die, DW_AT_macros, cu);
11712   if (attr == NULL)
11713     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11714   if (attr && cu->line_header)
11715     {
11716       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11717         complaint (&symfile_complaints,
11718                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11719
11720       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11721     }
11722   else
11723     {
11724       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11725       if (attr && cu->line_header)
11726         {
11727           unsigned int macro_offset = DW_UNSND (attr);
11728
11729           dwarf_decode_macros (cu, macro_offset, 0);
11730         }
11731     }
11732 }
11733
11734 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11735    Create the set of symtabs used by this TU, or if this TU is sharing
11736    symtabs with another TU and the symtabs have already been created
11737    then restore those symtabs in the line header.
11738    We don't need the pc/line-number mapping for type units.  */
11739
11740 static void
11741 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11742 {
11743   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11744   struct type_unit_group *tu_group;
11745   int first_time;
11746   struct attribute *attr;
11747   unsigned int i;
11748   struct signatured_type *sig_type;
11749
11750   gdb_assert (per_cu->is_debug_types);
11751   sig_type = (struct signatured_type *) per_cu;
11752
11753   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11754
11755   /* If we're using .gdb_index (includes -readnow) then
11756      per_cu->type_unit_group may not have been set up yet.  */
11757   if (sig_type->type_unit_group == NULL)
11758     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11759   tu_group = sig_type->type_unit_group;
11760
11761   /* If we've already processed this stmt_list there's no real need to
11762      do it again, we could fake it and just recreate the part we need
11763      (file name,index -> symtab mapping).  If data shows this optimization
11764      is useful we can do it then.  */
11765   first_time = tu_group->compunit_symtab == NULL;
11766
11767   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11768      debug info.  */
11769   line_header_up lh;
11770   if (attr != NULL)
11771     {
11772       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11773       lh = dwarf_decode_line_header (line_offset, cu);
11774     }
11775   if (lh == NULL)
11776     {
11777       if (first_time)
11778         dwarf2_start_symtab (cu, "", NULL, 0);
11779       else
11780         {
11781           gdb_assert (tu_group->symtabs == NULL);
11782           restart_symtab (tu_group->compunit_symtab, "", 0);
11783         }
11784       return;
11785     }
11786
11787   cu->line_header = lh.release ();
11788   cu->line_header_die_owner = die;
11789
11790   if (first_time)
11791     {
11792       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11793
11794       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11795          still initializing it, and our caller (a few levels up)
11796          process_full_type_unit still needs to know if this is the first
11797          time.  */
11798
11799       tu_group->num_symtabs = cu->line_header->file_names.size ();
11800       tu_group->symtabs = XNEWVEC (struct symtab *,
11801                                    cu->line_header->file_names.size ());
11802
11803       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11804         {
11805           file_entry &fe = cu->line_header->file_names[i];
11806
11807           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11808
11809           if (current_subfile->symtab == NULL)
11810             {
11811               /* NOTE: start_subfile will recognize when it's been
11812                  passed a file it has already seen.  So we can't
11813                  assume there's a simple mapping from
11814                  cu->line_header->file_names to subfiles, plus
11815                  cu->line_header->file_names may contain dups.  */
11816               current_subfile->symtab
11817                 = allocate_symtab (cust, current_subfile->name);
11818             }
11819
11820           fe.symtab = current_subfile->symtab;
11821           tu_group->symtabs[i] = fe.symtab;
11822         }
11823     }
11824   else
11825     {
11826       restart_symtab (tu_group->compunit_symtab, "", 0);
11827
11828       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11829         {
11830           file_entry &fe = cu->line_header->file_names[i];
11831
11832           fe.symtab = tu_group->symtabs[i];
11833         }
11834     }
11835
11836   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11837      so they don't have a "real" (so to speak) symtab anyway.
11838      There is later code that will assign the main symtab to all symbols
11839      that don't have one.  We need to handle the case of a symbol with a
11840      missing symtab (DW_AT_decl_file) anyway.  */
11841 }
11842
11843 /* Process DW_TAG_type_unit.
11844    For TUs we want to skip the first top level sibling if it's not the
11845    actual type being defined by this TU.  In this case the first top
11846    level sibling is there to provide context only.  */
11847
11848 static void
11849 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11850 {
11851   struct die_info *child_die;
11852
11853   prepare_one_comp_unit (cu, die, language_minimal);
11854
11855   /* Initialize (or reinitialize) the machinery for building symtabs.
11856      We do this before processing child DIEs, so that the line header table
11857      is available for DW_AT_decl_file.  */
11858   setup_type_unit_groups (die, cu);
11859
11860   if (die->child != NULL)
11861     {
11862       child_die = die->child;
11863       while (child_die && child_die->tag)
11864         {
11865           process_die (child_die, cu);
11866           child_die = sibling_die (child_die);
11867         }
11868     }
11869 }
11870 \f
11871 /* DWO/DWP files.
11872
11873    http://gcc.gnu.org/wiki/DebugFission
11874    http://gcc.gnu.org/wiki/DebugFissionDWP
11875
11876    To simplify handling of both DWO files ("object" files with the DWARF info)
11877    and DWP files (a file with the DWOs packaged up into one file), we treat
11878    DWP files as having a collection of virtual DWO files.  */
11879
11880 static hashval_t
11881 hash_dwo_file (const void *item)
11882 {
11883   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11884   hashval_t hash;
11885
11886   hash = htab_hash_string (dwo_file->dwo_name);
11887   if (dwo_file->comp_dir != NULL)
11888     hash += htab_hash_string (dwo_file->comp_dir);
11889   return hash;
11890 }
11891
11892 static int
11893 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11894 {
11895   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11896   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11897
11898   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11899     return 0;
11900   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11901     return lhs->comp_dir == rhs->comp_dir;
11902   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11903 }
11904
11905 /* Allocate a hash table for DWO files.  */
11906
11907 static htab_t
11908 allocate_dwo_file_hash_table (struct objfile *objfile)
11909 {
11910   return htab_create_alloc_ex (41,
11911                                hash_dwo_file,
11912                                eq_dwo_file,
11913                                NULL,
11914                                &objfile->objfile_obstack,
11915                                hashtab_obstack_allocate,
11916                                dummy_obstack_deallocate);
11917 }
11918
11919 /* Lookup DWO file DWO_NAME.  */
11920
11921 static void **
11922 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11923                       const char *dwo_name,
11924                       const char *comp_dir)
11925 {
11926   struct dwo_file find_entry;
11927   void **slot;
11928
11929   if (dwarf2_per_objfile->dwo_files == NULL)
11930     dwarf2_per_objfile->dwo_files
11931       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11932
11933   memset (&find_entry, 0, sizeof (find_entry));
11934   find_entry.dwo_name = dwo_name;
11935   find_entry.comp_dir = comp_dir;
11936   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11937
11938   return slot;
11939 }
11940
11941 static hashval_t
11942 hash_dwo_unit (const void *item)
11943 {
11944   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11945
11946   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11947   return dwo_unit->signature;
11948 }
11949
11950 static int
11951 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11952 {
11953   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11954   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11955
11956   /* The signature is assumed to be unique within the DWO file.
11957      So while object file CU dwo_id's always have the value zero,
11958      that's OK, assuming each object file DWO file has only one CU,
11959      and that's the rule for now.  */
11960   return lhs->signature == rhs->signature;
11961 }
11962
11963 /* Allocate a hash table for DWO CUs,TUs.
11964    There is one of these tables for each of CUs,TUs for each DWO file.  */
11965
11966 static htab_t
11967 allocate_dwo_unit_table (struct objfile *objfile)
11968 {
11969   /* Start out with a pretty small number.
11970      Generally DWO files contain only one CU and maybe some TUs.  */
11971   return htab_create_alloc_ex (3,
11972                                hash_dwo_unit,
11973                                eq_dwo_unit,
11974                                NULL,
11975                                &objfile->objfile_obstack,
11976                                hashtab_obstack_allocate,
11977                                dummy_obstack_deallocate);
11978 }
11979
11980 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11981
11982 struct create_dwo_cu_data
11983 {
11984   struct dwo_file *dwo_file;
11985   struct dwo_unit dwo_unit;
11986 };
11987
11988 /* die_reader_func for create_dwo_cu.  */
11989
11990 static void
11991 create_dwo_cu_reader (const struct die_reader_specs *reader,
11992                       const gdb_byte *info_ptr,
11993                       struct die_info *comp_unit_die,
11994                       int has_children,
11995                       void *datap)
11996 {
11997   struct dwarf2_cu *cu = reader->cu;
11998   sect_offset sect_off = cu->per_cu->sect_off;
11999   struct dwarf2_section_info *section = cu->per_cu->section;
12000   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
12001   struct dwo_file *dwo_file = data->dwo_file;
12002   struct dwo_unit *dwo_unit = &data->dwo_unit;
12003   struct attribute *attr;
12004
12005   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
12006   if (attr == NULL)
12007     {
12008       complaint (&symfile_complaints,
12009                  _("Dwarf Error: debug entry at offset 0x%x is missing"
12010                    " its dwo_id [in module %s]"),
12011                  to_underlying (sect_off), dwo_file->dwo_name);
12012       return;
12013     }
12014
12015   dwo_unit->dwo_file = dwo_file;
12016   dwo_unit->signature = DW_UNSND (attr);
12017   dwo_unit->section = section;
12018   dwo_unit->sect_off = sect_off;
12019   dwo_unit->length = cu->per_cu->length;
12020
12021   if (dwarf_read_debug)
12022     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
12023                         to_underlying (sect_off),
12024                         hex_string (dwo_unit->signature));
12025 }
12026
12027 /* Create the dwo_units for the CUs in a DWO_FILE.
12028    Note: This function processes DWO files only, not DWP files.  */
12029
12030 static void
12031 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12032                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12033                        htab_t &cus_htab)
12034 {
12035   struct objfile *objfile = dwarf2_per_objfile->objfile;
12036   const gdb_byte *info_ptr, *end_ptr;
12037
12038   dwarf2_read_section (objfile, &section);
12039   info_ptr = section.buffer;
12040
12041   if (info_ptr == NULL)
12042     return;
12043
12044   if (dwarf_read_debug)
12045     {
12046       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12047                           get_section_name (&section),
12048                           get_section_file_name (&section));
12049     }
12050
12051   end_ptr = info_ptr + section.size;
12052   while (info_ptr < end_ptr)
12053     {
12054       struct dwarf2_per_cu_data per_cu;
12055       struct create_dwo_cu_data create_dwo_cu_data;
12056       struct dwo_unit *dwo_unit;
12057       void **slot;
12058       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12059
12060       memset (&create_dwo_cu_data.dwo_unit, 0,
12061               sizeof (create_dwo_cu_data.dwo_unit));
12062       memset (&per_cu, 0, sizeof (per_cu));
12063       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12064       per_cu.is_debug_types = 0;
12065       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12066       per_cu.section = &section;
12067       create_dwo_cu_data.dwo_file = &dwo_file;
12068
12069       init_cutu_and_read_dies_no_follow (
12070           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12071       info_ptr += per_cu.length;
12072
12073       // If the unit could not be parsed, skip it.
12074       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12075         continue;
12076
12077       if (cus_htab == NULL)
12078         cus_htab = allocate_dwo_unit_table (objfile);
12079
12080       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12081       *dwo_unit = create_dwo_cu_data.dwo_unit;
12082       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12083       gdb_assert (slot != NULL);
12084       if (*slot != NULL)
12085         {
12086           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12087           sect_offset dup_sect_off = dup_cu->sect_off;
12088
12089           complaint (&symfile_complaints,
12090                      _("debug cu entry at offset 0x%x is duplicate to"
12091                        " the entry at offset 0x%x, signature %s"),
12092                      to_underlying (sect_off), to_underlying (dup_sect_off),
12093                      hex_string (dwo_unit->signature));
12094         }
12095       *slot = (void *)dwo_unit;
12096     }
12097 }
12098
12099 /* DWP file .debug_{cu,tu}_index section format:
12100    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12101
12102    DWP Version 1:
12103
12104    Both index sections have the same format, and serve to map a 64-bit
12105    signature to a set of section numbers.  Each section begins with a header,
12106    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12107    indexes, and a pool of 32-bit section numbers.  The index sections will be
12108    aligned at 8-byte boundaries in the file.
12109
12110    The index section header consists of:
12111
12112     V, 32 bit version number
12113     -, 32 bits unused
12114     N, 32 bit number of compilation units or type units in the index
12115     M, 32 bit number of slots in the hash table
12116
12117    Numbers are recorded using the byte order of the application binary.
12118
12119    The hash table begins at offset 16 in the section, and consists of an array
12120    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12121    order of the application binary).  Unused slots in the hash table are 0.
12122    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12123
12124    The parallel table begins immediately after the hash table
12125    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12126    array of 32-bit indexes (using the byte order of the application binary),
12127    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12128    table contains a 32-bit index into the pool of section numbers.  For unused
12129    hash table slots, the corresponding entry in the parallel table will be 0.
12130
12131    The pool of section numbers begins immediately following the hash table
12132    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12133    section numbers consists of an array of 32-bit words (using the byte order
12134    of the application binary).  Each item in the array is indexed starting
12135    from 0.  The hash table entry provides the index of the first section
12136    number in the set.  Additional section numbers in the set follow, and the
12137    set is terminated by a 0 entry (section number 0 is not used in ELF).
12138
12139    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12140    section must be the first entry in the set, and the .debug_abbrev.dwo must
12141    be the second entry. Other members of the set may follow in any order.
12142
12143    ---
12144
12145    DWP Version 2:
12146
12147    DWP Version 2 combines all the .debug_info, etc. sections into one,
12148    and the entries in the index tables are now offsets into these sections.
12149    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12150    section.
12151
12152    Index Section Contents:
12153     Header
12154     Hash Table of Signatures   dwp_hash_table.hash_table
12155     Parallel Table of Indices  dwp_hash_table.unit_table
12156     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12157     Table of Section Sizes     dwp_hash_table.v2.sizes
12158
12159    The index section header consists of:
12160
12161     V, 32 bit version number
12162     L, 32 bit number of columns in the table of section offsets
12163     N, 32 bit number of compilation units or type units in the index
12164     M, 32 bit number of slots in the hash table
12165
12166    Numbers are recorded using the byte order of the application binary.
12167
12168    The hash table has the same format as version 1.
12169    The parallel table of indices has the same format as version 1,
12170    except that the entries are origin-1 indices into the table of sections
12171    offsets and the table of section sizes.
12172
12173    The table of offsets begins immediately following the parallel table
12174    (at offset 16 + 12 * M from the beginning of the section).  The table is
12175    a two-dimensional array of 32-bit words (using the byte order of the
12176    application binary), with L columns and N+1 rows, in row-major order.
12177    Each row in the array is indexed starting from 0.  The first row provides
12178    a key to the remaining rows: each column in this row provides an identifier
12179    for a debug section, and the offsets in the same column of subsequent rows
12180    refer to that section.  The section identifiers are:
12181
12182     DW_SECT_INFO         1  .debug_info.dwo
12183     DW_SECT_TYPES        2  .debug_types.dwo
12184     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12185     DW_SECT_LINE         4  .debug_line.dwo
12186     DW_SECT_LOC          5  .debug_loc.dwo
12187     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12188     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12189     DW_SECT_MACRO        8  .debug_macro.dwo
12190
12191    The offsets provided by the CU and TU index sections are the base offsets
12192    for the contributions made by each CU or TU to the corresponding section
12193    in the package file.  Each CU and TU header contains an abbrev_offset
12194    field, used to find the abbreviations table for that CU or TU within the
12195    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12196    be interpreted as relative to the base offset given in the index section.
12197    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12198    should be interpreted as relative to the base offset for .debug_line.dwo,
12199    and offsets into other debug sections obtained from DWARF attributes should
12200    also be interpreted as relative to the corresponding base offset.
12201
12202    The table of sizes begins immediately following the table of offsets.
12203    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12204    with L columns and N rows, in row-major order.  Each row in the array is
12205    indexed starting from 1 (row 0 is shared by the two tables).
12206
12207    ---
12208
12209    Hash table lookup is handled the same in version 1 and 2:
12210
12211    We assume that N and M will not exceed 2^32 - 1.
12212    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12213
12214    Given a 64-bit compilation unit signature or a type signature S, an entry
12215    in the hash table is located as follows:
12216
12217    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12218       the low-order k bits all set to 1.
12219
12220    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12221
12222    3) If the hash table entry at index H matches the signature, use that
12223       entry.  If the hash table entry at index H is unused (all zeroes),
12224       terminate the search: the signature is not present in the table.
12225
12226    4) Let H = (H + H') modulo M. Repeat at Step 3.
12227
12228    Because M > N and H' and M are relatively prime, the search is guaranteed
12229    to stop at an unused slot or find the match.  */
12230
12231 /* Create a hash table to map DWO IDs to their CU/TU entry in
12232    .debug_{info,types}.dwo in DWP_FILE.
12233    Returns NULL if there isn't one.
12234    Note: This function processes DWP files only, not DWO files.  */
12235
12236 static struct dwp_hash_table *
12237 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12238                        struct dwp_file *dwp_file, int is_debug_types)
12239 {
12240   struct objfile *objfile = dwarf2_per_objfile->objfile;
12241   bfd *dbfd = dwp_file->dbfd;
12242   const gdb_byte *index_ptr, *index_end;
12243   struct dwarf2_section_info *index;
12244   uint32_t version, nr_columns, nr_units, nr_slots;
12245   struct dwp_hash_table *htab;
12246
12247   if (is_debug_types)
12248     index = &dwp_file->sections.tu_index;
12249   else
12250     index = &dwp_file->sections.cu_index;
12251
12252   if (dwarf2_section_empty_p (index))
12253     return NULL;
12254   dwarf2_read_section (objfile, index);
12255
12256   index_ptr = index->buffer;
12257   index_end = index_ptr + index->size;
12258
12259   version = read_4_bytes (dbfd, index_ptr);
12260   index_ptr += 4;
12261   if (version == 2)
12262     nr_columns = read_4_bytes (dbfd, index_ptr);
12263   else
12264     nr_columns = 0;
12265   index_ptr += 4;
12266   nr_units = read_4_bytes (dbfd, index_ptr);
12267   index_ptr += 4;
12268   nr_slots = read_4_bytes (dbfd, index_ptr);
12269   index_ptr += 4;
12270
12271   if (version != 1 && version != 2)
12272     {
12273       error (_("Dwarf Error: unsupported DWP file version (%s)"
12274                " [in module %s]"),
12275              pulongest (version), dwp_file->name);
12276     }
12277   if (nr_slots != (nr_slots & -nr_slots))
12278     {
12279       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12280                " is not power of 2 [in module %s]"),
12281              pulongest (nr_slots), dwp_file->name);
12282     }
12283
12284   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12285   htab->version = version;
12286   htab->nr_columns = nr_columns;
12287   htab->nr_units = nr_units;
12288   htab->nr_slots = nr_slots;
12289   htab->hash_table = index_ptr;
12290   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12291
12292   /* Exit early if the table is empty.  */
12293   if (nr_slots == 0 || nr_units == 0
12294       || (version == 2 && nr_columns == 0))
12295     {
12296       /* All must be zero.  */
12297       if (nr_slots != 0 || nr_units != 0
12298           || (version == 2 && nr_columns != 0))
12299         {
12300           complaint (&symfile_complaints,
12301                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12302                        " all zero [in modules %s]"),
12303                      dwp_file->name);
12304         }
12305       return htab;
12306     }
12307
12308   if (version == 1)
12309     {
12310       htab->section_pool.v1.indices =
12311         htab->unit_table + sizeof (uint32_t) * nr_slots;
12312       /* It's harder to decide whether the section is too small in v1.
12313          V1 is deprecated anyway so we punt.  */
12314     }
12315   else
12316     {
12317       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12318       int *ids = htab->section_pool.v2.section_ids;
12319       /* Reverse map for error checking.  */
12320       int ids_seen[DW_SECT_MAX + 1];
12321       int i;
12322
12323       if (nr_columns < 2)
12324         {
12325           error (_("Dwarf Error: bad DWP hash table, too few columns"
12326                    " in section table [in module %s]"),
12327                  dwp_file->name);
12328         }
12329       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12330         {
12331           error (_("Dwarf Error: bad DWP hash table, too many columns"
12332                    " in section table [in module %s]"),
12333                  dwp_file->name);
12334         }
12335       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12336       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12337       for (i = 0; i < nr_columns; ++i)
12338         {
12339           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12340
12341           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12342             {
12343               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12344                        " in section table [in module %s]"),
12345                      id, dwp_file->name);
12346             }
12347           if (ids_seen[id] != -1)
12348             {
12349               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12350                        " id %d in section table [in module %s]"),
12351                      id, dwp_file->name);
12352             }
12353           ids_seen[id] = i;
12354           ids[i] = id;
12355         }
12356       /* Must have exactly one info or types section.  */
12357       if (((ids_seen[DW_SECT_INFO] != -1)
12358            + (ids_seen[DW_SECT_TYPES] != -1))
12359           != 1)
12360         {
12361           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12362                    " DWO info/types section [in module %s]"),
12363                  dwp_file->name);
12364         }
12365       /* Must have an abbrev section.  */
12366       if (ids_seen[DW_SECT_ABBREV] == -1)
12367         {
12368           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12369                    " section [in module %s]"),
12370                  dwp_file->name);
12371         }
12372       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12373       htab->section_pool.v2.sizes =
12374         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12375                                          * nr_units * nr_columns);
12376       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12377                                           * nr_units * nr_columns))
12378           > index_end)
12379         {
12380           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12381                    " [in module %s]"),
12382                  dwp_file->name);
12383         }
12384     }
12385
12386   return htab;
12387 }
12388
12389 /* Update SECTIONS with the data from SECTP.
12390
12391    This function is like the other "locate" section routines that are
12392    passed to bfd_map_over_sections, but in this context the sections to
12393    read comes from the DWP V1 hash table, not the full ELF section table.
12394
12395    The result is non-zero for success, or zero if an error was found.  */
12396
12397 static int
12398 locate_v1_virtual_dwo_sections (asection *sectp,
12399                                 struct virtual_v1_dwo_sections *sections)
12400 {
12401   const struct dwop_section_names *names = &dwop_section_names;
12402
12403   if (section_is_p (sectp->name, &names->abbrev_dwo))
12404     {
12405       /* There can be only one.  */
12406       if (sections->abbrev.s.section != NULL)
12407         return 0;
12408       sections->abbrev.s.section = sectp;
12409       sections->abbrev.size = bfd_get_section_size (sectp);
12410     }
12411   else if (section_is_p (sectp->name, &names->info_dwo)
12412            || section_is_p (sectp->name, &names->types_dwo))
12413     {
12414       /* There can be only one.  */
12415       if (sections->info_or_types.s.section != NULL)
12416         return 0;
12417       sections->info_or_types.s.section = sectp;
12418       sections->info_or_types.size = bfd_get_section_size (sectp);
12419     }
12420   else if (section_is_p (sectp->name, &names->line_dwo))
12421     {
12422       /* There can be only one.  */
12423       if (sections->line.s.section != NULL)
12424         return 0;
12425       sections->line.s.section = sectp;
12426       sections->line.size = bfd_get_section_size (sectp);
12427     }
12428   else if (section_is_p (sectp->name, &names->loc_dwo))
12429     {
12430       /* There can be only one.  */
12431       if (sections->loc.s.section != NULL)
12432         return 0;
12433       sections->loc.s.section = sectp;
12434       sections->loc.size = bfd_get_section_size (sectp);
12435     }
12436   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12437     {
12438       /* There can be only one.  */
12439       if (sections->macinfo.s.section != NULL)
12440         return 0;
12441       sections->macinfo.s.section = sectp;
12442       sections->macinfo.size = bfd_get_section_size (sectp);
12443     }
12444   else if (section_is_p (sectp->name, &names->macro_dwo))
12445     {
12446       /* There can be only one.  */
12447       if (sections->macro.s.section != NULL)
12448         return 0;
12449       sections->macro.s.section = sectp;
12450       sections->macro.size = bfd_get_section_size (sectp);
12451     }
12452   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12453     {
12454       /* There can be only one.  */
12455       if (sections->str_offsets.s.section != NULL)
12456         return 0;
12457       sections->str_offsets.s.section = sectp;
12458       sections->str_offsets.size = bfd_get_section_size (sectp);
12459     }
12460   else
12461     {
12462       /* No other kind of section is valid.  */
12463       return 0;
12464     }
12465
12466   return 1;
12467 }
12468
12469 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12470    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12471    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12472    This is for DWP version 1 files.  */
12473
12474 static struct dwo_unit *
12475 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12476                            struct dwp_file *dwp_file,
12477                            uint32_t unit_index,
12478                            const char *comp_dir,
12479                            ULONGEST signature, int is_debug_types)
12480 {
12481   struct objfile *objfile = dwarf2_per_objfile->objfile;
12482   const struct dwp_hash_table *dwp_htab =
12483     is_debug_types ? dwp_file->tus : dwp_file->cus;
12484   bfd *dbfd = dwp_file->dbfd;
12485   const char *kind = is_debug_types ? "TU" : "CU";
12486   struct dwo_file *dwo_file;
12487   struct dwo_unit *dwo_unit;
12488   struct virtual_v1_dwo_sections sections;
12489   void **dwo_file_slot;
12490   int i;
12491
12492   gdb_assert (dwp_file->version == 1);
12493
12494   if (dwarf_read_debug)
12495     {
12496       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12497                           kind,
12498                           pulongest (unit_index), hex_string (signature),
12499                           dwp_file->name);
12500     }
12501
12502   /* Fetch the sections of this DWO unit.
12503      Put a limit on the number of sections we look for so that bad data
12504      doesn't cause us to loop forever.  */
12505
12506 #define MAX_NR_V1_DWO_SECTIONS \
12507   (1 /* .debug_info or .debug_types */ \
12508    + 1 /* .debug_abbrev */ \
12509    + 1 /* .debug_line */ \
12510    + 1 /* .debug_loc */ \
12511    + 1 /* .debug_str_offsets */ \
12512    + 1 /* .debug_macro or .debug_macinfo */ \
12513    + 1 /* trailing zero */)
12514
12515   memset (&sections, 0, sizeof (sections));
12516
12517   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12518     {
12519       asection *sectp;
12520       uint32_t section_nr =
12521         read_4_bytes (dbfd,
12522                       dwp_htab->section_pool.v1.indices
12523                       + (unit_index + i) * sizeof (uint32_t));
12524
12525       if (section_nr == 0)
12526         break;
12527       if (section_nr >= dwp_file->num_sections)
12528         {
12529           error (_("Dwarf Error: bad DWP hash table, section number too large"
12530                    " [in module %s]"),
12531                  dwp_file->name);
12532         }
12533
12534       sectp = dwp_file->elf_sections[section_nr];
12535       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12536         {
12537           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12538                    " [in module %s]"),
12539                  dwp_file->name);
12540         }
12541     }
12542
12543   if (i < 2
12544       || dwarf2_section_empty_p (&sections.info_or_types)
12545       || dwarf2_section_empty_p (&sections.abbrev))
12546     {
12547       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12548                " [in module %s]"),
12549              dwp_file->name);
12550     }
12551   if (i == MAX_NR_V1_DWO_SECTIONS)
12552     {
12553       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12554                " [in module %s]"),
12555              dwp_file->name);
12556     }
12557
12558   /* It's easier for the rest of the code if we fake a struct dwo_file and
12559      have dwo_unit "live" in that.  At least for now.
12560
12561      The DWP file can be made up of a random collection of CUs and TUs.
12562      However, for each CU + set of TUs that came from the same original DWO
12563      file, we can combine them back into a virtual DWO file to save space
12564      (fewer struct dwo_file objects to allocate).  Remember that for really
12565      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12566
12567   std::string virtual_dwo_name =
12568     string_printf ("virtual-dwo/%d-%d-%d-%d",
12569                    get_section_id (&sections.abbrev),
12570                    get_section_id (&sections.line),
12571                    get_section_id (&sections.loc),
12572                    get_section_id (&sections.str_offsets));
12573   /* Can we use an existing virtual DWO file?  */
12574   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12575                                         virtual_dwo_name.c_str (),
12576                                         comp_dir);
12577   /* Create one if necessary.  */
12578   if (*dwo_file_slot == NULL)
12579     {
12580       if (dwarf_read_debug)
12581         {
12582           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12583                               virtual_dwo_name.c_str ());
12584         }
12585       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12586       dwo_file->dwo_name
12587         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12588                                         virtual_dwo_name.c_str (),
12589                                         virtual_dwo_name.size ());
12590       dwo_file->comp_dir = comp_dir;
12591       dwo_file->sections.abbrev = sections.abbrev;
12592       dwo_file->sections.line = sections.line;
12593       dwo_file->sections.loc = sections.loc;
12594       dwo_file->sections.macinfo = sections.macinfo;
12595       dwo_file->sections.macro = sections.macro;
12596       dwo_file->sections.str_offsets = sections.str_offsets;
12597       /* The "str" section is global to the entire DWP file.  */
12598       dwo_file->sections.str = dwp_file->sections.str;
12599       /* The info or types section is assigned below to dwo_unit,
12600          there's no need to record it in dwo_file.
12601          Also, we can't simply record type sections in dwo_file because
12602          we record a pointer into the vector in dwo_unit.  As we collect more
12603          types we'll grow the vector and eventually have to reallocate space
12604          for it, invalidating all copies of pointers into the previous
12605          contents.  */
12606       *dwo_file_slot = dwo_file;
12607     }
12608   else
12609     {
12610       if (dwarf_read_debug)
12611         {
12612           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12613                               virtual_dwo_name.c_str ());
12614         }
12615       dwo_file = (struct dwo_file *) *dwo_file_slot;
12616     }
12617
12618   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12619   dwo_unit->dwo_file = dwo_file;
12620   dwo_unit->signature = signature;
12621   dwo_unit->section =
12622     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12623   *dwo_unit->section = sections.info_or_types;
12624   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12625
12626   return dwo_unit;
12627 }
12628
12629 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12630    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12631    piece within that section used by a TU/CU, return a virtual section
12632    of just that piece.  */
12633
12634 static struct dwarf2_section_info
12635 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12636                        struct dwarf2_section_info *section,
12637                        bfd_size_type offset, bfd_size_type size)
12638 {
12639   struct dwarf2_section_info result;
12640   asection *sectp;
12641
12642   gdb_assert (section != NULL);
12643   gdb_assert (!section->is_virtual);
12644
12645   memset (&result, 0, sizeof (result));
12646   result.s.containing_section = section;
12647   result.is_virtual = 1;
12648
12649   if (size == 0)
12650     return result;
12651
12652   sectp = get_section_bfd_section (section);
12653
12654   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12655      bounds of the real section.  This is a pretty-rare event, so just
12656      flag an error (easier) instead of a warning and trying to cope.  */
12657   if (sectp == NULL
12658       || offset + size > bfd_get_section_size (sectp))
12659     {
12660       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12661                " in section %s [in module %s]"),
12662              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12663              objfile_name (dwarf2_per_objfile->objfile));
12664     }
12665
12666   result.virtual_offset = offset;
12667   result.size = size;
12668   return result;
12669 }
12670
12671 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12672    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12673    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12674    This is for DWP version 2 files.  */
12675
12676 static struct dwo_unit *
12677 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12678                            struct dwp_file *dwp_file,
12679                            uint32_t unit_index,
12680                            const char *comp_dir,
12681                            ULONGEST signature, int is_debug_types)
12682 {
12683   struct objfile *objfile = dwarf2_per_objfile->objfile;
12684   const struct dwp_hash_table *dwp_htab =
12685     is_debug_types ? dwp_file->tus : dwp_file->cus;
12686   bfd *dbfd = dwp_file->dbfd;
12687   const char *kind = is_debug_types ? "TU" : "CU";
12688   struct dwo_file *dwo_file;
12689   struct dwo_unit *dwo_unit;
12690   struct virtual_v2_dwo_sections sections;
12691   void **dwo_file_slot;
12692   int i;
12693
12694   gdb_assert (dwp_file->version == 2);
12695
12696   if (dwarf_read_debug)
12697     {
12698       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12699                           kind,
12700                           pulongest (unit_index), hex_string (signature),
12701                           dwp_file->name);
12702     }
12703
12704   /* Fetch the section offsets of this DWO unit.  */
12705
12706   memset (&sections, 0, sizeof (sections));
12707
12708   for (i = 0; i < dwp_htab->nr_columns; ++i)
12709     {
12710       uint32_t offset = read_4_bytes (dbfd,
12711                                       dwp_htab->section_pool.v2.offsets
12712                                       + (((unit_index - 1) * dwp_htab->nr_columns
12713                                           + i)
12714                                          * sizeof (uint32_t)));
12715       uint32_t size = read_4_bytes (dbfd,
12716                                     dwp_htab->section_pool.v2.sizes
12717                                     + (((unit_index - 1) * dwp_htab->nr_columns
12718                                         + i)
12719                                        * sizeof (uint32_t)));
12720
12721       switch (dwp_htab->section_pool.v2.section_ids[i])
12722         {
12723         case DW_SECT_INFO:
12724         case DW_SECT_TYPES:
12725           sections.info_or_types_offset = offset;
12726           sections.info_or_types_size = size;
12727           break;
12728         case DW_SECT_ABBREV:
12729           sections.abbrev_offset = offset;
12730           sections.abbrev_size = size;
12731           break;
12732         case DW_SECT_LINE:
12733           sections.line_offset = offset;
12734           sections.line_size = size;
12735           break;
12736         case DW_SECT_LOC:
12737           sections.loc_offset = offset;
12738           sections.loc_size = size;
12739           break;
12740         case DW_SECT_STR_OFFSETS:
12741           sections.str_offsets_offset = offset;
12742           sections.str_offsets_size = size;
12743           break;
12744         case DW_SECT_MACINFO:
12745           sections.macinfo_offset = offset;
12746           sections.macinfo_size = size;
12747           break;
12748         case DW_SECT_MACRO:
12749           sections.macro_offset = offset;
12750           sections.macro_size = size;
12751           break;
12752         }
12753     }
12754
12755   /* It's easier for the rest of the code if we fake a struct dwo_file and
12756      have dwo_unit "live" in that.  At least for now.
12757
12758      The DWP file can be made up of a random collection of CUs and TUs.
12759      However, for each CU + set of TUs that came from the same original DWO
12760      file, we can combine them back into a virtual DWO file to save space
12761      (fewer struct dwo_file objects to allocate).  Remember that for really
12762      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12763
12764   std::string virtual_dwo_name =
12765     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12766                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12767                    (long) (sections.line_size ? sections.line_offset : 0),
12768                    (long) (sections.loc_size ? sections.loc_offset : 0),
12769                    (long) (sections.str_offsets_size
12770                            ? sections.str_offsets_offset : 0));
12771   /* Can we use an existing virtual DWO file?  */
12772   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12773                                         virtual_dwo_name.c_str (),
12774                                         comp_dir);
12775   /* Create one if necessary.  */
12776   if (*dwo_file_slot == NULL)
12777     {
12778       if (dwarf_read_debug)
12779         {
12780           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12781                               virtual_dwo_name.c_str ());
12782         }
12783       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12784       dwo_file->dwo_name
12785         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12786                                         virtual_dwo_name.c_str (),
12787                                         virtual_dwo_name.size ());
12788       dwo_file->comp_dir = comp_dir;
12789       dwo_file->sections.abbrev =
12790         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12791                                sections.abbrev_offset, sections.abbrev_size);
12792       dwo_file->sections.line =
12793         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12794                                sections.line_offset, sections.line_size);
12795       dwo_file->sections.loc =
12796         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12797                                sections.loc_offset, sections.loc_size);
12798       dwo_file->sections.macinfo =
12799         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12800                                sections.macinfo_offset, sections.macinfo_size);
12801       dwo_file->sections.macro =
12802         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12803                                sections.macro_offset, sections.macro_size);
12804       dwo_file->sections.str_offsets =
12805         create_dwp_v2_section (dwarf2_per_objfile,
12806                                &dwp_file->sections.str_offsets,
12807                                sections.str_offsets_offset,
12808                                sections.str_offsets_size);
12809       /* The "str" section is global to the entire DWP file.  */
12810       dwo_file->sections.str = dwp_file->sections.str;
12811       /* The info or types section is assigned below to dwo_unit,
12812          there's no need to record it in dwo_file.
12813          Also, we can't simply record type sections in dwo_file because
12814          we record a pointer into the vector in dwo_unit.  As we collect more
12815          types we'll grow the vector and eventually have to reallocate space
12816          for it, invalidating all copies of pointers into the previous
12817          contents.  */
12818       *dwo_file_slot = dwo_file;
12819     }
12820   else
12821     {
12822       if (dwarf_read_debug)
12823         {
12824           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12825                               virtual_dwo_name.c_str ());
12826         }
12827       dwo_file = (struct dwo_file *) *dwo_file_slot;
12828     }
12829
12830   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12831   dwo_unit->dwo_file = dwo_file;
12832   dwo_unit->signature = signature;
12833   dwo_unit->section =
12834     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12835   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12836                                               is_debug_types
12837                                               ? &dwp_file->sections.types
12838                                               : &dwp_file->sections.info,
12839                                               sections.info_or_types_offset,
12840                                               sections.info_or_types_size);
12841   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12842
12843   return dwo_unit;
12844 }
12845
12846 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12847    Returns NULL if the signature isn't found.  */
12848
12849 static struct dwo_unit *
12850 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12851                         struct dwp_file *dwp_file, const char *comp_dir,
12852                         ULONGEST signature, int is_debug_types)
12853 {
12854   const struct dwp_hash_table *dwp_htab =
12855     is_debug_types ? dwp_file->tus : dwp_file->cus;
12856   bfd *dbfd = dwp_file->dbfd;
12857   uint32_t mask = dwp_htab->nr_slots - 1;
12858   uint32_t hash = signature & mask;
12859   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12860   unsigned int i;
12861   void **slot;
12862   struct dwo_unit find_dwo_cu;
12863
12864   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12865   find_dwo_cu.signature = signature;
12866   slot = htab_find_slot (is_debug_types
12867                          ? dwp_file->loaded_tus
12868                          : dwp_file->loaded_cus,
12869                          &find_dwo_cu, INSERT);
12870
12871   if (*slot != NULL)
12872     return (struct dwo_unit *) *slot;
12873
12874   /* Use a for loop so that we don't loop forever on bad debug info.  */
12875   for (i = 0; i < dwp_htab->nr_slots; ++i)
12876     {
12877       ULONGEST signature_in_table;
12878
12879       signature_in_table =
12880         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12881       if (signature_in_table == signature)
12882         {
12883           uint32_t unit_index =
12884             read_4_bytes (dbfd,
12885                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12886
12887           if (dwp_file->version == 1)
12888             {
12889               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12890                                                  dwp_file, unit_index,
12891                                                  comp_dir, signature,
12892                                                  is_debug_types);
12893             }
12894           else
12895             {
12896               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12897                                                  dwp_file, unit_index,
12898                                                  comp_dir, signature,
12899                                                  is_debug_types);
12900             }
12901           return (struct dwo_unit *) *slot;
12902         }
12903       if (signature_in_table == 0)
12904         return NULL;
12905       hash = (hash + hash2) & mask;
12906     }
12907
12908   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12909            " [in module %s]"),
12910          dwp_file->name);
12911 }
12912
12913 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12914    Open the file specified by FILE_NAME and hand it off to BFD for
12915    preliminary analysis.  Return a newly initialized bfd *, which
12916    includes a canonicalized copy of FILE_NAME.
12917    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12918    SEARCH_CWD is true if the current directory is to be searched.
12919    It will be searched before debug-file-directory.
12920    If successful, the file is added to the bfd include table of the
12921    objfile's bfd (see gdb_bfd_record_inclusion).
12922    If unable to find/open the file, return NULL.
12923    NOTE: This function is derived from symfile_bfd_open.  */
12924
12925 static gdb_bfd_ref_ptr
12926 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12927                     const char *file_name, int is_dwp, int search_cwd)
12928 {
12929   int desc, flags;
12930   char *absolute_name;
12931   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12932      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12933      to debug_file_directory.  */
12934   char *search_path;
12935   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12936
12937   if (search_cwd)
12938     {
12939       if (*debug_file_directory != '\0')
12940         search_path = concat (".", dirname_separator_string,
12941                               debug_file_directory, (char *) NULL);
12942       else
12943         search_path = xstrdup (".");
12944     }
12945   else
12946     search_path = xstrdup (debug_file_directory);
12947
12948   flags = OPF_RETURN_REALPATH;
12949   if (is_dwp)
12950     flags |= OPF_SEARCH_IN_PATH;
12951   desc = openp (search_path, flags, file_name,
12952                 O_RDONLY | O_BINARY, &absolute_name);
12953   xfree (search_path);
12954   if (desc < 0)
12955     return NULL;
12956
12957   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12958   xfree (absolute_name);
12959   if (sym_bfd == NULL)
12960     return NULL;
12961   bfd_set_cacheable (sym_bfd.get (), 1);
12962
12963   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12964     return NULL;
12965
12966   /* Success.  Record the bfd as having been included by the objfile's bfd.
12967      This is important because things like demangled_names_hash lives in the
12968      objfile's per_bfd space and may have references to things like symbol
12969      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12970   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12971
12972   return sym_bfd;
12973 }
12974
12975 /* Try to open DWO file FILE_NAME.
12976    COMP_DIR is the DW_AT_comp_dir attribute.
12977    The result is the bfd handle of the file.
12978    If there is a problem finding or opening the file, return NULL.
12979    Upon success, the canonicalized path of the file is stored in the bfd,
12980    same as symfile_bfd_open.  */
12981
12982 static gdb_bfd_ref_ptr
12983 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12984                const char *file_name, const char *comp_dir)
12985 {
12986   if (IS_ABSOLUTE_PATH (file_name))
12987     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12988                                0 /*is_dwp*/, 0 /*search_cwd*/);
12989
12990   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12991
12992   if (comp_dir != NULL)
12993     {
12994       char *path_to_try = concat (comp_dir, SLASH_STRING,
12995                                   file_name, (char *) NULL);
12996
12997       /* NOTE: If comp_dir is a relative path, this will also try the
12998          search path, which seems useful.  */
12999       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
13000                                                 path_to_try,
13001                                                 0 /*is_dwp*/,
13002                                                 1 /*search_cwd*/));
13003       xfree (path_to_try);
13004       if (abfd != NULL)
13005         return abfd;
13006     }
13007
13008   /* That didn't work, try debug-file-directory, which, despite its name,
13009      is a list of paths.  */
13010
13011   if (*debug_file_directory == '\0')
13012     return NULL;
13013
13014   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13015                              0 /*is_dwp*/, 1 /*search_cwd*/);
13016 }
13017
13018 /* This function is mapped across the sections and remembers the offset and
13019    size of each of the DWO debugging sections we are interested in.  */
13020
13021 static void
13022 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13023 {
13024   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13025   const struct dwop_section_names *names = &dwop_section_names;
13026
13027   if (section_is_p (sectp->name, &names->abbrev_dwo))
13028     {
13029       dwo_sections->abbrev.s.section = sectp;
13030       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13031     }
13032   else if (section_is_p (sectp->name, &names->info_dwo))
13033     {
13034       dwo_sections->info.s.section = sectp;
13035       dwo_sections->info.size = bfd_get_section_size (sectp);
13036     }
13037   else if (section_is_p (sectp->name, &names->line_dwo))
13038     {
13039       dwo_sections->line.s.section = sectp;
13040       dwo_sections->line.size = bfd_get_section_size (sectp);
13041     }
13042   else if (section_is_p (sectp->name, &names->loc_dwo))
13043     {
13044       dwo_sections->loc.s.section = sectp;
13045       dwo_sections->loc.size = bfd_get_section_size (sectp);
13046     }
13047   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13048     {
13049       dwo_sections->macinfo.s.section = sectp;
13050       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13051     }
13052   else if (section_is_p (sectp->name, &names->macro_dwo))
13053     {
13054       dwo_sections->macro.s.section = sectp;
13055       dwo_sections->macro.size = bfd_get_section_size (sectp);
13056     }
13057   else if (section_is_p (sectp->name, &names->str_dwo))
13058     {
13059       dwo_sections->str.s.section = sectp;
13060       dwo_sections->str.size = bfd_get_section_size (sectp);
13061     }
13062   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13063     {
13064       dwo_sections->str_offsets.s.section = sectp;
13065       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13066     }
13067   else if (section_is_p (sectp->name, &names->types_dwo))
13068     {
13069       struct dwarf2_section_info type_section;
13070
13071       memset (&type_section, 0, sizeof (type_section));
13072       type_section.s.section = sectp;
13073       type_section.size = bfd_get_section_size (sectp);
13074       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13075                      &type_section);
13076     }
13077 }
13078
13079 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13080    by PER_CU.  This is for the non-DWP case.
13081    The result is NULL if DWO_NAME can't be found.  */
13082
13083 static struct dwo_file *
13084 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13085                         const char *dwo_name, const char *comp_dir)
13086 {
13087   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13088   struct objfile *objfile = dwarf2_per_objfile->objfile;
13089   struct dwo_file *dwo_file;
13090   struct cleanup *cleanups;
13091
13092   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13093   if (dbfd == NULL)
13094     {
13095       if (dwarf_read_debug)
13096         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13097       return NULL;
13098     }
13099   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13100   dwo_file->dwo_name = dwo_name;
13101   dwo_file->comp_dir = comp_dir;
13102   dwo_file->dbfd = dbfd.release ();
13103
13104   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13105   cleanup_data->dwo_file = dwo_file;
13106   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13107
13108   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13109
13110   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13111                          &dwo_file->sections);
13112
13113   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13114                          dwo_file->cus);
13115
13116   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13117                                  dwo_file->sections.types, dwo_file->tus);
13118
13119   discard_cleanups (cleanups);
13120
13121   if (dwarf_read_debug)
13122     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13123
13124   return dwo_file;
13125 }
13126
13127 /* This function is mapped across the sections and remembers the offset and
13128    size of each of the DWP debugging sections common to version 1 and 2 that
13129    we are interested in.  */
13130
13131 static void
13132 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13133                                    void *dwp_file_ptr)
13134 {
13135   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13136   const struct dwop_section_names *names = &dwop_section_names;
13137   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13138
13139   /* Record the ELF section number for later lookup: this is what the
13140      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13141   gdb_assert (elf_section_nr < dwp_file->num_sections);
13142   dwp_file->elf_sections[elf_section_nr] = sectp;
13143
13144   /* Look for specific sections that we need.  */
13145   if (section_is_p (sectp->name, &names->str_dwo))
13146     {
13147       dwp_file->sections.str.s.section = sectp;
13148       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13149     }
13150   else if (section_is_p (sectp->name, &names->cu_index))
13151     {
13152       dwp_file->sections.cu_index.s.section = sectp;
13153       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13154     }
13155   else if (section_is_p (sectp->name, &names->tu_index))
13156     {
13157       dwp_file->sections.tu_index.s.section = sectp;
13158       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13159     }
13160 }
13161
13162 /* This function is mapped across the sections and remembers the offset and
13163    size of each of the DWP version 2 debugging sections that we are interested
13164    in.  This is split into a separate function because we don't know if we
13165    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13166
13167 static void
13168 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13169 {
13170   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13171   const struct dwop_section_names *names = &dwop_section_names;
13172   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13173
13174   /* Record the ELF section number for later lookup: this is what the
13175      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13176   gdb_assert (elf_section_nr < dwp_file->num_sections);
13177   dwp_file->elf_sections[elf_section_nr] = sectp;
13178
13179   /* Look for specific sections that we need.  */
13180   if (section_is_p (sectp->name, &names->abbrev_dwo))
13181     {
13182       dwp_file->sections.abbrev.s.section = sectp;
13183       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13184     }
13185   else if (section_is_p (sectp->name, &names->info_dwo))
13186     {
13187       dwp_file->sections.info.s.section = sectp;
13188       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13189     }
13190   else if (section_is_p (sectp->name, &names->line_dwo))
13191     {
13192       dwp_file->sections.line.s.section = sectp;
13193       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13194     }
13195   else if (section_is_p (sectp->name, &names->loc_dwo))
13196     {
13197       dwp_file->sections.loc.s.section = sectp;
13198       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13199     }
13200   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13201     {
13202       dwp_file->sections.macinfo.s.section = sectp;
13203       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13204     }
13205   else if (section_is_p (sectp->name, &names->macro_dwo))
13206     {
13207       dwp_file->sections.macro.s.section = sectp;
13208       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13209     }
13210   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13211     {
13212       dwp_file->sections.str_offsets.s.section = sectp;
13213       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13214     }
13215   else if (section_is_p (sectp->name, &names->types_dwo))
13216     {
13217       dwp_file->sections.types.s.section = sectp;
13218       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13219     }
13220 }
13221
13222 /* Hash function for dwp_file loaded CUs/TUs.  */
13223
13224 static hashval_t
13225 hash_dwp_loaded_cutus (const void *item)
13226 {
13227   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13228
13229   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13230   return dwo_unit->signature;
13231 }
13232
13233 /* Equality function for dwp_file loaded CUs/TUs.  */
13234
13235 static int
13236 eq_dwp_loaded_cutus (const void *a, const void *b)
13237 {
13238   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13239   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13240
13241   return dua->signature == dub->signature;
13242 }
13243
13244 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13245
13246 static htab_t
13247 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13248 {
13249   return htab_create_alloc_ex (3,
13250                                hash_dwp_loaded_cutus,
13251                                eq_dwp_loaded_cutus,
13252                                NULL,
13253                                &objfile->objfile_obstack,
13254                                hashtab_obstack_allocate,
13255                                dummy_obstack_deallocate);
13256 }
13257
13258 /* Try to open DWP file FILE_NAME.
13259    The result is the bfd handle of the file.
13260    If there is a problem finding or opening the file, return NULL.
13261    Upon success, the canonicalized path of the file is stored in the bfd,
13262    same as symfile_bfd_open.  */
13263
13264 static gdb_bfd_ref_ptr
13265 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13266                const char *file_name)
13267 {
13268   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13269                                             1 /*is_dwp*/,
13270                                             1 /*search_cwd*/));
13271   if (abfd != NULL)
13272     return abfd;
13273
13274   /* Work around upstream bug 15652.
13275      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13276      [Whether that's a "bug" is debatable, but it is getting in our way.]
13277      We have no real idea where the dwp file is, because gdb's realpath-ing
13278      of the executable's path may have discarded the needed info.
13279      [IWBN if the dwp file name was recorded in the executable, akin to
13280      .gnu_debuglink, but that doesn't exist yet.]
13281      Strip the directory from FILE_NAME and search again.  */
13282   if (*debug_file_directory != '\0')
13283     {
13284       /* Don't implicitly search the current directory here.
13285          If the user wants to search "." to handle this case,
13286          it must be added to debug-file-directory.  */
13287       return try_open_dwop_file (dwarf2_per_objfile,
13288                                  lbasename (file_name), 1 /*is_dwp*/,
13289                                  0 /*search_cwd*/);
13290     }
13291
13292   return NULL;
13293 }
13294
13295 /* Initialize the use of the DWP file for the current objfile.
13296    By convention the name of the DWP file is ${objfile}.dwp.
13297    The result is NULL if it can't be found.  */
13298
13299 static struct dwp_file *
13300 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13301 {
13302   struct objfile *objfile = dwarf2_per_objfile->objfile;
13303   struct dwp_file *dwp_file;
13304
13305   /* Try to find first .dwp for the binary file before any symbolic links
13306      resolving.  */
13307
13308   /* If the objfile is a debug file, find the name of the real binary
13309      file and get the name of dwp file from there.  */
13310   std::string dwp_name;
13311   if (objfile->separate_debug_objfile_backlink != NULL)
13312     {
13313       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13314       const char *backlink_basename = lbasename (backlink->original_name);
13315
13316       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13317     }
13318   else
13319     dwp_name = objfile->original_name;
13320
13321   dwp_name += ".dwp";
13322
13323   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13324   if (dbfd == NULL
13325       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13326     {
13327       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13328       dwp_name = objfile_name (objfile);
13329       dwp_name += ".dwp";
13330       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13331     }
13332
13333   if (dbfd == NULL)
13334     {
13335       if (dwarf_read_debug)
13336         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13337       return NULL;
13338     }
13339   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13340   dwp_file->name = bfd_get_filename (dbfd.get ());
13341   dwp_file->dbfd = dbfd.release ();
13342
13343   /* +1: section 0 is unused */
13344   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13345   dwp_file->elf_sections =
13346     OBSTACK_CALLOC (&objfile->objfile_obstack,
13347                     dwp_file->num_sections, asection *);
13348
13349   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13350                          dwp_file);
13351
13352   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13353
13354   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13355
13356   /* The DWP file version is stored in the hash table.  Oh well.  */
13357   if (dwp_file->cus && dwp_file->tus
13358       && dwp_file->cus->version != dwp_file->tus->version)
13359     {
13360       /* Technically speaking, we should try to limp along, but this is
13361          pretty bizarre.  We use pulongest here because that's the established
13362          portability solution (e.g, we cannot use %u for uint32_t).  */
13363       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13364                " TU version %s [in DWP file %s]"),
13365              pulongest (dwp_file->cus->version),
13366              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13367     }
13368
13369   if (dwp_file->cus)
13370     dwp_file->version = dwp_file->cus->version;
13371   else if (dwp_file->tus)
13372     dwp_file->version = dwp_file->tus->version;
13373   else
13374     dwp_file->version = 2;
13375
13376   if (dwp_file->version == 2)
13377     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13378                            dwp_file);
13379
13380   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13381   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13382
13383   if (dwarf_read_debug)
13384     {
13385       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13386       fprintf_unfiltered (gdb_stdlog,
13387                           "    %s CUs, %s TUs\n",
13388                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13389                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13390     }
13391
13392   return dwp_file;
13393 }
13394
13395 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13396
13397 static struct dwp_file *
13398 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13399 {
13400   if (! dwarf2_per_objfile->dwp_checked)
13401     {
13402       dwarf2_per_objfile->dwp_file
13403         = open_and_init_dwp_file (dwarf2_per_objfile);
13404       dwarf2_per_objfile->dwp_checked = 1;
13405     }
13406   return dwarf2_per_objfile->dwp_file;
13407 }
13408
13409 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13410    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13411    or in the DWP file for the objfile, referenced by THIS_UNIT.
13412    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13413    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13414
13415    This is called, for example, when wanting to read a variable with a
13416    complex location.  Therefore we don't want to do file i/o for every call.
13417    Therefore we don't want to look for a DWO file on every call.
13418    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13419    then we check if we've already seen DWO_NAME, and only THEN do we check
13420    for a DWO file.
13421
13422    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13423    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13424
13425 static struct dwo_unit *
13426 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13427                  const char *dwo_name, const char *comp_dir,
13428                  ULONGEST signature, int is_debug_types)
13429 {
13430   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13431   struct objfile *objfile = dwarf2_per_objfile->objfile;
13432   const char *kind = is_debug_types ? "TU" : "CU";
13433   void **dwo_file_slot;
13434   struct dwo_file *dwo_file;
13435   struct dwp_file *dwp_file;
13436
13437   /* First see if there's a DWP file.
13438      If we have a DWP file but didn't find the DWO inside it, don't
13439      look for the original DWO file.  It makes gdb behave differently
13440      depending on whether one is debugging in the build tree.  */
13441
13442   dwp_file = get_dwp_file (dwarf2_per_objfile);
13443   if (dwp_file != NULL)
13444     {
13445       const struct dwp_hash_table *dwp_htab =
13446         is_debug_types ? dwp_file->tus : dwp_file->cus;
13447
13448       if (dwp_htab != NULL)
13449         {
13450           struct dwo_unit *dwo_cutu =
13451             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13452                                     signature, is_debug_types);
13453
13454           if (dwo_cutu != NULL)
13455             {
13456               if (dwarf_read_debug)
13457                 {
13458                   fprintf_unfiltered (gdb_stdlog,
13459                                       "Virtual DWO %s %s found: @%s\n",
13460                                       kind, hex_string (signature),
13461                                       host_address_to_string (dwo_cutu));
13462                 }
13463               return dwo_cutu;
13464             }
13465         }
13466     }
13467   else
13468     {
13469       /* No DWP file, look for the DWO file.  */
13470
13471       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13472                                             dwo_name, comp_dir);
13473       if (*dwo_file_slot == NULL)
13474         {
13475           /* Read in the file and build a table of the CUs/TUs it contains.  */
13476           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13477         }
13478       /* NOTE: This will be NULL if unable to open the file.  */
13479       dwo_file = (struct dwo_file *) *dwo_file_slot;
13480
13481       if (dwo_file != NULL)
13482         {
13483           struct dwo_unit *dwo_cutu = NULL;
13484
13485           if (is_debug_types && dwo_file->tus)
13486             {
13487               struct dwo_unit find_dwo_cutu;
13488
13489               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13490               find_dwo_cutu.signature = signature;
13491               dwo_cutu
13492                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13493             }
13494           else if (!is_debug_types && dwo_file->cus)
13495             {
13496               struct dwo_unit find_dwo_cutu;
13497
13498               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13499               find_dwo_cutu.signature = signature;
13500               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13501                                                        &find_dwo_cutu);
13502             }
13503
13504           if (dwo_cutu != NULL)
13505             {
13506               if (dwarf_read_debug)
13507                 {
13508                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13509                                       kind, dwo_name, hex_string (signature),
13510                                       host_address_to_string (dwo_cutu));
13511                 }
13512               return dwo_cutu;
13513             }
13514         }
13515     }
13516
13517   /* We didn't find it.  This could mean a dwo_id mismatch, or
13518      someone deleted the DWO/DWP file, or the search path isn't set up
13519      correctly to find the file.  */
13520
13521   if (dwarf_read_debug)
13522     {
13523       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13524                           kind, dwo_name, hex_string (signature));
13525     }
13526
13527   /* This is a warning and not a complaint because it can be caused by
13528      pilot error (e.g., user accidentally deleting the DWO).  */
13529   {
13530     /* Print the name of the DWP file if we looked there, helps the user
13531        better diagnose the problem.  */
13532     std::string dwp_text;
13533
13534     if (dwp_file != NULL)
13535       dwp_text = string_printf (" [in DWP file %s]",
13536                                 lbasename (dwp_file->name));
13537
13538     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13539                " [in module %s]"),
13540              kind, dwo_name, hex_string (signature),
13541              dwp_text.c_str (),
13542              this_unit->is_debug_types ? "TU" : "CU",
13543              to_underlying (this_unit->sect_off), objfile_name (objfile));
13544   }
13545   return NULL;
13546 }
13547
13548 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13549    See lookup_dwo_cutu_unit for details.  */
13550
13551 static struct dwo_unit *
13552 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13553                       const char *dwo_name, const char *comp_dir,
13554                       ULONGEST signature)
13555 {
13556   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13557 }
13558
13559 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13560    See lookup_dwo_cutu_unit for details.  */
13561
13562 static struct dwo_unit *
13563 lookup_dwo_type_unit (struct signatured_type *this_tu,
13564                       const char *dwo_name, const char *comp_dir)
13565 {
13566   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13567 }
13568
13569 /* Traversal function for queue_and_load_all_dwo_tus.  */
13570
13571 static int
13572 queue_and_load_dwo_tu (void **slot, void *info)
13573 {
13574   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13575   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13576   ULONGEST signature = dwo_unit->signature;
13577   struct signatured_type *sig_type =
13578     lookup_dwo_signatured_type (per_cu->cu, signature);
13579
13580   if (sig_type != NULL)
13581     {
13582       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13583
13584       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13585          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13586          while processing PER_CU.  */
13587       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13588         load_full_type_unit (sig_cu);
13589       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13590     }
13591
13592   return 1;
13593 }
13594
13595 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13596    The DWO may have the only definition of the type, though it may not be
13597    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13598    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13599
13600 static void
13601 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13602 {
13603   struct dwo_unit *dwo_unit;
13604   struct dwo_file *dwo_file;
13605
13606   gdb_assert (!per_cu->is_debug_types);
13607   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13608   gdb_assert (per_cu->cu != NULL);
13609
13610   dwo_unit = per_cu->cu->dwo_unit;
13611   gdb_assert (dwo_unit != NULL);
13612
13613   dwo_file = dwo_unit->dwo_file;
13614   if (dwo_file->tus != NULL)
13615     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13616 }
13617
13618 /* Free all resources associated with DWO_FILE.
13619    Close the DWO file and munmap the sections.
13620    All memory should be on the objfile obstack.  */
13621
13622 static void
13623 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13624 {
13625
13626   /* Note: dbfd is NULL for virtual DWO files.  */
13627   gdb_bfd_unref (dwo_file->dbfd);
13628
13629   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13630 }
13631
13632 /* Wrapper for free_dwo_file for use in cleanups.  */
13633
13634 static void
13635 free_dwo_file_cleanup (void *arg)
13636 {
13637   struct free_dwo_file_cleanup_data *data
13638     = (struct free_dwo_file_cleanup_data *) arg;
13639   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13640
13641   free_dwo_file (data->dwo_file, objfile);
13642
13643   xfree (data);
13644 }
13645
13646 /* Traversal function for free_dwo_files.  */
13647
13648 static int
13649 free_dwo_file_from_slot (void **slot, void *info)
13650 {
13651   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13652   struct objfile *objfile = (struct objfile *) info;
13653
13654   free_dwo_file (dwo_file, objfile);
13655
13656   return 1;
13657 }
13658
13659 /* Free all resources associated with DWO_FILES.  */
13660
13661 static void
13662 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13663 {
13664   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13665 }
13666 \f
13667 /* Read in various DIEs.  */
13668
13669 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13670    Inherit only the children of the DW_AT_abstract_origin DIE not being
13671    already referenced by DW_AT_abstract_origin from the children of the
13672    current DIE.  */
13673
13674 static void
13675 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13676 {
13677   struct die_info *child_die;
13678   sect_offset *offsetp;
13679   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13680   struct die_info *origin_die;
13681   /* Iterator of the ORIGIN_DIE children.  */
13682   struct die_info *origin_child_die;
13683   struct attribute *attr;
13684   struct dwarf2_cu *origin_cu;
13685   struct pending **origin_previous_list_in_scope;
13686
13687   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13688   if (!attr)
13689     return;
13690
13691   /* Note that following die references may follow to a die in a
13692      different cu.  */
13693
13694   origin_cu = cu;
13695   origin_die = follow_die_ref (die, attr, &origin_cu);
13696
13697   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13698      symbols in.  */
13699   origin_previous_list_in_scope = origin_cu->list_in_scope;
13700   origin_cu->list_in_scope = cu->list_in_scope;
13701
13702   if (die->tag != origin_die->tag
13703       && !(die->tag == DW_TAG_inlined_subroutine
13704            && origin_die->tag == DW_TAG_subprogram))
13705     complaint (&symfile_complaints,
13706                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13707                to_underlying (die->sect_off),
13708                to_underlying (origin_die->sect_off));
13709
13710   std::vector<sect_offset> offsets;
13711
13712   for (child_die = die->child;
13713        child_die && child_die->tag;
13714        child_die = sibling_die (child_die))
13715     {
13716       struct die_info *child_origin_die;
13717       struct dwarf2_cu *child_origin_cu;
13718
13719       /* We are trying to process concrete instance entries:
13720          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13721          it's not relevant to our analysis here. i.e. detecting DIEs that are
13722          present in the abstract instance but not referenced in the concrete
13723          one.  */
13724       if (child_die->tag == DW_TAG_call_site
13725           || child_die->tag == DW_TAG_GNU_call_site)
13726         continue;
13727
13728       /* For each CHILD_DIE, find the corresponding child of
13729          ORIGIN_DIE.  If there is more than one layer of
13730          DW_AT_abstract_origin, follow them all; there shouldn't be,
13731          but GCC versions at least through 4.4 generate this (GCC PR
13732          40573).  */
13733       child_origin_die = child_die;
13734       child_origin_cu = cu;
13735       while (1)
13736         {
13737           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13738                               child_origin_cu);
13739           if (attr == NULL)
13740             break;
13741           child_origin_die = follow_die_ref (child_origin_die, attr,
13742                                              &child_origin_cu);
13743         }
13744
13745       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13746          counterpart may exist.  */
13747       if (child_origin_die != child_die)
13748         {
13749           if (child_die->tag != child_origin_die->tag
13750               && !(child_die->tag == DW_TAG_inlined_subroutine
13751                    && child_origin_die->tag == DW_TAG_subprogram))
13752             complaint (&symfile_complaints,
13753                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13754                          "different tags"),
13755                        to_underlying (child_die->sect_off),
13756                        to_underlying (child_origin_die->sect_off));
13757           if (child_origin_die->parent != origin_die)
13758             complaint (&symfile_complaints,
13759                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13760                          "different parents"),
13761                        to_underlying (child_die->sect_off),
13762                        to_underlying (child_origin_die->sect_off));
13763           else
13764             offsets.push_back (child_origin_die->sect_off);
13765         }
13766     }
13767   std::sort (offsets.begin (), offsets.end ());
13768   sect_offset *offsets_end = offsets.data () + offsets.size ();
13769   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13770     if (offsetp[-1] == *offsetp)
13771       complaint (&symfile_complaints,
13772                  _("Multiple children of DIE 0x%x refer "
13773                    "to DIE 0x%x as their abstract origin"),
13774                  to_underlying (die->sect_off), to_underlying (*offsetp));
13775
13776   offsetp = offsets.data ();
13777   origin_child_die = origin_die->child;
13778   while (origin_child_die && origin_child_die->tag)
13779     {
13780       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13781       while (offsetp < offsets_end
13782              && *offsetp < origin_child_die->sect_off)
13783         offsetp++;
13784       if (offsetp >= offsets_end
13785           || *offsetp > origin_child_die->sect_off)
13786         {
13787           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13788              Check whether we're already processing ORIGIN_CHILD_DIE.
13789              This can happen with mutually referenced abstract_origins.
13790              PR 16581.  */
13791           if (!origin_child_die->in_process)
13792             process_die (origin_child_die, origin_cu);
13793         }
13794       origin_child_die = sibling_die (origin_child_die);
13795     }
13796   origin_cu->list_in_scope = origin_previous_list_in_scope;
13797 }
13798
13799 static void
13800 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13801 {
13802   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
13803   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13804   struct context_stack *newobj;
13805   CORE_ADDR lowpc;
13806   CORE_ADDR highpc;
13807   struct die_info *child_die;
13808   struct attribute *attr, *call_line, *call_file;
13809   const char *name;
13810   CORE_ADDR baseaddr;
13811   struct block *block;
13812   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13813   std::vector<struct symbol *> template_args;
13814   struct template_symbol *templ_func = NULL;
13815
13816   if (inlined_func)
13817     {
13818       /* If we do not have call site information, we can't show the
13819          caller of this inlined function.  That's too confusing, so
13820          only use the scope for local variables.  */
13821       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13822       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13823       if (call_line == NULL || call_file == NULL)
13824         {
13825           read_lexical_block_scope (die, cu);
13826           return;
13827         }
13828     }
13829
13830   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13831
13832   name = dwarf2_name (die, cu);
13833
13834   /* Ignore functions with missing or empty names.  These are actually
13835      illegal according to the DWARF standard.  */
13836   if (name == NULL)
13837     {
13838       complaint (&symfile_complaints,
13839                  _("missing name for subprogram DIE at %d"),
13840                  to_underlying (die->sect_off));
13841       return;
13842     }
13843
13844   /* Ignore functions with missing or invalid low and high pc attributes.  */
13845   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13846       <= PC_BOUNDS_INVALID)
13847     {
13848       attr = dwarf2_attr (die, DW_AT_external, cu);
13849       if (!attr || !DW_UNSND (attr))
13850         complaint (&symfile_complaints,
13851                    _("cannot get low and high bounds "
13852                      "for subprogram DIE at %d"),
13853                    to_underlying (die->sect_off));
13854       return;
13855     }
13856
13857   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13858   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13859
13860   /* If we have any template arguments, then we must allocate a
13861      different sort of symbol.  */
13862   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13863     {
13864       if (child_die->tag == DW_TAG_template_type_param
13865           || child_die->tag == DW_TAG_template_value_param)
13866         {
13867           templ_func = allocate_template_symbol (objfile);
13868           templ_func->subclass = SYMBOL_TEMPLATE;
13869           break;
13870         }
13871     }
13872
13873   newobj = push_context (0, lowpc);
13874   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
13875                                (struct symbol *) templ_func);
13876
13877   /* If there is a location expression for DW_AT_frame_base, record
13878      it.  */
13879   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13880   if (attr)
13881     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13882
13883   /* If there is a location for the static link, record it.  */
13884   newobj->static_link = NULL;
13885   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13886   if (attr)
13887     {
13888       newobj->static_link
13889         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13890       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13891     }
13892
13893   cu->list_in_scope = &local_symbols;
13894
13895   if (die->child != NULL)
13896     {
13897       child_die = die->child;
13898       while (child_die && child_die->tag)
13899         {
13900           if (child_die->tag == DW_TAG_template_type_param
13901               || child_die->tag == DW_TAG_template_value_param)
13902             {
13903               struct symbol *arg = new_symbol (child_die, NULL, cu);
13904
13905               if (arg != NULL)
13906                 template_args.push_back (arg);
13907             }
13908           else
13909             process_die (child_die, cu);
13910           child_die = sibling_die (child_die);
13911         }
13912     }
13913
13914   inherit_abstract_dies (die, cu);
13915
13916   /* If we have a DW_AT_specification, we might need to import using
13917      directives from the context of the specification DIE.  See the
13918      comment in determine_prefix.  */
13919   if (cu->language == language_cplus
13920       && dwarf2_attr (die, DW_AT_specification, cu))
13921     {
13922       struct dwarf2_cu *spec_cu = cu;
13923       struct die_info *spec_die = die_specification (die, &spec_cu);
13924
13925       while (spec_die)
13926         {
13927           child_die = spec_die->child;
13928           while (child_die && child_die->tag)
13929             {
13930               if (child_die->tag == DW_TAG_imported_module)
13931                 process_die (child_die, spec_cu);
13932               child_die = sibling_die (child_die);
13933             }
13934
13935           /* In some cases, GCC generates specification DIEs that
13936              themselves contain DW_AT_specification attributes.  */
13937           spec_die = die_specification (spec_die, &spec_cu);
13938         }
13939     }
13940
13941   newobj = pop_context ();
13942   /* Make a block for the local symbols within.  */
13943   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13944                         newobj->static_link, lowpc, highpc);
13945
13946   /* For C++, set the block's scope.  */
13947   if ((cu->language == language_cplus
13948        || cu->language == language_fortran
13949        || cu->language == language_d
13950        || cu->language == language_rust)
13951       && cu->processing_has_namespace_info)
13952     block_set_scope (block, determine_prefix (die, cu),
13953                      &objfile->objfile_obstack);
13954
13955   /* If we have address ranges, record them.  */
13956   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13957
13958   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13959
13960   /* Attach template arguments to function.  */
13961   if (!template_args.empty ())
13962     {
13963       gdb_assert (templ_func != NULL);
13964
13965       templ_func->n_template_arguments = template_args.size ();
13966       templ_func->template_arguments
13967         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13968                      templ_func->n_template_arguments);
13969       memcpy (templ_func->template_arguments,
13970               template_args.data (),
13971               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13972     }
13973
13974   /* In C++, we can have functions nested inside functions (e.g., when
13975      a function declares a class that has methods).  This means that
13976      when we finish processing a function scope, we may need to go
13977      back to building a containing block's symbol lists.  */
13978   local_symbols = newobj->locals;
13979   local_using_directives = newobj->local_using_directives;
13980
13981   /* If we've finished processing a top-level function, subsequent
13982      symbols go in the file symbol list.  */
13983   if (outermost_context_p ())
13984     cu->list_in_scope = &file_symbols;
13985 }
13986
13987 /* Process all the DIES contained within a lexical block scope.  Start
13988    a new scope, process the dies, and then close the scope.  */
13989
13990 static void
13991 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13992 {
13993   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
13994   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13995   struct context_stack *newobj;
13996   CORE_ADDR lowpc, highpc;
13997   struct die_info *child_die;
13998   CORE_ADDR baseaddr;
13999
14000   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14001
14002   /* Ignore blocks with missing or invalid low and high pc attributes.  */
14003   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
14004      as multiple lexical blocks?  Handling children in a sane way would
14005      be nasty.  Might be easier to properly extend generic blocks to
14006      describe ranges.  */
14007   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14008     {
14009     case PC_BOUNDS_NOT_PRESENT:
14010       /* DW_TAG_lexical_block has no attributes, process its children as if
14011          there was no wrapping by that DW_TAG_lexical_block.
14012          GCC does no longer produces such DWARF since GCC r224161.  */
14013       for (child_die = die->child;
14014            child_die != NULL && child_die->tag;
14015            child_die = sibling_die (child_die))
14016         process_die (child_die, cu);
14017       return;
14018     case PC_BOUNDS_INVALID:
14019       return;
14020     }
14021   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14022   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14023
14024   push_context (0, lowpc);
14025   if (die->child != NULL)
14026     {
14027       child_die = die->child;
14028       while (child_die && child_die->tag)
14029         {
14030           process_die (child_die, cu);
14031           child_die = sibling_die (child_die);
14032         }
14033     }
14034   inherit_abstract_dies (die, cu);
14035   newobj = pop_context ();
14036
14037   if (local_symbols != NULL || local_using_directives != NULL)
14038     {
14039       struct block *block
14040         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14041                         newobj->start_addr, highpc);
14042
14043       /* Note that recording ranges after traversing children, as we
14044          do here, means that recording a parent's ranges entails
14045          walking across all its children's ranges as they appear in
14046          the address map, which is quadratic behavior.
14047
14048          It would be nicer to record the parent's ranges before
14049          traversing its children, simply overriding whatever you find
14050          there.  But since we don't even decide whether to create a
14051          block until after we've traversed its children, that's hard
14052          to do.  */
14053       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14054     }
14055   local_symbols = newobj->locals;
14056   local_using_directives = newobj->local_using_directives;
14057 }
14058
14059 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14060
14061 static void
14062 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14063 {
14064   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14065   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14066   CORE_ADDR pc, baseaddr;
14067   struct attribute *attr;
14068   struct call_site *call_site, call_site_local;
14069   void **slot;
14070   int nparams;
14071   struct die_info *child_die;
14072
14073   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14074
14075   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14076   if (attr == NULL)
14077     {
14078       /* This was a pre-DWARF-5 GNU extension alias
14079          for DW_AT_call_return_pc.  */
14080       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14081     }
14082   if (!attr)
14083     {
14084       complaint (&symfile_complaints,
14085                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14086                    "DIE 0x%x [in module %s]"),
14087                  to_underlying (die->sect_off), objfile_name (objfile));
14088       return;
14089     }
14090   pc = attr_value_as_address (attr) + baseaddr;
14091   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14092
14093   if (cu->call_site_htab == NULL)
14094     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14095                                                NULL, &objfile->objfile_obstack,
14096                                                hashtab_obstack_allocate, NULL);
14097   call_site_local.pc = pc;
14098   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14099   if (*slot != NULL)
14100     {
14101       complaint (&symfile_complaints,
14102                  _("Duplicate PC %s for DW_TAG_call_site "
14103                    "DIE 0x%x [in module %s]"),
14104                  paddress (gdbarch, pc), to_underlying (die->sect_off),
14105                  objfile_name (objfile));
14106       return;
14107     }
14108
14109   /* Count parameters at the caller.  */
14110
14111   nparams = 0;
14112   for (child_die = die->child; child_die && child_die->tag;
14113        child_die = sibling_die (child_die))
14114     {
14115       if (child_die->tag != DW_TAG_call_site_parameter
14116           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14117         {
14118           complaint (&symfile_complaints,
14119                      _("Tag %d is not DW_TAG_call_site_parameter in "
14120                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14121                      child_die->tag, to_underlying (child_die->sect_off),
14122                      objfile_name (objfile));
14123           continue;
14124         }
14125
14126       nparams++;
14127     }
14128
14129   call_site
14130     = ((struct call_site *)
14131        obstack_alloc (&objfile->objfile_obstack,
14132                       sizeof (*call_site)
14133                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14134   *slot = call_site;
14135   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14136   call_site->pc = pc;
14137
14138   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14139       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14140     {
14141       struct die_info *func_die;
14142
14143       /* Skip also over DW_TAG_inlined_subroutine.  */
14144       for (func_die = die->parent;
14145            func_die && func_die->tag != DW_TAG_subprogram
14146            && func_die->tag != DW_TAG_subroutine_type;
14147            func_die = func_die->parent);
14148
14149       /* DW_AT_call_all_calls is a superset
14150          of DW_AT_call_all_tail_calls.  */
14151       if (func_die
14152           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14153           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14154           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14155           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14156         {
14157           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14158              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14159              both the initial caller containing the real return address PC and
14160              the final callee containing the current PC of a chain of tail
14161              calls do not need to have the tail call list complete.  But any
14162              function candidate for a virtual tail call frame searched via
14163              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14164              determined unambiguously.  */
14165         }
14166       else
14167         {
14168           struct type *func_type = NULL;
14169
14170           if (func_die)
14171             func_type = get_die_type (func_die, cu);
14172           if (func_type != NULL)
14173             {
14174               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14175
14176               /* Enlist this call site to the function.  */
14177               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14178               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14179             }
14180           else
14181             complaint (&symfile_complaints,
14182                        _("Cannot find function owning DW_TAG_call_site "
14183                          "DIE 0x%x [in module %s]"),
14184                        to_underlying (die->sect_off), objfile_name (objfile));
14185         }
14186     }
14187
14188   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14189   if (attr == NULL)
14190     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14191   if (attr == NULL)
14192     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14193   if (attr == NULL)
14194     {
14195       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14196       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14197     }
14198   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14199   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14200     /* Keep NULL DWARF_BLOCK.  */;
14201   else if (attr_form_is_block (attr))
14202     {
14203       struct dwarf2_locexpr_baton *dlbaton;
14204
14205       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14206       dlbaton->data = DW_BLOCK (attr)->data;
14207       dlbaton->size = DW_BLOCK (attr)->size;
14208       dlbaton->per_cu = cu->per_cu;
14209
14210       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14211     }
14212   else if (attr_form_is_ref (attr))
14213     {
14214       struct dwarf2_cu *target_cu = cu;
14215       struct die_info *target_die;
14216
14217       target_die = follow_die_ref (die, attr, &target_cu);
14218       gdb_assert (target_cu->dwarf2_per_objfile->objfile == objfile);
14219       if (die_is_declaration (target_die, target_cu))
14220         {
14221           const char *target_physname;
14222
14223           /* Prefer the mangled name; otherwise compute the demangled one.  */
14224           target_physname = dw2_linkage_name (target_die, target_cu);
14225           if (target_physname == NULL)
14226             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14227           if (target_physname == NULL)
14228             complaint (&symfile_complaints,
14229                        _("DW_AT_call_target target DIE has invalid "
14230                          "physname, for referencing DIE 0x%x [in module %s]"),
14231                        to_underlying (die->sect_off), objfile_name (objfile));
14232           else
14233             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14234         }
14235       else
14236         {
14237           CORE_ADDR lowpc;
14238
14239           /* DW_AT_entry_pc should be preferred.  */
14240           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14241               <= PC_BOUNDS_INVALID)
14242             complaint (&symfile_complaints,
14243                        _("DW_AT_call_target target DIE has invalid "
14244                          "low pc, for referencing DIE 0x%x [in module %s]"),
14245                        to_underlying (die->sect_off), objfile_name (objfile));
14246           else
14247             {
14248               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14249               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14250             }
14251         }
14252     }
14253   else
14254     complaint (&symfile_complaints,
14255                _("DW_TAG_call_site DW_AT_call_target is neither "
14256                  "block nor reference, for DIE 0x%x [in module %s]"),
14257                to_underlying (die->sect_off), objfile_name (objfile));
14258
14259   call_site->per_cu = cu->per_cu;
14260
14261   for (child_die = die->child;
14262        child_die && child_die->tag;
14263        child_die = sibling_die (child_die))
14264     {
14265       struct call_site_parameter *parameter;
14266       struct attribute *loc, *origin;
14267
14268       if (child_die->tag != DW_TAG_call_site_parameter
14269           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14270         {
14271           /* Already printed the complaint above.  */
14272           continue;
14273         }
14274
14275       gdb_assert (call_site->parameter_count < nparams);
14276       parameter = &call_site->parameter[call_site->parameter_count];
14277
14278       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14279          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14280          register is contained in DW_AT_call_value.  */
14281
14282       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14283       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14284       if (origin == NULL)
14285         {
14286           /* This was a pre-DWARF-5 GNU extension alias
14287              for DW_AT_call_parameter.  */
14288           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14289         }
14290       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14291         {
14292           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14293
14294           sect_offset sect_off
14295             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14296           if (!offset_in_cu_p (&cu->header, sect_off))
14297             {
14298               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14299                  binding can be done only inside one CU.  Such referenced DIE
14300                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14301               complaint (&symfile_complaints,
14302                          _("DW_AT_call_parameter offset is not in CU for "
14303                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14304                          to_underlying (child_die->sect_off),
14305                          objfile_name (objfile));
14306               continue;
14307             }
14308           parameter->u.param_cu_off
14309             = (cu_offset) (sect_off - cu->header.sect_off);
14310         }
14311       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14312         {
14313           complaint (&symfile_complaints,
14314                      _("No DW_FORM_block* DW_AT_location for "
14315                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14316                      to_underlying (child_die->sect_off), objfile_name (objfile));
14317           continue;
14318         }
14319       else
14320         {
14321           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14322             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14323           if (parameter->u.dwarf_reg != -1)
14324             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14325           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14326                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14327                                              &parameter->u.fb_offset))
14328             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14329           else
14330             {
14331               complaint (&symfile_complaints,
14332                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14333                            "for DW_FORM_block* DW_AT_location is supported for "
14334                            "DW_TAG_call_site child DIE 0x%x "
14335                            "[in module %s]"),
14336                          to_underlying (child_die->sect_off),
14337                          objfile_name (objfile));
14338               continue;
14339             }
14340         }
14341
14342       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14343       if (attr == NULL)
14344         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14345       if (!attr_form_is_block (attr))
14346         {
14347           complaint (&symfile_complaints,
14348                      _("No DW_FORM_block* DW_AT_call_value for "
14349                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14350                      to_underlying (child_die->sect_off),
14351                      objfile_name (objfile));
14352           continue;
14353         }
14354       parameter->value = DW_BLOCK (attr)->data;
14355       parameter->value_size = DW_BLOCK (attr)->size;
14356
14357       /* Parameters are not pre-cleared by memset above.  */
14358       parameter->data_value = NULL;
14359       parameter->data_value_size = 0;
14360       call_site->parameter_count++;
14361
14362       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14363       if (attr == NULL)
14364         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14365       if (attr)
14366         {
14367           if (!attr_form_is_block (attr))
14368             complaint (&symfile_complaints,
14369                        _("No DW_FORM_block* DW_AT_call_data_value for "
14370                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14371                        to_underlying (child_die->sect_off),
14372                        objfile_name (objfile));
14373           else
14374             {
14375               parameter->data_value = DW_BLOCK (attr)->data;
14376               parameter->data_value_size = DW_BLOCK (attr)->size;
14377             }
14378         }
14379     }
14380 }
14381
14382 /* Helper function for read_variable.  If DIE represents a virtual
14383    table, then return the type of the concrete object that is
14384    associated with the virtual table.  Otherwise, return NULL.  */
14385
14386 static struct type *
14387 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14388 {
14389   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14390   if (attr == NULL)
14391     return NULL;
14392
14393   /* Find the type DIE.  */
14394   struct die_info *type_die = NULL;
14395   struct dwarf2_cu *type_cu = cu;
14396
14397   if (attr_form_is_ref (attr))
14398     type_die = follow_die_ref (die, attr, &type_cu);
14399   if (type_die == NULL)
14400     return NULL;
14401
14402   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14403     return NULL;
14404   return die_containing_type (type_die, type_cu);
14405 }
14406
14407 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14408
14409 static void
14410 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14411 {
14412   struct rust_vtable_symbol *storage = NULL;
14413
14414   if (cu->language == language_rust)
14415     {
14416       struct type *containing_type = rust_containing_type (die, cu);
14417
14418       if (containing_type != NULL)
14419         {
14420           struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14421
14422           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14423                                     struct rust_vtable_symbol);
14424           initialize_objfile_symbol (storage);
14425           storage->concrete_type = containing_type;
14426           storage->subclass = SYMBOL_RUST_VTABLE;
14427         }
14428     }
14429
14430   new_symbol_full (die, NULL, cu, storage);
14431 }
14432
14433 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14434    reading .debug_rnglists.
14435    Callback's type should be:
14436     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14437    Return true if the attributes are present and valid, otherwise,
14438    return false.  */
14439
14440 template <typename Callback>
14441 static bool
14442 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14443                          Callback &&callback)
14444 {
14445   struct dwarf2_per_objfile *dwarf2_per_objfile
14446     = cu->dwarf2_per_objfile;
14447   struct objfile *objfile = dwarf2_per_objfile->objfile;
14448   bfd *obfd = objfile->obfd;
14449   /* Base address selection entry.  */
14450   CORE_ADDR base;
14451   int found_base;
14452   const gdb_byte *buffer;
14453   CORE_ADDR baseaddr;
14454   bool overflow = false;
14455
14456   found_base = cu->base_known;
14457   base = cu->base_address;
14458
14459   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14460   if (offset >= dwarf2_per_objfile->rnglists.size)
14461     {
14462       complaint (&symfile_complaints,
14463                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14464                  offset);
14465       return false;
14466     }
14467   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14468
14469   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14470
14471   while (1)
14472     {
14473       /* Initialize it due to a false compiler warning.  */
14474       CORE_ADDR range_beginning = 0, range_end = 0;
14475       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14476                                  + dwarf2_per_objfile->rnglists.size);
14477       unsigned int bytes_read;
14478
14479       if (buffer == buf_end)
14480         {
14481           overflow = true;
14482           break;
14483         }
14484       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14485       switch (rlet)
14486         {
14487         case DW_RLE_end_of_list:
14488           break;
14489         case DW_RLE_base_address:
14490           if (buffer + cu->header.addr_size > buf_end)
14491             {
14492               overflow = true;
14493               break;
14494             }
14495           base = read_address (obfd, buffer, cu, &bytes_read);
14496           found_base = 1;
14497           buffer += bytes_read;
14498           break;
14499         case DW_RLE_start_length:
14500           if (buffer + cu->header.addr_size > buf_end)
14501             {
14502               overflow = true;
14503               break;
14504             }
14505           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14506           buffer += bytes_read;
14507           range_end = (range_beginning
14508                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14509           buffer += bytes_read;
14510           if (buffer > buf_end)
14511             {
14512               overflow = true;
14513               break;
14514             }
14515           break;
14516         case DW_RLE_offset_pair:
14517           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14518           buffer += bytes_read;
14519           if (buffer > buf_end)
14520             {
14521               overflow = true;
14522               break;
14523             }
14524           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14525           buffer += bytes_read;
14526           if (buffer > buf_end)
14527             {
14528               overflow = true;
14529               break;
14530             }
14531           break;
14532         case DW_RLE_start_end:
14533           if (buffer + 2 * cu->header.addr_size > buf_end)
14534             {
14535               overflow = true;
14536               break;
14537             }
14538           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14539           buffer += bytes_read;
14540           range_end = read_address (obfd, buffer, cu, &bytes_read);
14541           buffer += bytes_read;
14542           break;
14543         default:
14544           complaint (&symfile_complaints,
14545                      _("Invalid .debug_rnglists data (no base address)"));
14546           return false;
14547         }
14548       if (rlet == DW_RLE_end_of_list || overflow)
14549         break;
14550       if (rlet == DW_RLE_base_address)
14551         continue;
14552
14553       if (!found_base)
14554         {
14555           /* We have no valid base address for the ranges
14556              data.  */
14557           complaint (&symfile_complaints,
14558                      _("Invalid .debug_rnglists data (no base address)"));
14559           return false;
14560         }
14561
14562       if (range_beginning > range_end)
14563         {
14564           /* Inverted range entries are invalid.  */
14565           complaint (&symfile_complaints,
14566                      _("Invalid .debug_rnglists data (inverted range)"));
14567           return false;
14568         }
14569
14570       /* Empty range entries have no effect.  */
14571       if (range_beginning == range_end)
14572         continue;
14573
14574       range_beginning += base;
14575       range_end += base;
14576
14577       /* A not-uncommon case of bad debug info.
14578          Don't pollute the addrmap with bad data.  */
14579       if (range_beginning + baseaddr == 0
14580           && !dwarf2_per_objfile->has_section_at_zero)
14581         {
14582           complaint (&symfile_complaints,
14583                      _(".debug_rnglists entry has start address of zero"
14584                        " [in module %s]"), objfile_name (objfile));
14585           continue;
14586         }
14587
14588       callback (range_beginning, range_end);
14589     }
14590
14591   if (overflow)
14592     {
14593       complaint (&symfile_complaints,
14594                  _("Offset %d is not terminated "
14595                    "for DW_AT_ranges attribute"),
14596                  offset);
14597       return false;
14598     }
14599
14600   return true;
14601 }
14602
14603 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14604    Callback's type should be:
14605     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14606    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14607
14608 template <typename Callback>
14609 static int
14610 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14611                        Callback &&callback)
14612 {
14613   struct dwarf2_per_objfile *dwarf2_per_objfile
14614       = cu->dwarf2_per_objfile;
14615   struct objfile *objfile = dwarf2_per_objfile->objfile;
14616   struct comp_unit_head *cu_header = &cu->header;
14617   bfd *obfd = objfile->obfd;
14618   unsigned int addr_size = cu_header->addr_size;
14619   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14620   /* Base address selection entry.  */
14621   CORE_ADDR base;
14622   int found_base;
14623   unsigned int dummy;
14624   const gdb_byte *buffer;
14625   CORE_ADDR baseaddr;
14626
14627   if (cu_header->version >= 5)
14628     return dwarf2_rnglists_process (offset, cu, callback);
14629
14630   found_base = cu->base_known;
14631   base = cu->base_address;
14632
14633   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14634   if (offset >= dwarf2_per_objfile->ranges.size)
14635     {
14636       complaint (&symfile_complaints,
14637                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14638                  offset);
14639       return 0;
14640     }
14641   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14642
14643   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14644
14645   while (1)
14646     {
14647       CORE_ADDR range_beginning, range_end;
14648
14649       range_beginning = read_address (obfd, buffer, cu, &dummy);
14650       buffer += addr_size;
14651       range_end = read_address (obfd, buffer, cu, &dummy);
14652       buffer += addr_size;
14653       offset += 2 * addr_size;
14654
14655       /* An end of list marker is a pair of zero addresses.  */
14656       if (range_beginning == 0 && range_end == 0)
14657         /* Found the end of list entry.  */
14658         break;
14659
14660       /* Each base address selection entry is a pair of 2 values.
14661          The first is the largest possible address, the second is
14662          the base address.  Check for a base address here.  */
14663       if ((range_beginning & mask) == mask)
14664         {
14665           /* If we found the largest possible address, then we already
14666              have the base address in range_end.  */
14667           base = range_end;
14668           found_base = 1;
14669           continue;
14670         }
14671
14672       if (!found_base)
14673         {
14674           /* We have no valid base address for the ranges
14675              data.  */
14676           complaint (&symfile_complaints,
14677                      _("Invalid .debug_ranges data (no base address)"));
14678           return 0;
14679         }
14680
14681       if (range_beginning > range_end)
14682         {
14683           /* Inverted range entries are invalid.  */
14684           complaint (&symfile_complaints,
14685                      _("Invalid .debug_ranges data (inverted range)"));
14686           return 0;
14687         }
14688
14689       /* Empty range entries have no effect.  */
14690       if (range_beginning == range_end)
14691         continue;
14692
14693       range_beginning += base;
14694       range_end += base;
14695
14696       /* A not-uncommon case of bad debug info.
14697          Don't pollute the addrmap with bad data.  */
14698       if (range_beginning + baseaddr == 0
14699           && !dwarf2_per_objfile->has_section_at_zero)
14700         {
14701           complaint (&symfile_complaints,
14702                      _(".debug_ranges entry has start address of zero"
14703                        " [in module %s]"), objfile_name (objfile));
14704           continue;
14705         }
14706
14707       callback (range_beginning, range_end);
14708     }
14709
14710   return 1;
14711 }
14712
14713 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14714    Return 1 if the attributes are present and valid, otherwise, return 0.
14715    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14716
14717 static int
14718 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14719                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14720                     struct partial_symtab *ranges_pst)
14721 {
14722   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14723   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14724   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14725                                        SECT_OFF_TEXT (objfile));
14726   int low_set = 0;
14727   CORE_ADDR low = 0;
14728   CORE_ADDR high = 0;
14729   int retval;
14730
14731   retval = dwarf2_ranges_process (offset, cu,
14732     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14733     {
14734       if (ranges_pst != NULL)
14735         {
14736           CORE_ADDR lowpc;
14737           CORE_ADDR highpc;
14738
14739           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14740                                               range_beginning + baseaddr);
14741           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14742                                                range_end + baseaddr);
14743           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14744                              ranges_pst);
14745         }
14746
14747       /* FIXME: This is recording everything as a low-high
14748          segment of consecutive addresses.  We should have a
14749          data structure for discontiguous block ranges
14750          instead.  */
14751       if (! low_set)
14752         {
14753           low = range_beginning;
14754           high = range_end;
14755           low_set = 1;
14756         }
14757       else
14758         {
14759           if (range_beginning < low)
14760             low = range_beginning;
14761           if (range_end > high)
14762             high = range_end;
14763         }
14764     });
14765   if (!retval)
14766     return 0;
14767
14768   if (! low_set)
14769     /* If the first entry is an end-of-list marker, the range
14770        describes an empty scope, i.e. no instructions.  */
14771     return 0;
14772
14773   if (low_return)
14774     *low_return = low;
14775   if (high_return)
14776     *high_return = high;
14777   return 1;
14778 }
14779
14780 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14781    definition for the return value.  *LOWPC and *HIGHPC are set iff
14782    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14783
14784 static enum pc_bounds_kind
14785 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14786                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14787                       struct partial_symtab *pst)
14788 {
14789   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
14790   struct attribute *attr;
14791   struct attribute *attr_high;
14792   CORE_ADDR low = 0;
14793   CORE_ADDR high = 0;
14794   enum pc_bounds_kind ret;
14795
14796   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14797   if (attr_high)
14798     {
14799       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14800       if (attr)
14801         {
14802           low = attr_value_as_address (attr);
14803           high = attr_value_as_address (attr_high);
14804           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14805             high += low;
14806         }
14807       else
14808         /* Found high w/o low attribute.  */
14809         return PC_BOUNDS_INVALID;
14810
14811       /* Found consecutive range of addresses.  */
14812       ret = PC_BOUNDS_HIGH_LOW;
14813     }
14814   else
14815     {
14816       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14817       if (attr != NULL)
14818         {
14819           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14820              We take advantage of the fact that DW_AT_ranges does not appear
14821              in DW_TAG_compile_unit of DWO files.  */
14822           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14823           unsigned int ranges_offset = (DW_UNSND (attr)
14824                                         + (need_ranges_base
14825                                            ? cu->ranges_base
14826                                            : 0));
14827
14828           /* Value of the DW_AT_ranges attribute is the offset in the
14829              .debug_ranges section.  */
14830           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14831             return PC_BOUNDS_INVALID;
14832           /* Found discontinuous range of addresses.  */
14833           ret = PC_BOUNDS_RANGES;
14834         }
14835       else
14836         return PC_BOUNDS_NOT_PRESENT;
14837     }
14838
14839   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14840   if (high <= low)
14841     return PC_BOUNDS_INVALID;
14842
14843   /* When using the GNU linker, .gnu.linkonce. sections are used to
14844      eliminate duplicate copies of functions and vtables and such.
14845      The linker will arbitrarily choose one and discard the others.
14846      The AT_*_pc values for such functions refer to local labels in
14847      these sections.  If the section from that file was discarded, the
14848      labels are not in the output, so the relocs get a value of 0.
14849      If this is a discarded function, mark the pc bounds as invalid,
14850      so that GDB will ignore it.  */
14851   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14852     return PC_BOUNDS_INVALID;
14853
14854   *lowpc = low;
14855   if (highpc)
14856     *highpc = high;
14857   return ret;
14858 }
14859
14860 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14861    its low and high PC addresses.  Do nothing if these addresses could not
14862    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14863    and HIGHPC to the high address if greater than HIGHPC.  */
14864
14865 static void
14866 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14867                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14868                                  struct dwarf2_cu *cu)
14869 {
14870   CORE_ADDR low, high;
14871   struct die_info *child = die->child;
14872
14873   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14874     {
14875       *lowpc = std::min (*lowpc, low);
14876       *highpc = std::max (*highpc, high);
14877     }
14878
14879   /* If the language does not allow nested subprograms (either inside
14880      subprograms or lexical blocks), we're done.  */
14881   if (cu->language != language_ada)
14882     return;
14883
14884   /* Check all the children of the given DIE.  If it contains nested
14885      subprograms, then check their pc bounds.  Likewise, we need to
14886      check lexical blocks as well, as they may also contain subprogram
14887      definitions.  */
14888   while (child && child->tag)
14889     {
14890       if (child->tag == DW_TAG_subprogram
14891           || child->tag == DW_TAG_lexical_block)
14892         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14893       child = sibling_die (child);
14894     }
14895 }
14896
14897 /* Get the low and high pc's represented by the scope DIE, and store
14898    them in *LOWPC and *HIGHPC.  If the correct values can't be
14899    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14900
14901 static void
14902 get_scope_pc_bounds (struct die_info *die,
14903                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14904                      struct dwarf2_cu *cu)
14905 {
14906   CORE_ADDR best_low = (CORE_ADDR) -1;
14907   CORE_ADDR best_high = (CORE_ADDR) 0;
14908   CORE_ADDR current_low, current_high;
14909
14910   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14911       >= PC_BOUNDS_RANGES)
14912     {
14913       best_low = current_low;
14914       best_high = current_high;
14915     }
14916   else
14917     {
14918       struct die_info *child = die->child;
14919
14920       while (child && child->tag)
14921         {
14922           switch (child->tag) {
14923           case DW_TAG_subprogram:
14924             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14925             break;
14926           case DW_TAG_namespace:
14927           case DW_TAG_module:
14928             /* FIXME: carlton/2004-01-16: Should we do this for
14929                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14930                that current GCC's always emit the DIEs corresponding
14931                to definitions of methods of classes as children of a
14932                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14933                the DIEs giving the declarations, which could be
14934                anywhere).  But I don't see any reason why the
14935                standards says that they have to be there.  */
14936             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14937
14938             if (current_low != ((CORE_ADDR) -1))
14939               {
14940                 best_low = std::min (best_low, current_low);
14941                 best_high = std::max (best_high, current_high);
14942               }
14943             break;
14944           default:
14945             /* Ignore.  */
14946             break;
14947           }
14948
14949           child = sibling_die (child);
14950         }
14951     }
14952
14953   *lowpc = best_low;
14954   *highpc = best_high;
14955 }
14956
14957 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14958    in DIE.  */
14959
14960 static void
14961 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14962                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14963 {
14964   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
14965   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14966   struct attribute *attr;
14967   struct attribute *attr_high;
14968
14969   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14970   if (attr_high)
14971     {
14972       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14973       if (attr)
14974         {
14975           CORE_ADDR low = attr_value_as_address (attr);
14976           CORE_ADDR high = attr_value_as_address (attr_high);
14977
14978           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14979             high += low;
14980
14981           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14982           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14983           record_block_range (block, low, high - 1);
14984         }
14985     }
14986
14987   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14988   if (attr)
14989     {
14990       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14991          We take advantage of the fact that DW_AT_ranges does not appear
14992          in DW_TAG_compile_unit of DWO files.  */
14993       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14994
14995       /* The value of the DW_AT_ranges attribute is the offset of the
14996          address range list in the .debug_ranges section.  */
14997       unsigned long offset = (DW_UNSND (attr)
14998                               + (need_ranges_base ? cu->ranges_base : 0));
14999       const gdb_byte *buffer;
15000
15001       /* For some target architectures, but not others, the
15002          read_address function sign-extends the addresses it returns.
15003          To recognize base address selection entries, we need a
15004          mask.  */
15005       unsigned int addr_size = cu->header.addr_size;
15006       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15007
15008       /* The base address, to which the next pair is relative.  Note
15009          that this 'base' is a DWARF concept: most entries in a range
15010          list are relative, to reduce the number of relocs against the
15011          debugging information.  This is separate from this function's
15012          'baseaddr' argument, which GDB uses to relocate debugging
15013          information from a shared library based on the address at
15014          which the library was loaded.  */
15015       CORE_ADDR base = cu->base_address;
15016       int base_known = cu->base_known;
15017
15018       dwarf2_ranges_process (offset, cu,
15019         [&] (CORE_ADDR start, CORE_ADDR end)
15020         {
15021           start += baseaddr;
15022           end += baseaddr;
15023           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15024           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15025           record_block_range (block, start, end - 1);
15026         });
15027     }
15028 }
15029
15030 /* Check whether the producer field indicates either of GCC < 4.6, or the
15031    Intel C/C++ compiler, and cache the result in CU.  */
15032
15033 static void
15034 check_producer (struct dwarf2_cu *cu)
15035 {
15036   int major, minor;
15037
15038   if (cu->producer == NULL)
15039     {
15040       /* For unknown compilers expect their behavior is DWARF version
15041          compliant.
15042
15043          GCC started to support .debug_types sections by -gdwarf-4 since
15044          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15045          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15046          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15047          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15048     }
15049   else if (producer_is_gcc (cu->producer, &major, &minor))
15050     {
15051       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15052       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15053     }
15054   else if (producer_is_icc (cu->producer, &major, &minor))
15055     cu->producer_is_icc_lt_14 = major < 14;
15056   else
15057     {
15058       /* For other non-GCC compilers, expect their behavior is DWARF version
15059          compliant.  */
15060     }
15061
15062   cu->checked_producer = 1;
15063 }
15064
15065 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15066    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15067    during 4.6.0 experimental.  */
15068
15069 static int
15070 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15071 {
15072   if (!cu->checked_producer)
15073     check_producer (cu);
15074
15075   return cu->producer_is_gxx_lt_4_6;
15076 }
15077
15078 /* Return the default accessibility type if it is not overriden by
15079    DW_AT_accessibility.  */
15080
15081 static enum dwarf_access_attribute
15082 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15083 {
15084   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15085     {
15086       /* The default DWARF 2 accessibility for members is public, the default
15087          accessibility for inheritance is private.  */
15088
15089       if (die->tag != DW_TAG_inheritance)
15090         return DW_ACCESS_public;
15091       else
15092         return DW_ACCESS_private;
15093     }
15094   else
15095     {
15096       /* DWARF 3+ defines the default accessibility a different way.  The same
15097          rules apply now for DW_TAG_inheritance as for the members and it only
15098          depends on the container kind.  */
15099
15100       if (die->parent->tag == DW_TAG_class_type)
15101         return DW_ACCESS_private;
15102       else
15103         return DW_ACCESS_public;
15104     }
15105 }
15106
15107 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15108    offset.  If the attribute was not found return 0, otherwise return
15109    1.  If it was found but could not properly be handled, set *OFFSET
15110    to 0.  */
15111
15112 static int
15113 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15114                              LONGEST *offset)
15115 {
15116   struct attribute *attr;
15117
15118   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15119   if (attr != NULL)
15120     {
15121       *offset = 0;
15122
15123       /* Note that we do not check for a section offset first here.
15124          This is because DW_AT_data_member_location is new in DWARF 4,
15125          so if we see it, we can assume that a constant form is really
15126          a constant and not a section offset.  */
15127       if (attr_form_is_constant (attr))
15128         *offset = dwarf2_get_attr_constant_value (attr, 0);
15129       else if (attr_form_is_section_offset (attr))
15130         dwarf2_complex_location_expr_complaint ();
15131       else if (attr_form_is_block (attr))
15132         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15133       else
15134         dwarf2_complex_location_expr_complaint ();
15135
15136       return 1;
15137     }
15138
15139   return 0;
15140 }
15141
15142 /* Add an aggregate field to the field list.  */
15143
15144 static void
15145 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15146                   struct dwarf2_cu *cu)
15147 {
15148   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15149   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15150   struct nextfield *new_field;
15151   struct attribute *attr;
15152   struct field *fp;
15153   const char *fieldname = "";
15154
15155   /* Allocate a new field list entry and link it in.  */
15156   new_field = XNEW (struct nextfield);
15157   make_cleanup (xfree, new_field);
15158   memset (new_field, 0, sizeof (struct nextfield));
15159
15160   if (die->tag == DW_TAG_inheritance)
15161     {
15162       new_field->next = fip->baseclasses;
15163       fip->baseclasses = new_field;
15164     }
15165   else
15166     {
15167       new_field->next = fip->fields;
15168       fip->fields = new_field;
15169     }
15170   fip->nfields++;
15171
15172   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15173   if (attr)
15174     new_field->accessibility = DW_UNSND (attr);
15175   else
15176     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15177   if (new_field->accessibility != DW_ACCESS_public)
15178     fip->non_public_fields = 1;
15179
15180   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15181   if (attr)
15182     new_field->virtuality = DW_UNSND (attr);
15183   else
15184     new_field->virtuality = DW_VIRTUALITY_none;
15185
15186   fp = &new_field->field;
15187
15188   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15189     {
15190       LONGEST offset;
15191
15192       /* Data member other than a C++ static data member.  */
15193
15194       /* Get type of field.  */
15195       fp->type = die_type (die, cu);
15196
15197       SET_FIELD_BITPOS (*fp, 0);
15198
15199       /* Get bit size of field (zero if none).  */
15200       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15201       if (attr)
15202         {
15203           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15204         }
15205       else
15206         {
15207           FIELD_BITSIZE (*fp) = 0;
15208         }
15209
15210       /* Get bit offset of field.  */
15211       if (handle_data_member_location (die, cu, &offset))
15212         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15213       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15214       if (attr)
15215         {
15216           if (gdbarch_bits_big_endian (gdbarch))
15217             {
15218               /* For big endian bits, the DW_AT_bit_offset gives the
15219                  additional bit offset from the MSB of the containing
15220                  anonymous object to the MSB of the field.  We don't
15221                  have to do anything special since we don't need to
15222                  know the size of the anonymous object.  */
15223               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15224             }
15225           else
15226             {
15227               /* For little endian bits, compute the bit offset to the
15228                  MSB of the anonymous object, subtract off the number of
15229                  bits from the MSB of the field to the MSB of the
15230                  object, and then subtract off the number of bits of
15231                  the field itself.  The result is the bit offset of
15232                  the LSB of the field.  */
15233               int anonymous_size;
15234               int bit_offset = DW_UNSND (attr);
15235
15236               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15237               if (attr)
15238                 {
15239                   /* The size of the anonymous object containing
15240                      the bit field is explicit, so use the
15241                      indicated size (in bytes).  */
15242                   anonymous_size = DW_UNSND (attr);
15243                 }
15244               else
15245                 {
15246                   /* The size of the anonymous object containing
15247                      the bit field must be inferred from the type
15248                      attribute of the data member containing the
15249                      bit field.  */
15250                   anonymous_size = TYPE_LENGTH (fp->type);
15251                 }
15252               SET_FIELD_BITPOS (*fp,
15253                                 (FIELD_BITPOS (*fp)
15254                                  + anonymous_size * bits_per_byte
15255                                  - bit_offset - FIELD_BITSIZE (*fp)));
15256             }
15257         }
15258       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15259       if (attr != NULL)
15260         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15261                                 + dwarf2_get_attr_constant_value (attr, 0)));
15262
15263       /* Get name of field.  */
15264       fieldname = dwarf2_name (die, cu);
15265       if (fieldname == NULL)
15266         fieldname = "";
15267
15268       /* The name is already allocated along with this objfile, so we don't
15269          need to duplicate it for the type.  */
15270       fp->name = fieldname;
15271
15272       /* Change accessibility for artificial fields (e.g. virtual table
15273          pointer or virtual base class pointer) to private.  */
15274       if (dwarf2_attr (die, DW_AT_artificial, cu))
15275         {
15276           FIELD_ARTIFICIAL (*fp) = 1;
15277           new_field->accessibility = DW_ACCESS_private;
15278           fip->non_public_fields = 1;
15279         }
15280     }
15281   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15282     {
15283       /* C++ static member.  */
15284
15285       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15286          is a declaration, but all versions of G++ as of this writing
15287          (so through at least 3.2.1) incorrectly generate
15288          DW_TAG_variable tags.  */
15289
15290       const char *physname;
15291
15292       /* Get name of field.  */
15293       fieldname = dwarf2_name (die, cu);
15294       if (fieldname == NULL)
15295         return;
15296
15297       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15298       if (attr
15299           /* Only create a symbol if this is an external value.
15300              new_symbol checks this and puts the value in the global symbol
15301              table, which we want.  If it is not external, new_symbol
15302              will try to put the value in cu->list_in_scope which is wrong.  */
15303           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15304         {
15305           /* A static const member, not much different than an enum as far as
15306              we're concerned, except that we can support more types.  */
15307           new_symbol (die, NULL, cu);
15308         }
15309
15310       /* Get physical name.  */
15311       physname = dwarf2_physname (fieldname, die, cu);
15312
15313       /* The name is already allocated along with this objfile, so we don't
15314          need to duplicate it for the type.  */
15315       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15316       FIELD_TYPE (*fp) = die_type (die, cu);
15317       FIELD_NAME (*fp) = fieldname;
15318     }
15319   else if (die->tag == DW_TAG_inheritance)
15320     {
15321       LONGEST offset;
15322
15323       /* C++ base class field.  */
15324       if (handle_data_member_location (die, cu, &offset))
15325         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15326       FIELD_BITSIZE (*fp) = 0;
15327       FIELD_TYPE (*fp) = die_type (die, cu);
15328       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15329       fip->nbaseclasses++;
15330     }
15331 }
15332
15333 /* Can the type given by DIE define another type?  */
15334
15335 static bool
15336 type_can_define_types (const struct die_info *die)
15337 {
15338   switch (die->tag)
15339     {
15340     case DW_TAG_typedef:
15341     case DW_TAG_class_type:
15342     case DW_TAG_structure_type:
15343     case DW_TAG_union_type:
15344     case DW_TAG_enumeration_type:
15345       return true;
15346
15347     default:
15348       return false;
15349     }
15350 }
15351
15352 /* Add a type definition defined in the scope of the FIP's class.  */
15353
15354 static void
15355 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15356                       struct dwarf2_cu *cu)
15357 {
15358   struct decl_field_list *new_field;
15359   struct decl_field *fp;
15360
15361   /* Allocate a new field list entry and link it in.  */
15362   new_field = XCNEW (struct decl_field_list);
15363   make_cleanup (xfree, new_field);
15364
15365   gdb_assert (type_can_define_types (die));
15366
15367   fp = &new_field->field;
15368
15369   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15370   fp->name = dwarf2_name (die, cu);
15371   fp->type = read_type_die (die, cu);
15372
15373   /* Save accessibility.  */
15374   enum dwarf_access_attribute accessibility;
15375   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15376   if (attr != NULL)
15377     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15378   else
15379     accessibility = dwarf2_default_access_attribute (die, cu);
15380   switch (accessibility)
15381     {
15382     case DW_ACCESS_public:
15383       /* The assumed value if neither private nor protected.  */
15384       break;
15385     case DW_ACCESS_private:
15386       fp->is_private = 1;
15387       break;
15388     case DW_ACCESS_protected:
15389       fp->is_protected = 1;
15390       break;
15391     default:
15392       complaint (&symfile_complaints,
15393                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15394     }
15395
15396   if (die->tag == DW_TAG_typedef)
15397     {
15398       new_field->next = fip->typedef_field_list;
15399       fip->typedef_field_list = new_field;
15400       fip->typedef_field_list_count++;
15401     }
15402   else
15403     {
15404       new_field->next = fip->nested_types_list;
15405       fip->nested_types_list = new_field;
15406       fip->nested_types_list_count++;
15407     }
15408 }
15409
15410 /* Create the vector of fields, and attach it to the type.  */
15411
15412 static void
15413 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15414                               struct dwarf2_cu *cu)
15415 {
15416   int nfields = fip->nfields;
15417
15418   /* Record the field count, allocate space for the array of fields,
15419      and create blank accessibility bitfields if necessary.  */
15420   TYPE_NFIELDS (type) = nfields;
15421   TYPE_FIELDS (type) = (struct field *)
15422     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15423   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15424
15425   if (fip->non_public_fields && cu->language != language_ada)
15426     {
15427       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15428
15429       TYPE_FIELD_PRIVATE_BITS (type) =
15430         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15431       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15432
15433       TYPE_FIELD_PROTECTED_BITS (type) =
15434         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15435       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15436
15437       TYPE_FIELD_IGNORE_BITS (type) =
15438         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15439       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15440     }
15441
15442   /* If the type has baseclasses, allocate and clear a bit vector for
15443      TYPE_FIELD_VIRTUAL_BITS.  */
15444   if (fip->nbaseclasses && cu->language != language_ada)
15445     {
15446       int num_bytes = B_BYTES (fip->nbaseclasses);
15447       unsigned char *pointer;
15448
15449       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15450       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15451       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15452       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15453       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15454     }
15455
15456   /* Copy the saved-up fields into the field vector.  Start from the head of
15457      the list, adding to the tail of the field array, so that they end up in
15458      the same order in the array in which they were added to the list.  */
15459   while (nfields-- > 0)
15460     {
15461       struct nextfield *fieldp;
15462
15463       if (fip->fields)
15464         {
15465           fieldp = fip->fields;
15466           fip->fields = fieldp->next;
15467         }
15468       else
15469         {
15470           fieldp = fip->baseclasses;
15471           fip->baseclasses = fieldp->next;
15472         }
15473
15474       TYPE_FIELD (type, nfields) = fieldp->field;
15475       switch (fieldp->accessibility)
15476         {
15477         case DW_ACCESS_private:
15478           if (cu->language != language_ada)
15479             SET_TYPE_FIELD_PRIVATE (type, nfields);
15480           break;
15481
15482         case DW_ACCESS_protected:
15483           if (cu->language != language_ada)
15484             SET_TYPE_FIELD_PROTECTED (type, nfields);
15485           break;
15486
15487         case DW_ACCESS_public:
15488           break;
15489
15490         default:
15491           /* Unknown accessibility.  Complain and treat it as public.  */
15492           {
15493             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15494                        fieldp->accessibility);
15495           }
15496           break;
15497         }
15498       if (nfields < fip->nbaseclasses)
15499         {
15500           switch (fieldp->virtuality)
15501             {
15502             case DW_VIRTUALITY_virtual:
15503             case DW_VIRTUALITY_pure_virtual:
15504               if (cu->language == language_ada)
15505                 error (_("unexpected virtuality in component of Ada type"));
15506               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15507               break;
15508             }
15509         }
15510     }
15511 }
15512
15513 /* Return true if this member function is a constructor, false
15514    otherwise.  */
15515
15516 static int
15517 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15518 {
15519   const char *fieldname;
15520   const char *type_name;
15521   int len;
15522
15523   if (die->parent == NULL)
15524     return 0;
15525
15526   if (die->parent->tag != DW_TAG_structure_type
15527       && die->parent->tag != DW_TAG_union_type
15528       && die->parent->tag != DW_TAG_class_type)
15529     return 0;
15530
15531   fieldname = dwarf2_name (die, cu);
15532   type_name = dwarf2_name (die->parent, cu);
15533   if (fieldname == NULL || type_name == NULL)
15534     return 0;
15535
15536   len = strlen (fieldname);
15537   return (strncmp (fieldname, type_name, len) == 0
15538           && (type_name[len] == '\0' || type_name[len] == '<'));
15539 }
15540
15541 /* Add a member function to the proper fieldlist.  */
15542
15543 static void
15544 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15545                       struct type *type, struct dwarf2_cu *cu)
15546 {
15547   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15548   struct attribute *attr;
15549   struct fnfieldlist *flp;
15550   int i;
15551   struct fn_field *fnp;
15552   const char *fieldname;
15553   struct nextfnfield *new_fnfield;
15554   struct type *this_type;
15555   enum dwarf_access_attribute accessibility;
15556
15557   if (cu->language == language_ada)
15558     error (_("unexpected member function in Ada type"));
15559
15560   /* Get name of member function.  */
15561   fieldname = dwarf2_name (die, cu);
15562   if (fieldname == NULL)
15563     return;
15564
15565   /* Look up member function name in fieldlist.  */
15566   for (i = 0; i < fip->nfnfields; i++)
15567     {
15568       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15569         break;
15570     }
15571
15572   /* Create new list element if necessary.  */
15573   if (i < fip->nfnfields)
15574     flp = &fip->fnfieldlists[i];
15575   else
15576     {
15577       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15578         {
15579           fip->fnfieldlists = (struct fnfieldlist *)
15580             xrealloc (fip->fnfieldlists,
15581                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15582                       * sizeof (struct fnfieldlist));
15583           if (fip->nfnfields == 0)
15584             make_cleanup (free_current_contents, &fip->fnfieldlists);
15585         }
15586       flp = &fip->fnfieldlists[fip->nfnfields];
15587       flp->name = fieldname;
15588       flp->length = 0;
15589       flp->head = NULL;
15590       i = fip->nfnfields++;
15591     }
15592
15593   /* Create a new member function field and chain it to the field list
15594      entry.  */
15595   new_fnfield = XNEW (struct nextfnfield);
15596   make_cleanup (xfree, new_fnfield);
15597   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15598   new_fnfield->next = flp->head;
15599   flp->head = new_fnfield;
15600   flp->length++;
15601
15602   /* Fill in the member function field info.  */
15603   fnp = &new_fnfield->fnfield;
15604
15605   /* Delay processing of the physname until later.  */
15606   if (cu->language == language_cplus)
15607     {
15608       add_to_method_list (type, i, flp->length - 1, fieldname,
15609                           die, cu);
15610     }
15611   else
15612     {
15613       const char *physname = dwarf2_physname (fieldname, die, cu);
15614       fnp->physname = physname ? physname : "";
15615     }
15616
15617   fnp->type = alloc_type (objfile);
15618   this_type = read_type_die (die, cu);
15619   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15620     {
15621       int nparams = TYPE_NFIELDS (this_type);
15622
15623       /* TYPE is the domain of this method, and THIS_TYPE is the type
15624            of the method itself (TYPE_CODE_METHOD).  */
15625       smash_to_method_type (fnp->type, type,
15626                             TYPE_TARGET_TYPE (this_type),
15627                             TYPE_FIELDS (this_type),
15628                             TYPE_NFIELDS (this_type),
15629                             TYPE_VARARGS (this_type));
15630
15631       /* Handle static member functions.
15632          Dwarf2 has no clean way to discern C++ static and non-static
15633          member functions.  G++ helps GDB by marking the first
15634          parameter for non-static member functions (which is the this
15635          pointer) as artificial.  We obtain this information from
15636          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15637       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15638         fnp->voffset = VOFFSET_STATIC;
15639     }
15640   else
15641     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15642                dwarf2_full_name (fieldname, die, cu));
15643
15644   /* Get fcontext from DW_AT_containing_type if present.  */
15645   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15646     fnp->fcontext = die_containing_type (die, cu);
15647
15648   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15649      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15650
15651   /* Get accessibility.  */
15652   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15653   if (attr)
15654     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15655   else
15656     accessibility = dwarf2_default_access_attribute (die, cu);
15657   switch (accessibility)
15658     {
15659     case DW_ACCESS_private:
15660       fnp->is_private = 1;
15661       break;
15662     case DW_ACCESS_protected:
15663       fnp->is_protected = 1;
15664       break;
15665     }
15666
15667   /* Check for artificial methods.  */
15668   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15669   if (attr && DW_UNSND (attr) != 0)
15670     fnp->is_artificial = 1;
15671
15672   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15673
15674   /* Get index in virtual function table if it is a virtual member
15675      function.  For older versions of GCC, this is an offset in the
15676      appropriate virtual table, as specified by DW_AT_containing_type.
15677      For everyone else, it is an expression to be evaluated relative
15678      to the object address.  */
15679
15680   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15681   if (attr)
15682     {
15683       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15684         {
15685           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15686             {
15687               /* Old-style GCC.  */
15688               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15689             }
15690           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15691                    || (DW_BLOCK (attr)->size > 1
15692                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15693                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15694             {
15695               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15696               if ((fnp->voffset % cu->header.addr_size) != 0)
15697                 dwarf2_complex_location_expr_complaint ();
15698               else
15699                 fnp->voffset /= cu->header.addr_size;
15700               fnp->voffset += 2;
15701             }
15702           else
15703             dwarf2_complex_location_expr_complaint ();
15704
15705           if (!fnp->fcontext)
15706             {
15707               /* If there is no `this' field and no DW_AT_containing_type,
15708                  we cannot actually find a base class context for the
15709                  vtable!  */
15710               if (TYPE_NFIELDS (this_type) == 0
15711                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15712                 {
15713                   complaint (&symfile_complaints,
15714                              _("cannot determine context for virtual member "
15715                                "function \"%s\" (offset %d)"),
15716                              fieldname, to_underlying (die->sect_off));
15717                 }
15718               else
15719                 {
15720                   fnp->fcontext
15721                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15722                 }
15723             }
15724         }
15725       else if (attr_form_is_section_offset (attr))
15726         {
15727           dwarf2_complex_location_expr_complaint ();
15728         }
15729       else
15730         {
15731           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15732                                                  fieldname);
15733         }
15734     }
15735   else
15736     {
15737       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15738       if (attr && DW_UNSND (attr))
15739         {
15740           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15741           complaint (&symfile_complaints,
15742                      _("Member function \"%s\" (offset %d) is virtual "
15743                        "but the vtable offset is not specified"),
15744                      fieldname, to_underlying (die->sect_off));
15745           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15746           TYPE_CPLUS_DYNAMIC (type) = 1;
15747         }
15748     }
15749 }
15750
15751 /* Create the vector of member function fields, and attach it to the type.  */
15752
15753 static void
15754 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15755                                  struct dwarf2_cu *cu)
15756 {
15757   struct fnfieldlist *flp;
15758   int i;
15759
15760   if (cu->language == language_ada)
15761     error (_("unexpected member functions in Ada type"));
15762
15763   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15764   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15765     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15766
15767   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15768     {
15769       struct nextfnfield *nfp = flp->head;
15770       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15771       int k;
15772
15773       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15774       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15775       fn_flp->fn_fields = (struct fn_field *)
15776         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15777       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15778         fn_flp->fn_fields[k] = nfp->fnfield;
15779     }
15780
15781   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15782 }
15783
15784 /* Returns non-zero if NAME is the name of a vtable member in CU's
15785    language, zero otherwise.  */
15786 static int
15787 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15788 {
15789   static const char vptr[] = "_vptr";
15790
15791   /* Look for the C++ form of the vtable.  */
15792   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15793     return 1;
15794
15795   return 0;
15796 }
15797
15798 /* GCC outputs unnamed structures that are really pointers to member
15799    functions, with the ABI-specified layout.  If TYPE describes
15800    such a structure, smash it into a member function type.
15801
15802    GCC shouldn't do this; it should just output pointer to member DIEs.
15803    This is GCC PR debug/28767.  */
15804
15805 static void
15806 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15807 {
15808   struct type *pfn_type, *self_type, *new_type;
15809
15810   /* Check for a structure with no name and two children.  */
15811   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15812     return;
15813
15814   /* Check for __pfn and __delta members.  */
15815   if (TYPE_FIELD_NAME (type, 0) == NULL
15816       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15817       || TYPE_FIELD_NAME (type, 1) == NULL
15818       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15819     return;
15820
15821   /* Find the type of the method.  */
15822   pfn_type = TYPE_FIELD_TYPE (type, 0);
15823   if (pfn_type == NULL
15824       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15825       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15826     return;
15827
15828   /* Look for the "this" argument.  */
15829   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15830   if (TYPE_NFIELDS (pfn_type) == 0
15831       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15832       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15833     return;
15834
15835   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15836   new_type = alloc_type (objfile);
15837   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15838                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15839                         TYPE_VARARGS (pfn_type));
15840   smash_to_methodptr_type (type, new_type);
15841 }
15842
15843
15844 /* Called when we find the DIE that starts a structure or union scope
15845    (definition) to create a type for the structure or union.  Fill in
15846    the type's name and general properties; the members will not be
15847    processed until process_structure_scope.  A symbol table entry for
15848    the type will also not be done until process_structure_scope (assuming
15849    the type has a name).
15850
15851    NOTE: we need to call these functions regardless of whether or not the
15852    DIE has a DW_AT_name attribute, since it might be an anonymous
15853    structure or union.  This gets the type entered into our set of
15854    user defined types.  */
15855
15856 static struct type *
15857 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15858 {
15859   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15860   struct type *type;
15861   struct attribute *attr;
15862   const char *name;
15863
15864   /* If the definition of this type lives in .debug_types, read that type.
15865      Don't follow DW_AT_specification though, that will take us back up
15866      the chain and we want to go down.  */
15867   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15868   if (attr)
15869     {
15870       type = get_DW_AT_signature_type (die, attr, cu);
15871
15872       /* The type's CU may not be the same as CU.
15873          Ensure TYPE is recorded with CU in die_type_hash.  */
15874       return set_die_type (die, type, cu);
15875     }
15876
15877   type = alloc_type (objfile);
15878   INIT_CPLUS_SPECIFIC (type);
15879
15880   name = dwarf2_name (die, cu);
15881   if (name != NULL)
15882     {
15883       if (cu->language == language_cplus
15884           || cu->language == language_d
15885           || cu->language == language_rust)
15886         {
15887           const char *full_name = dwarf2_full_name (name, die, cu);
15888
15889           /* dwarf2_full_name might have already finished building the DIE's
15890              type.  If so, there is no need to continue.  */
15891           if (get_die_type (die, cu) != NULL)
15892             return get_die_type (die, cu);
15893
15894           TYPE_TAG_NAME (type) = full_name;
15895           if (die->tag == DW_TAG_structure_type
15896               || die->tag == DW_TAG_class_type)
15897             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15898         }
15899       else
15900         {
15901           /* The name is already allocated along with this objfile, so
15902              we don't need to duplicate it for the type.  */
15903           TYPE_TAG_NAME (type) = name;
15904           if (die->tag == DW_TAG_class_type)
15905             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15906         }
15907     }
15908
15909   if (die->tag == DW_TAG_structure_type)
15910     {
15911       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15912     }
15913   else if (die->tag == DW_TAG_union_type)
15914     {
15915       TYPE_CODE (type) = TYPE_CODE_UNION;
15916     }
15917   else
15918     {
15919       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15920     }
15921
15922   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15923     TYPE_DECLARED_CLASS (type) = 1;
15924
15925   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15926   if (attr)
15927     {
15928       if (attr_form_is_constant (attr))
15929         TYPE_LENGTH (type) = DW_UNSND (attr);
15930       else
15931         {
15932           /* For the moment, dynamic type sizes are not supported
15933              by GDB's struct type.  The actual size is determined
15934              on-demand when resolving the type of a given object,
15935              so set the type's length to zero for now.  Otherwise,
15936              we record an expression as the length, and that expression
15937              could lead to a very large value, which could eventually
15938              lead to us trying to allocate that much memory when creating
15939              a value of that type.  */
15940           TYPE_LENGTH (type) = 0;
15941         }
15942     }
15943   else
15944     {
15945       TYPE_LENGTH (type) = 0;
15946     }
15947
15948   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15949     {
15950       /* ICC<14 does not output the required DW_AT_declaration on
15951          incomplete types, but gives them a size of zero.  */
15952       TYPE_STUB (type) = 1;
15953     }
15954   else
15955     TYPE_STUB_SUPPORTED (type) = 1;
15956
15957   if (die_is_declaration (die, cu))
15958     TYPE_STUB (type) = 1;
15959   else if (attr == NULL && die->child == NULL
15960            && producer_is_realview (cu->producer))
15961     /* RealView does not output the required DW_AT_declaration
15962        on incomplete types.  */
15963     TYPE_STUB (type) = 1;
15964
15965   /* We need to add the type field to the die immediately so we don't
15966      infinitely recurse when dealing with pointers to the structure
15967      type within the structure itself.  */
15968   set_die_type (die, type, cu);
15969
15970   /* set_die_type should be already done.  */
15971   set_descriptive_type (type, die, cu);
15972
15973   return type;
15974 }
15975
15976 /* Finish creating a structure or union type, including filling in
15977    its members and creating a symbol for it.  */
15978
15979 static void
15980 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15981 {
15982   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
15983   struct die_info *child_die;
15984   struct type *type;
15985
15986   type = get_die_type (die, cu);
15987   if (type == NULL)
15988     type = read_structure_type (die, cu);
15989
15990   if (die->child != NULL && ! die_is_declaration (die, cu))
15991     {
15992       struct field_info fi;
15993       std::vector<struct symbol *> template_args;
15994       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15995
15996       memset (&fi, 0, sizeof (struct field_info));
15997
15998       child_die = die->child;
15999
16000       while (child_die && child_die->tag)
16001         {
16002           if (child_die->tag == DW_TAG_member
16003               || child_die->tag == DW_TAG_variable)
16004             {
16005               /* NOTE: carlton/2002-11-05: A C++ static data member
16006                  should be a DW_TAG_member that is a declaration, but
16007                  all versions of G++ as of this writing (so through at
16008                  least 3.2.1) incorrectly generate DW_TAG_variable
16009                  tags for them instead.  */
16010               dwarf2_add_field (&fi, child_die, cu);
16011             }
16012           else if (child_die->tag == DW_TAG_subprogram)
16013             {
16014               /* Rust doesn't have member functions in the C++ sense.
16015                  However, it does emit ordinary functions as children
16016                  of a struct DIE.  */
16017               if (cu->language == language_rust)
16018                 read_func_scope (child_die, cu);
16019               else
16020                 {
16021                   /* C++ member function.  */
16022                   dwarf2_add_member_fn (&fi, child_die, type, cu);
16023                 }
16024             }
16025           else if (child_die->tag == DW_TAG_inheritance)
16026             {
16027               /* C++ base class field.  */
16028               dwarf2_add_field (&fi, child_die, cu);
16029             }
16030           else if (type_can_define_types (child_die))
16031             dwarf2_add_type_defn (&fi, child_die, cu);
16032           else if (child_die->tag == DW_TAG_template_type_param
16033                    || child_die->tag == DW_TAG_template_value_param)
16034             {
16035               struct symbol *arg = new_symbol (child_die, NULL, cu);
16036
16037               if (arg != NULL)
16038                 template_args.push_back (arg);
16039             }
16040
16041           child_die = sibling_die (child_die);
16042         }
16043
16044       /* Attach template arguments to type.  */
16045       if (!template_args.empty ())
16046         {
16047           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16048           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16049           TYPE_TEMPLATE_ARGUMENTS (type)
16050             = XOBNEWVEC (&objfile->objfile_obstack,
16051                          struct symbol *,
16052                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16053           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16054                   template_args.data (),
16055                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16056                    * sizeof (struct symbol *)));
16057         }
16058
16059       /* Attach fields and member functions to the type.  */
16060       if (fi.nfields)
16061         dwarf2_attach_fields_to_type (&fi, type, cu);
16062       if (fi.nfnfields)
16063         {
16064           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16065
16066           /* Get the type which refers to the base class (possibly this
16067              class itself) which contains the vtable pointer for the current
16068              class from the DW_AT_containing_type attribute.  This use of
16069              DW_AT_containing_type is a GNU extension.  */
16070
16071           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16072             {
16073               struct type *t = die_containing_type (die, cu);
16074
16075               set_type_vptr_basetype (type, t);
16076               if (type == t)
16077                 {
16078                   int i;
16079
16080                   /* Our own class provides vtbl ptr.  */
16081                   for (i = TYPE_NFIELDS (t) - 1;
16082                        i >= TYPE_N_BASECLASSES (t);
16083                        --i)
16084                     {
16085                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16086
16087                       if (is_vtable_name (fieldname, cu))
16088                         {
16089                           set_type_vptr_fieldno (type, i);
16090                           break;
16091                         }
16092                     }
16093
16094                   /* Complain if virtual function table field not found.  */
16095                   if (i < TYPE_N_BASECLASSES (t))
16096                     complaint (&symfile_complaints,
16097                                _("virtual function table pointer "
16098                                  "not found when defining class '%s'"),
16099                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16100                                "");
16101                 }
16102               else
16103                 {
16104                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16105                 }
16106             }
16107           else if (cu->producer
16108                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16109             {
16110               /* The IBM XLC compiler does not provide direct indication
16111                  of the containing type, but the vtable pointer is
16112                  always named __vfp.  */
16113
16114               int i;
16115
16116               for (i = TYPE_NFIELDS (type) - 1;
16117                    i >= TYPE_N_BASECLASSES (type);
16118                    --i)
16119                 {
16120                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16121                     {
16122                       set_type_vptr_fieldno (type, i);
16123                       set_type_vptr_basetype (type, type);
16124                       break;
16125                     }
16126                 }
16127             }
16128         }
16129
16130       /* Copy fi.typedef_field_list linked list elements content into the
16131          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16132       if (fi.typedef_field_list)
16133         {
16134           int i = fi.typedef_field_list_count;
16135
16136           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16137           TYPE_TYPEDEF_FIELD_ARRAY (type)
16138             = ((struct decl_field *)
16139                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16140           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16141
16142           /* Reverse the list order to keep the debug info elements order.  */
16143           while (--i >= 0)
16144             {
16145               struct decl_field *dest, *src;
16146
16147               dest = &TYPE_TYPEDEF_FIELD (type, i);
16148               src = &fi.typedef_field_list->field;
16149               fi.typedef_field_list = fi.typedef_field_list->next;
16150               *dest = *src;
16151             }
16152         }
16153
16154       /* Copy fi.nested_types_list linked list elements content into the
16155          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16156       if (fi.nested_types_list != NULL && cu->language != language_ada)
16157         {
16158           int i = fi.nested_types_list_count;
16159
16160           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16161           TYPE_NESTED_TYPES_ARRAY (type)
16162             = ((struct decl_field *)
16163                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16164           TYPE_NESTED_TYPES_COUNT (type) = i;
16165
16166           /* Reverse the list order to keep the debug info elements order.  */
16167           while (--i >= 0)
16168             {
16169               struct decl_field *dest, *src;
16170
16171               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16172               src = &fi.nested_types_list->field;
16173               fi.nested_types_list = fi.nested_types_list->next;
16174               *dest = *src;
16175             }
16176         }
16177
16178       do_cleanups (back_to);
16179     }
16180
16181   quirk_gcc_member_function_pointer (type, objfile);
16182
16183   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16184      snapshots) has been known to create a die giving a declaration
16185      for a class that has, as a child, a die giving a definition for a
16186      nested class.  So we have to process our children even if the
16187      current die is a declaration.  Normally, of course, a declaration
16188      won't have any children at all.  */
16189
16190   child_die = die->child;
16191
16192   while (child_die != NULL && child_die->tag)
16193     {
16194       if (child_die->tag == DW_TAG_member
16195           || child_die->tag == DW_TAG_variable
16196           || child_die->tag == DW_TAG_inheritance
16197           || child_die->tag == DW_TAG_template_value_param
16198           || child_die->tag == DW_TAG_template_type_param)
16199         {
16200           /* Do nothing.  */
16201         }
16202       else
16203         process_die (child_die, cu);
16204
16205       child_die = sibling_die (child_die);
16206     }
16207
16208   /* Do not consider external references.  According to the DWARF standard,
16209      these DIEs are identified by the fact that they have no byte_size
16210      attribute, and a declaration attribute.  */
16211   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16212       || !die_is_declaration (die, cu))
16213     new_symbol (die, type, cu);
16214 }
16215
16216 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16217    update TYPE using some information only available in DIE's children.  */
16218
16219 static void
16220 update_enumeration_type_from_children (struct die_info *die,
16221                                        struct type *type,
16222                                        struct dwarf2_cu *cu)
16223 {
16224   struct die_info *child_die;
16225   int unsigned_enum = 1;
16226   int flag_enum = 1;
16227   ULONGEST mask = 0;
16228
16229   auto_obstack obstack;
16230
16231   for (child_die = die->child;
16232        child_die != NULL && child_die->tag;
16233        child_die = sibling_die (child_die))
16234     {
16235       struct attribute *attr;
16236       LONGEST value;
16237       const gdb_byte *bytes;
16238       struct dwarf2_locexpr_baton *baton;
16239       const char *name;
16240
16241       if (child_die->tag != DW_TAG_enumerator)
16242         continue;
16243
16244       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16245       if (attr == NULL)
16246         continue;
16247
16248       name = dwarf2_name (child_die, cu);
16249       if (name == NULL)
16250         name = "<anonymous enumerator>";
16251
16252       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16253                                &value, &bytes, &baton);
16254       if (value < 0)
16255         {
16256           unsigned_enum = 0;
16257           flag_enum = 0;
16258         }
16259       else if ((mask & value) != 0)
16260         flag_enum = 0;
16261       else
16262         mask |= value;
16263
16264       /* If we already know that the enum type is neither unsigned, nor
16265          a flag type, no need to look at the rest of the enumerates.  */
16266       if (!unsigned_enum && !flag_enum)
16267         break;
16268     }
16269
16270   if (unsigned_enum)
16271     TYPE_UNSIGNED (type) = 1;
16272   if (flag_enum)
16273     TYPE_FLAG_ENUM (type) = 1;
16274 }
16275
16276 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16277    complete the type's fields yet, or create any symbols.  */
16278
16279 static struct type *
16280 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16281 {
16282   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16283   struct type *type;
16284   struct attribute *attr;
16285   const char *name;
16286
16287   /* If the definition of this type lives in .debug_types, read that type.
16288      Don't follow DW_AT_specification though, that will take us back up
16289      the chain and we want to go down.  */
16290   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16291   if (attr)
16292     {
16293       type = get_DW_AT_signature_type (die, attr, cu);
16294
16295       /* The type's CU may not be the same as CU.
16296          Ensure TYPE is recorded with CU in die_type_hash.  */
16297       return set_die_type (die, type, cu);
16298     }
16299
16300   type = alloc_type (objfile);
16301
16302   TYPE_CODE (type) = TYPE_CODE_ENUM;
16303   name = dwarf2_full_name (NULL, die, cu);
16304   if (name != NULL)
16305     TYPE_TAG_NAME (type) = name;
16306
16307   attr = dwarf2_attr (die, DW_AT_type, cu);
16308   if (attr != NULL)
16309     {
16310       struct type *underlying_type = die_type (die, cu);
16311
16312       TYPE_TARGET_TYPE (type) = underlying_type;
16313     }
16314
16315   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16316   if (attr)
16317     {
16318       TYPE_LENGTH (type) = DW_UNSND (attr);
16319     }
16320   else
16321     {
16322       TYPE_LENGTH (type) = 0;
16323     }
16324
16325   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16326      declared as private in the package spec, and then defined only
16327      inside the package body.  Such types are known as Taft Amendment
16328      Types.  When another package uses such a type, an incomplete DIE
16329      may be generated by the compiler.  */
16330   if (die_is_declaration (die, cu))
16331     TYPE_STUB (type) = 1;
16332
16333   /* Finish the creation of this type by using the enum's children.
16334      We must call this even when the underlying type has been provided
16335      so that we can determine if we're looking at a "flag" enum.  */
16336   update_enumeration_type_from_children (die, type, cu);
16337
16338   /* If this type has an underlying type that is not a stub, then we
16339      may use its attributes.  We always use the "unsigned" attribute
16340      in this situation, because ordinarily we guess whether the type
16341      is unsigned -- but the guess can be wrong and the underlying type
16342      can tell us the reality.  However, we defer to a local size
16343      attribute if one exists, because this lets the compiler override
16344      the underlying type if needed.  */
16345   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16346     {
16347       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16348       if (TYPE_LENGTH (type) == 0)
16349         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16350     }
16351
16352   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16353
16354   return set_die_type (die, type, cu);
16355 }
16356
16357 /* Given a pointer to a die which begins an enumeration, process all
16358    the dies that define the members of the enumeration, and create the
16359    symbol for the enumeration type.
16360
16361    NOTE: We reverse the order of the element list.  */
16362
16363 static void
16364 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16365 {
16366   struct type *this_type;
16367
16368   this_type = get_die_type (die, cu);
16369   if (this_type == NULL)
16370     this_type = read_enumeration_type (die, cu);
16371
16372   if (die->child != NULL)
16373     {
16374       struct die_info *child_die;
16375       struct symbol *sym;
16376       struct field *fields = NULL;
16377       int num_fields = 0;
16378       const char *name;
16379
16380       child_die = die->child;
16381       while (child_die && child_die->tag)
16382         {
16383           if (child_die->tag != DW_TAG_enumerator)
16384             {
16385               process_die (child_die, cu);
16386             }
16387           else
16388             {
16389               name = dwarf2_name (child_die, cu);
16390               if (name)
16391                 {
16392                   sym = new_symbol (child_die, this_type, cu);
16393
16394                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16395                     {
16396                       fields = (struct field *)
16397                         xrealloc (fields,
16398                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16399                                   * sizeof (struct field));
16400                     }
16401
16402                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16403                   FIELD_TYPE (fields[num_fields]) = NULL;
16404                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16405                   FIELD_BITSIZE (fields[num_fields]) = 0;
16406
16407                   num_fields++;
16408                 }
16409             }
16410
16411           child_die = sibling_die (child_die);
16412         }
16413
16414       if (num_fields)
16415         {
16416           TYPE_NFIELDS (this_type) = num_fields;
16417           TYPE_FIELDS (this_type) = (struct field *)
16418             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16419           memcpy (TYPE_FIELDS (this_type), fields,
16420                   sizeof (struct field) * num_fields);
16421           xfree (fields);
16422         }
16423     }
16424
16425   /* If we are reading an enum from a .debug_types unit, and the enum
16426      is a declaration, and the enum is not the signatured type in the
16427      unit, then we do not want to add a symbol for it.  Adding a
16428      symbol would in some cases obscure the true definition of the
16429      enum, giving users an incomplete type when the definition is
16430      actually available.  Note that we do not want to do this for all
16431      enums which are just declarations, because C++0x allows forward
16432      enum declarations.  */
16433   if (cu->per_cu->is_debug_types
16434       && die_is_declaration (die, cu))
16435     {
16436       struct signatured_type *sig_type;
16437
16438       sig_type = (struct signatured_type *) cu->per_cu;
16439       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16440       if (sig_type->type_offset_in_section != die->sect_off)
16441         return;
16442     }
16443
16444   new_symbol (die, this_type, cu);
16445 }
16446
16447 /* Extract all information from a DW_TAG_array_type DIE and put it in
16448    the DIE's type field.  For now, this only handles one dimensional
16449    arrays.  */
16450
16451 static struct type *
16452 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16453 {
16454   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16455   struct die_info *child_die;
16456   struct type *type;
16457   struct type *element_type, *range_type, *index_type;
16458   struct attribute *attr;
16459   const char *name;
16460   struct dynamic_prop *byte_stride_prop = NULL;
16461   unsigned int bit_stride = 0;
16462
16463   element_type = die_type (die, cu);
16464
16465   /* The die_type call above may have already set the type for this DIE.  */
16466   type = get_die_type (die, cu);
16467   if (type)
16468     return type;
16469
16470   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16471   if (attr != NULL)
16472     {
16473       int stride_ok;
16474
16475       byte_stride_prop
16476         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16477       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16478       if (!stride_ok)
16479         {
16480           complaint (&symfile_complaints,
16481                      _("unable to read array DW_AT_byte_stride "
16482                        " - DIE at 0x%x [in module %s]"),
16483                      to_underlying (die->sect_off),
16484                      objfile_name (cu->dwarf2_per_objfile->objfile));
16485           /* Ignore this attribute.  We will likely not be able to print
16486              arrays of this type correctly, but there is little we can do
16487              to help if we cannot read the attribute's value.  */
16488           byte_stride_prop = NULL;
16489         }
16490     }
16491
16492   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16493   if (attr != NULL)
16494     bit_stride = DW_UNSND (attr);
16495
16496   /* Irix 6.2 native cc creates array types without children for
16497      arrays with unspecified length.  */
16498   if (die->child == NULL)
16499     {
16500       index_type = objfile_type (objfile)->builtin_int;
16501       range_type = create_static_range_type (NULL, index_type, 0, -1);
16502       type = create_array_type_with_stride (NULL, element_type, range_type,
16503                                             byte_stride_prop, bit_stride);
16504       return set_die_type (die, type, cu);
16505     }
16506
16507   std::vector<struct type *> range_types;
16508   child_die = die->child;
16509   while (child_die && child_die->tag)
16510     {
16511       if (child_die->tag == DW_TAG_subrange_type)
16512         {
16513           struct type *child_type = read_type_die (child_die, cu);
16514
16515           if (child_type != NULL)
16516             {
16517               /* The range type was succesfully read.  Save it for the
16518                  array type creation.  */
16519               range_types.push_back (child_type);
16520             }
16521         }
16522       child_die = sibling_die (child_die);
16523     }
16524
16525   /* Dwarf2 dimensions are output from left to right, create the
16526      necessary array types in backwards order.  */
16527
16528   type = element_type;
16529
16530   if (read_array_order (die, cu) == DW_ORD_col_major)
16531     {
16532       int i = 0;
16533
16534       while (i < range_types.size ())
16535         type = create_array_type_with_stride (NULL, type, range_types[i++],
16536                                               byte_stride_prop, bit_stride);
16537     }
16538   else
16539     {
16540       size_t ndim = range_types.size ();
16541       while (ndim-- > 0)
16542         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16543                                               byte_stride_prop, bit_stride);
16544     }
16545
16546   /* Understand Dwarf2 support for vector types (like they occur on
16547      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16548      array type.  This is not part of the Dwarf2/3 standard yet, but a
16549      custom vendor extension.  The main difference between a regular
16550      array and the vector variant is that vectors are passed by value
16551      to functions.  */
16552   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16553   if (attr)
16554     make_vector_type (type);
16555
16556   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16557      implementation may choose to implement triple vectors using this
16558      attribute.  */
16559   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16560   if (attr)
16561     {
16562       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16563         TYPE_LENGTH (type) = DW_UNSND (attr);
16564       else
16565         complaint (&symfile_complaints,
16566                    _("DW_AT_byte_size for array type smaller "
16567                      "than the total size of elements"));
16568     }
16569
16570   name = dwarf2_name (die, cu);
16571   if (name)
16572     TYPE_NAME (type) = name;
16573
16574   /* Install the type in the die.  */
16575   set_die_type (die, type, cu);
16576
16577   /* set_die_type should be already done.  */
16578   set_descriptive_type (type, die, cu);
16579
16580   return type;
16581 }
16582
16583 static enum dwarf_array_dim_ordering
16584 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16585 {
16586   struct attribute *attr;
16587
16588   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16589
16590   if (attr)
16591     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16592
16593   /* GNU F77 is a special case, as at 08/2004 array type info is the
16594      opposite order to the dwarf2 specification, but data is still
16595      laid out as per normal fortran.
16596
16597      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16598      version checking.  */
16599
16600   if (cu->language == language_fortran
16601       && cu->producer && strstr (cu->producer, "GNU F77"))
16602     {
16603       return DW_ORD_row_major;
16604     }
16605
16606   switch (cu->language_defn->la_array_ordering)
16607     {
16608     case array_column_major:
16609       return DW_ORD_col_major;
16610     case array_row_major:
16611     default:
16612       return DW_ORD_row_major;
16613     };
16614 }
16615
16616 /* Extract all information from a DW_TAG_set_type DIE and put it in
16617    the DIE's type field.  */
16618
16619 static struct type *
16620 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16621 {
16622   struct type *domain_type, *set_type;
16623   struct attribute *attr;
16624
16625   domain_type = die_type (die, cu);
16626
16627   /* The die_type call above may have already set the type for this DIE.  */
16628   set_type = get_die_type (die, cu);
16629   if (set_type)
16630     return set_type;
16631
16632   set_type = create_set_type (NULL, domain_type);
16633
16634   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16635   if (attr)
16636     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16637
16638   return set_die_type (die, set_type, cu);
16639 }
16640
16641 /* A helper for read_common_block that creates a locexpr baton.
16642    SYM is the symbol which we are marking as computed.
16643    COMMON_DIE is the DIE for the common block.
16644    COMMON_LOC is the location expression attribute for the common
16645    block itself.
16646    MEMBER_LOC is the location expression attribute for the particular
16647    member of the common block that we are processing.
16648    CU is the CU from which the above come.  */
16649
16650 static void
16651 mark_common_block_symbol_computed (struct symbol *sym,
16652                                    struct die_info *common_die,
16653                                    struct attribute *common_loc,
16654                                    struct attribute *member_loc,
16655                                    struct dwarf2_cu *cu)
16656 {
16657   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
16658   struct objfile *objfile = dwarf2_per_objfile->objfile;
16659   struct dwarf2_locexpr_baton *baton;
16660   gdb_byte *ptr;
16661   unsigned int cu_off;
16662   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16663   LONGEST offset = 0;
16664
16665   gdb_assert (common_loc && member_loc);
16666   gdb_assert (attr_form_is_block (common_loc));
16667   gdb_assert (attr_form_is_block (member_loc)
16668               || attr_form_is_constant (member_loc));
16669
16670   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16671   baton->per_cu = cu->per_cu;
16672   gdb_assert (baton->per_cu);
16673
16674   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16675
16676   if (attr_form_is_constant (member_loc))
16677     {
16678       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16679       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16680     }
16681   else
16682     baton->size += DW_BLOCK (member_loc)->size;
16683
16684   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16685   baton->data = ptr;
16686
16687   *ptr++ = DW_OP_call4;
16688   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16689   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16690   ptr += 4;
16691
16692   if (attr_form_is_constant (member_loc))
16693     {
16694       *ptr++ = DW_OP_addr;
16695       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16696       ptr += cu->header.addr_size;
16697     }
16698   else
16699     {
16700       /* We have to copy the data here, because DW_OP_call4 will only
16701          use a DW_AT_location attribute.  */
16702       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16703       ptr += DW_BLOCK (member_loc)->size;
16704     }
16705
16706   *ptr++ = DW_OP_plus;
16707   gdb_assert (ptr - baton->data == baton->size);
16708
16709   SYMBOL_LOCATION_BATON (sym) = baton;
16710   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16711 }
16712
16713 /* Create appropriate locally-scoped variables for all the
16714    DW_TAG_common_block entries.  Also create a struct common_block
16715    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16716    is used to sepate the common blocks name namespace from regular
16717    variable names.  */
16718
16719 static void
16720 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16721 {
16722   struct attribute *attr;
16723
16724   attr = dwarf2_attr (die, DW_AT_location, cu);
16725   if (attr)
16726     {
16727       /* Support the .debug_loc offsets.  */
16728       if (attr_form_is_block (attr))
16729         {
16730           /* Ok.  */
16731         }
16732       else if (attr_form_is_section_offset (attr))
16733         {
16734           dwarf2_complex_location_expr_complaint ();
16735           attr = NULL;
16736         }
16737       else
16738         {
16739           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16740                                                  "common block member");
16741           attr = NULL;
16742         }
16743     }
16744
16745   if (die->child != NULL)
16746     {
16747       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16748       struct die_info *child_die;
16749       size_t n_entries = 0, size;
16750       struct common_block *common_block;
16751       struct symbol *sym;
16752
16753       for (child_die = die->child;
16754            child_die && child_die->tag;
16755            child_die = sibling_die (child_die))
16756         ++n_entries;
16757
16758       size = (sizeof (struct common_block)
16759               + (n_entries - 1) * sizeof (struct symbol *));
16760       common_block
16761         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16762                                                  size);
16763       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16764       common_block->n_entries = 0;
16765
16766       for (child_die = die->child;
16767            child_die && child_die->tag;
16768            child_die = sibling_die (child_die))
16769         {
16770           /* Create the symbol in the DW_TAG_common_block block in the current
16771              symbol scope.  */
16772           sym = new_symbol (child_die, NULL, cu);
16773           if (sym != NULL)
16774             {
16775               struct attribute *member_loc;
16776
16777               common_block->contents[common_block->n_entries++] = sym;
16778
16779               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16780                                         cu);
16781               if (member_loc)
16782                 {
16783                   /* GDB has handled this for a long time, but it is
16784                      not specified by DWARF.  It seems to have been
16785                      emitted by gfortran at least as recently as:
16786                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16787                   complaint (&symfile_complaints,
16788                              _("Variable in common block has "
16789                                "DW_AT_data_member_location "
16790                                "- DIE at 0x%x [in module %s]"),
16791                              to_underlying (child_die->sect_off),
16792                              objfile_name (cu->dwarf2_per_objfile->objfile));
16793
16794                   if (attr_form_is_section_offset (member_loc))
16795                     dwarf2_complex_location_expr_complaint ();
16796                   else if (attr_form_is_constant (member_loc)
16797                            || attr_form_is_block (member_loc))
16798                     {
16799                       if (attr)
16800                         mark_common_block_symbol_computed (sym, die, attr,
16801                                                            member_loc, cu);
16802                     }
16803                   else
16804                     dwarf2_complex_location_expr_complaint ();
16805                 }
16806             }
16807         }
16808
16809       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16810       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16811     }
16812 }
16813
16814 /* Create a type for a C++ namespace.  */
16815
16816 static struct type *
16817 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16818 {
16819   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16820   const char *previous_prefix, *name;
16821   int is_anonymous;
16822   struct type *type;
16823
16824   /* For extensions, reuse the type of the original namespace.  */
16825   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16826     {
16827       struct die_info *ext_die;
16828       struct dwarf2_cu *ext_cu = cu;
16829
16830       ext_die = dwarf2_extension (die, &ext_cu);
16831       type = read_type_die (ext_die, ext_cu);
16832
16833       /* EXT_CU may not be the same as CU.
16834          Ensure TYPE is recorded with CU in die_type_hash.  */
16835       return set_die_type (die, type, cu);
16836     }
16837
16838   name = namespace_name (die, &is_anonymous, cu);
16839
16840   /* Now build the name of the current namespace.  */
16841
16842   previous_prefix = determine_prefix (die, cu);
16843   if (previous_prefix[0] != '\0')
16844     name = typename_concat (&objfile->objfile_obstack,
16845                             previous_prefix, name, 0, cu);
16846
16847   /* Create the type.  */
16848   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16849   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16850
16851   return set_die_type (die, type, cu);
16852 }
16853
16854 /* Read a namespace scope.  */
16855
16856 static void
16857 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16858 {
16859   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16860   int is_anonymous;
16861
16862   /* Add a symbol associated to this if we haven't seen the namespace
16863      before.  Also, add a using directive if it's an anonymous
16864      namespace.  */
16865
16866   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16867     {
16868       struct type *type;
16869
16870       type = read_type_die (die, cu);
16871       new_symbol (die, type, cu);
16872
16873       namespace_name (die, &is_anonymous, cu);
16874       if (is_anonymous)
16875         {
16876           const char *previous_prefix = determine_prefix (die, cu);
16877
16878           std::vector<const char *> excludes;
16879           add_using_directive (using_directives (cu->language),
16880                                previous_prefix, TYPE_NAME (type), NULL,
16881                                NULL, excludes, 0, &objfile->objfile_obstack);
16882         }
16883     }
16884
16885   if (die->child != NULL)
16886     {
16887       struct die_info *child_die = die->child;
16888
16889       while (child_die && child_die->tag)
16890         {
16891           process_die (child_die, cu);
16892           child_die = sibling_die (child_die);
16893         }
16894     }
16895 }
16896
16897 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16898    imported module.  Still we need that type as local Fortran "use ... only"
16899    declaration imports depend on the created type in determine_prefix.  */
16900
16901 static struct type *
16902 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16903 {
16904   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
16905   const char *module_name;
16906   struct type *type;
16907
16908   module_name = dwarf2_name (die, cu);
16909   if (!module_name)
16910     complaint (&symfile_complaints,
16911                _("DW_TAG_module has no name, offset 0x%x"),
16912                to_underlying (die->sect_off));
16913   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16914
16915   /* determine_prefix uses TYPE_TAG_NAME.  */
16916   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16917
16918   return set_die_type (die, type, cu);
16919 }
16920
16921 /* Read a Fortran module.  */
16922
16923 static void
16924 read_module (struct die_info *die, struct dwarf2_cu *cu)
16925 {
16926   struct die_info *child_die = die->child;
16927   struct type *type;
16928
16929   type = read_type_die (die, cu);
16930   new_symbol (die, type, cu);
16931
16932   while (child_die && child_die->tag)
16933     {
16934       process_die (child_die, cu);
16935       child_die = sibling_die (child_die);
16936     }
16937 }
16938
16939 /* Return the name of the namespace represented by DIE.  Set
16940    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16941    namespace.  */
16942
16943 static const char *
16944 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16945 {
16946   struct die_info *current_die;
16947   const char *name = NULL;
16948
16949   /* Loop through the extensions until we find a name.  */
16950
16951   for (current_die = die;
16952        current_die != NULL;
16953        current_die = dwarf2_extension (die, &cu))
16954     {
16955       /* We don't use dwarf2_name here so that we can detect the absence
16956          of a name -> anonymous namespace.  */
16957       name = dwarf2_string_attr (die, DW_AT_name, cu);
16958
16959       if (name != NULL)
16960         break;
16961     }
16962
16963   /* Is it an anonymous namespace?  */
16964
16965   *is_anonymous = (name == NULL);
16966   if (*is_anonymous)
16967     name = CP_ANONYMOUS_NAMESPACE_STR;
16968
16969   return name;
16970 }
16971
16972 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16973    the user defined type vector.  */
16974
16975 static struct type *
16976 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16977 {
16978   struct gdbarch *gdbarch = get_objfile_arch (cu->dwarf2_per_objfile->objfile);
16979   struct comp_unit_head *cu_header = &cu->header;
16980   struct type *type;
16981   struct attribute *attr_byte_size;
16982   struct attribute *attr_address_class;
16983   int byte_size, addr_class;
16984   struct type *target_type;
16985
16986   target_type = die_type (die, cu);
16987
16988   /* The die_type call above may have already set the type for this DIE.  */
16989   type = get_die_type (die, cu);
16990   if (type)
16991     return type;
16992
16993   type = lookup_pointer_type (target_type);
16994
16995   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16996   if (attr_byte_size)
16997     byte_size = DW_UNSND (attr_byte_size);
16998   else
16999     byte_size = cu_header->addr_size;
17000
17001   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17002   if (attr_address_class)
17003     addr_class = DW_UNSND (attr_address_class);
17004   else
17005     addr_class = DW_ADDR_none;
17006
17007   /* If the pointer size or address class is different than the
17008      default, create a type variant marked as such and set the
17009      length accordingly.  */
17010   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17011     {
17012       if (gdbarch_address_class_type_flags_p (gdbarch))
17013         {
17014           int type_flags;
17015
17016           type_flags = gdbarch_address_class_type_flags
17017                          (gdbarch, byte_size, addr_class);
17018           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17019                       == 0);
17020           type = make_type_with_address_space (type, type_flags);
17021         }
17022       else if (TYPE_LENGTH (type) != byte_size)
17023         {
17024           complaint (&symfile_complaints,
17025                      _("invalid pointer size %d"), byte_size);
17026         }
17027       else
17028         {
17029           /* Should we also complain about unhandled address classes?  */
17030         }
17031     }
17032
17033   TYPE_LENGTH (type) = byte_size;
17034   return set_die_type (die, type, cu);
17035 }
17036
17037 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17038    the user defined type vector.  */
17039
17040 static struct type *
17041 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17042 {
17043   struct type *type;
17044   struct type *to_type;
17045   struct type *domain;
17046
17047   to_type = die_type (die, cu);
17048   domain = die_containing_type (die, cu);
17049
17050   /* The calls above may have already set the type for this DIE.  */
17051   type = get_die_type (die, cu);
17052   if (type)
17053     return type;
17054
17055   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17056     type = lookup_methodptr_type (to_type);
17057   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17058     {
17059       struct type *new_type = alloc_type (cu->dwarf2_per_objfile->objfile);
17060
17061       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17062                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17063                             TYPE_VARARGS (to_type));
17064       type = lookup_methodptr_type (new_type);
17065     }
17066   else
17067     type = lookup_memberptr_type (to_type, domain);
17068
17069   return set_die_type (die, type, cu);
17070 }
17071
17072 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17073    the user defined type vector.  */
17074
17075 static struct type *
17076 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17077                           enum type_code refcode)
17078 {
17079   struct comp_unit_head *cu_header = &cu->header;
17080   struct type *type, *target_type;
17081   struct attribute *attr;
17082
17083   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17084
17085   target_type = die_type (die, cu);
17086
17087   /* The die_type call above may have already set the type for this DIE.  */
17088   type = get_die_type (die, cu);
17089   if (type)
17090     return type;
17091
17092   type = lookup_reference_type (target_type, refcode);
17093   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17094   if (attr)
17095     {
17096       TYPE_LENGTH (type) = DW_UNSND (attr);
17097     }
17098   else
17099     {
17100       TYPE_LENGTH (type) = cu_header->addr_size;
17101     }
17102   return set_die_type (die, type, cu);
17103 }
17104
17105 /* Add the given cv-qualifiers to the element type of the array.  GCC
17106    outputs DWARF type qualifiers that apply to an array, not the
17107    element type.  But GDB relies on the array element type to carry
17108    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17109    specification.  */
17110
17111 static struct type *
17112 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17113                    struct type *base_type, int cnst, int voltl)
17114 {
17115   struct type *el_type, *inner_array;
17116
17117   base_type = copy_type (base_type);
17118   inner_array = base_type;
17119
17120   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17121     {
17122       TYPE_TARGET_TYPE (inner_array) =
17123         copy_type (TYPE_TARGET_TYPE (inner_array));
17124       inner_array = TYPE_TARGET_TYPE (inner_array);
17125     }
17126
17127   el_type = TYPE_TARGET_TYPE (inner_array);
17128   cnst |= TYPE_CONST (el_type);
17129   voltl |= TYPE_VOLATILE (el_type);
17130   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17131
17132   return set_die_type (die, base_type, cu);
17133 }
17134
17135 static struct type *
17136 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17137 {
17138   struct type *base_type, *cv_type;
17139
17140   base_type = die_type (die, cu);
17141
17142   /* The die_type call above may have already set the type for this DIE.  */
17143   cv_type = get_die_type (die, cu);
17144   if (cv_type)
17145     return cv_type;
17146
17147   /* In case the const qualifier is applied to an array type, the element type
17148      is so qualified, not the array type (section 6.7.3 of C99).  */
17149   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17150     return add_array_cv_type (die, cu, base_type, 1, 0);
17151
17152   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17153   return set_die_type (die, cv_type, cu);
17154 }
17155
17156 static struct type *
17157 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17158 {
17159   struct type *base_type, *cv_type;
17160
17161   base_type = die_type (die, cu);
17162
17163   /* The die_type call above may have already set the type for this DIE.  */
17164   cv_type = get_die_type (die, cu);
17165   if (cv_type)
17166     return cv_type;
17167
17168   /* In case the volatile qualifier is applied to an array type, the
17169      element type is so qualified, not the array type (section 6.7.3
17170      of C99).  */
17171   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17172     return add_array_cv_type (die, cu, base_type, 0, 1);
17173
17174   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17175   return set_die_type (die, cv_type, cu);
17176 }
17177
17178 /* Handle DW_TAG_restrict_type.  */
17179
17180 static struct type *
17181 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17182 {
17183   struct type *base_type, *cv_type;
17184
17185   base_type = die_type (die, cu);
17186
17187   /* The die_type call above may have already set the type for this DIE.  */
17188   cv_type = get_die_type (die, cu);
17189   if (cv_type)
17190     return cv_type;
17191
17192   cv_type = make_restrict_type (base_type);
17193   return set_die_type (die, cv_type, cu);
17194 }
17195
17196 /* Handle DW_TAG_atomic_type.  */
17197
17198 static struct type *
17199 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17200 {
17201   struct type *base_type, *cv_type;
17202
17203   base_type = die_type (die, cu);
17204
17205   /* The die_type call above may have already set the type for this DIE.  */
17206   cv_type = get_die_type (die, cu);
17207   if (cv_type)
17208     return cv_type;
17209
17210   cv_type = make_atomic_type (base_type);
17211   return set_die_type (die, cv_type, cu);
17212 }
17213
17214 /* Extract all information from a DW_TAG_string_type DIE and add to
17215    the user defined type vector.  It isn't really a user defined type,
17216    but it behaves like one, with other DIE's using an AT_user_def_type
17217    attribute to reference it.  */
17218
17219 static struct type *
17220 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17221 {
17222   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17223   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17224   struct type *type, *range_type, *index_type, *char_type;
17225   struct attribute *attr;
17226   unsigned int length;
17227
17228   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17229   if (attr)
17230     {
17231       length = DW_UNSND (attr);
17232     }
17233   else
17234     {
17235       /* Check for the DW_AT_byte_size attribute.  */
17236       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17237       if (attr)
17238         {
17239           length = DW_UNSND (attr);
17240         }
17241       else
17242         {
17243           length = 1;
17244         }
17245     }
17246
17247   index_type = objfile_type (objfile)->builtin_int;
17248   range_type = create_static_range_type (NULL, index_type, 1, length);
17249   char_type = language_string_char_type (cu->language_defn, gdbarch);
17250   type = create_string_type (NULL, char_type, range_type);
17251
17252   return set_die_type (die, type, cu);
17253 }
17254
17255 /* Assuming that DIE corresponds to a function, returns nonzero
17256    if the function is prototyped.  */
17257
17258 static int
17259 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17260 {
17261   struct attribute *attr;
17262
17263   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17264   if (attr && (DW_UNSND (attr) != 0))
17265     return 1;
17266
17267   /* The DWARF standard implies that the DW_AT_prototyped attribute
17268      is only meaninful for C, but the concept also extends to other
17269      languages that allow unprototyped functions (Eg: Objective C).
17270      For all other languages, assume that functions are always
17271      prototyped.  */
17272   if (cu->language != language_c
17273       && cu->language != language_objc
17274       && cu->language != language_opencl)
17275     return 1;
17276
17277   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17278      prototyped and unprototyped functions; default to prototyped,
17279      since that is more common in modern code (and RealView warns
17280      about unprototyped functions).  */
17281   if (producer_is_realview (cu->producer))
17282     return 1;
17283
17284   return 0;
17285 }
17286
17287 /* Handle DIES due to C code like:
17288
17289    struct foo
17290    {
17291    int (*funcp)(int a, long l);
17292    int b;
17293    };
17294
17295    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17296
17297 static struct type *
17298 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17299 {
17300   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17301   struct type *type;            /* Type that this function returns.  */
17302   struct type *ftype;           /* Function that returns above type.  */
17303   struct attribute *attr;
17304
17305   type = die_type (die, cu);
17306
17307   /* The die_type call above may have already set the type for this DIE.  */
17308   ftype = get_die_type (die, cu);
17309   if (ftype)
17310     return ftype;
17311
17312   ftype = lookup_function_type (type);
17313
17314   if (prototyped_function_p (die, cu))
17315     TYPE_PROTOTYPED (ftype) = 1;
17316
17317   /* Store the calling convention in the type if it's available in
17318      the subroutine die.  Otherwise set the calling convention to
17319      the default value DW_CC_normal.  */
17320   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17321   if (attr)
17322     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17323   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17324     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17325   else
17326     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17327
17328   /* Record whether the function returns normally to its caller or not
17329      if the DWARF producer set that information.  */
17330   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17331   if (attr && (DW_UNSND (attr) != 0))
17332     TYPE_NO_RETURN (ftype) = 1;
17333
17334   /* We need to add the subroutine type to the die immediately so
17335      we don't infinitely recurse when dealing with parameters
17336      declared as the same subroutine type.  */
17337   set_die_type (die, ftype, cu);
17338
17339   if (die->child != NULL)
17340     {
17341       struct type *void_type = objfile_type (objfile)->builtin_void;
17342       struct die_info *child_die;
17343       int nparams, iparams;
17344
17345       /* Count the number of parameters.
17346          FIXME: GDB currently ignores vararg functions, but knows about
17347          vararg member functions.  */
17348       nparams = 0;
17349       child_die = die->child;
17350       while (child_die && child_die->tag)
17351         {
17352           if (child_die->tag == DW_TAG_formal_parameter)
17353             nparams++;
17354           else if (child_die->tag == DW_TAG_unspecified_parameters)
17355             TYPE_VARARGS (ftype) = 1;
17356           child_die = sibling_die (child_die);
17357         }
17358
17359       /* Allocate storage for parameters and fill them in.  */
17360       TYPE_NFIELDS (ftype) = nparams;
17361       TYPE_FIELDS (ftype) = (struct field *)
17362         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17363
17364       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17365          even if we error out during the parameters reading below.  */
17366       for (iparams = 0; iparams < nparams; iparams++)
17367         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17368
17369       iparams = 0;
17370       child_die = die->child;
17371       while (child_die && child_die->tag)
17372         {
17373           if (child_die->tag == DW_TAG_formal_parameter)
17374             {
17375               struct type *arg_type;
17376
17377               /* DWARF version 2 has no clean way to discern C++
17378                  static and non-static member functions.  G++ helps
17379                  GDB by marking the first parameter for non-static
17380                  member functions (which is the this pointer) as
17381                  artificial.  We pass this information to
17382                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17383
17384                  DWARF version 3 added DW_AT_object_pointer, which GCC
17385                  4.5 does not yet generate.  */
17386               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17387               if (attr)
17388                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17389               else
17390                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17391               arg_type = die_type (child_die, cu);
17392
17393               /* RealView does not mark THIS as const, which the testsuite
17394                  expects.  GCC marks THIS as const in method definitions,
17395                  but not in the class specifications (GCC PR 43053).  */
17396               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17397                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17398                 {
17399                   int is_this = 0;
17400                   struct dwarf2_cu *arg_cu = cu;
17401                   const char *name = dwarf2_name (child_die, cu);
17402
17403                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17404                   if (attr)
17405                     {
17406                       /* If the compiler emits this, use it.  */
17407                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17408                         is_this = 1;
17409                     }
17410                   else if (name && strcmp (name, "this") == 0)
17411                     /* Function definitions will have the argument names.  */
17412                     is_this = 1;
17413                   else if (name == NULL && iparams == 0)
17414                     /* Declarations may not have the names, so like
17415                        elsewhere in GDB, assume an artificial first
17416                        argument is "this".  */
17417                     is_this = 1;
17418
17419                   if (is_this)
17420                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17421                                              arg_type, 0);
17422                 }
17423
17424               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17425               iparams++;
17426             }
17427           child_die = sibling_die (child_die);
17428         }
17429     }
17430
17431   return ftype;
17432 }
17433
17434 static struct type *
17435 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17436 {
17437   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17438   const char *name = NULL;
17439   struct type *this_type, *target_type;
17440
17441   name = dwarf2_full_name (NULL, die, cu);
17442   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17443   TYPE_TARGET_STUB (this_type) = 1;
17444   set_die_type (die, this_type, cu);
17445   target_type = die_type (die, cu);
17446   if (target_type != this_type)
17447     TYPE_TARGET_TYPE (this_type) = target_type;
17448   else
17449     {
17450       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17451          spec and cause infinite loops in GDB.  */
17452       complaint (&symfile_complaints,
17453                  _("Self-referential DW_TAG_typedef "
17454                    "- DIE at 0x%x [in module %s]"),
17455                  to_underlying (die->sect_off), objfile_name (objfile));
17456       TYPE_TARGET_TYPE (this_type) = NULL;
17457     }
17458   return this_type;
17459 }
17460
17461 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17462    (which may be different from NAME) to the architecture back-end to allow
17463    it to guess the correct format if necessary.  */
17464
17465 static struct type *
17466 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17467                         const char *name_hint)
17468 {
17469   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17470   const struct floatformat **format;
17471   struct type *type;
17472
17473   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17474   if (format)
17475     type = init_float_type (objfile, bits, name, format);
17476   else
17477     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17478
17479   return type;
17480 }
17481
17482 /* Find a representation of a given base type and install
17483    it in the TYPE field of the die.  */
17484
17485 static struct type *
17486 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17487 {
17488   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17489   struct type *type;
17490   struct attribute *attr;
17491   int encoding = 0, bits = 0;
17492   const char *name;
17493
17494   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17495   if (attr)
17496     {
17497       encoding = DW_UNSND (attr);
17498     }
17499   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17500   if (attr)
17501     {
17502       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17503     }
17504   name = dwarf2_name (die, cu);
17505   if (!name)
17506     {
17507       complaint (&symfile_complaints,
17508                  _("DW_AT_name missing from DW_TAG_base_type"));
17509     }
17510
17511   switch (encoding)
17512     {
17513       case DW_ATE_address:
17514         /* Turn DW_ATE_address into a void * pointer.  */
17515         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17516         type = init_pointer_type (objfile, bits, name, type);
17517         break;
17518       case DW_ATE_boolean:
17519         type = init_boolean_type (objfile, bits, 1, name);
17520         break;
17521       case DW_ATE_complex_float:
17522         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17523         type = init_complex_type (objfile, name, type);
17524         break;
17525       case DW_ATE_decimal_float:
17526         type = init_decfloat_type (objfile, bits, name);
17527         break;
17528       case DW_ATE_float:
17529         type = dwarf2_init_float_type (objfile, bits, name, name);
17530         break;
17531       case DW_ATE_signed:
17532         type = init_integer_type (objfile, bits, 0, name);
17533         break;
17534       case DW_ATE_unsigned:
17535         if (cu->language == language_fortran
17536             && name
17537             && startswith (name, "character("))
17538           type = init_character_type (objfile, bits, 1, name);
17539         else
17540           type = init_integer_type (objfile, bits, 1, name);
17541         break;
17542       case DW_ATE_signed_char:
17543         if (cu->language == language_ada || cu->language == language_m2
17544             || cu->language == language_pascal
17545             || cu->language == language_fortran)
17546           type = init_character_type (objfile, bits, 0, name);
17547         else
17548           type = init_integer_type (objfile, bits, 0, name);
17549         break;
17550       case DW_ATE_unsigned_char:
17551         if (cu->language == language_ada || cu->language == language_m2
17552             || cu->language == language_pascal
17553             || cu->language == language_fortran
17554             || cu->language == language_rust)
17555           type = init_character_type (objfile, bits, 1, name);
17556         else
17557           type = init_integer_type (objfile, bits, 1, name);
17558         break;
17559       case DW_ATE_UTF:
17560         {
17561           gdbarch *arch = get_objfile_arch (objfile);
17562
17563           if (bits == 16)
17564             type = builtin_type (arch)->builtin_char16;
17565           else if (bits == 32)
17566             type = builtin_type (arch)->builtin_char32;
17567           else
17568             {
17569               complaint (&symfile_complaints,
17570                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17571                          bits);
17572               type = init_integer_type (objfile, bits, 1, name);
17573             }
17574           return set_die_type (die, type, cu);
17575         }
17576         break;
17577
17578       default:
17579         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17580                    dwarf_type_encoding_name (encoding));
17581         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17582         break;
17583     }
17584
17585   if (name && strcmp (name, "char") == 0)
17586     TYPE_NOSIGN (type) = 1;
17587
17588   return set_die_type (die, type, cu);
17589 }
17590
17591 /* Parse dwarf attribute if it's a block, reference or constant and put the
17592    resulting value of the attribute into struct bound_prop.
17593    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17594
17595 static int
17596 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17597                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17598 {
17599   struct dwarf2_property_baton *baton;
17600   struct obstack *obstack = &cu->dwarf2_per_objfile->objfile->objfile_obstack;
17601
17602   if (attr == NULL || prop == NULL)
17603     return 0;
17604
17605   if (attr_form_is_block (attr))
17606     {
17607       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17608       baton->referenced_type = NULL;
17609       baton->locexpr.per_cu = cu->per_cu;
17610       baton->locexpr.size = DW_BLOCK (attr)->size;
17611       baton->locexpr.data = DW_BLOCK (attr)->data;
17612       prop->data.baton = baton;
17613       prop->kind = PROP_LOCEXPR;
17614       gdb_assert (prop->data.baton != NULL);
17615     }
17616   else if (attr_form_is_ref (attr))
17617     {
17618       struct dwarf2_cu *target_cu = cu;
17619       struct die_info *target_die;
17620       struct attribute *target_attr;
17621
17622       target_die = follow_die_ref (die, attr, &target_cu);
17623       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17624       if (target_attr == NULL)
17625         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17626                                    target_cu);
17627       if (target_attr == NULL)
17628         return 0;
17629
17630       switch (target_attr->name)
17631         {
17632           case DW_AT_location:
17633             if (attr_form_is_section_offset (target_attr))
17634               {
17635                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17636                 baton->referenced_type = die_type (target_die, target_cu);
17637                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17638                 prop->data.baton = baton;
17639                 prop->kind = PROP_LOCLIST;
17640                 gdb_assert (prop->data.baton != NULL);
17641               }
17642             else if (attr_form_is_block (target_attr))
17643               {
17644                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17645                 baton->referenced_type = die_type (target_die, target_cu);
17646                 baton->locexpr.per_cu = cu->per_cu;
17647                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17648                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17649                 prop->data.baton = baton;
17650                 prop->kind = PROP_LOCEXPR;
17651                 gdb_assert (prop->data.baton != NULL);
17652               }
17653             else
17654               {
17655                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17656                                                        "dynamic property");
17657                 return 0;
17658               }
17659             break;
17660           case DW_AT_data_member_location:
17661             {
17662               LONGEST offset;
17663
17664               if (!handle_data_member_location (target_die, target_cu,
17665                                                 &offset))
17666                 return 0;
17667
17668               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17669               baton->referenced_type = read_type_die (target_die->parent,
17670                                                       target_cu);
17671               baton->offset_info.offset = offset;
17672               baton->offset_info.type = die_type (target_die, target_cu);
17673               prop->data.baton = baton;
17674               prop->kind = PROP_ADDR_OFFSET;
17675               break;
17676             }
17677         }
17678     }
17679   else if (attr_form_is_constant (attr))
17680     {
17681       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17682       prop->kind = PROP_CONST;
17683     }
17684   else
17685     {
17686       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17687                                              dwarf2_name (die, cu));
17688       return 0;
17689     }
17690
17691   return 1;
17692 }
17693
17694 /* Read the given DW_AT_subrange DIE.  */
17695
17696 static struct type *
17697 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17698 {
17699   struct type *base_type, *orig_base_type;
17700   struct type *range_type;
17701   struct attribute *attr;
17702   struct dynamic_prop low, high;
17703   int low_default_is_valid;
17704   int high_bound_is_count = 0;
17705   const char *name;
17706   LONGEST negative_mask;
17707
17708   orig_base_type = die_type (die, cu);
17709   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17710      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17711      creating the range type, but we use the result of check_typedef
17712      when examining properties of the type.  */
17713   base_type = check_typedef (orig_base_type);
17714
17715   /* The die_type call above may have already set the type for this DIE.  */
17716   range_type = get_die_type (die, cu);
17717   if (range_type)
17718     return range_type;
17719
17720   low.kind = PROP_CONST;
17721   high.kind = PROP_CONST;
17722   high.data.const_val = 0;
17723
17724   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17725      omitting DW_AT_lower_bound.  */
17726   switch (cu->language)
17727     {
17728     case language_c:
17729     case language_cplus:
17730       low.data.const_val = 0;
17731       low_default_is_valid = 1;
17732       break;
17733     case language_fortran:
17734       low.data.const_val = 1;
17735       low_default_is_valid = 1;
17736       break;
17737     case language_d:
17738     case language_objc:
17739     case language_rust:
17740       low.data.const_val = 0;
17741       low_default_is_valid = (cu->header.version >= 4);
17742       break;
17743     case language_ada:
17744     case language_m2:
17745     case language_pascal:
17746       low.data.const_val = 1;
17747       low_default_is_valid = (cu->header.version >= 4);
17748       break;
17749     default:
17750       low.data.const_val = 0;
17751       low_default_is_valid = 0;
17752       break;
17753     }
17754
17755   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17756   if (attr)
17757     attr_to_dynamic_prop (attr, die, cu, &low);
17758   else if (!low_default_is_valid)
17759     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17760                                       "- DIE at 0x%x [in module %s]"),
17761                to_underlying (die->sect_off),
17762                objfile_name (cu->dwarf2_per_objfile->objfile));
17763
17764   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17765   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17766     {
17767       attr = dwarf2_attr (die, DW_AT_count, cu);
17768       if (attr_to_dynamic_prop (attr, die, cu, &high))
17769         {
17770           /* If bounds are constant do the final calculation here.  */
17771           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17772             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17773           else
17774             high_bound_is_count = 1;
17775         }
17776     }
17777
17778   /* Dwarf-2 specifications explicitly allows to create subrange types
17779      without specifying a base type.
17780      In that case, the base type must be set to the type of
17781      the lower bound, upper bound or count, in that order, if any of these
17782      three attributes references an object that has a type.
17783      If no base type is found, the Dwarf-2 specifications say that
17784      a signed integer type of size equal to the size of an address should
17785      be used.
17786      For the following C code: `extern char gdb_int [];'
17787      GCC produces an empty range DIE.
17788      FIXME: muller/2010-05-28: Possible references to object for low bound,
17789      high bound or count are not yet handled by this code.  */
17790   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17791     {
17792       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
17793       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17794       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17795       struct type *int_type = objfile_type (objfile)->builtin_int;
17796
17797       /* Test "int", "long int", and "long long int" objfile types,
17798          and select the first one having a size above or equal to the
17799          architecture address size.  */
17800       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17801         base_type = int_type;
17802       else
17803         {
17804           int_type = objfile_type (objfile)->builtin_long;
17805           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17806             base_type = int_type;
17807           else
17808             {
17809               int_type = objfile_type (objfile)->builtin_long_long;
17810               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17811                 base_type = int_type;
17812             }
17813         }
17814     }
17815
17816   /* Normally, the DWARF producers are expected to use a signed
17817      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17818      But this is unfortunately not always the case, as witnessed
17819      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17820      is used instead.  To work around that ambiguity, we treat
17821      the bounds as signed, and thus sign-extend their values, when
17822      the base type is signed.  */
17823   negative_mask =
17824     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17825   if (low.kind == PROP_CONST
17826       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17827     low.data.const_val |= negative_mask;
17828   if (high.kind == PROP_CONST
17829       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17830     high.data.const_val |= negative_mask;
17831
17832   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17833
17834   if (high_bound_is_count)
17835     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17836
17837   /* Ada expects an empty array on no boundary attributes.  */
17838   if (attr == NULL && cu->language != language_ada)
17839     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17840
17841   name = dwarf2_name (die, cu);
17842   if (name)
17843     TYPE_NAME (range_type) = name;
17844
17845   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17846   if (attr)
17847     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17848
17849   set_die_type (die, range_type, cu);
17850
17851   /* set_die_type should be already done.  */
17852   set_descriptive_type (range_type, die, cu);
17853
17854   return range_type;
17855 }
17856
17857 static struct type *
17858 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17859 {
17860   struct type *type;
17861
17862   type = init_type (cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID, 0, NULL);
17863   TYPE_NAME (type) = dwarf2_name (die, cu);
17864
17865   /* In Ada, an unspecified type is typically used when the description
17866      of the type is defered to a different unit.  When encountering
17867      such a type, we treat it as a stub, and try to resolve it later on,
17868      when needed.  */
17869   if (cu->language == language_ada)
17870     TYPE_STUB (type) = 1;
17871
17872   return set_die_type (die, type, cu);
17873 }
17874
17875 /* Read a single die and all its descendents.  Set the die's sibling
17876    field to NULL; set other fields in the die correctly, and set all
17877    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17878    location of the info_ptr after reading all of those dies.  PARENT
17879    is the parent of the die in question.  */
17880
17881 static struct die_info *
17882 read_die_and_children (const struct die_reader_specs *reader,
17883                        const gdb_byte *info_ptr,
17884                        const gdb_byte **new_info_ptr,
17885                        struct die_info *parent)
17886 {
17887   struct die_info *die;
17888   const gdb_byte *cur_ptr;
17889   int has_children;
17890
17891   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17892   if (die == NULL)
17893     {
17894       *new_info_ptr = cur_ptr;
17895       return NULL;
17896     }
17897   store_in_ref_table (die, reader->cu);
17898
17899   if (has_children)
17900     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17901   else
17902     {
17903       die->child = NULL;
17904       *new_info_ptr = cur_ptr;
17905     }
17906
17907   die->sibling = NULL;
17908   die->parent = parent;
17909   return die;
17910 }
17911
17912 /* Read a die, all of its descendents, and all of its siblings; set
17913    all of the fields of all of the dies correctly.  Arguments are as
17914    in read_die_and_children.  */
17915
17916 static struct die_info *
17917 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17918                          const gdb_byte *info_ptr,
17919                          const gdb_byte **new_info_ptr,
17920                          struct die_info *parent)
17921 {
17922   struct die_info *first_die, *last_sibling;
17923   const gdb_byte *cur_ptr;
17924
17925   cur_ptr = info_ptr;
17926   first_die = last_sibling = NULL;
17927
17928   while (1)
17929     {
17930       struct die_info *die
17931         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17932
17933       if (die == NULL)
17934         {
17935           *new_info_ptr = cur_ptr;
17936           return first_die;
17937         }
17938
17939       if (!first_die)
17940         first_die = die;
17941       else
17942         last_sibling->sibling = die;
17943
17944       last_sibling = die;
17945     }
17946 }
17947
17948 /* Read a die, all of its descendents, and all of its siblings; set
17949    all of the fields of all of the dies correctly.  Arguments are as
17950    in read_die_and_children.
17951    This the main entry point for reading a DIE and all its children.  */
17952
17953 static struct die_info *
17954 read_die_and_siblings (const struct die_reader_specs *reader,
17955                        const gdb_byte *info_ptr,
17956                        const gdb_byte **new_info_ptr,
17957                        struct die_info *parent)
17958 {
17959   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17960                                                   new_info_ptr, parent);
17961
17962   if (dwarf_die_debug)
17963     {
17964       fprintf_unfiltered (gdb_stdlog,
17965                           "Read die from %s@0x%x of %s:\n",
17966                           get_section_name (reader->die_section),
17967                           (unsigned) (info_ptr - reader->die_section->buffer),
17968                           bfd_get_filename (reader->abfd));
17969       dump_die (die, dwarf_die_debug);
17970     }
17971
17972   return die;
17973 }
17974
17975 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17976    attributes.
17977    The caller is responsible for filling in the extra attributes
17978    and updating (*DIEP)->num_attrs.
17979    Set DIEP to point to a newly allocated die with its information,
17980    except for its child, sibling, and parent fields.
17981    Set HAS_CHILDREN to tell whether the die has children or not.  */
17982
17983 static const gdb_byte *
17984 read_full_die_1 (const struct die_reader_specs *reader,
17985                  struct die_info **diep, const gdb_byte *info_ptr,
17986                  int *has_children, int num_extra_attrs)
17987 {
17988   unsigned int abbrev_number, bytes_read, i;
17989   struct abbrev_info *abbrev;
17990   struct die_info *die;
17991   struct dwarf2_cu *cu = reader->cu;
17992   bfd *abfd = reader->abfd;
17993
17994   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17995   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17996   info_ptr += bytes_read;
17997   if (!abbrev_number)
17998     {
17999       *diep = NULL;
18000       *has_children = 0;
18001       return info_ptr;
18002     }
18003
18004   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
18005   if (!abbrev)
18006     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18007            abbrev_number,
18008            bfd_get_filename (abfd));
18009
18010   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18011   die->sect_off = sect_off;
18012   die->tag = abbrev->tag;
18013   die->abbrev = abbrev_number;
18014
18015   /* Make the result usable.
18016      The caller needs to update num_attrs after adding the extra
18017      attributes.  */
18018   die->num_attrs = abbrev->num_attrs;
18019
18020   for (i = 0; i < abbrev->num_attrs; ++i)
18021     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18022                                info_ptr);
18023
18024   *diep = die;
18025   *has_children = abbrev->has_children;
18026   return info_ptr;
18027 }
18028
18029 /* Read a die and all its attributes.
18030    Set DIEP to point to a newly allocated die with its information,
18031    except for its child, sibling, and parent fields.
18032    Set HAS_CHILDREN to tell whether the die has children or not.  */
18033
18034 static const gdb_byte *
18035 read_full_die (const struct die_reader_specs *reader,
18036                struct die_info **diep, const gdb_byte *info_ptr,
18037                int *has_children)
18038 {
18039   const gdb_byte *result;
18040
18041   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18042
18043   if (dwarf_die_debug)
18044     {
18045       fprintf_unfiltered (gdb_stdlog,
18046                           "Read die from %s@0x%x of %s:\n",
18047                           get_section_name (reader->die_section),
18048                           (unsigned) (info_ptr - reader->die_section->buffer),
18049                           bfd_get_filename (reader->abfd));
18050       dump_die (*diep, dwarf_die_debug);
18051     }
18052
18053   return result;
18054 }
18055 \f
18056 /* Abbreviation tables.
18057
18058    In DWARF version 2, the description of the debugging information is
18059    stored in a separate .debug_abbrev section.  Before we read any
18060    dies from a section we read in all abbreviations and install them
18061    in a hash table.  */
18062
18063 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18064
18065 static struct abbrev_info *
18066 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
18067 {
18068   struct abbrev_info *abbrev;
18069
18070   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
18071   memset (abbrev, 0, sizeof (struct abbrev_info));
18072
18073   return abbrev;
18074 }
18075
18076 /* Add an abbreviation to the table.  */
18077
18078 static void
18079 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
18080                          unsigned int abbrev_number,
18081                          struct abbrev_info *abbrev)
18082 {
18083   unsigned int hash_number;
18084
18085   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18086   abbrev->next = abbrev_table->abbrevs[hash_number];
18087   abbrev_table->abbrevs[hash_number] = abbrev;
18088 }
18089
18090 /* Look up an abbrev in the table.
18091    Returns NULL if the abbrev is not found.  */
18092
18093 static struct abbrev_info *
18094 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
18095                             unsigned int abbrev_number)
18096 {
18097   unsigned int hash_number;
18098   struct abbrev_info *abbrev;
18099
18100   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18101   abbrev = abbrev_table->abbrevs[hash_number];
18102
18103   while (abbrev)
18104     {
18105       if (abbrev->number == abbrev_number)
18106         return abbrev;
18107       abbrev = abbrev->next;
18108     }
18109   return NULL;
18110 }
18111
18112 /* Read in an abbrev table.  */
18113
18114 static struct abbrev_table *
18115 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18116                          struct dwarf2_section_info *section,
18117                          sect_offset sect_off)
18118 {
18119   struct objfile *objfile = dwarf2_per_objfile->objfile;
18120   bfd *abfd = get_section_bfd_owner (section);
18121   struct abbrev_table *abbrev_table;
18122   const gdb_byte *abbrev_ptr;
18123   struct abbrev_info *cur_abbrev;
18124   unsigned int abbrev_number, bytes_read, abbrev_name;
18125   unsigned int abbrev_form;
18126   struct attr_abbrev *cur_attrs;
18127   unsigned int allocated_attrs;
18128
18129   abbrev_table = XNEW (struct abbrev_table);
18130   abbrev_table->sect_off = sect_off;
18131   obstack_init (&abbrev_table->abbrev_obstack);
18132   abbrev_table->abbrevs =
18133     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
18134                ABBREV_HASH_SIZE);
18135   memset (abbrev_table->abbrevs, 0,
18136           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
18137
18138   dwarf2_read_section (objfile, section);
18139   abbrev_ptr = section->buffer + to_underlying (sect_off);
18140   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18141   abbrev_ptr += bytes_read;
18142
18143   allocated_attrs = ATTR_ALLOC_CHUNK;
18144   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18145
18146   /* Loop until we reach an abbrev number of 0.  */
18147   while (abbrev_number)
18148     {
18149       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
18150
18151       /* read in abbrev header */
18152       cur_abbrev->number = abbrev_number;
18153       cur_abbrev->tag
18154         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18155       abbrev_ptr += bytes_read;
18156       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18157       abbrev_ptr += 1;
18158
18159       /* now read in declarations */
18160       for (;;)
18161         {
18162           LONGEST implicit_const;
18163
18164           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18165           abbrev_ptr += bytes_read;
18166           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18167           abbrev_ptr += bytes_read;
18168           if (abbrev_form == DW_FORM_implicit_const)
18169             {
18170               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18171                                                    &bytes_read);
18172               abbrev_ptr += bytes_read;
18173             }
18174           else
18175             {
18176               /* Initialize it due to a false compiler warning.  */
18177               implicit_const = -1;
18178             }
18179
18180           if (abbrev_name == 0)
18181             break;
18182
18183           if (cur_abbrev->num_attrs == allocated_attrs)
18184             {
18185               allocated_attrs += ATTR_ALLOC_CHUNK;
18186               cur_attrs
18187                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18188             }
18189
18190           cur_attrs[cur_abbrev->num_attrs].name
18191             = (enum dwarf_attribute) abbrev_name;
18192           cur_attrs[cur_abbrev->num_attrs].form
18193             = (enum dwarf_form) abbrev_form;
18194           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18195           ++cur_abbrev->num_attrs;
18196         }
18197
18198       cur_abbrev->attrs =
18199         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18200                    cur_abbrev->num_attrs);
18201       memcpy (cur_abbrev->attrs, cur_attrs,
18202               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18203
18204       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
18205
18206       /* Get next abbreviation.
18207          Under Irix6 the abbreviations for a compilation unit are not
18208          always properly terminated with an abbrev number of 0.
18209          Exit loop if we encounter an abbreviation which we have
18210          already read (which means we are about to read the abbreviations
18211          for the next compile unit) or if the end of the abbreviation
18212          table is reached.  */
18213       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18214         break;
18215       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18216       abbrev_ptr += bytes_read;
18217       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
18218         break;
18219     }
18220
18221   xfree (cur_attrs);
18222   return abbrev_table;
18223 }
18224
18225 /* Free the resources held by ABBREV_TABLE.  */
18226
18227 static void
18228 abbrev_table_free (struct abbrev_table *abbrev_table)
18229 {
18230   obstack_free (&abbrev_table->abbrev_obstack, NULL);
18231   xfree (abbrev_table);
18232 }
18233
18234 /* Same as abbrev_table_free but as a cleanup.
18235    We pass in a pointer to the pointer to the table so that we can
18236    set the pointer to NULL when we're done.  It also simplifies
18237    build_type_psymtabs_1.  */
18238
18239 static void
18240 abbrev_table_free_cleanup (void *table_ptr)
18241 {
18242   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
18243
18244   if (*abbrev_table_ptr != NULL)
18245     abbrev_table_free (*abbrev_table_ptr);
18246   *abbrev_table_ptr = NULL;
18247 }
18248
18249 /* Read the abbrev table for CU from ABBREV_SECTION.  */
18250
18251 static void
18252 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
18253                      struct dwarf2_section_info *abbrev_section)
18254 {
18255   cu->abbrev_table =
18256     abbrev_table_read_table (cu->dwarf2_per_objfile, abbrev_section,
18257                              cu->header.abbrev_sect_off);
18258 }
18259
18260 /* Release the memory used by the abbrev table for a compilation unit.  */
18261
18262 static void
18263 dwarf2_free_abbrev_table (void *ptr_to_cu)
18264 {
18265   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
18266
18267   if (cu->abbrev_table != NULL)
18268     abbrev_table_free (cu->abbrev_table);
18269   /* Set this to NULL so that we SEGV if we try to read it later,
18270      and also because free_comp_unit verifies this is NULL.  */
18271   cu->abbrev_table = NULL;
18272 }
18273 \f
18274 /* Returns nonzero if TAG represents a type that we might generate a partial
18275    symbol for.  */
18276
18277 static int
18278 is_type_tag_for_partial (int tag)
18279 {
18280   switch (tag)
18281     {
18282 #if 0
18283     /* Some types that would be reasonable to generate partial symbols for,
18284        that we don't at present.  */
18285     case DW_TAG_array_type:
18286     case DW_TAG_file_type:
18287     case DW_TAG_ptr_to_member_type:
18288     case DW_TAG_set_type:
18289     case DW_TAG_string_type:
18290     case DW_TAG_subroutine_type:
18291 #endif
18292     case DW_TAG_base_type:
18293     case DW_TAG_class_type:
18294     case DW_TAG_interface_type:
18295     case DW_TAG_enumeration_type:
18296     case DW_TAG_structure_type:
18297     case DW_TAG_subrange_type:
18298     case DW_TAG_typedef:
18299     case DW_TAG_union_type:
18300       return 1;
18301     default:
18302       return 0;
18303     }
18304 }
18305
18306 /* Load all DIEs that are interesting for partial symbols into memory.  */
18307
18308 static struct partial_die_info *
18309 load_partial_dies (const struct die_reader_specs *reader,
18310                    const gdb_byte *info_ptr, int building_psymtab)
18311 {
18312   struct dwarf2_cu *cu = reader->cu;
18313   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18314   struct partial_die_info *part_die;
18315   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18316   struct abbrev_info *abbrev;
18317   unsigned int bytes_read;
18318   unsigned int load_all = 0;
18319   int nesting_level = 1;
18320
18321   parent_die = NULL;
18322   last_die = NULL;
18323
18324   gdb_assert (cu->per_cu != NULL);
18325   if (cu->per_cu->load_all_dies)
18326     load_all = 1;
18327
18328   cu->partial_dies
18329     = htab_create_alloc_ex (cu->header.length / 12,
18330                             partial_die_hash,
18331                             partial_die_eq,
18332                             NULL,
18333                             &cu->comp_unit_obstack,
18334                             hashtab_obstack_allocate,
18335                             dummy_obstack_deallocate);
18336
18337   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18338
18339   while (1)
18340     {
18341       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
18342
18343       /* A NULL abbrev means the end of a series of children.  */
18344       if (abbrev == NULL)
18345         {
18346           if (--nesting_level == 0)
18347             {
18348               /* PART_DIE was probably the last thing allocated on the
18349                  comp_unit_obstack, so we could call obstack_free
18350                  here.  We don't do that because the waste is small,
18351                  and will be cleaned up when we're done with this
18352                  compilation unit.  This way, we're also more robust
18353                  against other users of the comp_unit_obstack.  */
18354               return first_die;
18355             }
18356           info_ptr += bytes_read;
18357           last_die = parent_die;
18358           parent_die = parent_die->die_parent;
18359           continue;
18360         }
18361
18362       /* Check for template arguments.  We never save these; if
18363          they're seen, we just mark the parent, and go on our way.  */
18364       if (parent_die != NULL
18365           && cu->language == language_cplus
18366           && (abbrev->tag == DW_TAG_template_type_param
18367               || abbrev->tag == DW_TAG_template_value_param))
18368         {
18369           parent_die->has_template_arguments = 1;
18370
18371           if (!load_all)
18372             {
18373               /* We don't need a partial DIE for the template argument.  */
18374               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18375               continue;
18376             }
18377         }
18378
18379       /* We only recurse into c++ subprograms looking for template arguments.
18380          Skip their other children.  */
18381       if (!load_all
18382           && cu->language == language_cplus
18383           && parent_die != NULL
18384           && parent_die->tag == DW_TAG_subprogram)
18385         {
18386           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18387           continue;
18388         }
18389
18390       /* Check whether this DIE is interesting enough to save.  Normally
18391          we would not be interested in members here, but there may be
18392          later variables referencing them via DW_AT_specification (for
18393          static members).  */
18394       if (!load_all
18395           && !is_type_tag_for_partial (abbrev->tag)
18396           && abbrev->tag != DW_TAG_constant
18397           && abbrev->tag != DW_TAG_enumerator
18398           && abbrev->tag != DW_TAG_subprogram
18399           && abbrev->tag != DW_TAG_lexical_block
18400           && abbrev->tag != DW_TAG_variable
18401           && abbrev->tag != DW_TAG_namespace
18402           && abbrev->tag != DW_TAG_module
18403           && abbrev->tag != DW_TAG_member
18404           && abbrev->tag != DW_TAG_imported_unit
18405           && abbrev->tag != DW_TAG_imported_declaration)
18406         {
18407           /* Otherwise we skip to the next sibling, if any.  */
18408           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18409           continue;
18410         }
18411
18412       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18413                                    info_ptr);
18414
18415       /* This two-pass algorithm for processing partial symbols has a
18416          high cost in cache pressure.  Thus, handle some simple cases
18417          here which cover the majority of C partial symbols.  DIEs
18418          which neither have specification tags in them, nor could have
18419          specification tags elsewhere pointing at them, can simply be
18420          processed and discarded.
18421
18422          This segment is also optional; scan_partial_symbols and
18423          add_partial_symbol will handle these DIEs if we chain
18424          them in normally.  When compilers which do not emit large
18425          quantities of duplicate debug information are more common,
18426          this code can probably be removed.  */
18427
18428       /* Any complete simple types at the top level (pretty much all
18429          of them, for a language without namespaces), can be processed
18430          directly.  */
18431       if (parent_die == NULL
18432           && part_die->has_specification == 0
18433           && part_die->is_declaration == 0
18434           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18435               || part_die->tag == DW_TAG_base_type
18436               || part_die->tag == DW_TAG_subrange_type))
18437         {
18438           if (building_psymtab && part_die->name != NULL)
18439             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18440                                  VAR_DOMAIN, LOC_TYPEDEF,
18441                                  &objfile->static_psymbols,
18442                                  0, cu->language, objfile);
18443           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18444           continue;
18445         }
18446
18447       /* The exception for DW_TAG_typedef with has_children above is
18448          a workaround of GCC PR debug/47510.  In the case of this complaint
18449          type_name_no_tag_or_error will error on such types later.
18450
18451          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18452          it could not find the child DIEs referenced later, this is checked
18453          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18454
18455       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18456         complaint (&symfile_complaints,
18457                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18458                      "- DIE at 0x%x [in module %s]"),
18459                    to_underlying (part_die->sect_off), objfile_name (objfile));
18460
18461       /* If we're at the second level, and we're an enumerator, and
18462          our parent has no specification (meaning possibly lives in a
18463          namespace elsewhere), then we can add the partial symbol now
18464          instead of queueing it.  */
18465       if (part_die->tag == DW_TAG_enumerator
18466           && parent_die != NULL
18467           && parent_die->die_parent == NULL
18468           && parent_die->tag == DW_TAG_enumeration_type
18469           && parent_die->has_specification == 0)
18470         {
18471           if (part_die->name == NULL)
18472             complaint (&symfile_complaints,
18473                        _("malformed enumerator DIE ignored"));
18474           else if (building_psymtab)
18475             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18476                                  VAR_DOMAIN, LOC_CONST,
18477                                  cu->language == language_cplus
18478                                  ? &objfile->global_psymbols
18479                                  : &objfile->static_psymbols,
18480                                  0, cu->language, objfile);
18481
18482           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18483           continue;
18484         }
18485
18486       /* We'll save this DIE so link it in.  */
18487       part_die->die_parent = parent_die;
18488       part_die->die_sibling = NULL;
18489       part_die->die_child = NULL;
18490
18491       if (last_die && last_die == parent_die)
18492         last_die->die_child = part_die;
18493       else if (last_die)
18494         last_die->die_sibling = part_die;
18495
18496       last_die = part_die;
18497
18498       if (first_die == NULL)
18499         first_die = part_die;
18500
18501       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18502          find interesting need to be in the hash table, because we
18503          also have the parent/sibling/child chains; only those that we
18504          might refer to by offset later during partial symbol reading.
18505
18506          For now this means things that might have be the target of a
18507          DW_AT_specification, DW_AT_abstract_origin, or
18508          DW_AT_extension.  DW_AT_extension will refer only to
18509          namespaces; DW_AT_abstract_origin refers to functions (and
18510          many things under the function DIE, but we do not recurse
18511          into function DIEs during partial symbol reading) and
18512          possibly variables as well; DW_AT_specification refers to
18513          declarations.  Declarations ought to have the DW_AT_declaration
18514          flag.  It happens that GCC forgets to put it in sometimes, but
18515          only for functions, not for types.
18516
18517          Adding more things than necessary to the hash table is harmless
18518          except for the performance cost.  Adding too few will result in
18519          wasted time in find_partial_die, when we reread the compilation
18520          unit with load_all_dies set.  */
18521
18522       if (load_all
18523           || abbrev->tag == DW_TAG_constant
18524           || abbrev->tag == DW_TAG_subprogram
18525           || abbrev->tag == DW_TAG_variable
18526           || abbrev->tag == DW_TAG_namespace
18527           || part_die->is_declaration)
18528         {
18529           void **slot;
18530
18531           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18532                                            to_underlying (part_die->sect_off),
18533                                            INSERT);
18534           *slot = part_die;
18535         }
18536
18537       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18538
18539       /* For some DIEs we want to follow their children (if any).  For C
18540          we have no reason to follow the children of structures; for other
18541          languages we have to, so that we can get at method physnames
18542          to infer fully qualified class names, for DW_AT_specification,
18543          and for C++ template arguments.  For C++, we also look one level
18544          inside functions to find template arguments (if the name of the
18545          function does not already contain the template arguments).
18546
18547          For Ada, we need to scan the children of subprograms and lexical
18548          blocks as well because Ada allows the definition of nested
18549          entities that could be interesting for the debugger, such as
18550          nested subprograms for instance.  */
18551       if (last_die->has_children
18552           && (load_all
18553               || last_die->tag == DW_TAG_namespace
18554               || last_die->tag == DW_TAG_module
18555               || last_die->tag == DW_TAG_enumeration_type
18556               || (cu->language == language_cplus
18557                   && last_die->tag == DW_TAG_subprogram
18558                   && (last_die->name == NULL
18559                       || strchr (last_die->name, '<') == NULL))
18560               || (cu->language != language_c
18561                   && (last_die->tag == DW_TAG_class_type
18562                       || last_die->tag == DW_TAG_interface_type
18563                       || last_die->tag == DW_TAG_structure_type
18564                       || last_die->tag == DW_TAG_union_type))
18565               || (cu->language == language_ada
18566                   && (last_die->tag == DW_TAG_subprogram
18567                       || last_die->tag == DW_TAG_lexical_block))))
18568         {
18569           nesting_level++;
18570           parent_die = last_die;
18571           continue;
18572         }
18573
18574       /* Otherwise we skip to the next sibling, if any.  */
18575       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18576
18577       /* Back to the top, do it again.  */
18578     }
18579 }
18580
18581 /* Read a minimal amount of information into the minimal die structure.  */
18582
18583 static const gdb_byte *
18584 read_partial_die (const struct die_reader_specs *reader,
18585                   struct partial_die_info *part_die,
18586                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18587                   const gdb_byte *info_ptr)
18588 {
18589   struct dwarf2_cu *cu = reader->cu;
18590   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
18591   struct objfile *objfile = dwarf2_per_objfile->objfile;
18592   const gdb_byte *buffer = reader->buffer;
18593   unsigned int i;
18594   struct attribute attr;
18595   int has_low_pc_attr = 0;
18596   int has_high_pc_attr = 0;
18597   int high_pc_relative = 0;
18598
18599   memset (part_die, 0, sizeof (struct partial_die_info));
18600
18601   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18602
18603   info_ptr += abbrev_len;
18604
18605   if (abbrev == NULL)
18606     return info_ptr;
18607
18608   part_die->tag = abbrev->tag;
18609   part_die->has_children = abbrev->has_children;
18610
18611   for (i = 0; i < abbrev->num_attrs; ++i)
18612     {
18613       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18614
18615       /* Store the data if it is of an attribute we want to keep in a
18616          partial symbol table.  */
18617       switch (attr.name)
18618         {
18619         case DW_AT_name:
18620           switch (part_die->tag)
18621             {
18622             case DW_TAG_compile_unit:
18623             case DW_TAG_partial_unit:
18624             case DW_TAG_type_unit:
18625               /* Compilation units have a DW_AT_name that is a filename, not
18626                  a source language identifier.  */
18627             case DW_TAG_enumeration_type:
18628             case DW_TAG_enumerator:
18629               /* These tags always have simple identifiers already; no need
18630                  to canonicalize them.  */
18631               part_die->name = DW_STRING (&attr);
18632               break;
18633             default:
18634               part_die->name
18635                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18636                                             &objfile->per_bfd->storage_obstack);
18637               break;
18638             }
18639           break;
18640         case DW_AT_linkage_name:
18641         case DW_AT_MIPS_linkage_name:
18642           /* Note that both forms of linkage name might appear.  We
18643              assume they will be the same, and we only store the last
18644              one we see.  */
18645           if (cu->language == language_ada)
18646             part_die->name = DW_STRING (&attr);
18647           part_die->linkage_name = DW_STRING (&attr);
18648           break;
18649         case DW_AT_low_pc:
18650           has_low_pc_attr = 1;
18651           part_die->lowpc = attr_value_as_address (&attr);
18652           break;
18653         case DW_AT_high_pc:
18654           has_high_pc_attr = 1;
18655           part_die->highpc = attr_value_as_address (&attr);
18656           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18657                 high_pc_relative = 1;
18658           break;
18659         case DW_AT_location:
18660           /* Support the .debug_loc offsets.  */
18661           if (attr_form_is_block (&attr))
18662             {
18663                part_die->d.locdesc = DW_BLOCK (&attr);
18664             }
18665           else if (attr_form_is_section_offset (&attr))
18666             {
18667               dwarf2_complex_location_expr_complaint ();
18668             }
18669           else
18670             {
18671               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18672                                                      "partial symbol information");
18673             }
18674           break;
18675         case DW_AT_external:
18676           part_die->is_external = DW_UNSND (&attr);
18677           break;
18678         case DW_AT_declaration:
18679           part_die->is_declaration = DW_UNSND (&attr);
18680           break;
18681         case DW_AT_type:
18682           part_die->has_type = 1;
18683           break;
18684         case DW_AT_abstract_origin:
18685         case DW_AT_specification:
18686         case DW_AT_extension:
18687           part_die->has_specification = 1;
18688           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18689           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18690                                    || cu->per_cu->is_dwz);
18691           break;
18692         case DW_AT_sibling:
18693           /* Ignore absolute siblings, they might point outside of
18694              the current compile unit.  */
18695           if (attr.form == DW_FORM_ref_addr)
18696             complaint (&symfile_complaints,
18697                        _("ignoring absolute DW_AT_sibling"));
18698           else
18699             {
18700               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18701               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18702
18703               if (sibling_ptr < info_ptr)
18704                 complaint (&symfile_complaints,
18705                            _("DW_AT_sibling points backwards"));
18706               else if (sibling_ptr > reader->buffer_end)
18707                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18708               else
18709                 part_die->sibling = sibling_ptr;
18710             }
18711           break;
18712         case DW_AT_byte_size:
18713           part_die->has_byte_size = 1;
18714           break;
18715         case DW_AT_const_value:
18716           part_die->has_const_value = 1;
18717           break;
18718         case DW_AT_calling_convention:
18719           /* DWARF doesn't provide a way to identify a program's source-level
18720              entry point.  DW_AT_calling_convention attributes are only meant
18721              to describe functions' calling conventions.
18722
18723              However, because it's a necessary piece of information in
18724              Fortran, and before DWARF 4 DW_CC_program was the only
18725              piece of debugging information whose definition refers to
18726              a 'main program' at all, several compilers marked Fortran
18727              main programs with DW_CC_program --- even when those
18728              functions use the standard calling conventions.
18729
18730              Although DWARF now specifies a way to provide this
18731              information, we support this practice for backward
18732              compatibility.  */
18733           if (DW_UNSND (&attr) == DW_CC_program
18734               && cu->language == language_fortran)
18735             part_die->main_subprogram = 1;
18736           break;
18737         case DW_AT_inline:
18738           if (DW_UNSND (&attr) == DW_INL_inlined
18739               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18740             part_die->may_be_inlined = 1;
18741           break;
18742
18743         case DW_AT_import:
18744           if (part_die->tag == DW_TAG_imported_unit)
18745             {
18746               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18747               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18748                                   || cu->per_cu->is_dwz);
18749             }
18750           break;
18751
18752         case DW_AT_main_subprogram:
18753           part_die->main_subprogram = DW_UNSND (&attr);
18754           break;
18755
18756         default:
18757           break;
18758         }
18759     }
18760
18761   if (high_pc_relative)
18762     part_die->highpc += part_die->lowpc;
18763
18764   if (has_low_pc_attr && has_high_pc_attr)
18765     {
18766       /* When using the GNU linker, .gnu.linkonce. sections are used to
18767          eliminate duplicate copies of functions and vtables and such.
18768          The linker will arbitrarily choose one and discard the others.
18769          The AT_*_pc values for such functions refer to local labels in
18770          these sections.  If the section from that file was discarded, the
18771          labels are not in the output, so the relocs get a value of 0.
18772          If this is a discarded function, mark the pc bounds as invalid,
18773          so that GDB will ignore it.  */
18774       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18775         {
18776           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18777
18778           complaint (&symfile_complaints,
18779                      _("DW_AT_low_pc %s is zero "
18780                        "for DIE at 0x%x [in module %s]"),
18781                      paddress (gdbarch, part_die->lowpc),
18782                      to_underlying (part_die->sect_off), objfile_name (objfile));
18783         }
18784       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18785       else if (part_die->lowpc >= part_die->highpc)
18786         {
18787           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18788
18789           complaint (&symfile_complaints,
18790                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18791                        "for DIE at 0x%x [in module %s]"),
18792                      paddress (gdbarch, part_die->lowpc),
18793                      paddress (gdbarch, part_die->highpc),
18794                      to_underlying (part_die->sect_off),
18795                      objfile_name (objfile));
18796         }
18797       else
18798         part_die->has_pc_info = 1;
18799     }
18800
18801   return info_ptr;
18802 }
18803
18804 /* Find a cached partial DIE at OFFSET in CU.  */
18805
18806 static struct partial_die_info *
18807 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18808 {
18809   struct partial_die_info *lookup_die = NULL;
18810   struct partial_die_info part_die;
18811
18812   part_die.sect_off = sect_off;
18813   lookup_die = ((struct partial_die_info *)
18814                 htab_find_with_hash (cu->partial_dies, &part_die,
18815                                      to_underlying (sect_off)));
18816
18817   return lookup_die;
18818 }
18819
18820 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18821    except in the case of .debug_types DIEs which do not reference
18822    outside their CU (they do however referencing other types via
18823    DW_FORM_ref_sig8).  */
18824
18825 static struct partial_die_info *
18826 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18827 {
18828   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
18829   struct objfile *objfile = dwarf2_per_objfile->objfile;
18830   struct dwarf2_per_cu_data *per_cu = NULL;
18831   struct partial_die_info *pd = NULL;
18832
18833   if (offset_in_dwz == cu->per_cu->is_dwz
18834       && offset_in_cu_p (&cu->header, sect_off))
18835     {
18836       pd = find_partial_die_in_comp_unit (sect_off, cu);
18837       if (pd != NULL)
18838         return pd;
18839       /* We missed recording what we needed.
18840          Load all dies and try again.  */
18841       per_cu = cu->per_cu;
18842     }
18843   else
18844     {
18845       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18846       if (cu->per_cu->is_debug_types)
18847         {
18848           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18849                    " external reference to offset 0x%x [in module %s].\n"),
18850                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18851                  bfd_get_filename (objfile->obfd));
18852         }
18853       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18854                                                  dwarf2_per_objfile);
18855
18856       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18857         load_partial_comp_unit (per_cu);
18858
18859       per_cu->cu->last_used = 0;
18860       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18861     }
18862
18863   /* If we didn't find it, and not all dies have been loaded,
18864      load them all and try again.  */
18865
18866   if (pd == NULL && per_cu->load_all_dies == 0)
18867     {
18868       per_cu->load_all_dies = 1;
18869
18870       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18871          THIS_CU->cu may already be in use.  So we can't just free it and
18872          replace its DIEs with the ones we read in.  Instead, we leave those
18873          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18874          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18875          set.  */
18876       load_partial_comp_unit (per_cu);
18877
18878       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18879     }
18880
18881   if (pd == NULL)
18882     internal_error (__FILE__, __LINE__,
18883                     _("could not find partial DIE 0x%x "
18884                       "in cache [from module %s]\n"),
18885                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18886   return pd;
18887 }
18888
18889 /* See if we can figure out if the class lives in a namespace.  We do
18890    this by looking for a member function; its demangled name will
18891    contain namespace info, if there is any.  */
18892
18893 static void
18894 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18895                                   struct dwarf2_cu *cu)
18896 {
18897   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18898      what template types look like, because the demangler
18899      frequently doesn't give the same name as the debug info.  We
18900      could fix this by only using the demangled name to get the
18901      prefix (but see comment in read_structure_type).  */
18902
18903   struct partial_die_info *real_pdi;
18904   struct partial_die_info *child_pdi;
18905
18906   /* If this DIE (this DIE's specification, if any) has a parent, then
18907      we should not do this.  We'll prepend the parent's fully qualified
18908      name when we create the partial symbol.  */
18909
18910   real_pdi = struct_pdi;
18911   while (real_pdi->has_specification)
18912     real_pdi = find_partial_die (real_pdi->spec_offset,
18913                                  real_pdi->spec_is_dwz, cu);
18914
18915   if (real_pdi->die_parent != NULL)
18916     return;
18917
18918   for (child_pdi = struct_pdi->die_child;
18919        child_pdi != NULL;
18920        child_pdi = child_pdi->die_sibling)
18921     {
18922       if (child_pdi->tag == DW_TAG_subprogram
18923           && child_pdi->linkage_name != NULL)
18924         {
18925           char *actual_class_name
18926             = language_class_name_from_physname (cu->language_defn,
18927                                                  child_pdi->linkage_name);
18928           if (actual_class_name != NULL)
18929             {
18930               struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
18931               struct_pdi->name
18932                 = ((const char *)
18933                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18934                                   actual_class_name,
18935                                   strlen (actual_class_name)));
18936               xfree (actual_class_name);
18937             }
18938           break;
18939         }
18940     }
18941 }
18942
18943 /* Adjust PART_DIE before generating a symbol for it.  This function
18944    may set the is_external flag or change the DIE's name.  */
18945
18946 static void
18947 fixup_partial_die (struct partial_die_info *part_die,
18948                    struct dwarf2_cu *cu)
18949 {
18950   /* Once we've fixed up a die, there's no point in doing so again.
18951      This also avoids a memory leak if we were to call
18952      guess_partial_die_structure_name multiple times.  */
18953   if (part_die->fixup_called)
18954     return;
18955
18956   /* If we found a reference attribute and the DIE has no name, try
18957      to find a name in the referred to DIE.  */
18958
18959   if (part_die->name == NULL && part_die->has_specification)
18960     {
18961       struct partial_die_info *spec_die;
18962
18963       spec_die = find_partial_die (part_die->spec_offset,
18964                                    part_die->spec_is_dwz, cu);
18965
18966       fixup_partial_die (spec_die, cu);
18967
18968       if (spec_die->name)
18969         {
18970           part_die->name = spec_die->name;
18971
18972           /* Copy DW_AT_external attribute if it is set.  */
18973           if (spec_die->is_external)
18974             part_die->is_external = spec_die->is_external;
18975         }
18976     }
18977
18978   /* Set default names for some unnamed DIEs.  */
18979
18980   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18981     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18982
18983   /* If there is no parent die to provide a namespace, and there are
18984      children, see if we can determine the namespace from their linkage
18985      name.  */
18986   if (cu->language == language_cplus
18987       && !VEC_empty (dwarf2_section_info_def, cu->dwarf2_per_objfile->types)
18988       && part_die->die_parent == NULL
18989       && part_die->has_children
18990       && (part_die->tag == DW_TAG_class_type
18991           || part_die->tag == DW_TAG_structure_type
18992           || part_die->tag == DW_TAG_union_type))
18993     guess_partial_die_structure_name (part_die, cu);
18994
18995   /* GCC might emit a nameless struct or union that has a linkage
18996      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18997   if (part_die->name == NULL
18998       && (part_die->tag == DW_TAG_class_type
18999           || part_die->tag == DW_TAG_interface_type
19000           || part_die->tag == DW_TAG_structure_type
19001           || part_die->tag == DW_TAG_union_type)
19002       && part_die->linkage_name != NULL)
19003     {
19004       char *demangled;
19005
19006       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
19007       if (demangled)
19008         {
19009           const char *base;
19010
19011           /* Strip any leading namespaces/classes, keep only the base name.
19012              DW_AT_name for named DIEs does not contain the prefixes.  */
19013           base = strrchr (demangled, ':');
19014           if (base && base > demangled && base[-1] == ':')
19015             base++;
19016           else
19017             base = demangled;
19018
19019           struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
19020           part_die->name
19021             = ((const char *)
19022                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19023                               base, strlen (base)));
19024           xfree (demangled);
19025         }
19026     }
19027
19028   part_die->fixup_called = 1;
19029 }
19030
19031 /* Read an attribute value described by an attribute form.  */
19032
19033 static const gdb_byte *
19034 read_attribute_value (const struct die_reader_specs *reader,
19035                       struct attribute *attr, unsigned form,
19036                       LONGEST implicit_const, const gdb_byte *info_ptr)
19037 {
19038   struct dwarf2_cu *cu = reader->cu;
19039   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
19040   struct objfile *objfile = dwarf2_per_objfile->objfile;
19041   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19042   bfd *abfd = reader->abfd;
19043   struct comp_unit_head *cu_header = &cu->header;
19044   unsigned int bytes_read;
19045   struct dwarf_block *blk;
19046
19047   attr->form = (enum dwarf_form) form;
19048   switch (form)
19049     {
19050     case DW_FORM_ref_addr:
19051       if (cu->header.version == 2)
19052         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19053       else
19054         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19055                                        &cu->header, &bytes_read);
19056       info_ptr += bytes_read;
19057       break;
19058     case DW_FORM_GNU_ref_alt:
19059       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19060       info_ptr += bytes_read;
19061       break;
19062     case DW_FORM_addr:
19063       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19064       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19065       info_ptr += bytes_read;
19066       break;
19067     case DW_FORM_block2:
19068       blk = dwarf_alloc_block (cu);
19069       blk->size = read_2_bytes (abfd, info_ptr);
19070       info_ptr += 2;
19071       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19072       info_ptr += blk->size;
19073       DW_BLOCK (attr) = blk;
19074       break;
19075     case DW_FORM_block4:
19076       blk = dwarf_alloc_block (cu);
19077       blk->size = read_4_bytes (abfd, info_ptr);
19078       info_ptr += 4;
19079       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19080       info_ptr += blk->size;
19081       DW_BLOCK (attr) = blk;
19082       break;
19083     case DW_FORM_data2:
19084       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19085       info_ptr += 2;
19086       break;
19087     case DW_FORM_data4:
19088       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19089       info_ptr += 4;
19090       break;
19091     case DW_FORM_data8:
19092       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19093       info_ptr += 8;
19094       break;
19095     case DW_FORM_data16:
19096       blk = dwarf_alloc_block (cu);
19097       blk->size = 16;
19098       blk->data = read_n_bytes (abfd, info_ptr, 16);
19099       info_ptr += 16;
19100       DW_BLOCK (attr) = blk;
19101       break;
19102     case DW_FORM_sec_offset:
19103       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19104       info_ptr += bytes_read;
19105       break;
19106     case DW_FORM_string:
19107       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19108       DW_STRING_IS_CANONICAL (attr) = 0;
19109       info_ptr += bytes_read;
19110       break;
19111     case DW_FORM_strp:
19112       if (!cu->per_cu->is_dwz)
19113         {
19114           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19115                                                    abfd, info_ptr, cu_header,
19116                                                    &bytes_read);
19117           DW_STRING_IS_CANONICAL (attr) = 0;
19118           info_ptr += bytes_read;
19119           break;
19120         }
19121       /* FALLTHROUGH */
19122     case DW_FORM_line_strp:
19123       if (!cu->per_cu->is_dwz)
19124         {
19125           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19126                                                         abfd, info_ptr,
19127                                                         cu_header, &bytes_read);
19128           DW_STRING_IS_CANONICAL (attr) = 0;
19129           info_ptr += bytes_read;
19130           break;
19131         }
19132       /* FALLTHROUGH */
19133     case DW_FORM_GNU_strp_alt:
19134       {
19135         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19136         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19137                                           &bytes_read);
19138
19139         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19140                                                           dwz, str_offset);
19141         DW_STRING_IS_CANONICAL (attr) = 0;
19142         info_ptr += bytes_read;
19143       }
19144       break;
19145     case DW_FORM_exprloc:
19146     case DW_FORM_block:
19147       blk = dwarf_alloc_block (cu);
19148       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19149       info_ptr += bytes_read;
19150       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19151       info_ptr += blk->size;
19152       DW_BLOCK (attr) = blk;
19153       break;
19154     case DW_FORM_block1:
19155       blk = dwarf_alloc_block (cu);
19156       blk->size = read_1_byte (abfd, info_ptr);
19157       info_ptr += 1;
19158       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19159       info_ptr += blk->size;
19160       DW_BLOCK (attr) = blk;
19161       break;
19162     case DW_FORM_data1:
19163       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19164       info_ptr += 1;
19165       break;
19166     case DW_FORM_flag:
19167       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19168       info_ptr += 1;
19169       break;
19170     case DW_FORM_flag_present:
19171       DW_UNSND (attr) = 1;
19172       break;
19173     case DW_FORM_sdata:
19174       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19175       info_ptr += bytes_read;
19176       break;
19177     case DW_FORM_udata:
19178       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19179       info_ptr += bytes_read;
19180       break;
19181     case DW_FORM_ref1:
19182       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19183                          + read_1_byte (abfd, info_ptr));
19184       info_ptr += 1;
19185       break;
19186     case DW_FORM_ref2:
19187       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19188                          + read_2_bytes (abfd, info_ptr));
19189       info_ptr += 2;
19190       break;
19191     case DW_FORM_ref4:
19192       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19193                          + read_4_bytes (abfd, info_ptr));
19194       info_ptr += 4;
19195       break;
19196     case DW_FORM_ref8:
19197       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19198                          + read_8_bytes (abfd, info_ptr));
19199       info_ptr += 8;
19200       break;
19201     case DW_FORM_ref_sig8:
19202       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19203       info_ptr += 8;
19204       break;
19205     case DW_FORM_ref_udata:
19206       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19207                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19208       info_ptr += bytes_read;
19209       break;
19210     case DW_FORM_indirect:
19211       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19212       info_ptr += bytes_read;
19213       if (form == DW_FORM_implicit_const)
19214         {
19215           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19216           info_ptr += bytes_read;
19217         }
19218       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19219                                        info_ptr);
19220       break;
19221     case DW_FORM_implicit_const:
19222       DW_SND (attr) = implicit_const;
19223       break;
19224     case DW_FORM_GNU_addr_index:
19225       if (reader->dwo_file == NULL)
19226         {
19227           /* For now flag a hard error.
19228              Later we can turn this into a complaint.  */
19229           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19230                  dwarf_form_name (form),
19231                  bfd_get_filename (abfd));
19232         }
19233       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19234       info_ptr += bytes_read;
19235       break;
19236     case DW_FORM_GNU_str_index:
19237       if (reader->dwo_file == NULL)
19238         {
19239           /* For now flag a hard error.
19240              Later we can turn this into a complaint if warranted.  */
19241           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19242                  dwarf_form_name (form),
19243                  bfd_get_filename (abfd));
19244         }
19245       {
19246         ULONGEST str_index =
19247           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19248
19249         DW_STRING (attr) = read_str_index (reader, str_index);
19250         DW_STRING_IS_CANONICAL (attr) = 0;
19251         info_ptr += bytes_read;
19252       }
19253       break;
19254     default:
19255       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19256              dwarf_form_name (form),
19257              bfd_get_filename (abfd));
19258     }
19259
19260   /* Super hack.  */
19261   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19262     attr->form = DW_FORM_GNU_ref_alt;
19263
19264   /* We have seen instances where the compiler tried to emit a byte
19265      size attribute of -1 which ended up being encoded as an unsigned
19266      0xffffffff.  Although 0xffffffff is technically a valid size value,
19267      an object of this size seems pretty unlikely so we can relatively
19268      safely treat these cases as if the size attribute was invalid and
19269      treat them as zero by default.  */
19270   if (attr->name == DW_AT_byte_size
19271       && form == DW_FORM_data4
19272       && DW_UNSND (attr) >= 0xffffffff)
19273     {
19274       complaint
19275         (&symfile_complaints,
19276          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19277          hex_string (DW_UNSND (attr)));
19278       DW_UNSND (attr) = 0;
19279     }
19280
19281   return info_ptr;
19282 }
19283
19284 /* Read an attribute described by an abbreviated attribute.  */
19285
19286 static const gdb_byte *
19287 read_attribute (const struct die_reader_specs *reader,
19288                 struct attribute *attr, struct attr_abbrev *abbrev,
19289                 const gdb_byte *info_ptr)
19290 {
19291   attr->name = abbrev->name;
19292   return read_attribute_value (reader, attr, abbrev->form,
19293                                abbrev->implicit_const, info_ptr);
19294 }
19295
19296 /* Read dwarf information from a buffer.  */
19297
19298 static unsigned int
19299 read_1_byte (bfd *abfd, const gdb_byte *buf)
19300 {
19301   return bfd_get_8 (abfd, buf);
19302 }
19303
19304 static int
19305 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19306 {
19307   return bfd_get_signed_8 (abfd, buf);
19308 }
19309
19310 static unsigned int
19311 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19312 {
19313   return bfd_get_16 (abfd, buf);
19314 }
19315
19316 static int
19317 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19318 {
19319   return bfd_get_signed_16 (abfd, buf);
19320 }
19321
19322 static unsigned int
19323 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19324 {
19325   return bfd_get_32 (abfd, buf);
19326 }
19327
19328 static int
19329 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19330 {
19331   return bfd_get_signed_32 (abfd, buf);
19332 }
19333
19334 static ULONGEST
19335 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19336 {
19337   return bfd_get_64 (abfd, buf);
19338 }
19339
19340 static CORE_ADDR
19341 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19342               unsigned int *bytes_read)
19343 {
19344   struct comp_unit_head *cu_header = &cu->header;
19345   CORE_ADDR retval = 0;
19346
19347   if (cu_header->signed_addr_p)
19348     {
19349       switch (cu_header->addr_size)
19350         {
19351         case 2:
19352           retval = bfd_get_signed_16 (abfd, buf);
19353           break;
19354         case 4:
19355           retval = bfd_get_signed_32 (abfd, buf);
19356           break;
19357         case 8:
19358           retval = bfd_get_signed_64 (abfd, buf);
19359           break;
19360         default:
19361           internal_error (__FILE__, __LINE__,
19362                           _("read_address: bad switch, signed [in module %s]"),
19363                           bfd_get_filename (abfd));
19364         }
19365     }
19366   else
19367     {
19368       switch (cu_header->addr_size)
19369         {
19370         case 2:
19371           retval = bfd_get_16 (abfd, buf);
19372           break;
19373         case 4:
19374           retval = bfd_get_32 (abfd, buf);
19375           break;
19376         case 8:
19377           retval = bfd_get_64 (abfd, buf);
19378           break;
19379         default:
19380           internal_error (__FILE__, __LINE__,
19381                           _("read_address: bad switch, "
19382                             "unsigned [in module %s]"),
19383                           bfd_get_filename (abfd));
19384         }
19385     }
19386
19387   *bytes_read = cu_header->addr_size;
19388   return retval;
19389 }
19390
19391 /* Read the initial length from a section.  The (draft) DWARF 3
19392    specification allows the initial length to take up either 4 bytes
19393    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19394    bytes describe the length and all offsets will be 8 bytes in length
19395    instead of 4.
19396
19397    An older, non-standard 64-bit format is also handled by this
19398    function.  The older format in question stores the initial length
19399    as an 8-byte quantity without an escape value.  Lengths greater
19400    than 2^32 aren't very common which means that the initial 4 bytes
19401    is almost always zero.  Since a length value of zero doesn't make
19402    sense for the 32-bit format, this initial zero can be considered to
19403    be an escape value which indicates the presence of the older 64-bit
19404    format.  As written, the code can't detect (old format) lengths
19405    greater than 4GB.  If it becomes necessary to handle lengths
19406    somewhat larger than 4GB, we could allow other small values (such
19407    as the non-sensical values of 1, 2, and 3) to also be used as
19408    escape values indicating the presence of the old format.
19409
19410    The value returned via bytes_read should be used to increment the
19411    relevant pointer after calling read_initial_length().
19412
19413    [ Note:  read_initial_length() and read_offset() are based on the
19414      document entitled "DWARF Debugging Information Format", revision
19415      3, draft 8, dated November 19, 2001.  This document was obtained
19416      from:
19417
19418         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19419
19420      This document is only a draft and is subject to change.  (So beware.)
19421
19422      Details regarding the older, non-standard 64-bit format were
19423      determined empirically by examining 64-bit ELF files produced by
19424      the SGI toolchain on an IRIX 6.5 machine.
19425
19426      - Kevin, July 16, 2002
19427    ] */
19428
19429 static LONGEST
19430 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19431 {
19432   LONGEST length = bfd_get_32 (abfd, buf);
19433
19434   if (length == 0xffffffff)
19435     {
19436       length = bfd_get_64 (abfd, buf + 4);
19437       *bytes_read = 12;
19438     }
19439   else if (length == 0)
19440     {
19441       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19442       length = bfd_get_64 (abfd, buf);
19443       *bytes_read = 8;
19444     }
19445   else
19446     {
19447       *bytes_read = 4;
19448     }
19449
19450   return length;
19451 }
19452
19453 /* Cover function for read_initial_length.
19454    Returns the length of the object at BUF, and stores the size of the
19455    initial length in *BYTES_READ and stores the size that offsets will be in
19456    *OFFSET_SIZE.
19457    If the initial length size is not equivalent to that specified in
19458    CU_HEADER then issue a complaint.
19459    This is useful when reading non-comp-unit headers.  */
19460
19461 static LONGEST
19462 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19463                                         const struct comp_unit_head *cu_header,
19464                                         unsigned int *bytes_read,
19465                                         unsigned int *offset_size)
19466 {
19467   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19468
19469   gdb_assert (cu_header->initial_length_size == 4
19470               || cu_header->initial_length_size == 8
19471               || cu_header->initial_length_size == 12);
19472
19473   if (cu_header->initial_length_size != *bytes_read)
19474     complaint (&symfile_complaints,
19475                _("intermixed 32-bit and 64-bit DWARF sections"));
19476
19477   *offset_size = (*bytes_read == 4) ? 4 : 8;
19478   return length;
19479 }
19480
19481 /* Read an offset from the data stream.  The size of the offset is
19482    given by cu_header->offset_size.  */
19483
19484 static LONGEST
19485 read_offset (bfd *abfd, const gdb_byte *buf,
19486              const struct comp_unit_head *cu_header,
19487              unsigned int *bytes_read)
19488 {
19489   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19490
19491   *bytes_read = cu_header->offset_size;
19492   return offset;
19493 }
19494
19495 /* Read an offset from the data stream.  */
19496
19497 static LONGEST
19498 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19499 {
19500   LONGEST retval = 0;
19501
19502   switch (offset_size)
19503     {
19504     case 4:
19505       retval = bfd_get_32 (abfd, buf);
19506       break;
19507     case 8:
19508       retval = bfd_get_64 (abfd, buf);
19509       break;
19510     default:
19511       internal_error (__FILE__, __LINE__,
19512                       _("read_offset_1: bad switch [in module %s]"),
19513                       bfd_get_filename (abfd));
19514     }
19515
19516   return retval;
19517 }
19518
19519 static const gdb_byte *
19520 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19521 {
19522   /* If the size of a host char is 8 bits, we can return a pointer
19523      to the buffer, otherwise we have to copy the data to a buffer
19524      allocated on the temporary obstack.  */
19525   gdb_assert (HOST_CHAR_BIT == 8);
19526   return buf;
19527 }
19528
19529 static const char *
19530 read_direct_string (bfd *abfd, const gdb_byte *buf,
19531                     unsigned int *bytes_read_ptr)
19532 {
19533   /* If the size of a host char is 8 bits, we can return a pointer
19534      to the string, otherwise we have to copy the string to a buffer
19535      allocated on the temporary obstack.  */
19536   gdb_assert (HOST_CHAR_BIT == 8);
19537   if (*buf == '\0')
19538     {
19539       *bytes_read_ptr = 1;
19540       return NULL;
19541     }
19542   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19543   return (const char *) buf;
19544 }
19545
19546 /* Return pointer to string at section SECT offset STR_OFFSET with error
19547    reporting strings FORM_NAME and SECT_NAME.  */
19548
19549 static const char *
19550 read_indirect_string_at_offset_from (struct objfile *objfile,
19551                                      bfd *abfd, LONGEST str_offset,
19552                                      struct dwarf2_section_info *sect,
19553                                      const char *form_name,
19554                                      const char *sect_name)
19555 {
19556   dwarf2_read_section (objfile, sect);
19557   if (sect->buffer == NULL)
19558     error (_("%s used without %s section [in module %s]"),
19559            form_name, sect_name, bfd_get_filename (abfd));
19560   if (str_offset >= sect->size)
19561     error (_("%s pointing outside of %s section [in module %s]"),
19562            form_name, sect_name, bfd_get_filename (abfd));
19563   gdb_assert (HOST_CHAR_BIT == 8);
19564   if (sect->buffer[str_offset] == '\0')
19565     return NULL;
19566   return (const char *) (sect->buffer + str_offset);
19567 }
19568
19569 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19570
19571 static const char *
19572 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19573                                 bfd *abfd, LONGEST str_offset)
19574 {
19575   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19576                                               abfd, str_offset,
19577                                               &dwarf2_per_objfile->str,
19578                                               "DW_FORM_strp", ".debug_str");
19579 }
19580
19581 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19582
19583 static const char *
19584 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19585                                      bfd *abfd, LONGEST str_offset)
19586 {
19587   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19588                                               abfd, str_offset,
19589                                               &dwarf2_per_objfile->line_str,
19590                                               "DW_FORM_line_strp",
19591                                               ".debug_line_str");
19592 }
19593
19594 /* Read a string at offset STR_OFFSET in the .debug_str section from
19595    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19596    the string consists of a single NUL byte, return NULL; otherwise
19597    return a pointer to the string.  */
19598
19599 static const char *
19600 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19601                                LONGEST str_offset)
19602 {
19603   dwarf2_read_section (objfile, &dwz->str);
19604
19605   if (dwz->str.buffer == NULL)
19606     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19607              "section [in module %s]"),
19608            bfd_get_filename (dwz->dwz_bfd));
19609   if (str_offset >= dwz->str.size)
19610     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19611              ".debug_str section [in module %s]"),
19612            bfd_get_filename (dwz->dwz_bfd));
19613   gdb_assert (HOST_CHAR_BIT == 8);
19614   if (dwz->str.buffer[str_offset] == '\0')
19615     return NULL;
19616   return (const char *) (dwz->str.buffer + str_offset);
19617 }
19618
19619 /* Return pointer to string at .debug_str offset as read from BUF.
19620    BUF is assumed to be in a compilation unit described by CU_HEADER.
19621    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19622
19623 static const char *
19624 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19625                       const gdb_byte *buf,
19626                       const struct comp_unit_head *cu_header,
19627                       unsigned int *bytes_read_ptr)
19628 {
19629   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19630
19631   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19632 }
19633
19634 /* Return pointer to string at .debug_line_str offset as read from BUF.
19635    BUF is assumed to be in a compilation unit described by CU_HEADER.
19636    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19637
19638 static const char *
19639 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19640                            bfd *abfd, const gdb_byte *buf,
19641                            const struct comp_unit_head *cu_header,
19642                            unsigned int *bytes_read_ptr)
19643 {
19644   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19645
19646   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19647                                               str_offset);
19648 }
19649
19650 ULONGEST
19651 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19652                           unsigned int *bytes_read_ptr)
19653 {
19654   ULONGEST result;
19655   unsigned int num_read;
19656   int shift;
19657   unsigned char byte;
19658
19659   result = 0;
19660   shift = 0;
19661   num_read = 0;
19662   while (1)
19663     {
19664       byte = bfd_get_8 (abfd, buf);
19665       buf++;
19666       num_read++;
19667       result |= ((ULONGEST) (byte & 127) << shift);
19668       if ((byte & 128) == 0)
19669         {
19670           break;
19671         }
19672       shift += 7;
19673     }
19674   *bytes_read_ptr = num_read;
19675   return result;
19676 }
19677
19678 static LONGEST
19679 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19680                     unsigned int *bytes_read_ptr)
19681 {
19682   LONGEST result;
19683   int shift, num_read;
19684   unsigned char byte;
19685
19686   result = 0;
19687   shift = 0;
19688   num_read = 0;
19689   while (1)
19690     {
19691       byte = bfd_get_8 (abfd, buf);
19692       buf++;
19693       num_read++;
19694       result |= ((LONGEST) (byte & 127) << shift);
19695       shift += 7;
19696       if ((byte & 128) == 0)
19697         {
19698           break;
19699         }
19700     }
19701   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19702     result |= -(((LONGEST) 1) << shift);
19703   *bytes_read_ptr = num_read;
19704   return result;
19705 }
19706
19707 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19708    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19709    ADDR_SIZE is the size of addresses from the CU header.  */
19710
19711 static CORE_ADDR
19712 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19713                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19714 {
19715   struct objfile *objfile = dwarf2_per_objfile->objfile;
19716   bfd *abfd = objfile->obfd;
19717   const gdb_byte *info_ptr;
19718
19719   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19720   if (dwarf2_per_objfile->addr.buffer == NULL)
19721     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19722            objfile_name (objfile));
19723   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19724     error (_("DW_FORM_addr_index pointing outside of "
19725              ".debug_addr section [in module %s]"),
19726            objfile_name (objfile));
19727   info_ptr = (dwarf2_per_objfile->addr.buffer
19728               + addr_base + addr_index * addr_size);
19729   if (addr_size == 4)
19730     return bfd_get_32 (abfd, info_ptr);
19731   else
19732     return bfd_get_64 (abfd, info_ptr);
19733 }
19734
19735 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19736
19737 static CORE_ADDR
19738 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19739 {
19740   return read_addr_index_1 (cu->dwarf2_per_objfile, addr_index, cu->addr_base,
19741                             cu->header.addr_size);
19742 }
19743
19744 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19745
19746 static CORE_ADDR
19747 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19748                              unsigned int *bytes_read)
19749 {
19750   bfd *abfd = cu->dwarf2_per_objfile->objfile->obfd;
19751   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19752
19753   return read_addr_index (cu, addr_index);
19754 }
19755
19756 /* Data structure to pass results from dwarf2_read_addr_index_reader
19757    back to dwarf2_read_addr_index.  */
19758
19759 struct dwarf2_read_addr_index_data
19760 {
19761   ULONGEST addr_base;
19762   int addr_size;
19763 };
19764
19765 /* die_reader_func for dwarf2_read_addr_index.  */
19766
19767 static void
19768 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19769                                const gdb_byte *info_ptr,
19770                                struct die_info *comp_unit_die,
19771                                int has_children,
19772                                void *data)
19773 {
19774   struct dwarf2_cu *cu = reader->cu;
19775   struct dwarf2_read_addr_index_data *aidata =
19776     (struct dwarf2_read_addr_index_data *) data;
19777
19778   aidata->addr_base = cu->addr_base;
19779   aidata->addr_size = cu->header.addr_size;
19780 }
19781
19782 /* Given an index in .debug_addr, fetch the value.
19783    NOTE: This can be called during dwarf expression evaluation,
19784    long after the debug information has been read, and thus per_cu->cu
19785    may no longer exist.  */
19786
19787 CORE_ADDR
19788 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19789                         unsigned int addr_index)
19790 {
19791   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19792   struct objfile *objfile = dwarf2_per_objfile->objfile;
19793   struct dwarf2_cu *cu = per_cu->cu;
19794   ULONGEST addr_base;
19795   int addr_size;
19796
19797   /* We need addr_base and addr_size.
19798      If we don't have PER_CU->cu, we have to get it.
19799      Nasty, but the alternative is storing the needed info in PER_CU,
19800      which at this point doesn't seem justified: it's not clear how frequently
19801      it would get used and it would increase the size of every PER_CU.
19802      Entry points like dwarf2_per_cu_addr_size do a similar thing
19803      so we're not in uncharted territory here.
19804      Alas we need to be a bit more complicated as addr_base is contained
19805      in the DIE.
19806
19807      We don't need to read the entire CU(/TU).
19808      We just need the header and top level die.
19809
19810      IWBN to use the aging mechanism to let us lazily later discard the CU.
19811      For now we skip this optimization.  */
19812
19813   if (cu != NULL)
19814     {
19815       addr_base = cu->addr_base;
19816       addr_size = cu->header.addr_size;
19817     }
19818   else
19819     {
19820       struct dwarf2_read_addr_index_data aidata;
19821
19822       /* Note: We can't use init_cutu_and_read_dies_simple here,
19823          we need addr_base.  */
19824       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19825                                dwarf2_read_addr_index_reader, &aidata);
19826       addr_base = aidata.addr_base;
19827       addr_size = aidata.addr_size;
19828     }
19829
19830   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19831                             addr_size);
19832 }
19833
19834 /* Given a DW_FORM_GNU_str_index, fetch the string.
19835    This is only used by the Fission support.  */
19836
19837 static const char *
19838 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19839 {
19840   struct dwarf2_cu *cu = reader->cu;
19841   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
19842   struct objfile *objfile = dwarf2_per_objfile->objfile;
19843   const char *objf_name = objfile_name (objfile);
19844   bfd *abfd = objfile->obfd;
19845   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19846   struct dwarf2_section_info *str_offsets_section =
19847     &reader->dwo_file->sections.str_offsets;
19848   const gdb_byte *info_ptr;
19849   ULONGEST str_offset;
19850   static const char form_name[] = "DW_FORM_GNU_str_index";
19851
19852   dwarf2_read_section (objfile, str_section);
19853   dwarf2_read_section (objfile, str_offsets_section);
19854   if (str_section->buffer == NULL)
19855     error (_("%s used without .debug_str.dwo section"
19856              " in CU at offset 0x%x [in module %s]"),
19857            form_name, to_underlying (cu->header.sect_off), objf_name);
19858   if (str_offsets_section->buffer == NULL)
19859     error (_("%s used without .debug_str_offsets.dwo section"
19860              " in CU at offset 0x%x [in module %s]"),
19861            form_name, to_underlying (cu->header.sect_off), objf_name);
19862   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19863     error (_("%s pointing outside of .debug_str_offsets.dwo"
19864              " section in CU at offset 0x%x [in module %s]"),
19865            form_name, to_underlying (cu->header.sect_off), objf_name);
19866   info_ptr = (str_offsets_section->buffer
19867               + str_index * cu->header.offset_size);
19868   if (cu->header.offset_size == 4)
19869     str_offset = bfd_get_32 (abfd, info_ptr);
19870   else
19871     str_offset = bfd_get_64 (abfd, info_ptr);
19872   if (str_offset >= str_section->size)
19873     error (_("Offset from %s pointing outside of"
19874              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19875            form_name, to_underlying (cu->header.sect_off), objf_name);
19876   return (const char *) (str_section->buffer + str_offset);
19877 }
19878
19879 /* Return the length of an LEB128 number in BUF.  */
19880
19881 static int
19882 leb128_size (const gdb_byte *buf)
19883 {
19884   const gdb_byte *begin = buf;
19885   gdb_byte byte;
19886
19887   while (1)
19888     {
19889       byte = *buf++;
19890       if ((byte & 128) == 0)
19891         return buf - begin;
19892     }
19893 }
19894
19895 static void
19896 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19897 {
19898   switch (lang)
19899     {
19900     case DW_LANG_C89:
19901     case DW_LANG_C99:
19902     case DW_LANG_C11:
19903     case DW_LANG_C:
19904     case DW_LANG_UPC:
19905       cu->language = language_c;
19906       break;
19907     case DW_LANG_Java:
19908     case DW_LANG_C_plus_plus:
19909     case DW_LANG_C_plus_plus_11:
19910     case DW_LANG_C_plus_plus_14:
19911       cu->language = language_cplus;
19912       break;
19913     case DW_LANG_D:
19914       cu->language = language_d;
19915       break;
19916     case DW_LANG_Fortran77:
19917     case DW_LANG_Fortran90:
19918     case DW_LANG_Fortran95:
19919     case DW_LANG_Fortran03:
19920     case DW_LANG_Fortran08:
19921       cu->language = language_fortran;
19922       break;
19923     case DW_LANG_Go:
19924       cu->language = language_go;
19925       break;
19926     case DW_LANG_Mips_Assembler:
19927       cu->language = language_asm;
19928       break;
19929     case DW_LANG_Ada83:
19930     case DW_LANG_Ada95:
19931       cu->language = language_ada;
19932       break;
19933     case DW_LANG_Modula2:
19934       cu->language = language_m2;
19935       break;
19936     case DW_LANG_Pascal83:
19937       cu->language = language_pascal;
19938       break;
19939     case DW_LANG_ObjC:
19940       cu->language = language_objc;
19941       break;
19942     case DW_LANG_Rust:
19943     case DW_LANG_Rust_old:
19944       cu->language = language_rust;
19945       break;
19946     case DW_LANG_Cobol74:
19947     case DW_LANG_Cobol85:
19948     default:
19949       cu->language = language_minimal;
19950       break;
19951     }
19952   cu->language_defn = language_def (cu->language);
19953 }
19954
19955 /* Return the named attribute or NULL if not there.  */
19956
19957 static struct attribute *
19958 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19959 {
19960   for (;;)
19961     {
19962       unsigned int i;
19963       struct attribute *spec = NULL;
19964
19965       for (i = 0; i < die->num_attrs; ++i)
19966         {
19967           if (die->attrs[i].name == name)
19968             return &die->attrs[i];
19969           if (die->attrs[i].name == DW_AT_specification
19970               || die->attrs[i].name == DW_AT_abstract_origin)
19971             spec = &die->attrs[i];
19972         }
19973
19974       if (!spec)
19975         break;
19976
19977       die = follow_die_ref (die, spec, &cu);
19978     }
19979
19980   return NULL;
19981 }
19982
19983 /* Return the named attribute or NULL if not there,
19984    but do not follow DW_AT_specification, etc.
19985    This is for use in contexts where we're reading .debug_types dies.
19986    Following DW_AT_specification, DW_AT_abstract_origin will take us
19987    back up the chain, and we want to go down.  */
19988
19989 static struct attribute *
19990 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19991 {
19992   unsigned int i;
19993
19994   for (i = 0; i < die->num_attrs; ++i)
19995     if (die->attrs[i].name == name)
19996       return &die->attrs[i];
19997
19998   return NULL;
19999 }
20000
20001 /* Return the string associated with a string-typed attribute, or NULL if it
20002    is either not found or is of an incorrect type.  */
20003
20004 static const char *
20005 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20006 {
20007   struct attribute *attr;
20008   const char *str = NULL;
20009
20010   attr = dwarf2_attr (die, name, cu);
20011
20012   if (attr != NULL)
20013     {
20014       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20015           || attr->form == DW_FORM_string
20016           || attr->form == DW_FORM_GNU_str_index
20017           || attr->form == DW_FORM_GNU_strp_alt)
20018         str = DW_STRING (attr);
20019       else
20020         complaint (&symfile_complaints,
20021                    _("string type expected for attribute %s for "
20022                      "DIE at 0x%x in module %s"),
20023                    dwarf_attr_name (name), to_underlying (die->sect_off),
20024                    objfile_name (cu->dwarf2_per_objfile->objfile));
20025     }
20026
20027   return str;
20028 }
20029
20030 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20031    and holds a non-zero value.  This function should only be used for
20032    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20033
20034 static int
20035 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20036 {
20037   struct attribute *attr = dwarf2_attr (die, name, cu);
20038
20039   return (attr && DW_UNSND (attr));
20040 }
20041
20042 static int
20043 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20044 {
20045   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20046      which value is non-zero.  However, we have to be careful with
20047      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20048      (via dwarf2_flag_true_p) follows this attribute.  So we may
20049      end up accidently finding a declaration attribute that belongs
20050      to a different DIE referenced by the specification attribute,
20051      even though the given DIE does not have a declaration attribute.  */
20052   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20053           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20054 }
20055
20056 /* Return the die giving the specification for DIE, if there is
20057    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20058    containing the return value on output.  If there is no
20059    specification, but there is an abstract origin, that is
20060    returned.  */
20061
20062 static struct die_info *
20063 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20064 {
20065   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20066                                              *spec_cu);
20067
20068   if (spec_attr == NULL)
20069     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20070
20071   if (spec_attr == NULL)
20072     return NULL;
20073   else
20074     return follow_die_ref (die, spec_attr, spec_cu);
20075 }
20076
20077 /* Stub for free_line_header to match void * callback types.  */
20078
20079 static void
20080 free_line_header_voidp (void *arg)
20081 {
20082   struct line_header *lh = (struct line_header *) arg;
20083
20084   delete lh;
20085 }
20086
20087 void
20088 line_header::add_include_dir (const char *include_dir)
20089 {
20090   if (dwarf_line_debug >= 2)
20091     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20092                         include_dirs.size () + 1, include_dir);
20093
20094   include_dirs.push_back (include_dir);
20095 }
20096
20097 void
20098 line_header::add_file_name (const char *name,
20099                             dir_index d_index,
20100                             unsigned int mod_time,
20101                             unsigned int length)
20102 {
20103   if (dwarf_line_debug >= 2)
20104     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20105                         (unsigned) file_names.size () + 1, name);
20106
20107   file_names.emplace_back (name, d_index, mod_time, length);
20108 }
20109
20110 /* A convenience function to find the proper .debug_line section for a CU.  */
20111
20112 static struct dwarf2_section_info *
20113 get_debug_line_section (struct dwarf2_cu *cu)
20114 {
20115   struct dwarf2_section_info *section;
20116   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
20117
20118   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20119      DWO file.  */
20120   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20121     section = &cu->dwo_unit->dwo_file->sections.line;
20122   else if (cu->per_cu->is_dwz)
20123     {
20124       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20125
20126       section = &dwz->line;
20127     }
20128   else
20129     section = &dwarf2_per_objfile->line;
20130
20131   return section;
20132 }
20133
20134 /* Read directory or file name entry format, starting with byte of
20135    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20136    entries count and the entries themselves in the described entry
20137    format.  */
20138
20139 static void
20140 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20141                         bfd *abfd, const gdb_byte **bufp,
20142                         struct line_header *lh,
20143                         const struct comp_unit_head *cu_header,
20144                         void (*callback) (struct line_header *lh,
20145                                           const char *name,
20146                                           dir_index d_index,
20147                                           unsigned int mod_time,
20148                                           unsigned int length))
20149 {
20150   gdb_byte format_count, formati;
20151   ULONGEST data_count, datai;
20152   const gdb_byte *buf = *bufp;
20153   const gdb_byte *format_header_data;
20154   unsigned int bytes_read;
20155
20156   format_count = read_1_byte (abfd, buf);
20157   buf += 1;
20158   format_header_data = buf;
20159   for (formati = 0; formati < format_count; formati++)
20160     {
20161       read_unsigned_leb128 (abfd, buf, &bytes_read);
20162       buf += bytes_read;
20163       read_unsigned_leb128 (abfd, buf, &bytes_read);
20164       buf += bytes_read;
20165     }
20166
20167   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20168   buf += bytes_read;
20169   for (datai = 0; datai < data_count; datai++)
20170     {
20171       const gdb_byte *format = format_header_data;
20172       struct file_entry fe;
20173
20174       for (formati = 0; formati < format_count; formati++)
20175         {
20176           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20177           format += bytes_read;
20178
20179           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20180           format += bytes_read;
20181
20182           gdb::optional<const char *> string;
20183           gdb::optional<unsigned int> uint;
20184
20185           switch (form)
20186             {
20187             case DW_FORM_string:
20188               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20189               buf += bytes_read;
20190               break;
20191
20192             case DW_FORM_line_strp:
20193               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20194                                                          abfd, buf,
20195                                                          cu_header,
20196                                                          &bytes_read));
20197               buf += bytes_read;
20198               break;
20199
20200             case DW_FORM_data1:
20201               uint.emplace (read_1_byte (abfd, buf));
20202               buf += 1;
20203               break;
20204
20205             case DW_FORM_data2:
20206               uint.emplace (read_2_bytes (abfd, buf));
20207               buf += 2;
20208               break;
20209
20210             case DW_FORM_data4:
20211               uint.emplace (read_4_bytes (abfd, buf));
20212               buf += 4;
20213               break;
20214
20215             case DW_FORM_data8:
20216               uint.emplace (read_8_bytes (abfd, buf));
20217               buf += 8;
20218               break;
20219
20220             case DW_FORM_udata:
20221               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20222               buf += bytes_read;
20223               break;
20224
20225             case DW_FORM_block:
20226               /* It is valid only for DW_LNCT_timestamp which is ignored by
20227                  current GDB.  */
20228               break;
20229             }
20230
20231           switch (content_type)
20232             {
20233             case DW_LNCT_path:
20234               if (string.has_value ())
20235                 fe.name = *string;
20236               break;
20237             case DW_LNCT_directory_index:
20238               if (uint.has_value ())
20239                 fe.d_index = (dir_index) *uint;
20240               break;
20241             case DW_LNCT_timestamp:
20242               if (uint.has_value ())
20243                 fe.mod_time = *uint;
20244               break;
20245             case DW_LNCT_size:
20246               if (uint.has_value ())
20247                 fe.length = *uint;
20248               break;
20249             case DW_LNCT_MD5:
20250               break;
20251             default:
20252               complaint (&symfile_complaints,
20253                          _("Unknown format content type %s"),
20254                          pulongest (content_type));
20255             }
20256         }
20257
20258       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20259     }
20260
20261   *bufp = buf;
20262 }
20263
20264 /* Read the statement program header starting at OFFSET in
20265    .debug_line, or .debug_line.dwo.  Return a pointer
20266    to a struct line_header, allocated using xmalloc.
20267    Returns NULL if there is a problem reading the header, e.g., if it
20268    has a version we don't understand.
20269
20270    NOTE: the strings in the include directory and file name tables of
20271    the returned object point into the dwarf line section buffer,
20272    and must not be freed.  */
20273
20274 static line_header_up
20275 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20276 {
20277   const gdb_byte *line_ptr;
20278   unsigned int bytes_read, offset_size;
20279   int i;
20280   const char *cur_dir, *cur_file;
20281   struct dwarf2_section_info *section;
20282   bfd *abfd;
20283   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
20284
20285   section = get_debug_line_section (cu);
20286   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20287   if (section->buffer == NULL)
20288     {
20289       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20290         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20291       else
20292         complaint (&symfile_complaints, _("missing .debug_line section"));
20293       return 0;
20294     }
20295
20296   /* We can't do this until we know the section is non-empty.
20297      Only then do we know we have such a section.  */
20298   abfd = get_section_bfd_owner (section);
20299
20300   /* Make sure that at least there's room for the total_length field.
20301      That could be 12 bytes long, but we're just going to fudge that.  */
20302   if (to_underlying (sect_off) + 4 >= section->size)
20303     {
20304       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20305       return 0;
20306     }
20307
20308   line_header_up lh (new line_header ());
20309
20310   lh->sect_off = sect_off;
20311   lh->offset_in_dwz = cu->per_cu->is_dwz;
20312
20313   line_ptr = section->buffer + to_underlying (sect_off);
20314
20315   /* Read in the header.  */
20316   lh->total_length =
20317     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20318                                             &bytes_read, &offset_size);
20319   line_ptr += bytes_read;
20320   if (line_ptr + lh->total_length > (section->buffer + section->size))
20321     {
20322       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20323       return 0;
20324     }
20325   lh->statement_program_end = line_ptr + lh->total_length;
20326   lh->version = read_2_bytes (abfd, line_ptr);
20327   line_ptr += 2;
20328   if (lh->version > 5)
20329     {
20330       /* This is a version we don't understand.  The format could have
20331          changed in ways we don't handle properly so just punt.  */
20332       complaint (&symfile_complaints,
20333                  _("unsupported version in .debug_line section"));
20334       return NULL;
20335     }
20336   if (lh->version >= 5)
20337     {
20338       gdb_byte segment_selector_size;
20339
20340       /* Skip address size.  */
20341       read_1_byte (abfd, line_ptr);
20342       line_ptr += 1;
20343
20344       segment_selector_size = read_1_byte (abfd, line_ptr);
20345       line_ptr += 1;
20346       if (segment_selector_size != 0)
20347         {
20348           complaint (&symfile_complaints,
20349                      _("unsupported segment selector size %u "
20350                        "in .debug_line section"),
20351                      segment_selector_size);
20352           return NULL;
20353         }
20354     }
20355   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20356   line_ptr += offset_size;
20357   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20358   line_ptr += 1;
20359   if (lh->version >= 4)
20360     {
20361       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20362       line_ptr += 1;
20363     }
20364   else
20365     lh->maximum_ops_per_instruction = 1;
20366
20367   if (lh->maximum_ops_per_instruction == 0)
20368     {
20369       lh->maximum_ops_per_instruction = 1;
20370       complaint (&symfile_complaints,
20371                  _("invalid maximum_ops_per_instruction "
20372                    "in `.debug_line' section"));
20373     }
20374
20375   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20376   line_ptr += 1;
20377   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20378   line_ptr += 1;
20379   lh->line_range = read_1_byte (abfd, line_ptr);
20380   line_ptr += 1;
20381   lh->opcode_base = read_1_byte (abfd, line_ptr);
20382   line_ptr += 1;
20383   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20384
20385   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20386   for (i = 1; i < lh->opcode_base; ++i)
20387     {
20388       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20389       line_ptr += 1;
20390     }
20391
20392   if (lh->version >= 5)
20393     {
20394       /* Read directory table.  */
20395       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20396                               &cu->header,
20397                               [] (struct line_header *lh, const char *name,
20398                                   dir_index d_index, unsigned int mod_time,
20399                                   unsigned int length)
20400         {
20401           lh->add_include_dir (name);
20402         });
20403
20404       /* Read file name table.  */
20405       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20406                               &cu->header,
20407                               [] (struct line_header *lh, const char *name,
20408                                   dir_index d_index, unsigned int mod_time,
20409                                   unsigned int length)
20410         {
20411           lh->add_file_name (name, d_index, mod_time, length);
20412         });
20413     }
20414   else
20415     {
20416       /* Read directory table.  */
20417       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20418         {
20419           line_ptr += bytes_read;
20420           lh->add_include_dir (cur_dir);
20421         }
20422       line_ptr += bytes_read;
20423
20424       /* Read file name table.  */
20425       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20426         {
20427           unsigned int mod_time, length;
20428           dir_index d_index;
20429
20430           line_ptr += bytes_read;
20431           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20432           line_ptr += bytes_read;
20433           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20434           line_ptr += bytes_read;
20435           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20436           line_ptr += bytes_read;
20437
20438           lh->add_file_name (cur_file, d_index, mod_time, length);
20439         }
20440       line_ptr += bytes_read;
20441     }
20442   lh->statement_program_start = line_ptr;
20443
20444   if (line_ptr > (section->buffer + section->size))
20445     complaint (&symfile_complaints,
20446                _("line number info header doesn't "
20447                  "fit in `.debug_line' section"));
20448
20449   return lh;
20450 }
20451
20452 /* Subroutine of dwarf_decode_lines to simplify it.
20453    Return the file name of the psymtab for included file FILE_INDEX
20454    in line header LH of PST.
20455    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20456    If space for the result is malloc'd, it will be freed by a cleanup.
20457    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20458
20459    The function creates dangling cleanup registration.  */
20460
20461 static const char *
20462 psymtab_include_file_name (const struct line_header *lh, int file_index,
20463                            const struct partial_symtab *pst,
20464                            const char *comp_dir)
20465 {
20466   const file_entry &fe = lh->file_names[file_index];
20467   const char *include_name = fe.name;
20468   const char *include_name_to_compare = include_name;
20469   const char *pst_filename;
20470   char *copied_name = NULL;
20471   int file_is_pst;
20472
20473   const char *dir_name = fe.include_dir (lh);
20474
20475   if (!IS_ABSOLUTE_PATH (include_name)
20476       && (dir_name != NULL || comp_dir != NULL))
20477     {
20478       /* Avoid creating a duplicate psymtab for PST.
20479          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20480          Before we do the comparison, however, we need to account
20481          for DIR_NAME and COMP_DIR.
20482          First prepend dir_name (if non-NULL).  If we still don't
20483          have an absolute path prepend comp_dir (if non-NULL).
20484          However, the directory we record in the include-file's
20485          psymtab does not contain COMP_DIR (to match the
20486          corresponding symtab(s)).
20487
20488          Example:
20489
20490          bash$ cd /tmp
20491          bash$ gcc -g ./hello.c
20492          include_name = "hello.c"
20493          dir_name = "."
20494          DW_AT_comp_dir = comp_dir = "/tmp"
20495          DW_AT_name = "./hello.c"
20496
20497       */
20498
20499       if (dir_name != NULL)
20500         {
20501           char *tem = concat (dir_name, SLASH_STRING,
20502                               include_name, (char *)NULL);
20503
20504           make_cleanup (xfree, tem);
20505           include_name = tem;
20506           include_name_to_compare = include_name;
20507         }
20508       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20509         {
20510           char *tem = concat (comp_dir, SLASH_STRING,
20511                               include_name, (char *)NULL);
20512
20513           make_cleanup (xfree, tem);
20514           include_name_to_compare = tem;
20515         }
20516     }
20517
20518   pst_filename = pst->filename;
20519   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20520     {
20521       copied_name = concat (pst->dirname, SLASH_STRING,
20522                             pst_filename, (char *)NULL);
20523       pst_filename = copied_name;
20524     }
20525
20526   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20527
20528   if (copied_name != NULL)
20529     xfree (copied_name);
20530
20531   if (file_is_pst)
20532     return NULL;
20533   return include_name;
20534 }
20535
20536 /* State machine to track the state of the line number program.  */
20537
20538 class lnp_state_machine
20539 {
20540 public:
20541   /* Initialize a machine state for the start of a line number
20542      program.  */
20543   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20544
20545   file_entry *current_file ()
20546   {
20547     /* lh->file_names is 0-based, but the file name numbers in the
20548        statement program are 1-based.  */
20549     return m_line_header->file_name_at (m_file);
20550   }
20551
20552   /* Record the line in the state machine.  END_SEQUENCE is true if
20553      we're processing the end of a sequence.  */
20554   void record_line (bool end_sequence);
20555
20556   /* Check address and if invalid nop-out the rest of the lines in this
20557      sequence.  */
20558   void check_line_address (struct dwarf2_cu *cu,
20559                            const gdb_byte *line_ptr,
20560                            CORE_ADDR lowpc, CORE_ADDR address);
20561
20562   void handle_set_discriminator (unsigned int discriminator)
20563   {
20564     m_discriminator = discriminator;
20565     m_line_has_non_zero_discriminator |= discriminator != 0;
20566   }
20567
20568   /* Handle DW_LNE_set_address.  */
20569   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20570   {
20571     m_op_index = 0;
20572     address += baseaddr;
20573     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20574   }
20575
20576   /* Handle DW_LNS_advance_pc.  */
20577   void handle_advance_pc (CORE_ADDR adjust);
20578
20579   /* Handle a special opcode.  */
20580   void handle_special_opcode (unsigned char op_code);
20581
20582   /* Handle DW_LNS_advance_line.  */
20583   void handle_advance_line (int line_delta)
20584   {
20585     advance_line (line_delta);
20586   }
20587
20588   /* Handle DW_LNS_set_file.  */
20589   void handle_set_file (file_name_index file);
20590
20591   /* Handle DW_LNS_negate_stmt.  */
20592   void handle_negate_stmt ()
20593   {
20594     m_is_stmt = !m_is_stmt;
20595   }
20596
20597   /* Handle DW_LNS_const_add_pc.  */
20598   void handle_const_add_pc ();
20599
20600   /* Handle DW_LNS_fixed_advance_pc.  */
20601   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20602   {
20603     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20604     m_op_index = 0;
20605   }
20606
20607   /* Handle DW_LNS_copy.  */
20608   void handle_copy ()
20609   {
20610     record_line (false);
20611     m_discriminator = 0;
20612   }
20613
20614   /* Handle DW_LNE_end_sequence.  */
20615   void handle_end_sequence ()
20616   {
20617     m_record_line_callback = ::record_line;
20618   }
20619
20620 private:
20621   /* Advance the line by LINE_DELTA.  */
20622   void advance_line (int line_delta)
20623   {
20624     m_line += line_delta;
20625
20626     if (line_delta != 0)
20627       m_line_has_non_zero_discriminator = m_discriminator != 0;
20628   }
20629
20630   gdbarch *m_gdbarch;
20631
20632   /* True if we're recording lines.
20633      Otherwise we're building partial symtabs and are just interested in
20634      finding include files mentioned by the line number program.  */
20635   bool m_record_lines_p;
20636
20637   /* The line number header.  */
20638   line_header *m_line_header;
20639
20640   /* These are part of the standard DWARF line number state machine,
20641      and initialized according to the DWARF spec.  */
20642
20643   unsigned char m_op_index = 0;
20644   /* The line table index (1-based) of the current file.  */
20645   file_name_index m_file = (file_name_index) 1;
20646   unsigned int m_line = 1;
20647
20648   /* These are initialized in the constructor.  */
20649
20650   CORE_ADDR m_address;
20651   bool m_is_stmt;
20652   unsigned int m_discriminator;
20653
20654   /* Additional bits of state we need to track.  */
20655
20656   /* The last file that we called dwarf2_start_subfile for.
20657      This is only used for TLLs.  */
20658   unsigned int m_last_file = 0;
20659   /* The last file a line number was recorded for.  */
20660   struct subfile *m_last_subfile = NULL;
20661
20662   /* The function to call to record a line.  */
20663   record_line_ftype *m_record_line_callback = NULL;
20664
20665   /* The last line number that was recorded, used to coalesce
20666      consecutive entries for the same line.  This can happen, for
20667      example, when discriminators are present.  PR 17276.  */
20668   unsigned int m_last_line = 0;
20669   bool m_line_has_non_zero_discriminator = false;
20670 };
20671
20672 void
20673 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20674 {
20675   CORE_ADDR addr_adj = (((m_op_index + adjust)
20676                          / m_line_header->maximum_ops_per_instruction)
20677                         * m_line_header->minimum_instruction_length);
20678   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20679   m_op_index = ((m_op_index + adjust)
20680                 % m_line_header->maximum_ops_per_instruction);
20681 }
20682
20683 void
20684 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20685 {
20686   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20687   CORE_ADDR addr_adj = (((m_op_index
20688                           + (adj_opcode / m_line_header->line_range))
20689                          / m_line_header->maximum_ops_per_instruction)
20690                         * m_line_header->minimum_instruction_length);
20691   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20692   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20693                 % m_line_header->maximum_ops_per_instruction);
20694
20695   int line_delta = (m_line_header->line_base
20696                     + (adj_opcode % m_line_header->line_range));
20697   advance_line (line_delta);
20698   record_line (false);
20699   m_discriminator = 0;
20700 }
20701
20702 void
20703 lnp_state_machine::handle_set_file (file_name_index file)
20704 {
20705   m_file = file;
20706
20707   const file_entry *fe = current_file ();
20708   if (fe == NULL)
20709     dwarf2_debug_line_missing_file_complaint ();
20710   else if (m_record_lines_p)
20711     {
20712       const char *dir = fe->include_dir (m_line_header);
20713
20714       m_last_subfile = current_subfile;
20715       m_line_has_non_zero_discriminator = m_discriminator != 0;
20716       dwarf2_start_subfile (fe->name, dir);
20717     }
20718 }
20719
20720 void
20721 lnp_state_machine::handle_const_add_pc ()
20722 {
20723   CORE_ADDR adjust
20724     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20725
20726   CORE_ADDR addr_adj
20727     = (((m_op_index + adjust)
20728         / m_line_header->maximum_ops_per_instruction)
20729        * m_line_header->minimum_instruction_length);
20730
20731   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20732   m_op_index = ((m_op_index + adjust)
20733                 % m_line_header->maximum_ops_per_instruction);
20734 }
20735
20736 /* Ignore this record_line request.  */
20737
20738 static void
20739 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20740 {
20741   return;
20742 }
20743
20744 /* Return non-zero if we should add LINE to the line number table.
20745    LINE is the line to add, LAST_LINE is the last line that was added,
20746    LAST_SUBFILE is the subfile for LAST_LINE.
20747    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20748    had a non-zero discriminator.
20749
20750    We have to be careful in the presence of discriminators.
20751    E.g., for this line:
20752
20753      for (i = 0; i < 100000; i++);
20754
20755    clang can emit four line number entries for that one line,
20756    each with a different discriminator.
20757    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20758
20759    However, we want gdb to coalesce all four entries into one.
20760    Otherwise the user could stepi into the middle of the line and
20761    gdb would get confused about whether the pc really was in the
20762    middle of the line.
20763
20764    Things are further complicated by the fact that two consecutive
20765    line number entries for the same line is a heuristic used by gcc
20766    to denote the end of the prologue.  So we can't just discard duplicate
20767    entries, we have to be selective about it.  The heuristic we use is
20768    that we only collapse consecutive entries for the same line if at least
20769    one of those entries has a non-zero discriminator.  PR 17276.
20770
20771    Note: Addresses in the line number state machine can never go backwards
20772    within one sequence, thus this coalescing is ok.  */
20773
20774 static int
20775 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20776                      int line_has_non_zero_discriminator,
20777                      struct subfile *last_subfile)
20778 {
20779   if (current_subfile != last_subfile)
20780     return 1;
20781   if (line != last_line)
20782     return 1;
20783   /* Same line for the same file that we've seen already.
20784      As a last check, for pr 17276, only record the line if the line
20785      has never had a non-zero discriminator.  */
20786   if (!line_has_non_zero_discriminator)
20787     return 1;
20788   return 0;
20789 }
20790
20791 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20792    in the line table of subfile SUBFILE.  */
20793
20794 static void
20795 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20796                      unsigned int line, CORE_ADDR address,
20797                      record_line_ftype p_record_line)
20798 {
20799   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20800
20801   if (dwarf_line_debug)
20802     {
20803       fprintf_unfiltered (gdb_stdlog,
20804                           "Recording line %u, file %s, address %s\n",
20805                           line, lbasename (subfile->name),
20806                           paddress (gdbarch, address));
20807     }
20808
20809   (*p_record_line) (subfile, line, addr);
20810 }
20811
20812 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20813    Mark the end of a set of line number records.
20814    The arguments are the same as for dwarf_record_line_1.
20815    If SUBFILE is NULL the request is ignored.  */
20816
20817 static void
20818 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20819                    CORE_ADDR address, record_line_ftype p_record_line)
20820 {
20821   if (subfile == NULL)
20822     return;
20823
20824   if (dwarf_line_debug)
20825     {
20826       fprintf_unfiltered (gdb_stdlog,
20827                           "Finishing current line, file %s, address %s\n",
20828                           lbasename (subfile->name),
20829                           paddress (gdbarch, address));
20830     }
20831
20832   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20833 }
20834
20835 void
20836 lnp_state_machine::record_line (bool end_sequence)
20837 {
20838   if (dwarf_line_debug)
20839     {
20840       fprintf_unfiltered (gdb_stdlog,
20841                           "Processing actual line %u: file %u,"
20842                           " address %s, is_stmt %u, discrim %u\n",
20843                           m_line, to_underlying (m_file),
20844                           paddress (m_gdbarch, m_address),
20845                           m_is_stmt, m_discriminator);
20846     }
20847
20848   file_entry *fe = current_file ();
20849
20850   if (fe == NULL)
20851     dwarf2_debug_line_missing_file_complaint ();
20852   /* For now we ignore lines not starting on an instruction boundary.
20853      But not when processing end_sequence for compatibility with the
20854      previous version of the code.  */
20855   else if (m_op_index == 0 || end_sequence)
20856     {
20857       fe->included_p = 1;
20858       if (m_record_lines_p && m_is_stmt)
20859         {
20860           if (m_last_subfile != current_subfile || end_sequence)
20861             {
20862               dwarf_finish_line (m_gdbarch, m_last_subfile,
20863                                  m_address, m_record_line_callback);
20864             }
20865
20866           if (!end_sequence)
20867             {
20868               if (dwarf_record_line_p (m_line, m_last_line,
20869                                        m_line_has_non_zero_discriminator,
20870                                        m_last_subfile))
20871                 {
20872                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20873                                        m_line, m_address,
20874                                        m_record_line_callback);
20875                 }
20876               m_last_subfile = current_subfile;
20877               m_last_line = m_line;
20878             }
20879         }
20880     }
20881 }
20882
20883 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20884                                       bool record_lines_p)
20885 {
20886   m_gdbarch = arch;
20887   m_record_lines_p = record_lines_p;
20888   m_line_header = lh;
20889
20890   m_record_line_callback = ::record_line;
20891
20892   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20893      was a line entry for it so that the backend has a chance to adjust it
20894      and also record it in case it needs it.  This is currently used by MIPS
20895      code, cf. `mips_adjust_dwarf2_line'.  */
20896   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20897   m_is_stmt = lh->default_is_stmt;
20898   m_discriminator = 0;
20899 }
20900
20901 void
20902 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20903                                        const gdb_byte *line_ptr,
20904                                        CORE_ADDR lowpc, CORE_ADDR address)
20905 {
20906   /* If address < lowpc then it's not a usable value, it's outside the
20907      pc range of the CU.  However, we restrict the test to only address
20908      values of zero to preserve GDB's previous behaviour which is to
20909      handle the specific case of a function being GC'd by the linker.  */
20910
20911   if (address == 0 && address < lowpc)
20912     {
20913       /* This line table is for a function which has been
20914          GCd by the linker.  Ignore it.  PR gdb/12528 */
20915
20916       struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
20917       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20918
20919       complaint (&symfile_complaints,
20920                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20921                  line_offset, objfile_name (objfile));
20922       m_record_line_callback = noop_record_line;
20923       /* Note: record_line_callback is left as noop_record_line until
20924          we see DW_LNE_end_sequence.  */
20925     }
20926 }
20927
20928 /* Subroutine of dwarf_decode_lines to simplify it.
20929    Process the line number information in LH.
20930    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20931    program in order to set included_p for every referenced header.  */
20932
20933 static void
20934 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20935                       const int decode_for_pst_p, CORE_ADDR lowpc)
20936 {
20937   const gdb_byte *line_ptr, *extended_end;
20938   const gdb_byte *line_end;
20939   unsigned int bytes_read, extended_len;
20940   unsigned char op_code, extended_op;
20941   CORE_ADDR baseaddr;
20942   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
20943   bfd *abfd = objfile->obfd;
20944   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20945   /* True if we're recording line info (as opposed to building partial
20946      symtabs and just interested in finding include files mentioned by
20947      the line number program).  */
20948   bool record_lines_p = !decode_for_pst_p;
20949
20950   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20951
20952   line_ptr = lh->statement_program_start;
20953   line_end = lh->statement_program_end;
20954
20955   /* Read the statement sequences until there's nothing left.  */
20956   while (line_ptr < line_end)
20957     {
20958       /* The DWARF line number program state machine.  Reset the state
20959          machine at the start of each sequence.  */
20960       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20961       bool end_sequence = false;
20962
20963       if (record_lines_p)
20964         {
20965           /* Start a subfile for the current file of the state
20966              machine.  */
20967           const file_entry *fe = state_machine.current_file ();
20968
20969           if (fe != NULL)
20970             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20971         }
20972
20973       /* Decode the table.  */
20974       while (line_ptr < line_end && !end_sequence)
20975         {
20976           op_code = read_1_byte (abfd, line_ptr);
20977           line_ptr += 1;
20978
20979           if (op_code >= lh->opcode_base)
20980             {
20981               /* Special opcode.  */
20982               state_machine.handle_special_opcode (op_code);
20983             }
20984           else switch (op_code)
20985             {
20986             case DW_LNS_extended_op:
20987               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20988                                                    &bytes_read);
20989               line_ptr += bytes_read;
20990               extended_end = line_ptr + extended_len;
20991               extended_op = read_1_byte (abfd, line_ptr);
20992               line_ptr += 1;
20993               switch (extended_op)
20994                 {
20995                 case DW_LNE_end_sequence:
20996                   state_machine.handle_end_sequence ();
20997                   end_sequence = true;
20998                   break;
20999                 case DW_LNE_set_address:
21000                   {
21001                     CORE_ADDR address
21002                       = read_address (abfd, line_ptr, cu, &bytes_read);
21003                     line_ptr += bytes_read;
21004
21005                     state_machine.check_line_address (cu, line_ptr,
21006                                                       lowpc, address);
21007                     state_machine.handle_set_address (baseaddr, address);
21008                   }
21009                   break;
21010                 case DW_LNE_define_file:
21011                   {
21012                     const char *cur_file;
21013                     unsigned int mod_time, length;
21014                     dir_index dindex;
21015
21016                     cur_file = read_direct_string (abfd, line_ptr,
21017                                                    &bytes_read);
21018                     line_ptr += bytes_read;
21019                     dindex = (dir_index)
21020                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21021                     line_ptr += bytes_read;
21022                     mod_time =
21023                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21024                     line_ptr += bytes_read;
21025                     length =
21026                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21027                     line_ptr += bytes_read;
21028                     lh->add_file_name (cur_file, dindex, mod_time, length);
21029                   }
21030                   break;
21031                 case DW_LNE_set_discriminator:
21032                   {
21033                     /* The discriminator is not interesting to the
21034                        debugger; just ignore it.  We still need to
21035                        check its value though:
21036                        if there are consecutive entries for the same
21037                        (non-prologue) line we want to coalesce them.
21038                        PR 17276.  */
21039                     unsigned int discr
21040                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21041                     line_ptr += bytes_read;
21042
21043                     state_machine.handle_set_discriminator (discr);
21044                   }
21045                   break;
21046                 default:
21047                   complaint (&symfile_complaints,
21048                              _("mangled .debug_line section"));
21049                   return;
21050                 }
21051               /* Make sure that we parsed the extended op correctly.  If e.g.
21052                  we expected a different address size than the producer used,
21053                  we may have read the wrong number of bytes.  */
21054               if (line_ptr != extended_end)
21055                 {
21056                   complaint (&symfile_complaints,
21057                              _("mangled .debug_line section"));
21058                   return;
21059                 }
21060               break;
21061             case DW_LNS_copy:
21062               state_machine.handle_copy ();
21063               break;
21064             case DW_LNS_advance_pc:
21065               {
21066                 CORE_ADDR adjust
21067                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21068                 line_ptr += bytes_read;
21069
21070                 state_machine.handle_advance_pc (adjust);
21071               }
21072               break;
21073             case DW_LNS_advance_line:
21074               {
21075                 int line_delta
21076                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21077                 line_ptr += bytes_read;
21078
21079                 state_machine.handle_advance_line (line_delta);
21080               }
21081               break;
21082             case DW_LNS_set_file:
21083               {
21084                 file_name_index file
21085                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21086                                                             &bytes_read);
21087                 line_ptr += bytes_read;
21088
21089                 state_machine.handle_set_file (file);
21090               }
21091               break;
21092             case DW_LNS_set_column:
21093               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21094               line_ptr += bytes_read;
21095               break;
21096             case DW_LNS_negate_stmt:
21097               state_machine.handle_negate_stmt ();
21098               break;
21099             case DW_LNS_set_basic_block:
21100               break;
21101             /* Add to the address register of the state machine the
21102                address increment value corresponding to special opcode
21103                255.  I.e., this value is scaled by the minimum
21104                instruction length since special opcode 255 would have
21105                scaled the increment.  */
21106             case DW_LNS_const_add_pc:
21107               state_machine.handle_const_add_pc ();
21108               break;
21109             case DW_LNS_fixed_advance_pc:
21110               {
21111                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21112                 line_ptr += 2;
21113
21114                 state_machine.handle_fixed_advance_pc (addr_adj);
21115               }
21116               break;
21117             default:
21118               {
21119                 /* Unknown standard opcode, ignore it.  */
21120                 int i;
21121
21122                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21123                   {
21124                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21125                     line_ptr += bytes_read;
21126                   }
21127               }
21128             }
21129         }
21130
21131       if (!end_sequence)
21132         dwarf2_debug_line_missing_end_sequence_complaint ();
21133
21134       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21135          in which case we still finish recording the last line).  */
21136       state_machine.record_line (true);
21137     }
21138 }
21139
21140 /* Decode the Line Number Program (LNP) for the given line_header
21141    structure and CU.  The actual information extracted and the type
21142    of structures created from the LNP depends on the value of PST.
21143
21144    1. If PST is NULL, then this procedure uses the data from the program
21145       to create all necessary symbol tables, and their linetables.
21146
21147    2. If PST is not NULL, this procedure reads the program to determine
21148       the list of files included by the unit represented by PST, and
21149       builds all the associated partial symbol tables.
21150
21151    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21152    It is used for relative paths in the line table.
21153    NOTE: When processing partial symtabs (pst != NULL),
21154    comp_dir == pst->dirname.
21155
21156    NOTE: It is important that psymtabs have the same file name (via strcmp)
21157    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21158    symtab we don't use it in the name of the psymtabs we create.
21159    E.g. expand_line_sal requires this when finding psymtabs to expand.
21160    A good testcase for this is mb-inline.exp.
21161
21162    LOWPC is the lowest address in CU (or 0 if not known).
21163
21164    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21165    for its PC<->lines mapping information.  Otherwise only the filename
21166    table is read in.  */
21167
21168 static void
21169 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21170                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21171                     CORE_ADDR lowpc, int decode_mapping)
21172 {
21173   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21174   const int decode_for_pst_p = (pst != NULL);
21175
21176   if (decode_mapping)
21177     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21178
21179   if (decode_for_pst_p)
21180     {
21181       int file_index;
21182
21183       /* Now that we're done scanning the Line Header Program, we can
21184          create the psymtab of each included file.  */
21185       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21186         if (lh->file_names[file_index].included_p == 1)
21187           {
21188             const char *include_name =
21189               psymtab_include_file_name (lh, file_index, pst, comp_dir);
21190             if (include_name != NULL)
21191               dwarf2_create_include_psymtab (include_name, pst, objfile);
21192           }
21193     }
21194   else
21195     {
21196       /* Make sure a symtab is created for every file, even files
21197          which contain only variables (i.e. no code with associated
21198          line numbers).  */
21199       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21200       int i;
21201
21202       for (i = 0; i < lh->file_names.size (); i++)
21203         {
21204           file_entry &fe = lh->file_names[i];
21205
21206           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21207
21208           if (current_subfile->symtab == NULL)
21209             {
21210               current_subfile->symtab
21211                 = allocate_symtab (cust, current_subfile->name);
21212             }
21213           fe.symtab = current_subfile->symtab;
21214         }
21215     }
21216 }
21217
21218 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21219    DIRNAME the name of the source directory which contains FILENAME
21220    or NULL if not known.
21221    This routine tries to keep line numbers from identical absolute and
21222    relative file names in a common subfile.
21223
21224    Using the `list' example from the GDB testsuite, which resides in
21225    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21226    of /srcdir/list0.c yields the following debugging information for list0.c:
21227
21228    DW_AT_name:          /srcdir/list0.c
21229    DW_AT_comp_dir:      /compdir
21230    files.files[0].name: list0.h
21231    files.files[0].dir:  /srcdir
21232    files.files[1].name: list0.c
21233    files.files[1].dir:  /srcdir
21234
21235    The line number information for list0.c has to end up in a single
21236    subfile, so that `break /srcdir/list0.c:1' works as expected.
21237    start_subfile will ensure that this happens provided that we pass the
21238    concatenation of files.files[1].dir and files.files[1].name as the
21239    subfile's name.  */
21240
21241 static void
21242 dwarf2_start_subfile (const char *filename, const char *dirname)
21243 {
21244   char *copy = NULL;
21245
21246   /* In order not to lose the line information directory,
21247      we concatenate it to the filename when it makes sense.
21248      Note that the Dwarf3 standard says (speaking of filenames in line
21249      information): ``The directory index is ignored for file names
21250      that represent full path names''.  Thus ignoring dirname in the
21251      `else' branch below isn't an issue.  */
21252
21253   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21254     {
21255       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21256       filename = copy;
21257     }
21258
21259   start_subfile (filename);
21260
21261   if (copy != NULL)
21262     xfree (copy);
21263 }
21264
21265 /* Start a symtab for DWARF.
21266    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21267
21268 static struct compunit_symtab *
21269 dwarf2_start_symtab (struct dwarf2_cu *cu,
21270                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21271 {
21272   struct compunit_symtab *cust
21273     = start_symtab (cu->dwarf2_per_objfile->objfile, name, comp_dir, low_pc,
21274                     cu->language);
21275
21276   record_debugformat ("DWARF 2");
21277   record_producer (cu->producer);
21278
21279   /* We assume that we're processing GCC output.  */
21280   processing_gcc_compilation = 2;
21281
21282   cu->processing_has_namespace_info = 0;
21283
21284   return cust;
21285 }
21286
21287 static void
21288 var_decode_location (struct attribute *attr, struct symbol *sym,
21289                      struct dwarf2_cu *cu)
21290 {
21291   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21292   struct comp_unit_head *cu_header = &cu->header;
21293
21294   /* NOTE drow/2003-01-30: There used to be a comment and some special
21295      code here to turn a symbol with DW_AT_external and a
21296      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21297      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21298      with some versions of binutils) where shared libraries could have
21299      relocations against symbols in their debug information - the
21300      minimal symbol would have the right address, but the debug info
21301      would not.  It's no longer necessary, because we will explicitly
21302      apply relocations when we read in the debug information now.  */
21303
21304   /* A DW_AT_location attribute with no contents indicates that a
21305      variable has been optimized away.  */
21306   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21307     {
21308       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21309       return;
21310     }
21311
21312   /* Handle one degenerate form of location expression specially, to
21313      preserve GDB's previous behavior when section offsets are
21314      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21315      then mark this symbol as LOC_STATIC.  */
21316
21317   if (attr_form_is_block (attr)
21318       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21319            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21320           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21321               && (DW_BLOCK (attr)->size
21322                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21323     {
21324       unsigned int dummy;
21325
21326       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21327         SYMBOL_VALUE_ADDRESS (sym) =
21328           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21329       else
21330         SYMBOL_VALUE_ADDRESS (sym) =
21331           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21332       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21333       fixup_symbol_section (sym, objfile);
21334       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21335                                               SYMBOL_SECTION (sym));
21336       return;
21337     }
21338
21339   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21340      expression evaluator, and use LOC_COMPUTED only when necessary
21341      (i.e. when the value of a register or memory location is
21342      referenced, or a thread-local block, etc.).  Then again, it might
21343      not be worthwhile.  I'm assuming that it isn't unless performance
21344      or memory numbers show me otherwise.  */
21345
21346   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21347
21348   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21349     cu->has_loclist = 1;
21350 }
21351
21352 /* Given a pointer to a DWARF information entry, figure out if we need
21353    to make a symbol table entry for it, and if so, create a new entry
21354    and return a pointer to it.
21355    If TYPE is NULL, determine symbol type from the die, otherwise
21356    used the passed type.
21357    If SPACE is not NULL, use it to hold the new symbol.  If it is
21358    NULL, allocate a new symbol on the objfile's obstack.  */
21359
21360 static struct symbol *
21361 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21362                  struct symbol *space)
21363 {
21364   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
21365   struct objfile *objfile = dwarf2_per_objfile->objfile;
21366   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21367   struct symbol *sym = NULL;
21368   const char *name;
21369   struct attribute *attr = NULL;
21370   struct attribute *attr2 = NULL;
21371   CORE_ADDR baseaddr;
21372   struct pending **list_to_add = NULL;
21373
21374   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21375
21376   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21377
21378   name = dwarf2_name (die, cu);
21379   if (name)
21380     {
21381       const char *linkagename;
21382       int suppress_add = 0;
21383
21384       if (space)
21385         sym = space;
21386       else
21387         sym = allocate_symbol (objfile);
21388       OBJSTAT (objfile, n_syms++);
21389
21390       /* Cache this symbol's name and the name's demangled form (if any).  */
21391       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21392       linkagename = dwarf2_physname (name, die, cu);
21393       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21394
21395       /* Fortran does not have mangling standard and the mangling does differ
21396          between gfortran, iFort etc.  */
21397       if (cu->language == language_fortran
21398           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21399         symbol_set_demangled_name (&(sym->ginfo),
21400                                    dwarf2_full_name (name, die, cu),
21401                                    NULL);
21402
21403       /* Default assumptions.
21404          Use the passed type or decode it from the die.  */
21405       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21406       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21407       if (type != NULL)
21408         SYMBOL_TYPE (sym) = type;
21409       else
21410         SYMBOL_TYPE (sym) = die_type (die, cu);
21411       attr = dwarf2_attr (die,
21412                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21413                           cu);
21414       if (attr)
21415         {
21416           SYMBOL_LINE (sym) = DW_UNSND (attr);
21417         }
21418
21419       attr = dwarf2_attr (die,
21420                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21421                           cu);
21422       if (attr)
21423         {
21424           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21425           struct file_entry *fe;
21426
21427           if (cu->line_header != NULL)
21428             fe = cu->line_header->file_name_at (file_index);
21429           else
21430             fe = NULL;
21431
21432           if (fe == NULL)
21433             complaint (&symfile_complaints,
21434                        _("file index out of range"));
21435           else
21436             symbol_set_symtab (sym, fe->symtab);
21437         }
21438
21439       switch (die->tag)
21440         {
21441         case DW_TAG_label:
21442           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21443           if (attr)
21444             {
21445               CORE_ADDR addr;
21446
21447               addr = attr_value_as_address (attr);
21448               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21449               SYMBOL_VALUE_ADDRESS (sym) = addr;
21450             }
21451           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21452           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21453           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21454           add_symbol_to_list (sym, cu->list_in_scope);
21455           break;
21456         case DW_TAG_subprogram:
21457           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21458              finish_block.  */
21459           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21460           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21461           if ((attr2 && (DW_UNSND (attr2) != 0))
21462               || cu->language == language_ada)
21463             {
21464               /* Subprograms marked external are stored as a global symbol.
21465                  Ada subprograms, whether marked external or not, are always
21466                  stored as a global symbol, because we want to be able to
21467                  access them globally.  For instance, we want to be able
21468                  to break on a nested subprogram without having to
21469                  specify the context.  */
21470               list_to_add = &global_symbols;
21471             }
21472           else
21473             {
21474               list_to_add = cu->list_in_scope;
21475             }
21476           break;
21477         case DW_TAG_inlined_subroutine:
21478           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21479              finish_block.  */
21480           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21481           SYMBOL_INLINED (sym) = 1;
21482           list_to_add = cu->list_in_scope;
21483           break;
21484         case DW_TAG_template_value_param:
21485           suppress_add = 1;
21486           /* Fall through.  */
21487         case DW_TAG_constant:
21488         case DW_TAG_variable:
21489         case DW_TAG_member:
21490           /* Compilation with minimal debug info may result in
21491              variables with missing type entries.  Change the
21492              misleading `void' type to something sensible.  */
21493           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21494             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21495
21496           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21497           /* In the case of DW_TAG_member, we should only be called for
21498              static const members.  */
21499           if (die->tag == DW_TAG_member)
21500             {
21501               /* dwarf2_add_field uses die_is_declaration,
21502                  so we do the same.  */
21503               gdb_assert (die_is_declaration (die, cu));
21504               gdb_assert (attr);
21505             }
21506           if (attr)
21507             {
21508               dwarf2_const_value (attr, sym, cu);
21509               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21510               if (!suppress_add)
21511                 {
21512                   if (attr2 && (DW_UNSND (attr2) != 0))
21513                     list_to_add = &global_symbols;
21514                   else
21515                     list_to_add = cu->list_in_scope;
21516                 }
21517               break;
21518             }
21519           attr = dwarf2_attr (die, DW_AT_location, cu);
21520           if (attr)
21521             {
21522               var_decode_location (attr, sym, cu);
21523               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21524
21525               /* Fortran explicitly imports any global symbols to the local
21526                  scope by DW_TAG_common_block.  */
21527               if (cu->language == language_fortran && die->parent
21528                   && die->parent->tag == DW_TAG_common_block)
21529                 attr2 = NULL;
21530
21531               if (SYMBOL_CLASS (sym) == LOC_STATIC
21532                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21533                   && !dwarf2_per_objfile->has_section_at_zero)
21534                 {
21535                   /* When a static variable is eliminated by the linker,
21536                      the corresponding debug information is not stripped
21537                      out, but the variable address is set to null;
21538                      do not add such variables into symbol table.  */
21539                 }
21540               else if (attr2 && (DW_UNSND (attr2) != 0))
21541                 {
21542                   /* Workaround gfortran PR debug/40040 - it uses
21543                      DW_AT_location for variables in -fPIC libraries which may
21544                      get overriden by other libraries/executable and get
21545                      a different address.  Resolve it by the minimal symbol
21546                      which may come from inferior's executable using copy
21547                      relocation.  Make this workaround only for gfortran as for
21548                      other compilers GDB cannot guess the minimal symbol
21549                      Fortran mangling kind.  */
21550                   if (cu->language == language_fortran && die->parent
21551                       && die->parent->tag == DW_TAG_module
21552                       && cu->producer
21553                       && startswith (cu->producer, "GNU Fortran"))
21554                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21555
21556                   /* A variable with DW_AT_external is never static,
21557                      but it may be block-scoped.  */
21558                   list_to_add = (cu->list_in_scope == &file_symbols
21559                                  ? &global_symbols : cu->list_in_scope);
21560                 }
21561               else
21562                 list_to_add = cu->list_in_scope;
21563             }
21564           else
21565             {
21566               /* We do not know the address of this symbol.
21567                  If it is an external symbol and we have type information
21568                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21569                  The address of the variable will then be determined from
21570                  the minimal symbol table whenever the variable is
21571                  referenced.  */
21572               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21573
21574               /* Fortran explicitly imports any global symbols to the local
21575                  scope by DW_TAG_common_block.  */
21576               if (cu->language == language_fortran && die->parent
21577                   && die->parent->tag == DW_TAG_common_block)
21578                 {
21579                   /* SYMBOL_CLASS doesn't matter here because
21580                      read_common_block is going to reset it.  */
21581                   if (!suppress_add)
21582                     list_to_add = cu->list_in_scope;
21583                 }
21584               else if (attr2 && (DW_UNSND (attr2) != 0)
21585                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21586                 {
21587                   /* A variable with DW_AT_external is never static, but it
21588                      may be block-scoped.  */
21589                   list_to_add = (cu->list_in_scope == &file_symbols
21590                                  ? &global_symbols : cu->list_in_scope);
21591
21592                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21593                 }
21594               else if (!die_is_declaration (die, cu))
21595                 {
21596                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21597                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21598                   if (!suppress_add)
21599                     list_to_add = cu->list_in_scope;
21600                 }
21601             }
21602           break;
21603         case DW_TAG_formal_parameter:
21604           /* If we are inside a function, mark this as an argument.  If
21605              not, we might be looking at an argument to an inlined function
21606              when we do not have enough information to show inlined frames;
21607              pretend it's a local variable in that case so that the user can
21608              still see it.  */
21609           if (context_stack_depth > 0
21610               && context_stack[context_stack_depth - 1].name != NULL)
21611             SYMBOL_IS_ARGUMENT (sym) = 1;
21612           attr = dwarf2_attr (die, DW_AT_location, cu);
21613           if (attr)
21614             {
21615               var_decode_location (attr, sym, cu);
21616             }
21617           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21618           if (attr)
21619             {
21620               dwarf2_const_value (attr, sym, cu);
21621             }
21622
21623           list_to_add = cu->list_in_scope;
21624           break;
21625         case DW_TAG_unspecified_parameters:
21626           /* From varargs functions; gdb doesn't seem to have any
21627              interest in this information, so just ignore it for now.
21628              (FIXME?) */
21629           break;
21630         case DW_TAG_template_type_param:
21631           suppress_add = 1;
21632           /* Fall through.  */
21633         case DW_TAG_class_type:
21634         case DW_TAG_interface_type:
21635         case DW_TAG_structure_type:
21636         case DW_TAG_union_type:
21637         case DW_TAG_set_type:
21638         case DW_TAG_enumeration_type:
21639           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21640           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21641
21642           {
21643             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21644                really ever be static objects: otherwise, if you try
21645                to, say, break of a class's method and you're in a file
21646                which doesn't mention that class, it won't work unless
21647                the check for all static symbols in lookup_symbol_aux
21648                saves you.  See the OtherFileClass tests in
21649                gdb.c++/namespace.exp.  */
21650
21651             if (!suppress_add)
21652               {
21653                 list_to_add = (cu->list_in_scope == &file_symbols
21654                                && cu->language == language_cplus
21655                                ? &global_symbols : cu->list_in_scope);
21656
21657                 /* The semantics of C++ state that "struct foo {
21658                    ... }" also defines a typedef for "foo".  */
21659                 if (cu->language == language_cplus
21660                     || cu->language == language_ada
21661                     || cu->language == language_d
21662                     || cu->language == language_rust)
21663                   {
21664                     /* The symbol's name is already allocated along
21665                        with this objfile, so we don't need to
21666                        duplicate it for the type.  */
21667                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21668                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21669                   }
21670               }
21671           }
21672           break;
21673         case DW_TAG_typedef:
21674           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21675           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21676           list_to_add = cu->list_in_scope;
21677           break;
21678         case DW_TAG_base_type:
21679         case DW_TAG_subrange_type:
21680           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21681           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21682           list_to_add = cu->list_in_scope;
21683           break;
21684         case DW_TAG_enumerator:
21685           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21686           if (attr)
21687             {
21688               dwarf2_const_value (attr, sym, cu);
21689             }
21690           {
21691             /* NOTE: carlton/2003-11-10: See comment above in the
21692                DW_TAG_class_type, etc. block.  */
21693
21694             list_to_add = (cu->list_in_scope == &file_symbols
21695                            && cu->language == language_cplus
21696                            ? &global_symbols : cu->list_in_scope);
21697           }
21698           break;
21699         case DW_TAG_imported_declaration:
21700         case DW_TAG_namespace:
21701           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21702           list_to_add = &global_symbols;
21703           break;
21704         case DW_TAG_module:
21705           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21706           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21707           list_to_add = &global_symbols;
21708           break;
21709         case DW_TAG_common_block:
21710           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21711           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21712           add_symbol_to_list (sym, cu->list_in_scope);
21713           break;
21714         default:
21715           /* Not a tag we recognize.  Hopefully we aren't processing
21716              trash data, but since we must specifically ignore things
21717              we don't recognize, there is nothing else we should do at
21718              this point.  */
21719           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21720                      dwarf_tag_name (die->tag));
21721           break;
21722         }
21723
21724       if (suppress_add)
21725         {
21726           sym->hash_next = objfile->template_symbols;
21727           objfile->template_symbols = sym;
21728           list_to_add = NULL;
21729         }
21730
21731       if (list_to_add != NULL)
21732         add_symbol_to_list (sym, list_to_add);
21733
21734       /* For the benefit of old versions of GCC, check for anonymous
21735          namespaces based on the demangled name.  */
21736       if (!cu->processing_has_namespace_info
21737           && cu->language == language_cplus)
21738         cp_scan_for_anonymous_namespaces (sym, objfile);
21739     }
21740   return (sym);
21741 }
21742
21743 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
21744
21745 static struct symbol *
21746 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21747 {
21748   return new_symbol_full (die, type, cu, NULL);
21749 }
21750
21751 /* Given an attr with a DW_FORM_dataN value in host byte order,
21752    zero-extend it as appropriate for the symbol's type.  The DWARF
21753    standard (v4) is not entirely clear about the meaning of using
21754    DW_FORM_dataN for a constant with a signed type, where the type is
21755    wider than the data.  The conclusion of a discussion on the DWARF
21756    list was that this is unspecified.  We choose to always zero-extend
21757    because that is the interpretation long in use by GCC.  */
21758
21759 static gdb_byte *
21760 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21761                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21762 {
21763   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21764   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21765                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21766   LONGEST l = DW_UNSND (attr);
21767
21768   if (bits < sizeof (*value) * 8)
21769     {
21770       l &= ((LONGEST) 1 << bits) - 1;
21771       *value = l;
21772     }
21773   else if (bits == sizeof (*value) * 8)
21774     *value = l;
21775   else
21776     {
21777       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21778       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21779       return bytes;
21780     }
21781
21782   return NULL;
21783 }
21784
21785 /* Read a constant value from an attribute.  Either set *VALUE, or if
21786    the value does not fit in *VALUE, set *BYTES - either already
21787    allocated on the objfile obstack, or newly allocated on OBSTACK,
21788    or, set *BATON, if we translated the constant to a location
21789    expression.  */
21790
21791 static void
21792 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21793                          const char *name, struct obstack *obstack,
21794                          struct dwarf2_cu *cu,
21795                          LONGEST *value, const gdb_byte **bytes,
21796                          struct dwarf2_locexpr_baton **baton)
21797 {
21798   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21799   struct comp_unit_head *cu_header = &cu->header;
21800   struct dwarf_block *blk;
21801   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21802                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21803
21804   *value = 0;
21805   *bytes = NULL;
21806   *baton = NULL;
21807
21808   switch (attr->form)
21809     {
21810     case DW_FORM_addr:
21811     case DW_FORM_GNU_addr_index:
21812       {
21813         gdb_byte *data;
21814
21815         if (TYPE_LENGTH (type) != cu_header->addr_size)
21816           dwarf2_const_value_length_mismatch_complaint (name,
21817                                                         cu_header->addr_size,
21818                                                         TYPE_LENGTH (type));
21819         /* Symbols of this form are reasonably rare, so we just
21820            piggyback on the existing location code rather than writing
21821            a new implementation of symbol_computed_ops.  */
21822         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21823         (*baton)->per_cu = cu->per_cu;
21824         gdb_assert ((*baton)->per_cu);
21825
21826         (*baton)->size = 2 + cu_header->addr_size;
21827         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21828         (*baton)->data = data;
21829
21830         data[0] = DW_OP_addr;
21831         store_unsigned_integer (&data[1], cu_header->addr_size,
21832                                 byte_order, DW_ADDR (attr));
21833         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21834       }
21835       break;
21836     case DW_FORM_string:
21837     case DW_FORM_strp:
21838     case DW_FORM_GNU_str_index:
21839     case DW_FORM_GNU_strp_alt:
21840       /* DW_STRING is already allocated on the objfile obstack, point
21841          directly to it.  */
21842       *bytes = (const gdb_byte *) DW_STRING (attr);
21843       break;
21844     case DW_FORM_block1:
21845     case DW_FORM_block2:
21846     case DW_FORM_block4:
21847     case DW_FORM_block:
21848     case DW_FORM_exprloc:
21849     case DW_FORM_data16:
21850       blk = DW_BLOCK (attr);
21851       if (TYPE_LENGTH (type) != blk->size)
21852         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21853                                                       TYPE_LENGTH (type));
21854       *bytes = blk->data;
21855       break;
21856
21857       /* The DW_AT_const_value attributes are supposed to carry the
21858          symbol's value "represented as it would be on the target
21859          architecture."  By the time we get here, it's already been
21860          converted to host endianness, so we just need to sign- or
21861          zero-extend it as appropriate.  */
21862     case DW_FORM_data1:
21863       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21864       break;
21865     case DW_FORM_data2:
21866       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21867       break;
21868     case DW_FORM_data4:
21869       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21870       break;
21871     case DW_FORM_data8:
21872       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21873       break;
21874
21875     case DW_FORM_sdata:
21876     case DW_FORM_implicit_const:
21877       *value = DW_SND (attr);
21878       break;
21879
21880     case DW_FORM_udata:
21881       *value = DW_UNSND (attr);
21882       break;
21883
21884     default:
21885       complaint (&symfile_complaints,
21886                  _("unsupported const value attribute form: '%s'"),
21887                  dwarf_form_name (attr->form));
21888       *value = 0;
21889       break;
21890     }
21891 }
21892
21893
21894 /* Copy constant value from an attribute to a symbol.  */
21895
21896 static void
21897 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21898                     struct dwarf2_cu *cu)
21899 {
21900   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
21901   LONGEST value;
21902   const gdb_byte *bytes;
21903   struct dwarf2_locexpr_baton *baton;
21904
21905   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21906                            SYMBOL_PRINT_NAME (sym),
21907                            &objfile->objfile_obstack, cu,
21908                            &value, &bytes, &baton);
21909
21910   if (baton != NULL)
21911     {
21912       SYMBOL_LOCATION_BATON (sym) = baton;
21913       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21914     }
21915   else if (bytes != NULL)
21916      {
21917       SYMBOL_VALUE_BYTES (sym) = bytes;
21918       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21919     }
21920   else
21921     {
21922       SYMBOL_VALUE (sym) = value;
21923       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21924     }
21925 }
21926
21927 /* Return the type of the die in question using its DW_AT_type attribute.  */
21928
21929 static struct type *
21930 die_type (struct die_info *die, struct dwarf2_cu *cu)
21931 {
21932   struct attribute *type_attr;
21933
21934   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21935   if (!type_attr)
21936     {
21937       /* A missing DW_AT_type represents a void type.  */
21938       return objfile_type (cu->dwarf2_per_objfile->objfile)->builtin_void;
21939     }
21940
21941   return lookup_die_type (die, type_attr, cu);
21942 }
21943
21944 /* True iff CU's producer generates GNAT Ada auxiliary information
21945    that allows to find parallel types through that information instead
21946    of having to do expensive parallel lookups by type name.  */
21947
21948 static int
21949 need_gnat_info (struct dwarf2_cu *cu)
21950 {
21951   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21952      of GNAT produces this auxiliary information, without any indication
21953      that it is produced.  Part of enhancing the FSF version of GNAT
21954      to produce that information will be to put in place an indicator
21955      that we can use in order to determine whether the descriptive type
21956      info is available or not.  One suggestion that has been made is
21957      to use a new attribute, attached to the CU die.  For now, assume
21958      that the descriptive type info is not available.  */
21959   return 0;
21960 }
21961
21962 /* Return the auxiliary type of the die in question using its
21963    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21964    attribute is not present.  */
21965
21966 static struct type *
21967 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21968 {
21969   struct attribute *type_attr;
21970
21971   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21972   if (!type_attr)
21973     return NULL;
21974
21975   return lookup_die_type (die, type_attr, cu);
21976 }
21977
21978 /* If DIE has a descriptive_type attribute, then set the TYPE's
21979    descriptive type accordingly.  */
21980
21981 static void
21982 set_descriptive_type (struct type *type, struct die_info *die,
21983                       struct dwarf2_cu *cu)
21984 {
21985   struct type *descriptive_type = die_descriptive_type (die, cu);
21986
21987   if (descriptive_type)
21988     {
21989       ALLOCATE_GNAT_AUX_TYPE (type);
21990       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21991     }
21992 }
21993
21994 /* Return the containing type of the die in question using its
21995    DW_AT_containing_type attribute.  */
21996
21997 static struct type *
21998 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21999 {
22000   struct attribute *type_attr;
22001
22002   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22003   if (!type_attr)
22004     error (_("Dwarf Error: Problem turning containing type into gdb type "
22005              "[in module %s]"), objfile_name (cu->dwarf2_per_objfile->objfile));
22006
22007   return lookup_die_type (die, type_attr, cu);
22008 }
22009
22010 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22011
22012 static struct type *
22013 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22014 {
22015   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
22016   struct objfile *objfile = dwarf2_per_objfile->objfile;
22017   char *message, *saved;
22018
22019   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
22020                         objfile_name (objfile),
22021                         to_underlying (cu->header.sect_off),
22022                         to_underlying (die->sect_off));
22023   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22024                                   message, strlen (message));
22025   xfree (message);
22026
22027   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22028 }
22029
22030 /* Look up the type of DIE in CU using its type attribute ATTR.
22031    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22032    DW_AT_containing_type.
22033    If there is no type substitute an error marker.  */
22034
22035 static struct type *
22036 lookup_die_type (struct die_info *die, const struct attribute *attr,
22037                  struct dwarf2_cu *cu)
22038 {
22039   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
22040   struct objfile *objfile = dwarf2_per_objfile->objfile;
22041   struct type *this_type;
22042
22043   gdb_assert (attr->name == DW_AT_type
22044               || attr->name == DW_AT_GNAT_descriptive_type
22045               || attr->name == DW_AT_containing_type);
22046
22047   /* First see if we have it cached.  */
22048
22049   if (attr->form == DW_FORM_GNU_ref_alt)
22050     {
22051       struct dwarf2_per_cu_data *per_cu;
22052       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22053
22054       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22055                                                  dwarf2_per_objfile);
22056       this_type = get_die_type_at_offset (sect_off, per_cu);
22057     }
22058   else if (attr_form_is_ref (attr))
22059     {
22060       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22061
22062       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22063     }
22064   else if (attr->form == DW_FORM_ref_sig8)
22065     {
22066       ULONGEST signature = DW_SIGNATURE (attr);
22067
22068       return get_signatured_type (die, signature, cu);
22069     }
22070   else
22071     {
22072       complaint (&symfile_complaints,
22073                  _("Dwarf Error: Bad type attribute %s in DIE"
22074                    " at 0x%x [in module %s]"),
22075                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
22076                  objfile_name (objfile));
22077       return build_error_marker_type (cu, die);
22078     }
22079
22080   /* If not cached we need to read it in.  */
22081
22082   if (this_type == NULL)
22083     {
22084       struct die_info *type_die = NULL;
22085       struct dwarf2_cu *type_cu = cu;
22086
22087       if (attr_form_is_ref (attr))
22088         type_die = follow_die_ref (die, attr, &type_cu);
22089       if (type_die == NULL)
22090         return build_error_marker_type (cu, die);
22091       /* If we find the type now, it's probably because the type came
22092          from an inter-CU reference and the type's CU got expanded before
22093          ours.  */
22094       this_type = read_type_die (type_die, type_cu);
22095     }
22096
22097   /* If we still don't have a type use an error marker.  */
22098
22099   if (this_type == NULL)
22100     return build_error_marker_type (cu, die);
22101
22102   return this_type;
22103 }
22104
22105 /* Return the type in DIE, CU.
22106    Returns NULL for invalid types.
22107
22108    This first does a lookup in die_type_hash,
22109    and only reads the die in if necessary.
22110
22111    NOTE: This can be called when reading in partial or full symbols.  */
22112
22113 static struct type *
22114 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22115 {
22116   struct type *this_type;
22117
22118   this_type = get_die_type (die, cu);
22119   if (this_type)
22120     return this_type;
22121
22122   return read_type_die_1 (die, cu);
22123 }
22124
22125 /* Read the type in DIE, CU.
22126    Returns NULL for invalid types.  */
22127
22128 static struct type *
22129 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22130 {
22131   struct type *this_type = NULL;
22132
22133   switch (die->tag)
22134     {
22135     case DW_TAG_class_type:
22136     case DW_TAG_interface_type:
22137     case DW_TAG_structure_type:
22138     case DW_TAG_union_type:
22139       this_type = read_structure_type (die, cu);
22140       break;
22141     case DW_TAG_enumeration_type:
22142       this_type = read_enumeration_type (die, cu);
22143       break;
22144     case DW_TAG_subprogram:
22145     case DW_TAG_subroutine_type:
22146     case DW_TAG_inlined_subroutine:
22147       this_type = read_subroutine_type (die, cu);
22148       break;
22149     case DW_TAG_array_type:
22150       this_type = read_array_type (die, cu);
22151       break;
22152     case DW_TAG_set_type:
22153       this_type = read_set_type (die, cu);
22154       break;
22155     case DW_TAG_pointer_type:
22156       this_type = read_tag_pointer_type (die, cu);
22157       break;
22158     case DW_TAG_ptr_to_member_type:
22159       this_type = read_tag_ptr_to_member_type (die, cu);
22160       break;
22161     case DW_TAG_reference_type:
22162       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22163       break;
22164     case DW_TAG_rvalue_reference_type:
22165       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22166       break;
22167     case DW_TAG_const_type:
22168       this_type = read_tag_const_type (die, cu);
22169       break;
22170     case DW_TAG_volatile_type:
22171       this_type = read_tag_volatile_type (die, cu);
22172       break;
22173     case DW_TAG_restrict_type:
22174       this_type = read_tag_restrict_type (die, cu);
22175       break;
22176     case DW_TAG_string_type:
22177       this_type = read_tag_string_type (die, cu);
22178       break;
22179     case DW_TAG_typedef:
22180       this_type = read_typedef (die, cu);
22181       break;
22182     case DW_TAG_subrange_type:
22183       this_type = read_subrange_type (die, cu);
22184       break;
22185     case DW_TAG_base_type:
22186       this_type = read_base_type (die, cu);
22187       break;
22188     case DW_TAG_unspecified_type:
22189       this_type = read_unspecified_type (die, cu);
22190       break;
22191     case DW_TAG_namespace:
22192       this_type = read_namespace_type (die, cu);
22193       break;
22194     case DW_TAG_module:
22195       this_type = read_module_type (die, cu);
22196       break;
22197     case DW_TAG_atomic_type:
22198       this_type = read_tag_atomic_type (die, cu);
22199       break;
22200     default:
22201       complaint (&symfile_complaints,
22202                  _("unexpected tag in read_type_die: '%s'"),
22203                  dwarf_tag_name (die->tag));
22204       break;
22205     }
22206
22207   return this_type;
22208 }
22209
22210 /* See if we can figure out if the class lives in a namespace.  We do
22211    this by looking for a member function; its demangled name will
22212    contain namespace info, if there is any.
22213    Return the computed name or NULL.
22214    Space for the result is allocated on the objfile's obstack.
22215    This is the full-die version of guess_partial_die_structure_name.
22216    In this case we know DIE has no useful parent.  */
22217
22218 static char *
22219 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22220 {
22221   struct die_info *spec_die;
22222   struct dwarf2_cu *spec_cu;
22223   struct die_info *child;
22224   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22225
22226   spec_cu = cu;
22227   spec_die = die_specification (die, &spec_cu);
22228   if (spec_die != NULL)
22229     {
22230       die = spec_die;
22231       cu = spec_cu;
22232     }
22233
22234   for (child = die->child;
22235        child != NULL;
22236        child = child->sibling)
22237     {
22238       if (child->tag == DW_TAG_subprogram)
22239         {
22240           const char *linkage_name = dw2_linkage_name (child, cu);
22241
22242           if (linkage_name != NULL)
22243             {
22244               char *actual_name
22245                 = language_class_name_from_physname (cu->language_defn,
22246                                                      linkage_name);
22247               char *name = NULL;
22248
22249               if (actual_name != NULL)
22250                 {
22251                   const char *die_name = dwarf2_name (die, cu);
22252
22253                   if (die_name != NULL
22254                       && strcmp (die_name, actual_name) != 0)
22255                     {
22256                       /* Strip off the class name from the full name.
22257                          We want the prefix.  */
22258                       int die_name_len = strlen (die_name);
22259                       int actual_name_len = strlen (actual_name);
22260
22261                       /* Test for '::' as a sanity check.  */
22262                       if (actual_name_len > die_name_len + 2
22263                           && actual_name[actual_name_len
22264                                          - die_name_len - 1] == ':')
22265                         name = (char *) obstack_copy0 (
22266                           &objfile->per_bfd->storage_obstack,
22267                           actual_name, actual_name_len - die_name_len - 2);
22268                     }
22269                 }
22270               xfree (actual_name);
22271               return name;
22272             }
22273         }
22274     }
22275
22276   return NULL;
22277 }
22278
22279 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22280    prefix part in such case.  See
22281    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22282
22283 static const char *
22284 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22285 {
22286   struct attribute *attr;
22287   const char *base;
22288
22289   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22290       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22291     return NULL;
22292
22293   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22294     return NULL;
22295
22296   attr = dw2_linkage_name_attr (die, cu);
22297   if (attr == NULL || DW_STRING (attr) == NULL)
22298     return NULL;
22299
22300   /* dwarf2_name had to be already called.  */
22301   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22302
22303   /* Strip the base name, keep any leading namespaces/classes.  */
22304   base = strrchr (DW_STRING (attr), ':');
22305   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22306     return "";
22307
22308   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22309   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22310                                  DW_STRING (attr),
22311                                  &base[-1] - DW_STRING (attr));
22312 }
22313
22314 /* Return the name of the namespace/class that DIE is defined within,
22315    or "" if we can't tell.  The caller should not xfree the result.
22316
22317    For example, if we're within the method foo() in the following
22318    code:
22319
22320    namespace N {
22321      class C {
22322        void foo () {
22323        }
22324      };
22325    }
22326
22327    then determine_prefix on foo's die will return "N::C".  */
22328
22329 static const char *
22330 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22331 {
22332   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
22333   struct die_info *parent, *spec_die;
22334   struct dwarf2_cu *spec_cu;
22335   struct type *parent_type;
22336   const char *retval;
22337
22338   if (cu->language != language_cplus
22339       && cu->language != language_fortran && cu->language != language_d
22340       && cu->language != language_rust)
22341     return "";
22342
22343   retval = anonymous_struct_prefix (die, cu);
22344   if (retval)
22345     return retval;
22346
22347   /* We have to be careful in the presence of DW_AT_specification.
22348      For example, with GCC 3.4, given the code
22349
22350      namespace N {
22351        void foo() {
22352          // Definition of N::foo.
22353        }
22354      }
22355
22356      then we'll have a tree of DIEs like this:
22357
22358      1: DW_TAG_compile_unit
22359        2: DW_TAG_namespace        // N
22360          3: DW_TAG_subprogram     // declaration of N::foo
22361        4: DW_TAG_subprogram       // definition of N::foo
22362             DW_AT_specification   // refers to die #3
22363
22364      Thus, when processing die #4, we have to pretend that we're in
22365      the context of its DW_AT_specification, namely the contex of die
22366      #3.  */
22367   spec_cu = cu;
22368   spec_die = die_specification (die, &spec_cu);
22369   if (spec_die == NULL)
22370     parent = die->parent;
22371   else
22372     {
22373       parent = spec_die->parent;
22374       cu = spec_cu;
22375     }
22376
22377   if (parent == NULL)
22378     return "";
22379   else if (parent->building_fullname)
22380     {
22381       const char *name;
22382       const char *parent_name;
22383
22384       /* It has been seen on RealView 2.2 built binaries,
22385          DW_TAG_template_type_param types actually _defined_ as
22386          children of the parent class:
22387
22388          enum E {};
22389          template class <class Enum> Class{};
22390          Class<enum E> class_e;
22391
22392          1: DW_TAG_class_type (Class)
22393            2: DW_TAG_enumeration_type (E)
22394              3: DW_TAG_enumerator (enum1:0)
22395              3: DW_TAG_enumerator (enum2:1)
22396              ...
22397            2: DW_TAG_template_type_param
22398               DW_AT_type  DW_FORM_ref_udata (E)
22399
22400          Besides being broken debug info, it can put GDB into an
22401          infinite loop.  Consider:
22402
22403          When we're building the full name for Class<E>, we'll start
22404          at Class, and go look over its template type parameters,
22405          finding E.  We'll then try to build the full name of E, and
22406          reach here.  We're now trying to build the full name of E,
22407          and look over the parent DIE for containing scope.  In the
22408          broken case, if we followed the parent DIE of E, we'd again
22409          find Class, and once again go look at its template type
22410          arguments, etc., etc.  Simply don't consider such parent die
22411          as source-level parent of this die (it can't be, the language
22412          doesn't allow it), and break the loop here.  */
22413       name = dwarf2_name (die, cu);
22414       parent_name = dwarf2_name (parent, cu);
22415       complaint (&symfile_complaints,
22416                  _("template param type '%s' defined within parent '%s'"),
22417                  name ? name : "<unknown>",
22418                  parent_name ? parent_name : "<unknown>");
22419       return "";
22420     }
22421   else
22422     switch (parent->tag)
22423       {
22424       case DW_TAG_namespace:
22425         parent_type = read_type_die (parent, cu);
22426         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22427            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22428            Work around this problem here.  */
22429         if (cu->language == language_cplus
22430             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22431           return "";
22432         /* We give a name to even anonymous namespaces.  */
22433         return TYPE_TAG_NAME (parent_type);
22434       case DW_TAG_class_type:
22435       case DW_TAG_interface_type:
22436       case DW_TAG_structure_type:
22437       case DW_TAG_union_type:
22438       case DW_TAG_module:
22439         parent_type = read_type_die (parent, cu);
22440         if (TYPE_TAG_NAME (parent_type) != NULL)
22441           return TYPE_TAG_NAME (parent_type);
22442         else
22443           /* An anonymous structure is only allowed non-static data
22444              members; no typedefs, no member functions, et cetera.
22445              So it does not need a prefix.  */
22446           return "";
22447       case DW_TAG_compile_unit:
22448       case DW_TAG_partial_unit:
22449         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22450         if (cu->language == language_cplus
22451             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22452             && die->child != NULL
22453             && (die->tag == DW_TAG_class_type
22454                 || die->tag == DW_TAG_structure_type
22455                 || die->tag == DW_TAG_union_type))
22456           {
22457             char *name = guess_full_die_structure_name (die, cu);
22458             if (name != NULL)
22459               return name;
22460           }
22461         return "";
22462       case DW_TAG_enumeration_type:
22463         parent_type = read_type_die (parent, cu);
22464         if (TYPE_DECLARED_CLASS (parent_type))
22465           {
22466             if (TYPE_TAG_NAME (parent_type) != NULL)
22467               return TYPE_TAG_NAME (parent_type);
22468             return "";
22469           }
22470         /* Fall through.  */
22471       default:
22472         return determine_prefix (parent, cu);
22473       }
22474 }
22475
22476 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22477    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22478    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22479    an obconcat, otherwise allocate storage for the result.  The CU argument is
22480    used to determine the language and hence, the appropriate separator.  */
22481
22482 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22483
22484 static char *
22485 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22486                  int physname, struct dwarf2_cu *cu)
22487 {
22488   const char *lead = "";
22489   const char *sep;
22490
22491   if (suffix == NULL || suffix[0] == '\0'
22492       || prefix == NULL || prefix[0] == '\0')
22493     sep = "";
22494   else if (cu->language == language_d)
22495     {
22496       /* For D, the 'main' function could be defined in any module, but it
22497          should never be prefixed.  */
22498       if (strcmp (suffix, "D main") == 0)
22499         {
22500           prefix = "";
22501           sep = "";
22502         }
22503       else
22504         sep = ".";
22505     }
22506   else if (cu->language == language_fortran && physname)
22507     {
22508       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22509          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22510
22511       lead = "__";
22512       sep = "_MOD_";
22513     }
22514   else
22515     sep = "::";
22516
22517   if (prefix == NULL)
22518     prefix = "";
22519   if (suffix == NULL)
22520     suffix = "";
22521
22522   if (obs == NULL)
22523     {
22524       char *retval
22525         = ((char *)
22526            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22527
22528       strcpy (retval, lead);
22529       strcat (retval, prefix);
22530       strcat (retval, sep);
22531       strcat (retval, suffix);
22532       return retval;
22533     }
22534   else
22535     {
22536       /* We have an obstack.  */
22537       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22538     }
22539 }
22540
22541 /* Return sibling of die, NULL if no sibling.  */
22542
22543 static struct die_info *
22544 sibling_die (struct die_info *die)
22545 {
22546   return die->sibling;
22547 }
22548
22549 /* Get name of a die, return NULL if not found.  */
22550
22551 static const char *
22552 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22553                           struct obstack *obstack)
22554 {
22555   if (name && cu->language == language_cplus)
22556     {
22557       std::string canon_name = cp_canonicalize_string (name);
22558
22559       if (!canon_name.empty ())
22560         {
22561           if (canon_name != name)
22562             name = (const char *) obstack_copy0 (obstack,
22563                                                  canon_name.c_str (),
22564                                                  canon_name.length ());
22565         }
22566     }
22567
22568   return name;
22569 }
22570
22571 /* Get name of a die, return NULL if not found.
22572    Anonymous namespaces are converted to their magic string.  */
22573
22574 static const char *
22575 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22576 {
22577   struct attribute *attr;
22578   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
22579
22580   attr = dwarf2_attr (die, DW_AT_name, cu);
22581   if ((!attr || !DW_STRING (attr))
22582       && die->tag != DW_TAG_namespace
22583       && die->tag != DW_TAG_class_type
22584       && die->tag != DW_TAG_interface_type
22585       && die->tag != DW_TAG_structure_type
22586       && die->tag != DW_TAG_union_type)
22587     return NULL;
22588
22589   switch (die->tag)
22590     {
22591     case DW_TAG_compile_unit:
22592     case DW_TAG_partial_unit:
22593       /* Compilation units have a DW_AT_name that is a filename, not
22594          a source language identifier.  */
22595     case DW_TAG_enumeration_type:
22596     case DW_TAG_enumerator:
22597       /* These tags always have simple identifiers already; no need
22598          to canonicalize them.  */
22599       return DW_STRING (attr);
22600
22601     case DW_TAG_namespace:
22602       if (attr != NULL && DW_STRING (attr) != NULL)
22603         return DW_STRING (attr);
22604       return CP_ANONYMOUS_NAMESPACE_STR;
22605
22606     case DW_TAG_class_type:
22607     case DW_TAG_interface_type:
22608     case DW_TAG_structure_type:
22609     case DW_TAG_union_type:
22610       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22611          structures or unions.  These were of the form "._%d" in GCC 4.1,
22612          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22613          and GCC 4.4.  We work around this problem by ignoring these.  */
22614       if (attr && DW_STRING (attr)
22615           && (startswith (DW_STRING (attr), "._")
22616               || startswith (DW_STRING (attr), "<anonymous")))
22617         return NULL;
22618
22619       /* GCC might emit a nameless typedef that has a linkage name.  See
22620          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22621       if (!attr || DW_STRING (attr) == NULL)
22622         {
22623           char *demangled = NULL;
22624
22625           attr = dw2_linkage_name_attr (die, cu);
22626           if (attr == NULL || DW_STRING (attr) == NULL)
22627             return NULL;
22628
22629           /* Avoid demangling DW_STRING (attr) the second time on a second
22630              call for the same DIE.  */
22631           if (!DW_STRING_IS_CANONICAL (attr))
22632             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22633
22634           if (demangled)
22635             {
22636               const char *base;
22637
22638               /* FIXME: we already did this for the partial symbol... */
22639               DW_STRING (attr)
22640                 = ((const char *)
22641                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22642                                   demangled, strlen (demangled)));
22643               DW_STRING_IS_CANONICAL (attr) = 1;
22644               xfree (demangled);
22645
22646               /* Strip any leading namespaces/classes, keep only the base name.
22647                  DW_AT_name for named DIEs does not contain the prefixes.  */
22648               base = strrchr (DW_STRING (attr), ':');
22649               if (base && base > DW_STRING (attr) && base[-1] == ':')
22650                 return &base[1];
22651               else
22652                 return DW_STRING (attr);
22653             }
22654         }
22655       break;
22656
22657     default:
22658       break;
22659     }
22660
22661   if (!DW_STRING_IS_CANONICAL (attr))
22662     {
22663       DW_STRING (attr)
22664         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22665                                     &objfile->per_bfd->storage_obstack);
22666       DW_STRING_IS_CANONICAL (attr) = 1;
22667     }
22668   return DW_STRING (attr);
22669 }
22670
22671 /* Return the die that this die in an extension of, or NULL if there
22672    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22673    containing the return value on output.  */
22674
22675 static struct die_info *
22676 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22677 {
22678   struct attribute *attr;
22679
22680   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22681   if (attr == NULL)
22682     return NULL;
22683
22684   return follow_die_ref (die, attr, ext_cu);
22685 }
22686
22687 /* Convert a DIE tag into its string name.  */
22688
22689 static const char *
22690 dwarf_tag_name (unsigned tag)
22691 {
22692   const char *name = get_DW_TAG_name (tag);
22693
22694   if (name == NULL)
22695     return "DW_TAG_<unknown>";
22696
22697   return name;
22698 }
22699
22700 /* Convert a DWARF attribute code into its string name.  */
22701
22702 static const char *
22703 dwarf_attr_name (unsigned attr)
22704 {
22705   const char *name;
22706
22707 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22708   if (attr == DW_AT_MIPS_fde)
22709     return "DW_AT_MIPS_fde";
22710 #else
22711   if (attr == DW_AT_HP_block_index)
22712     return "DW_AT_HP_block_index";
22713 #endif
22714
22715   name = get_DW_AT_name (attr);
22716
22717   if (name == NULL)
22718     return "DW_AT_<unknown>";
22719
22720   return name;
22721 }
22722
22723 /* Convert a DWARF value form code into its string name.  */
22724
22725 static const char *
22726 dwarf_form_name (unsigned form)
22727 {
22728   const char *name = get_DW_FORM_name (form);
22729
22730   if (name == NULL)
22731     return "DW_FORM_<unknown>";
22732
22733   return name;
22734 }
22735
22736 static const char *
22737 dwarf_bool_name (unsigned mybool)
22738 {
22739   if (mybool)
22740     return "TRUE";
22741   else
22742     return "FALSE";
22743 }
22744
22745 /* Convert a DWARF type code into its string name.  */
22746
22747 static const char *
22748 dwarf_type_encoding_name (unsigned enc)
22749 {
22750   const char *name = get_DW_ATE_name (enc);
22751
22752   if (name == NULL)
22753     return "DW_ATE_<unknown>";
22754
22755   return name;
22756 }
22757
22758 static void
22759 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22760 {
22761   unsigned int i;
22762
22763   print_spaces (indent, f);
22764   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22765                       dwarf_tag_name (die->tag), die->abbrev,
22766                       to_underlying (die->sect_off));
22767
22768   if (die->parent != NULL)
22769     {
22770       print_spaces (indent, f);
22771       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22772                           to_underlying (die->parent->sect_off));
22773     }
22774
22775   print_spaces (indent, f);
22776   fprintf_unfiltered (f, "  has children: %s\n",
22777            dwarf_bool_name (die->child != NULL));
22778
22779   print_spaces (indent, f);
22780   fprintf_unfiltered (f, "  attributes:\n");
22781
22782   for (i = 0; i < die->num_attrs; ++i)
22783     {
22784       print_spaces (indent, f);
22785       fprintf_unfiltered (f, "    %s (%s) ",
22786                dwarf_attr_name (die->attrs[i].name),
22787                dwarf_form_name (die->attrs[i].form));
22788
22789       switch (die->attrs[i].form)
22790         {
22791         case DW_FORM_addr:
22792         case DW_FORM_GNU_addr_index:
22793           fprintf_unfiltered (f, "address: ");
22794           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22795           break;
22796         case DW_FORM_block2:
22797         case DW_FORM_block4:
22798         case DW_FORM_block:
22799         case DW_FORM_block1:
22800           fprintf_unfiltered (f, "block: size %s",
22801                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22802           break;
22803         case DW_FORM_exprloc:
22804           fprintf_unfiltered (f, "expression: size %s",
22805                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22806           break;
22807         case DW_FORM_data16:
22808           fprintf_unfiltered (f, "constant of 16 bytes");
22809           break;
22810         case DW_FORM_ref_addr:
22811           fprintf_unfiltered (f, "ref address: ");
22812           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22813           break;
22814         case DW_FORM_GNU_ref_alt:
22815           fprintf_unfiltered (f, "alt ref address: ");
22816           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22817           break;
22818         case DW_FORM_ref1:
22819         case DW_FORM_ref2:
22820         case DW_FORM_ref4:
22821         case DW_FORM_ref8:
22822         case DW_FORM_ref_udata:
22823           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22824                               (long) (DW_UNSND (&die->attrs[i])));
22825           break;
22826         case DW_FORM_data1:
22827         case DW_FORM_data2:
22828         case DW_FORM_data4:
22829         case DW_FORM_data8:
22830         case DW_FORM_udata:
22831         case DW_FORM_sdata:
22832           fprintf_unfiltered (f, "constant: %s",
22833                               pulongest (DW_UNSND (&die->attrs[i])));
22834           break;
22835         case DW_FORM_sec_offset:
22836           fprintf_unfiltered (f, "section offset: %s",
22837                               pulongest (DW_UNSND (&die->attrs[i])));
22838           break;
22839         case DW_FORM_ref_sig8:
22840           fprintf_unfiltered (f, "signature: %s",
22841                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22842           break;
22843         case DW_FORM_string:
22844         case DW_FORM_strp:
22845         case DW_FORM_line_strp:
22846         case DW_FORM_GNU_str_index:
22847         case DW_FORM_GNU_strp_alt:
22848           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22849                    DW_STRING (&die->attrs[i])
22850                    ? DW_STRING (&die->attrs[i]) : "",
22851                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22852           break;
22853         case DW_FORM_flag:
22854           if (DW_UNSND (&die->attrs[i]))
22855             fprintf_unfiltered (f, "flag: TRUE");
22856           else
22857             fprintf_unfiltered (f, "flag: FALSE");
22858           break;
22859         case DW_FORM_flag_present:
22860           fprintf_unfiltered (f, "flag: TRUE");
22861           break;
22862         case DW_FORM_indirect:
22863           /* The reader will have reduced the indirect form to
22864              the "base form" so this form should not occur.  */
22865           fprintf_unfiltered (f, 
22866                               "unexpected attribute form: DW_FORM_indirect");
22867           break;
22868         case DW_FORM_implicit_const:
22869           fprintf_unfiltered (f, "constant: %s",
22870                               plongest (DW_SND (&die->attrs[i])));
22871           break;
22872         default:
22873           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22874                    die->attrs[i].form);
22875           break;
22876         }
22877       fprintf_unfiltered (f, "\n");
22878     }
22879 }
22880
22881 static void
22882 dump_die_for_error (struct die_info *die)
22883 {
22884   dump_die_shallow (gdb_stderr, 0, die);
22885 }
22886
22887 static void
22888 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22889 {
22890   int indent = level * 4;
22891
22892   gdb_assert (die != NULL);
22893
22894   if (level >= max_level)
22895     return;
22896
22897   dump_die_shallow (f, indent, die);
22898
22899   if (die->child != NULL)
22900     {
22901       print_spaces (indent, f);
22902       fprintf_unfiltered (f, "  Children:");
22903       if (level + 1 < max_level)
22904         {
22905           fprintf_unfiltered (f, "\n");
22906           dump_die_1 (f, level + 1, max_level, die->child);
22907         }
22908       else
22909         {
22910           fprintf_unfiltered (f,
22911                               " [not printed, max nesting level reached]\n");
22912         }
22913     }
22914
22915   if (die->sibling != NULL && level > 0)
22916     {
22917       dump_die_1 (f, level, max_level, die->sibling);
22918     }
22919 }
22920
22921 /* This is called from the pdie macro in gdbinit.in.
22922    It's not static so gcc will keep a copy callable from gdb.  */
22923
22924 void
22925 dump_die (struct die_info *die, int max_level)
22926 {
22927   dump_die_1 (gdb_stdlog, 0, max_level, die);
22928 }
22929
22930 static void
22931 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22932 {
22933   void **slot;
22934
22935   slot = htab_find_slot_with_hash (cu->die_hash, die,
22936                                    to_underlying (die->sect_off),
22937                                    INSERT);
22938
22939   *slot = die;
22940 }
22941
22942 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22943    required kind.  */
22944
22945 static sect_offset
22946 dwarf2_get_ref_die_offset (const struct attribute *attr)
22947 {
22948   if (attr_form_is_ref (attr))
22949     return (sect_offset) DW_UNSND (attr);
22950
22951   complaint (&symfile_complaints,
22952              _("unsupported die ref attribute form: '%s'"),
22953              dwarf_form_name (attr->form));
22954   return {};
22955 }
22956
22957 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22958  * the value held by the attribute is not constant.  */
22959
22960 static LONGEST
22961 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22962 {
22963   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22964     return DW_SND (attr);
22965   else if (attr->form == DW_FORM_udata
22966            || attr->form == DW_FORM_data1
22967            || attr->form == DW_FORM_data2
22968            || attr->form == DW_FORM_data4
22969            || attr->form == DW_FORM_data8)
22970     return DW_UNSND (attr);
22971   else
22972     {
22973       /* For DW_FORM_data16 see attr_form_is_constant.  */
22974       complaint (&symfile_complaints,
22975                  _("Attribute value is not a constant (%s)"),
22976                  dwarf_form_name (attr->form));
22977       return default_value;
22978     }
22979 }
22980
22981 /* Follow reference or signature attribute ATTR of SRC_DIE.
22982    On entry *REF_CU is the CU of SRC_DIE.
22983    On exit *REF_CU is the CU of the result.  */
22984
22985 static struct die_info *
22986 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22987                        struct dwarf2_cu **ref_cu)
22988 {
22989   struct die_info *die;
22990
22991   if (attr_form_is_ref (attr))
22992     die = follow_die_ref (src_die, attr, ref_cu);
22993   else if (attr->form == DW_FORM_ref_sig8)
22994     die = follow_die_sig (src_die, attr, ref_cu);
22995   else
22996     {
22997       dump_die_for_error (src_die);
22998       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22999              objfile_name ((*ref_cu)->dwarf2_per_objfile->objfile));
23000     }
23001
23002   return die;
23003 }
23004
23005 /* Follow reference OFFSET.
23006    On entry *REF_CU is the CU of the source die referencing OFFSET.
23007    On exit *REF_CU is the CU of the result.
23008    Returns NULL if OFFSET is invalid.  */
23009
23010 static struct die_info *
23011 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23012                    struct dwarf2_cu **ref_cu)
23013 {
23014   struct die_info temp_die;
23015   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23016   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
23017   struct objfile *objfile = dwarf2_per_objfile->objfile;
23018
23019   gdb_assert (cu->per_cu != NULL);
23020
23021   target_cu = cu;
23022
23023   if (cu->per_cu->is_debug_types)
23024     {
23025       /* .debug_types CUs cannot reference anything outside their CU.
23026          If they need to, they have to reference a signatured type via
23027          DW_FORM_ref_sig8.  */
23028       if (!offset_in_cu_p (&cu->header, sect_off))
23029         return NULL;
23030     }
23031   else if (offset_in_dwz != cu->per_cu->is_dwz
23032            || !offset_in_cu_p (&cu->header, sect_off))
23033     {
23034       struct dwarf2_per_cu_data *per_cu;
23035
23036       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23037                                                  dwarf2_per_objfile);
23038
23039       /* If necessary, add it to the queue and load its DIEs.  */
23040       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23041         load_full_comp_unit (per_cu, cu->language);
23042
23043       target_cu = per_cu->cu;
23044     }
23045   else if (cu->dies == NULL)
23046     {
23047       /* We're loading full DIEs during partial symbol reading.  */
23048       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23049       load_full_comp_unit (cu->per_cu, language_minimal);
23050     }
23051
23052   *ref_cu = target_cu;
23053   temp_die.sect_off = sect_off;
23054   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23055                                                   &temp_die,
23056                                                   to_underlying (sect_off));
23057 }
23058
23059 /* Follow reference attribute ATTR of SRC_DIE.
23060    On entry *REF_CU is the CU of SRC_DIE.
23061    On exit *REF_CU is the CU of the result.  */
23062
23063 static struct die_info *
23064 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23065                 struct dwarf2_cu **ref_cu)
23066 {
23067   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23068   struct dwarf2_cu *cu = *ref_cu;
23069   struct die_info *die;
23070
23071   die = follow_die_offset (sect_off,
23072                            (attr->form == DW_FORM_GNU_ref_alt
23073                             || cu->per_cu->is_dwz),
23074                            ref_cu);
23075   if (!die)
23076     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
23077            "at 0x%x [in module %s]"),
23078            to_underlying (sect_off), to_underlying (src_die->sect_off),
23079            objfile_name (cu->dwarf2_per_objfile->objfile));
23080
23081   return die;
23082 }
23083
23084 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23085    Returned value is intended for DW_OP_call*.  Returned
23086    dwarf2_locexpr_baton->data has lifetime of
23087    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23088
23089 struct dwarf2_locexpr_baton
23090 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23091                                struct dwarf2_per_cu_data *per_cu,
23092                                CORE_ADDR (*get_frame_pc) (void *baton),
23093                                void *baton)
23094 {
23095   struct dwarf2_cu *cu;
23096   struct die_info *die;
23097   struct attribute *attr;
23098   struct dwarf2_locexpr_baton retval;
23099   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23100   struct dwarf2_per_objfile *dwarf2_per_objfile
23101     = get_dwarf2_per_objfile (objfile);
23102
23103   if (per_cu->cu == NULL)
23104     load_cu (per_cu);
23105   cu = per_cu->cu;
23106   if (cu == NULL)
23107     {
23108       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23109          Instead just throw an error, not much else we can do.  */
23110       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23111              to_underlying (sect_off), objfile_name (objfile));
23112     }
23113
23114   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23115   if (!die)
23116     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23117            to_underlying (sect_off), objfile_name (objfile));
23118
23119   attr = dwarf2_attr (die, DW_AT_location, cu);
23120   if (!attr)
23121     {
23122       /* DWARF: "If there is no such attribute, then there is no effect.".
23123          DATA is ignored if SIZE is 0.  */
23124
23125       retval.data = NULL;
23126       retval.size = 0;
23127     }
23128   else if (attr_form_is_section_offset (attr))
23129     {
23130       struct dwarf2_loclist_baton loclist_baton;
23131       CORE_ADDR pc = (*get_frame_pc) (baton);
23132       size_t size;
23133
23134       fill_in_loclist_baton (cu, &loclist_baton, attr);
23135
23136       retval.data = dwarf2_find_location_expression (&loclist_baton,
23137                                                      &size, pc);
23138       retval.size = size;
23139     }
23140   else
23141     {
23142       if (!attr_form_is_block (attr))
23143         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
23144                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23145                to_underlying (sect_off), objfile_name (objfile));
23146
23147       retval.data = DW_BLOCK (attr)->data;
23148       retval.size = DW_BLOCK (attr)->size;
23149     }
23150   retval.per_cu = cu->per_cu;
23151
23152   age_cached_comp_units (dwarf2_per_objfile);
23153
23154   return retval;
23155 }
23156
23157 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23158    offset.  */
23159
23160 struct dwarf2_locexpr_baton
23161 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23162                              struct dwarf2_per_cu_data *per_cu,
23163                              CORE_ADDR (*get_frame_pc) (void *baton),
23164                              void *baton)
23165 {
23166   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23167
23168   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23169 }
23170
23171 /* Write a constant of a given type as target-ordered bytes into
23172    OBSTACK.  */
23173
23174 static const gdb_byte *
23175 write_constant_as_bytes (struct obstack *obstack,
23176                          enum bfd_endian byte_order,
23177                          struct type *type,
23178                          ULONGEST value,
23179                          LONGEST *len)
23180 {
23181   gdb_byte *result;
23182
23183   *len = TYPE_LENGTH (type);
23184   result = (gdb_byte *) obstack_alloc (obstack, *len);
23185   store_unsigned_integer (result, *len, byte_order, value);
23186
23187   return result;
23188 }
23189
23190 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23191    pointer to the constant bytes and set LEN to the length of the
23192    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23193    does not have a DW_AT_const_value, return NULL.  */
23194
23195 const gdb_byte *
23196 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23197                              struct dwarf2_per_cu_data *per_cu,
23198                              struct obstack *obstack,
23199                              LONGEST *len)
23200 {
23201   struct dwarf2_cu *cu;
23202   struct die_info *die;
23203   struct attribute *attr;
23204   const gdb_byte *result = NULL;
23205   struct type *type;
23206   LONGEST value;
23207   enum bfd_endian byte_order;
23208   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23209
23210   if (per_cu->cu == NULL)
23211     load_cu (per_cu);
23212   cu = per_cu->cu;
23213   if (cu == NULL)
23214     {
23215       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23216          Instead just throw an error, not much else we can do.  */
23217       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23218              to_underlying (sect_off), objfile_name (objfile));
23219     }
23220
23221   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23222   if (!die)
23223     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23224            to_underlying (sect_off), objfile_name (objfile));
23225
23226
23227   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23228   if (attr == NULL)
23229     return NULL;
23230
23231   byte_order = (bfd_big_endian (objfile->obfd)
23232                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23233
23234   switch (attr->form)
23235     {
23236     case DW_FORM_addr:
23237     case DW_FORM_GNU_addr_index:
23238       {
23239         gdb_byte *tem;
23240
23241         *len = cu->header.addr_size;
23242         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23243         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23244         result = tem;
23245       }
23246       break;
23247     case DW_FORM_string:
23248     case DW_FORM_strp:
23249     case DW_FORM_GNU_str_index:
23250     case DW_FORM_GNU_strp_alt:
23251       /* DW_STRING is already allocated on the objfile obstack, point
23252          directly to it.  */
23253       result = (const gdb_byte *) DW_STRING (attr);
23254       *len = strlen (DW_STRING (attr));
23255       break;
23256     case DW_FORM_block1:
23257     case DW_FORM_block2:
23258     case DW_FORM_block4:
23259     case DW_FORM_block:
23260     case DW_FORM_exprloc:
23261     case DW_FORM_data16:
23262       result = DW_BLOCK (attr)->data;
23263       *len = DW_BLOCK (attr)->size;
23264       break;
23265
23266       /* The DW_AT_const_value attributes are supposed to carry the
23267          symbol's value "represented as it would be on the target
23268          architecture."  By the time we get here, it's already been
23269          converted to host endianness, so we just need to sign- or
23270          zero-extend it as appropriate.  */
23271     case DW_FORM_data1:
23272       type = die_type (die, cu);
23273       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23274       if (result == NULL)
23275         result = write_constant_as_bytes (obstack, byte_order,
23276                                           type, value, len);
23277       break;
23278     case DW_FORM_data2:
23279       type = die_type (die, cu);
23280       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23281       if (result == NULL)
23282         result = write_constant_as_bytes (obstack, byte_order,
23283                                           type, value, len);
23284       break;
23285     case DW_FORM_data4:
23286       type = die_type (die, cu);
23287       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23288       if (result == NULL)
23289         result = write_constant_as_bytes (obstack, byte_order,
23290                                           type, value, len);
23291       break;
23292     case DW_FORM_data8:
23293       type = die_type (die, cu);
23294       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23295       if (result == NULL)
23296         result = write_constant_as_bytes (obstack, byte_order,
23297                                           type, value, len);
23298       break;
23299
23300     case DW_FORM_sdata:
23301     case DW_FORM_implicit_const:
23302       type = die_type (die, cu);
23303       result = write_constant_as_bytes (obstack, byte_order,
23304                                         type, DW_SND (attr), len);
23305       break;
23306
23307     case DW_FORM_udata:
23308       type = die_type (die, cu);
23309       result = write_constant_as_bytes (obstack, byte_order,
23310                                         type, DW_UNSND (attr), len);
23311       break;
23312
23313     default:
23314       complaint (&symfile_complaints,
23315                  _("unsupported const value attribute form: '%s'"),
23316                  dwarf_form_name (attr->form));
23317       break;
23318     }
23319
23320   return result;
23321 }
23322
23323 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23324    valid type for this die is found.  */
23325
23326 struct type *
23327 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23328                                 struct dwarf2_per_cu_data *per_cu)
23329 {
23330   struct dwarf2_cu *cu;
23331   struct die_info *die;
23332
23333   if (per_cu->cu == NULL)
23334     load_cu (per_cu);
23335   cu = per_cu->cu;
23336   if (!cu)
23337     return NULL;
23338
23339   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23340   if (!die)
23341     return NULL;
23342
23343   return die_type (die, cu);
23344 }
23345
23346 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23347    PER_CU.  */
23348
23349 struct type *
23350 dwarf2_get_die_type (cu_offset die_offset,
23351                      struct dwarf2_per_cu_data *per_cu)
23352 {
23353   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23354   return get_die_type_at_offset (die_offset_sect, per_cu);
23355 }
23356
23357 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23358    On entry *REF_CU is the CU of SRC_DIE.
23359    On exit *REF_CU is the CU of the result.
23360    Returns NULL if the referenced DIE isn't found.  */
23361
23362 static struct die_info *
23363 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23364                   struct dwarf2_cu **ref_cu)
23365 {
23366   struct die_info temp_die;
23367   struct dwarf2_cu *sig_cu;
23368   struct die_info *die;
23369
23370   /* While it might be nice to assert sig_type->type == NULL here,
23371      we can get here for DW_AT_imported_declaration where we need
23372      the DIE not the type.  */
23373
23374   /* If necessary, add it to the queue and load its DIEs.  */
23375
23376   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23377     read_signatured_type (sig_type);
23378
23379   sig_cu = sig_type->per_cu.cu;
23380   gdb_assert (sig_cu != NULL);
23381   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23382   temp_die.sect_off = sig_type->type_offset_in_section;
23383   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23384                                                  to_underlying (temp_die.sect_off));
23385   if (die)
23386     {
23387       struct dwarf2_per_objfile *dwarf2_per_objfile
23388         = (*ref_cu)->dwarf2_per_objfile;
23389
23390       /* For .gdb_index version 7 keep track of included TUs.
23391          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23392       if (dwarf2_per_objfile->index_table != NULL
23393           && dwarf2_per_objfile->index_table->version <= 7)
23394         {
23395           VEC_safe_push (dwarf2_per_cu_ptr,
23396                          (*ref_cu)->per_cu->imported_symtabs,
23397                          sig_cu->per_cu);
23398         }
23399
23400       *ref_cu = sig_cu;
23401       return die;
23402     }
23403
23404   return NULL;
23405 }
23406
23407 /* Follow signatured type referenced by ATTR in SRC_DIE.
23408    On entry *REF_CU is the CU of SRC_DIE.
23409    On exit *REF_CU is the CU of the result.
23410    The result is the DIE of the type.
23411    If the referenced type cannot be found an error is thrown.  */
23412
23413 static struct die_info *
23414 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23415                 struct dwarf2_cu **ref_cu)
23416 {
23417   ULONGEST signature = DW_SIGNATURE (attr);
23418   struct signatured_type *sig_type;
23419   struct die_info *die;
23420
23421   gdb_assert (attr->form == DW_FORM_ref_sig8);
23422
23423   sig_type = lookup_signatured_type (*ref_cu, signature);
23424   /* sig_type will be NULL if the signatured type is missing from
23425      the debug info.  */
23426   if (sig_type == NULL)
23427     {
23428       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23429                " from DIE at 0x%x [in module %s]"),
23430              hex_string (signature), to_underlying (src_die->sect_off),
23431              objfile_name ((*ref_cu)->dwarf2_per_objfile->objfile));
23432     }
23433
23434   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23435   if (die == NULL)
23436     {
23437       dump_die_for_error (src_die);
23438       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23439                " from DIE at 0x%x [in module %s]"),
23440              hex_string (signature), to_underlying (src_die->sect_off),
23441              objfile_name ((*ref_cu)->dwarf2_per_objfile->objfile));
23442     }
23443
23444   return die;
23445 }
23446
23447 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23448    reading in and processing the type unit if necessary.  */
23449
23450 static struct type *
23451 get_signatured_type (struct die_info *die, ULONGEST signature,
23452                      struct dwarf2_cu *cu)
23453 {
23454   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
23455   struct signatured_type *sig_type;
23456   struct dwarf2_cu *type_cu;
23457   struct die_info *type_die;
23458   struct type *type;
23459
23460   sig_type = lookup_signatured_type (cu, signature);
23461   /* sig_type will be NULL if the signatured type is missing from
23462      the debug info.  */
23463   if (sig_type == NULL)
23464     {
23465       complaint (&symfile_complaints,
23466                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23467                    " from DIE at 0x%x [in module %s]"),
23468                  hex_string (signature), to_underlying (die->sect_off),
23469                  objfile_name (dwarf2_per_objfile->objfile));
23470       return build_error_marker_type (cu, die);
23471     }
23472
23473   /* If we already know the type we're done.  */
23474   if (sig_type->type != NULL)
23475     return sig_type->type;
23476
23477   type_cu = cu;
23478   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23479   if (type_die != NULL)
23480     {
23481       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23482          is created.  This is important, for example, because for c++ classes
23483          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23484       type = read_type_die (type_die, type_cu);
23485       if (type == NULL)
23486         {
23487           complaint (&symfile_complaints,
23488                      _("Dwarf Error: Cannot build signatured type %s"
23489                        " referenced from DIE at 0x%x [in module %s]"),
23490                      hex_string (signature), to_underlying (die->sect_off),
23491                      objfile_name (dwarf2_per_objfile->objfile));
23492           type = build_error_marker_type (cu, die);
23493         }
23494     }
23495   else
23496     {
23497       complaint (&symfile_complaints,
23498                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23499                    " from DIE at 0x%x [in module %s]"),
23500                  hex_string (signature), to_underlying (die->sect_off),
23501                  objfile_name (dwarf2_per_objfile->objfile));
23502       type = build_error_marker_type (cu, die);
23503     }
23504   sig_type->type = type;
23505
23506   return type;
23507 }
23508
23509 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23510    reading in and processing the type unit if necessary.  */
23511
23512 static struct type *
23513 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23514                           struct dwarf2_cu *cu) /* ARI: editCase function */
23515 {
23516   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23517   if (attr_form_is_ref (attr))
23518     {
23519       struct dwarf2_cu *type_cu = cu;
23520       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23521
23522       return read_type_die (type_die, type_cu);
23523     }
23524   else if (attr->form == DW_FORM_ref_sig8)
23525     {
23526       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23527     }
23528   else
23529     {
23530       struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
23531
23532       complaint (&symfile_complaints,
23533                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23534                    " at 0x%x [in module %s]"),
23535                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23536                  objfile_name (dwarf2_per_objfile->objfile));
23537       return build_error_marker_type (cu, die);
23538     }
23539 }
23540
23541 /* Load the DIEs associated with type unit PER_CU into memory.  */
23542
23543 static void
23544 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23545 {
23546   struct signatured_type *sig_type;
23547
23548   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23549   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23550
23551   /* We have the per_cu, but we need the signatured_type.
23552      Fortunately this is an easy translation.  */
23553   gdb_assert (per_cu->is_debug_types);
23554   sig_type = (struct signatured_type *) per_cu;
23555
23556   gdb_assert (per_cu->cu == NULL);
23557
23558   read_signatured_type (sig_type);
23559
23560   gdb_assert (per_cu->cu != NULL);
23561 }
23562
23563 /* die_reader_func for read_signatured_type.
23564    This is identical to load_full_comp_unit_reader,
23565    but is kept separate for now.  */
23566
23567 static void
23568 read_signatured_type_reader (const struct die_reader_specs *reader,
23569                              const gdb_byte *info_ptr,
23570                              struct die_info *comp_unit_die,
23571                              int has_children,
23572                              void *data)
23573 {
23574   struct dwarf2_cu *cu = reader->cu;
23575
23576   gdb_assert (cu->die_hash == NULL);
23577   cu->die_hash =
23578     htab_create_alloc_ex (cu->header.length / 12,
23579                           die_hash,
23580                           die_eq,
23581                           NULL,
23582                           &cu->comp_unit_obstack,
23583                           hashtab_obstack_allocate,
23584                           dummy_obstack_deallocate);
23585
23586   if (has_children)
23587     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23588                                                   &info_ptr, comp_unit_die);
23589   cu->dies = comp_unit_die;
23590   /* comp_unit_die is not stored in die_hash, no need.  */
23591
23592   /* We try not to read any attributes in this function, because not
23593      all CUs needed for references have been loaded yet, and symbol
23594      table processing isn't initialized.  But we have to set the CU language,
23595      or we won't be able to build types correctly.
23596      Similarly, if we do not read the producer, we can not apply
23597      producer-specific interpretation.  */
23598   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23599 }
23600
23601 /* Read in a signatured type and build its CU and DIEs.
23602    If the type is a stub for the real type in a DWO file,
23603    read in the real type from the DWO file as well.  */
23604
23605 static void
23606 read_signatured_type (struct signatured_type *sig_type)
23607 {
23608   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23609
23610   gdb_assert (per_cu->is_debug_types);
23611   gdb_assert (per_cu->cu == NULL);
23612
23613   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23614                            read_signatured_type_reader, NULL);
23615   sig_type->per_cu.tu_read = 1;
23616 }
23617
23618 /* Decode simple location descriptions.
23619    Given a pointer to a dwarf block that defines a location, compute
23620    the location and return the value.
23621
23622    NOTE drow/2003-11-18: This function is called in two situations
23623    now: for the address of static or global variables (partial symbols
23624    only) and for offsets into structures which are expected to be
23625    (more or less) constant.  The partial symbol case should go away,
23626    and only the constant case should remain.  That will let this
23627    function complain more accurately.  A few special modes are allowed
23628    without complaint for global variables (for instance, global
23629    register values and thread-local values).
23630
23631    A location description containing no operations indicates that the
23632    object is optimized out.  The return value is 0 for that case.
23633    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23634    callers will only want a very basic result and this can become a
23635    complaint.
23636
23637    Note that stack[0] is unused except as a default error return.  */
23638
23639 static CORE_ADDR
23640 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23641 {
23642   struct objfile *objfile = cu->dwarf2_per_objfile->objfile;
23643   size_t i;
23644   size_t size = blk->size;
23645   const gdb_byte *data = blk->data;
23646   CORE_ADDR stack[64];
23647   int stacki;
23648   unsigned int bytes_read, unsnd;
23649   gdb_byte op;
23650
23651   i = 0;
23652   stacki = 0;
23653   stack[stacki] = 0;
23654   stack[++stacki] = 0;
23655
23656   while (i < size)
23657     {
23658       op = data[i++];
23659       switch (op)
23660         {
23661         case DW_OP_lit0:
23662         case DW_OP_lit1:
23663         case DW_OP_lit2:
23664         case DW_OP_lit3:
23665         case DW_OP_lit4:
23666         case DW_OP_lit5:
23667         case DW_OP_lit6:
23668         case DW_OP_lit7:
23669         case DW_OP_lit8:
23670         case DW_OP_lit9:
23671         case DW_OP_lit10:
23672         case DW_OP_lit11:
23673         case DW_OP_lit12:
23674         case DW_OP_lit13:
23675         case DW_OP_lit14:
23676         case DW_OP_lit15:
23677         case DW_OP_lit16:
23678         case DW_OP_lit17:
23679         case DW_OP_lit18:
23680         case DW_OP_lit19:
23681         case DW_OP_lit20:
23682         case DW_OP_lit21:
23683         case DW_OP_lit22:
23684         case DW_OP_lit23:
23685         case DW_OP_lit24:
23686         case DW_OP_lit25:
23687         case DW_OP_lit26:
23688         case DW_OP_lit27:
23689         case DW_OP_lit28:
23690         case DW_OP_lit29:
23691         case DW_OP_lit30:
23692         case DW_OP_lit31:
23693           stack[++stacki] = op - DW_OP_lit0;
23694           break;
23695
23696         case DW_OP_reg0:
23697         case DW_OP_reg1:
23698         case DW_OP_reg2:
23699         case DW_OP_reg3:
23700         case DW_OP_reg4:
23701         case DW_OP_reg5:
23702         case DW_OP_reg6:
23703         case DW_OP_reg7:
23704         case DW_OP_reg8:
23705         case DW_OP_reg9:
23706         case DW_OP_reg10:
23707         case DW_OP_reg11:
23708         case DW_OP_reg12:
23709         case DW_OP_reg13:
23710         case DW_OP_reg14:
23711         case DW_OP_reg15:
23712         case DW_OP_reg16:
23713         case DW_OP_reg17:
23714         case DW_OP_reg18:
23715         case DW_OP_reg19:
23716         case DW_OP_reg20:
23717         case DW_OP_reg21:
23718         case DW_OP_reg22:
23719         case DW_OP_reg23:
23720         case DW_OP_reg24:
23721         case DW_OP_reg25:
23722         case DW_OP_reg26:
23723         case DW_OP_reg27:
23724         case DW_OP_reg28:
23725         case DW_OP_reg29:
23726         case DW_OP_reg30:
23727         case DW_OP_reg31:
23728           stack[++stacki] = op - DW_OP_reg0;
23729           if (i < size)
23730             dwarf2_complex_location_expr_complaint ();
23731           break;
23732
23733         case DW_OP_regx:
23734           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23735           i += bytes_read;
23736           stack[++stacki] = unsnd;
23737           if (i < size)
23738             dwarf2_complex_location_expr_complaint ();
23739           break;
23740
23741         case DW_OP_addr:
23742           stack[++stacki] = read_address (objfile->obfd, &data[i],
23743                                           cu, &bytes_read);
23744           i += bytes_read;
23745           break;
23746
23747         case DW_OP_const1u:
23748           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23749           i += 1;
23750           break;
23751
23752         case DW_OP_const1s:
23753           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23754           i += 1;
23755           break;
23756
23757         case DW_OP_const2u:
23758           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23759           i += 2;
23760           break;
23761
23762         case DW_OP_const2s:
23763           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23764           i += 2;
23765           break;
23766
23767         case DW_OP_const4u:
23768           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23769           i += 4;
23770           break;
23771
23772         case DW_OP_const4s:
23773           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23774           i += 4;
23775           break;
23776
23777         case DW_OP_const8u:
23778           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23779           i += 8;
23780           break;
23781
23782         case DW_OP_constu:
23783           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23784                                                   &bytes_read);
23785           i += bytes_read;
23786           break;
23787
23788         case DW_OP_consts:
23789           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23790           i += bytes_read;
23791           break;
23792
23793         case DW_OP_dup:
23794           stack[stacki + 1] = stack[stacki];
23795           stacki++;
23796           break;
23797
23798         case DW_OP_plus:
23799           stack[stacki - 1] += stack[stacki];
23800           stacki--;
23801           break;
23802
23803         case DW_OP_plus_uconst:
23804           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23805                                                  &bytes_read);
23806           i += bytes_read;
23807           break;
23808
23809         case DW_OP_minus:
23810           stack[stacki - 1] -= stack[stacki];
23811           stacki--;
23812           break;
23813
23814         case DW_OP_deref:
23815           /* If we're not the last op, then we definitely can't encode
23816              this using GDB's address_class enum.  This is valid for partial
23817              global symbols, although the variable's address will be bogus
23818              in the psymtab.  */
23819           if (i < size)
23820             dwarf2_complex_location_expr_complaint ();
23821           break;
23822
23823         case DW_OP_GNU_push_tls_address:
23824         case DW_OP_form_tls_address:
23825           /* The top of the stack has the offset from the beginning
23826              of the thread control block at which the variable is located.  */
23827           /* Nothing should follow this operator, so the top of stack would
23828              be returned.  */
23829           /* This is valid for partial global symbols, but the variable's
23830              address will be bogus in the psymtab.  Make it always at least
23831              non-zero to not look as a variable garbage collected by linker
23832              which have DW_OP_addr 0.  */
23833           if (i < size)
23834             dwarf2_complex_location_expr_complaint ();
23835           stack[stacki]++;
23836           break;
23837
23838         case DW_OP_GNU_uninit:
23839           break;
23840
23841         case DW_OP_GNU_addr_index:
23842         case DW_OP_GNU_const_index:
23843           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23844                                                          &bytes_read);
23845           i += bytes_read;
23846           break;
23847
23848         default:
23849           {
23850             const char *name = get_DW_OP_name (op);
23851
23852             if (name)
23853               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23854                          name);
23855             else
23856               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23857                          op);
23858           }
23859
23860           return (stack[stacki]);
23861         }
23862
23863       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23864          outside of the allocated space.  Also enforce minimum>0.  */
23865       if (stacki >= ARRAY_SIZE (stack) - 1)
23866         {
23867           complaint (&symfile_complaints,
23868                      _("location description stack overflow"));
23869           return 0;
23870         }
23871
23872       if (stacki <= 0)
23873         {
23874           complaint (&symfile_complaints,
23875                      _("location description stack underflow"));
23876           return 0;
23877         }
23878     }
23879   return (stack[stacki]);
23880 }
23881
23882 /* memory allocation interface */
23883
23884 static struct dwarf_block *
23885 dwarf_alloc_block (struct dwarf2_cu *cu)
23886 {
23887   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23888 }
23889
23890 static struct die_info *
23891 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23892 {
23893   struct die_info *die;
23894   size_t size = sizeof (struct die_info);
23895
23896   if (num_attrs > 1)
23897     size += (num_attrs - 1) * sizeof (struct attribute);
23898
23899   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23900   memset (die, 0, sizeof (struct die_info));
23901   return (die);
23902 }
23903
23904 \f
23905 /* Macro support.  */
23906
23907 /* Return file name relative to the compilation directory of file number I in
23908    *LH's file name table.  The result is allocated using xmalloc; the caller is
23909    responsible for freeing it.  */
23910
23911 static char *
23912 file_file_name (int file, struct line_header *lh)
23913 {
23914   /* Is the file number a valid index into the line header's file name
23915      table?  Remember that file numbers start with one, not zero.  */
23916   if (1 <= file && file <= lh->file_names.size ())
23917     {
23918       const file_entry &fe = lh->file_names[file - 1];
23919
23920       if (!IS_ABSOLUTE_PATH (fe.name))
23921         {
23922           const char *dir = fe.include_dir (lh);
23923           if (dir != NULL)
23924             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23925         }
23926       return xstrdup (fe.name);
23927     }
23928   else
23929     {
23930       /* The compiler produced a bogus file number.  We can at least
23931          record the macro definitions made in the file, even if we
23932          won't be able to find the file by name.  */
23933       char fake_name[80];
23934
23935       xsnprintf (fake_name, sizeof (fake_name),
23936                  "<bad macro file number %d>", file);
23937
23938       complaint (&symfile_complaints,
23939                  _("bad file number in macro information (%d)"),
23940                  file);
23941
23942       return xstrdup (fake_name);
23943     }
23944 }
23945
23946 /* Return the full name of file number I in *LH's file name table.
23947    Use COMP_DIR as the name of the current directory of the
23948    compilation.  The result is allocated using xmalloc; the caller is
23949    responsible for freeing it.  */
23950 static char *
23951 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23952 {
23953   /* Is the file number a valid index into the line header's file name
23954      table?  Remember that file numbers start with one, not zero.  */
23955   if (1 <= file && file <= lh->file_names.size ())
23956     {
23957       char *relative = file_file_name (file, lh);
23958
23959       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23960         return relative;
23961       return reconcat (relative, comp_dir, SLASH_STRING,
23962                        relative, (char *) NULL);
23963     }
23964   else
23965     return file_file_name (file, lh);
23966 }
23967
23968
23969 static struct macro_source_file *
23970 macro_start_file (int file, int line,
23971                   struct macro_source_file *current_file,
23972                   struct line_header *lh)
23973 {
23974   /* File name relative to the compilation directory of this source file.  */
23975   char *file_name = file_file_name (file, lh);
23976
23977   if (! current_file)
23978     {
23979       /* Note: We don't create a macro table for this compilation unit
23980          at all until we actually get a filename.  */
23981       struct macro_table *macro_table = get_macro_table ();
23982
23983       /* If we have no current file, then this must be the start_file
23984          directive for the compilation unit's main source file.  */
23985       current_file = macro_set_main (macro_table, file_name);
23986       macro_define_special (macro_table);
23987     }
23988   else
23989     current_file = macro_include (current_file, line, file_name);
23990
23991   xfree (file_name);
23992
23993   return current_file;
23994 }
23995
23996 static const char *
23997 consume_improper_spaces (const char *p, const char *body)
23998 {
23999   if (*p == ' ')
24000     {
24001       complaint (&symfile_complaints,
24002                  _("macro definition contains spaces "
24003                    "in formal argument list:\n`%s'"),
24004                  body);
24005
24006       while (*p == ' ')
24007         p++;
24008     }
24009
24010   return p;
24011 }
24012
24013
24014 static void
24015 parse_macro_definition (struct macro_source_file *file, int line,
24016                         const char *body)
24017 {
24018   const char *p;
24019
24020   /* The body string takes one of two forms.  For object-like macro
24021      definitions, it should be:
24022
24023         <macro name> " " <definition>
24024
24025      For function-like macro definitions, it should be:
24026
24027         <macro name> "() " <definition>
24028      or
24029         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24030
24031      Spaces may appear only where explicitly indicated, and in the
24032      <definition>.
24033
24034      The Dwarf 2 spec says that an object-like macro's name is always
24035      followed by a space, but versions of GCC around March 2002 omit
24036      the space when the macro's definition is the empty string.
24037
24038      The Dwarf 2 spec says that there should be no spaces between the
24039      formal arguments in a function-like macro's formal argument list,
24040      but versions of GCC around March 2002 include spaces after the
24041      commas.  */
24042
24043
24044   /* Find the extent of the macro name.  The macro name is terminated
24045      by either a space or null character (for an object-like macro) or
24046      an opening paren (for a function-like macro).  */
24047   for (p = body; *p; p++)
24048     if (*p == ' ' || *p == '(')
24049       break;
24050
24051   if (*p == ' ' || *p == '\0')
24052     {
24053       /* It's an object-like macro.  */
24054       int name_len = p - body;
24055       char *name = savestring (body, name_len);
24056       const char *replacement;
24057
24058       if (*p == ' ')
24059         replacement = body + name_len + 1;
24060       else
24061         {
24062           dwarf2_macro_malformed_definition_complaint (body);
24063           replacement = body + name_len;
24064         }
24065
24066       macro_define_object (file, line, name, replacement);
24067
24068       xfree (name);
24069     }
24070   else if (*p == '(')
24071     {
24072       /* It's a function-like macro.  */
24073       char *name = savestring (body, p - body);
24074       int argc = 0;
24075       int argv_size = 1;
24076       char **argv = XNEWVEC (char *, argv_size);
24077
24078       p++;
24079
24080       p = consume_improper_spaces (p, body);
24081
24082       /* Parse the formal argument list.  */
24083       while (*p && *p != ')')
24084         {
24085           /* Find the extent of the current argument name.  */
24086           const char *arg_start = p;
24087
24088           while (*p && *p != ',' && *p != ')' && *p != ' ')
24089             p++;
24090
24091           if (! *p || p == arg_start)
24092             dwarf2_macro_malformed_definition_complaint (body);
24093           else
24094             {
24095               /* Make sure argv has room for the new argument.  */
24096               if (argc >= argv_size)
24097                 {
24098                   argv_size *= 2;
24099                   argv = XRESIZEVEC (char *, argv, argv_size);
24100                 }
24101
24102               argv[argc++] = savestring (arg_start, p - arg_start);
24103             }
24104
24105           p = consume_improper_spaces (p, body);
24106
24107           /* Consume the comma, if present.  */
24108           if (*p == ',')
24109             {
24110               p++;
24111
24112               p = consume_improper_spaces (p, body);
24113             }
24114         }
24115
24116       if (*p == ')')
24117         {
24118           p++;
24119
24120           if (*p == ' ')
24121             /* Perfectly formed definition, no complaints.  */
24122             macro_define_function (file, line, name,
24123                                    argc, (const char **) argv,
24124                                    p + 1);
24125           else if (*p == '\0')
24126             {
24127               /* Complain, but do define it.  */
24128               dwarf2_macro_malformed_definition_complaint (body);
24129               macro_define_function (file, line, name,
24130                                      argc, (const char **) argv,
24131                                      p);
24132             }
24133           else
24134             /* Just complain.  */
24135             dwarf2_macro_malformed_definition_complaint (body);
24136         }
24137       else
24138         /* Just complain.  */
24139         dwarf2_macro_malformed_definition_complaint (body);
24140
24141       xfree (name);
24142       {
24143         int i;
24144
24145         for (i = 0; i < argc; i++)
24146           xfree (argv[i]);
24147       }
24148       xfree (argv);
24149     }
24150   else
24151     dwarf2_macro_malformed_definition_complaint (body);
24152 }
24153
24154 /* Skip some bytes from BYTES according to the form given in FORM.
24155    Returns the new pointer.  */
24156
24157 static const gdb_byte *
24158 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24159                  enum dwarf_form form,
24160                  unsigned int offset_size,
24161                  struct dwarf2_section_info *section)
24162 {
24163   unsigned int bytes_read;
24164
24165   switch (form)
24166     {
24167     case DW_FORM_data1:
24168     case DW_FORM_flag:
24169       ++bytes;
24170       break;
24171
24172     case DW_FORM_data2:
24173       bytes += 2;
24174       break;
24175
24176     case DW_FORM_data4:
24177       bytes += 4;
24178       break;
24179
24180     case DW_FORM_data8:
24181       bytes += 8;
24182       break;
24183
24184     case DW_FORM_data16:
24185       bytes += 16;
24186       break;
24187
24188     case DW_FORM_string:
24189       read_direct_string (abfd, bytes, &bytes_read);
24190       bytes += bytes_read;
24191       break;
24192
24193     case DW_FORM_sec_offset:
24194     case DW_FORM_strp:
24195     case DW_FORM_GNU_strp_alt:
24196       bytes += offset_size;
24197       break;
24198
24199     case DW_FORM_block:
24200       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24201       bytes += bytes_read;
24202       break;
24203
24204     case DW_FORM_block1:
24205       bytes += 1 + read_1_byte (abfd, bytes);
24206       break;
24207     case DW_FORM_block2:
24208       bytes += 2 + read_2_bytes (abfd, bytes);
24209       break;
24210     case DW_FORM_block4:
24211       bytes += 4 + read_4_bytes (abfd, bytes);
24212       break;
24213
24214     case DW_FORM_sdata:
24215     case DW_FORM_udata:
24216     case DW_FORM_GNU_addr_index:
24217     case DW_FORM_GNU_str_index:
24218       bytes = gdb_skip_leb128 (bytes, buffer_end);
24219       if (bytes == NULL)
24220         {
24221           dwarf2_section_buffer_overflow_complaint (section);
24222           return NULL;
24223         }
24224       break;
24225
24226     case DW_FORM_implicit_const:
24227       break;
24228
24229     default:
24230       {
24231         complaint (&symfile_complaints,
24232                    _("invalid form 0x%x in `%s'"),
24233                    form, get_section_name (section));
24234         return NULL;
24235       }
24236     }
24237
24238   return bytes;
24239 }
24240
24241 /* A helper for dwarf_decode_macros that handles skipping an unknown
24242    opcode.  Returns an updated pointer to the macro data buffer; or,
24243    on error, issues a complaint and returns NULL.  */
24244
24245 static const gdb_byte *
24246 skip_unknown_opcode (unsigned int opcode,
24247                      const gdb_byte **opcode_definitions,
24248                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24249                      bfd *abfd,
24250                      unsigned int offset_size,
24251                      struct dwarf2_section_info *section)
24252 {
24253   unsigned int bytes_read, i;
24254   unsigned long arg;
24255   const gdb_byte *defn;
24256
24257   if (opcode_definitions[opcode] == NULL)
24258     {
24259       complaint (&symfile_complaints,
24260                  _("unrecognized DW_MACFINO opcode 0x%x"),
24261                  opcode);
24262       return NULL;
24263     }
24264
24265   defn = opcode_definitions[opcode];
24266   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24267   defn += bytes_read;
24268
24269   for (i = 0; i < arg; ++i)
24270     {
24271       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24272                                  (enum dwarf_form) defn[i], offset_size,
24273                                  section);
24274       if (mac_ptr == NULL)
24275         {
24276           /* skip_form_bytes already issued the complaint.  */
24277           return NULL;
24278         }
24279     }
24280
24281   return mac_ptr;
24282 }
24283
24284 /* A helper function which parses the header of a macro section.
24285    If the macro section is the extended (for now called "GNU") type,
24286    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24287    the header, or issues a complaint and returns NULL on error.  */
24288
24289 static const gdb_byte *
24290 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24291                           bfd *abfd,
24292                           const gdb_byte *mac_ptr,
24293                           unsigned int *offset_size,
24294                           int section_is_gnu)
24295 {
24296   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24297
24298   if (section_is_gnu)
24299     {
24300       unsigned int version, flags;
24301
24302       version = read_2_bytes (abfd, mac_ptr);
24303       if (version != 4 && version != 5)
24304         {
24305           complaint (&symfile_complaints,
24306                      _("unrecognized version `%d' in .debug_macro section"),
24307                      version);
24308           return NULL;
24309         }
24310       mac_ptr += 2;
24311
24312       flags = read_1_byte (abfd, mac_ptr);
24313       ++mac_ptr;
24314       *offset_size = (flags & 1) ? 8 : 4;
24315
24316       if ((flags & 2) != 0)
24317         /* We don't need the line table offset.  */
24318         mac_ptr += *offset_size;
24319
24320       /* Vendor opcode descriptions.  */
24321       if ((flags & 4) != 0)
24322         {
24323           unsigned int i, count;
24324
24325           count = read_1_byte (abfd, mac_ptr);
24326           ++mac_ptr;
24327           for (i = 0; i < count; ++i)
24328             {
24329               unsigned int opcode, bytes_read;
24330               unsigned long arg;
24331
24332               opcode = read_1_byte (abfd, mac_ptr);
24333               ++mac_ptr;
24334               opcode_definitions[opcode] = mac_ptr;
24335               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24336               mac_ptr += bytes_read;
24337               mac_ptr += arg;
24338             }
24339         }
24340     }
24341
24342   return mac_ptr;
24343 }
24344
24345 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24346    including DW_MACRO_import.  */
24347
24348 static void
24349 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24350                           bfd *abfd,
24351                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24352                           struct macro_source_file *current_file,
24353                           struct line_header *lh,
24354                           struct dwarf2_section_info *section,
24355                           int section_is_gnu, int section_is_dwz,
24356                           unsigned int offset_size,
24357                           htab_t include_hash)
24358 {
24359   struct objfile *objfile = dwarf2_per_objfile->objfile;
24360   enum dwarf_macro_record_type macinfo_type;
24361   int at_commandline;
24362   const gdb_byte *opcode_definitions[256];
24363
24364   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24365                                       &offset_size, section_is_gnu);
24366   if (mac_ptr == NULL)
24367     {
24368       /* We already issued a complaint.  */
24369       return;
24370     }
24371
24372   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24373      GDB is still reading the definitions from command line.  First
24374      DW_MACINFO_start_file will need to be ignored as it was already executed
24375      to create CURRENT_FILE for the main source holding also the command line
24376      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24377      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24378
24379   at_commandline = 1;
24380
24381   do
24382     {
24383       /* Do we at least have room for a macinfo type byte?  */
24384       if (mac_ptr >= mac_end)
24385         {
24386           dwarf2_section_buffer_overflow_complaint (section);
24387           break;
24388         }
24389
24390       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24391       mac_ptr++;
24392
24393       /* Note that we rely on the fact that the corresponding GNU and
24394          DWARF constants are the same.  */
24395       DIAGNOSTIC_PUSH
24396       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24397       switch (macinfo_type)
24398         {
24399           /* A zero macinfo type indicates the end of the macro
24400              information.  */
24401         case 0:
24402           break;
24403
24404         case DW_MACRO_define:
24405         case DW_MACRO_undef:
24406         case DW_MACRO_define_strp:
24407         case DW_MACRO_undef_strp:
24408         case DW_MACRO_define_sup:
24409         case DW_MACRO_undef_sup:
24410           {
24411             unsigned int bytes_read;
24412             int line;
24413             const char *body;
24414             int is_define;
24415
24416             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24417             mac_ptr += bytes_read;
24418
24419             if (macinfo_type == DW_MACRO_define
24420                 || macinfo_type == DW_MACRO_undef)
24421               {
24422                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24423                 mac_ptr += bytes_read;
24424               }
24425             else
24426               {
24427                 LONGEST str_offset;
24428
24429                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24430                 mac_ptr += offset_size;
24431
24432                 if (macinfo_type == DW_MACRO_define_sup
24433                     || macinfo_type == DW_MACRO_undef_sup
24434                     || section_is_dwz)
24435                   {
24436                     struct dwz_file *dwz
24437                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24438
24439                     body = read_indirect_string_from_dwz (objfile,
24440                                                           dwz, str_offset);
24441                   }
24442                 else
24443                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24444                                                          abfd, str_offset);
24445               }
24446
24447             is_define = (macinfo_type == DW_MACRO_define
24448                          || macinfo_type == DW_MACRO_define_strp
24449                          || macinfo_type == DW_MACRO_define_sup);
24450             if (! current_file)
24451               {
24452                 /* DWARF violation as no main source is present.  */
24453                 complaint (&symfile_complaints,
24454                            _("debug info with no main source gives macro %s "
24455                              "on line %d: %s"),
24456                            is_define ? _("definition") : _("undefinition"),
24457                            line, body);
24458                 break;
24459               }
24460             if ((line == 0 && !at_commandline)
24461                 || (line != 0 && at_commandline))
24462               complaint (&symfile_complaints,
24463                          _("debug info gives %s macro %s with %s line %d: %s"),
24464                          at_commandline ? _("command-line") : _("in-file"),
24465                          is_define ? _("definition") : _("undefinition"),
24466                          line == 0 ? _("zero") : _("non-zero"), line, body);
24467
24468             if (is_define)
24469               parse_macro_definition (current_file, line, body);
24470             else
24471               {
24472                 gdb_assert (macinfo_type == DW_MACRO_undef
24473                             || macinfo_type == DW_MACRO_undef_strp
24474                             || macinfo_type == DW_MACRO_undef_sup);
24475                 macro_undef (current_file, line, body);
24476               }
24477           }
24478           break;
24479
24480         case DW_MACRO_start_file:
24481           {
24482             unsigned int bytes_read;
24483             int line, file;
24484
24485             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24486             mac_ptr += bytes_read;
24487             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24488             mac_ptr += bytes_read;
24489
24490             if ((line == 0 && !at_commandline)
24491                 || (line != 0 && at_commandline))
24492               complaint (&symfile_complaints,
24493                          _("debug info gives source %d included "
24494                            "from %s at %s line %d"),
24495                          file, at_commandline ? _("command-line") : _("file"),
24496                          line == 0 ? _("zero") : _("non-zero"), line);
24497
24498             if (at_commandline)
24499               {
24500                 /* This DW_MACRO_start_file was executed in the
24501                    pass one.  */
24502                 at_commandline = 0;
24503               }
24504             else
24505               current_file = macro_start_file (file, line, current_file, lh);
24506           }
24507           break;
24508
24509         case DW_MACRO_end_file:
24510           if (! current_file)
24511             complaint (&symfile_complaints,
24512                        _("macro debug info has an unmatched "
24513                          "`close_file' directive"));
24514           else
24515             {
24516               current_file = current_file->included_by;
24517               if (! current_file)
24518                 {
24519                   enum dwarf_macro_record_type next_type;
24520
24521                   /* GCC circa March 2002 doesn't produce the zero
24522                      type byte marking the end of the compilation
24523                      unit.  Complain if it's not there, but exit no
24524                      matter what.  */
24525
24526                   /* Do we at least have room for a macinfo type byte?  */
24527                   if (mac_ptr >= mac_end)
24528                     {
24529                       dwarf2_section_buffer_overflow_complaint (section);
24530                       return;
24531                     }
24532
24533                   /* We don't increment mac_ptr here, so this is just
24534                      a look-ahead.  */
24535                   next_type
24536                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24537                                                                   mac_ptr);
24538                   if (next_type != 0)
24539                     complaint (&symfile_complaints,
24540                                _("no terminating 0-type entry for "
24541                                  "macros in `.debug_macinfo' section"));
24542
24543                   return;
24544                 }
24545             }
24546           break;
24547
24548         case DW_MACRO_import:
24549         case DW_MACRO_import_sup:
24550           {
24551             LONGEST offset;
24552             void **slot;
24553             bfd *include_bfd = abfd;
24554             struct dwarf2_section_info *include_section = section;
24555             const gdb_byte *include_mac_end = mac_end;
24556             int is_dwz = section_is_dwz;
24557             const gdb_byte *new_mac_ptr;
24558
24559             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24560             mac_ptr += offset_size;
24561
24562             if (macinfo_type == DW_MACRO_import_sup)
24563               {
24564                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24565
24566                 dwarf2_read_section (objfile, &dwz->macro);
24567
24568                 include_section = &dwz->macro;
24569                 include_bfd = get_section_bfd_owner (include_section);
24570                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24571                 is_dwz = 1;
24572               }
24573
24574             new_mac_ptr = include_section->buffer + offset;
24575             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24576
24577             if (*slot != NULL)
24578               {
24579                 /* This has actually happened; see
24580                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24581                 complaint (&symfile_complaints,
24582                            _("recursive DW_MACRO_import in "
24583                              ".debug_macro section"));
24584               }
24585             else
24586               {
24587                 *slot = (void *) new_mac_ptr;
24588
24589                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24590                                           include_bfd, new_mac_ptr,
24591                                           include_mac_end, current_file, lh,
24592                                           section, section_is_gnu, is_dwz,
24593                                           offset_size, include_hash);
24594
24595                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24596               }
24597           }
24598           break;
24599
24600         case DW_MACINFO_vendor_ext:
24601           if (!section_is_gnu)
24602             {
24603               unsigned int bytes_read;
24604
24605               /* This reads the constant, but since we don't recognize
24606                  any vendor extensions, we ignore it.  */
24607               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24608               mac_ptr += bytes_read;
24609               read_direct_string (abfd, mac_ptr, &bytes_read);
24610               mac_ptr += bytes_read;
24611
24612               /* We don't recognize any vendor extensions.  */
24613               break;
24614             }
24615           /* FALLTHROUGH */
24616
24617         default:
24618           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24619                                          mac_ptr, mac_end, abfd, offset_size,
24620                                          section);
24621           if (mac_ptr == NULL)
24622             return;
24623           break;
24624         }
24625       DIAGNOSTIC_POP
24626     } while (macinfo_type != 0);
24627 }
24628
24629 static void
24630 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24631                      int section_is_gnu)
24632 {
24633   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
24634   struct objfile *objfile = dwarf2_per_objfile->objfile;
24635   struct line_header *lh = cu->line_header;
24636   bfd *abfd;
24637   const gdb_byte *mac_ptr, *mac_end;
24638   struct macro_source_file *current_file = 0;
24639   enum dwarf_macro_record_type macinfo_type;
24640   unsigned int offset_size = cu->header.offset_size;
24641   const gdb_byte *opcode_definitions[256];
24642   void **slot;
24643   struct dwarf2_section_info *section;
24644   const char *section_name;
24645
24646   if (cu->dwo_unit != NULL)
24647     {
24648       if (section_is_gnu)
24649         {
24650           section = &cu->dwo_unit->dwo_file->sections.macro;
24651           section_name = ".debug_macro.dwo";
24652         }
24653       else
24654         {
24655           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24656           section_name = ".debug_macinfo.dwo";
24657         }
24658     }
24659   else
24660     {
24661       if (section_is_gnu)
24662         {
24663           section = &dwarf2_per_objfile->macro;
24664           section_name = ".debug_macro";
24665         }
24666       else
24667         {
24668           section = &dwarf2_per_objfile->macinfo;
24669           section_name = ".debug_macinfo";
24670         }
24671     }
24672
24673   dwarf2_read_section (objfile, section);
24674   if (section->buffer == NULL)
24675     {
24676       complaint (&symfile_complaints, _("missing %s section"), section_name);
24677       return;
24678     }
24679   abfd = get_section_bfd_owner (section);
24680
24681   /* First pass: Find the name of the base filename.
24682      This filename is needed in order to process all macros whose definition
24683      (or undefinition) comes from the command line.  These macros are defined
24684      before the first DW_MACINFO_start_file entry, and yet still need to be
24685      associated to the base file.
24686
24687      To determine the base file name, we scan the macro definitions until we
24688      reach the first DW_MACINFO_start_file entry.  We then initialize
24689      CURRENT_FILE accordingly so that any macro definition found before the
24690      first DW_MACINFO_start_file can still be associated to the base file.  */
24691
24692   mac_ptr = section->buffer + offset;
24693   mac_end = section->buffer + section->size;
24694
24695   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24696                                       &offset_size, section_is_gnu);
24697   if (mac_ptr == NULL)
24698     {
24699       /* We already issued a complaint.  */
24700       return;
24701     }
24702
24703   do
24704     {
24705       /* Do we at least have room for a macinfo type byte?  */
24706       if (mac_ptr >= mac_end)
24707         {
24708           /* Complaint is printed during the second pass as GDB will probably
24709              stop the first pass earlier upon finding
24710              DW_MACINFO_start_file.  */
24711           break;
24712         }
24713
24714       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24715       mac_ptr++;
24716
24717       /* Note that we rely on the fact that the corresponding GNU and
24718          DWARF constants are the same.  */
24719       DIAGNOSTIC_PUSH
24720       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24721       switch (macinfo_type)
24722         {
24723           /* A zero macinfo type indicates the end of the macro
24724              information.  */
24725         case 0:
24726           break;
24727
24728         case DW_MACRO_define:
24729         case DW_MACRO_undef:
24730           /* Only skip the data by MAC_PTR.  */
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           break;
24740
24741         case DW_MACRO_start_file:
24742           {
24743             unsigned int bytes_read;
24744             int line, file;
24745
24746             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24747             mac_ptr += bytes_read;
24748             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24749             mac_ptr += bytes_read;
24750
24751             current_file = macro_start_file (file, line, current_file, lh);
24752           }
24753           break;
24754
24755         case DW_MACRO_end_file:
24756           /* No data to skip by MAC_PTR.  */
24757           break;
24758
24759         case DW_MACRO_define_strp:
24760         case DW_MACRO_undef_strp:
24761         case DW_MACRO_define_sup:
24762         case DW_MACRO_undef_sup:
24763           {
24764             unsigned int bytes_read;
24765
24766             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24767             mac_ptr += bytes_read;
24768             mac_ptr += offset_size;
24769           }
24770           break;
24771
24772         case DW_MACRO_import:
24773         case DW_MACRO_import_sup:
24774           /* Note that, according to the spec, a transparent include
24775              chain cannot call DW_MACRO_start_file.  So, we can just
24776              skip this opcode.  */
24777           mac_ptr += offset_size;
24778           break;
24779
24780         case DW_MACINFO_vendor_ext:
24781           /* Only skip the data by MAC_PTR.  */
24782           if (!section_is_gnu)
24783             {
24784               unsigned int bytes_read;
24785
24786               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24787               mac_ptr += bytes_read;
24788               read_direct_string (abfd, mac_ptr, &bytes_read);
24789               mac_ptr += bytes_read;
24790             }
24791           /* FALLTHROUGH */
24792
24793         default:
24794           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24795                                          mac_ptr, mac_end, abfd, offset_size,
24796                                          section);
24797           if (mac_ptr == NULL)
24798             return;
24799           break;
24800         }
24801       DIAGNOSTIC_POP
24802     } while (macinfo_type != 0 && current_file == NULL);
24803
24804   /* Second pass: Process all entries.
24805
24806      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24807      command-line macro definitions/undefinitions.  This flag is unset when we
24808      reach the first DW_MACINFO_start_file entry.  */
24809
24810   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24811                                            htab_eq_pointer,
24812                                            NULL, xcalloc, xfree));
24813   mac_ptr = section->buffer + offset;
24814   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24815   *slot = (void *) mac_ptr;
24816   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24817                             abfd, mac_ptr, mac_end,
24818                             current_file, lh, section,
24819                             section_is_gnu, 0, offset_size,
24820                             include_hash.get ());
24821 }
24822
24823 /* Check if the attribute's form is a DW_FORM_block*
24824    if so return true else false.  */
24825
24826 static int
24827 attr_form_is_block (const struct attribute *attr)
24828 {
24829   return (attr == NULL ? 0 :
24830       attr->form == DW_FORM_block1
24831       || attr->form == DW_FORM_block2
24832       || attr->form == DW_FORM_block4
24833       || attr->form == DW_FORM_block
24834       || attr->form == DW_FORM_exprloc);
24835 }
24836
24837 /* Return non-zero if ATTR's value is a section offset --- classes
24838    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24839    You may use DW_UNSND (attr) to retrieve such offsets.
24840
24841    Section 7.5.4, "Attribute Encodings", explains that no attribute
24842    may have a value that belongs to more than one of these classes; it
24843    would be ambiguous if we did, because we use the same forms for all
24844    of them.  */
24845
24846 static int
24847 attr_form_is_section_offset (const struct attribute *attr)
24848 {
24849   return (attr->form == DW_FORM_data4
24850           || attr->form == DW_FORM_data8
24851           || attr->form == DW_FORM_sec_offset);
24852 }
24853
24854 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24855    zero otherwise.  When this function returns true, you can apply
24856    dwarf2_get_attr_constant_value to it.
24857
24858    However, note that for some attributes you must check
24859    attr_form_is_section_offset before using this test.  DW_FORM_data4
24860    and DW_FORM_data8 are members of both the constant class, and of
24861    the classes that contain offsets into other debug sections
24862    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24863    that, if an attribute's can be either a constant or one of the
24864    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24865    taken as section offsets, not constants.
24866
24867    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24868    cannot handle that.  */
24869
24870 static int
24871 attr_form_is_constant (const struct attribute *attr)
24872 {
24873   switch (attr->form)
24874     {
24875     case DW_FORM_sdata:
24876     case DW_FORM_udata:
24877     case DW_FORM_data1:
24878     case DW_FORM_data2:
24879     case DW_FORM_data4:
24880     case DW_FORM_data8:
24881     case DW_FORM_implicit_const:
24882       return 1;
24883     default:
24884       return 0;
24885     }
24886 }
24887
24888
24889 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24890    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24891
24892 static int
24893 attr_form_is_ref (const struct attribute *attr)
24894 {
24895   switch (attr->form)
24896     {
24897     case DW_FORM_ref_addr:
24898     case DW_FORM_ref1:
24899     case DW_FORM_ref2:
24900     case DW_FORM_ref4:
24901     case DW_FORM_ref8:
24902     case DW_FORM_ref_udata:
24903     case DW_FORM_GNU_ref_alt:
24904       return 1;
24905     default:
24906       return 0;
24907     }
24908 }
24909
24910 /* Return the .debug_loc section to use for CU.
24911    For DWO files use .debug_loc.dwo.  */
24912
24913 static struct dwarf2_section_info *
24914 cu_debug_loc_section (struct dwarf2_cu *cu)
24915 {
24916   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
24917
24918   if (cu->dwo_unit)
24919     {
24920       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24921       
24922       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24923     }
24924   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24925                                   : &dwarf2_per_objfile->loc);
24926 }
24927
24928 /* A helper function that fills in a dwarf2_loclist_baton.  */
24929
24930 static void
24931 fill_in_loclist_baton (struct dwarf2_cu *cu,
24932                        struct dwarf2_loclist_baton *baton,
24933                        const struct attribute *attr)
24934 {
24935   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
24936   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24937
24938   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24939
24940   baton->per_cu = cu->per_cu;
24941   gdb_assert (baton->per_cu);
24942   /* We don't know how long the location list is, but make sure we
24943      don't run off the edge of the section.  */
24944   baton->size = section->size - DW_UNSND (attr);
24945   baton->data = section->buffer + DW_UNSND (attr);
24946   baton->base_address = cu->base_address;
24947   baton->from_dwo = cu->dwo_unit != NULL;
24948 }
24949
24950 static void
24951 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24952                              struct dwarf2_cu *cu, int is_block)
24953 {
24954   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
24955   struct objfile *objfile = dwarf2_per_objfile->objfile;
24956   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24957
24958   if (attr_form_is_section_offset (attr)
24959       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24960          the section.  If so, fall through to the complaint in the
24961          other branch.  */
24962       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24963     {
24964       struct dwarf2_loclist_baton *baton;
24965
24966       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24967
24968       fill_in_loclist_baton (cu, baton, attr);
24969
24970       if (cu->base_known == 0)
24971         complaint (&symfile_complaints,
24972                    _("Location list used without "
24973                      "specifying the CU base address."));
24974
24975       SYMBOL_ACLASS_INDEX (sym) = (is_block
24976                                    ? dwarf2_loclist_block_index
24977                                    : dwarf2_loclist_index);
24978       SYMBOL_LOCATION_BATON (sym) = baton;
24979     }
24980   else
24981     {
24982       struct dwarf2_locexpr_baton *baton;
24983
24984       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24985       baton->per_cu = cu->per_cu;
24986       gdb_assert (baton->per_cu);
24987
24988       if (attr_form_is_block (attr))
24989         {
24990           /* Note that we're just copying the block's data pointer
24991              here, not the actual data.  We're still pointing into the
24992              info_buffer for SYM's objfile; right now we never release
24993              that buffer, but when we do clean up properly this may
24994              need to change.  */
24995           baton->size = DW_BLOCK (attr)->size;
24996           baton->data = DW_BLOCK (attr)->data;
24997         }
24998       else
24999         {
25000           dwarf2_invalid_attrib_class_complaint ("location description",
25001                                                  SYMBOL_NATURAL_NAME (sym));
25002           baton->size = 0;
25003         }
25004
25005       SYMBOL_ACLASS_INDEX (sym) = (is_block
25006                                    ? dwarf2_locexpr_block_index
25007                                    : dwarf2_locexpr_index);
25008       SYMBOL_LOCATION_BATON (sym) = baton;
25009     }
25010 }
25011
25012 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25013    came from a separate debuginfo file, then the master objfile is
25014    returned.  */
25015
25016 struct objfile *
25017 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25018 {
25019   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25020
25021   /* Return the master objfile, so that we can report and look up the
25022      correct file containing this variable.  */
25023   if (objfile->separate_debug_objfile_backlink)
25024     objfile = objfile->separate_debug_objfile_backlink;
25025
25026   return objfile;
25027 }
25028
25029 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25030    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25031    CU_HEADERP first.  */
25032
25033 static const struct comp_unit_head *
25034 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25035                        struct dwarf2_per_cu_data *per_cu)
25036 {
25037   const gdb_byte *info_ptr;
25038
25039   if (per_cu->cu)
25040     return &per_cu->cu->header;
25041
25042   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25043
25044   memset (cu_headerp, 0, sizeof (*cu_headerp));
25045   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25046                        rcuh_kind::COMPILE);
25047
25048   return cu_headerp;
25049 }
25050
25051 /* Return the address size given in the compilation unit header for CU.  */
25052
25053 int
25054 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25055 {
25056   struct comp_unit_head cu_header_local;
25057   const struct comp_unit_head *cu_headerp;
25058
25059   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25060
25061   return cu_headerp->addr_size;
25062 }
25063
25064 /* Return the offset size given in the compilation unit header for CU.  */
25065
25066 int
25067 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25068 {
25069   struct comp_unit_head cu_header_local;
25070   const struct comp_unit_head *cu_headerp;
25071
25072   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25073
25074   return cu_headerp->offset_size;
25075 }
25076
25077 /* See its dwarf2loc.h declaration.  */
25078
25079 int
25080 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25081 {
25082   struct comp_unit_head cu_header_local;
25083   const struct comp_unit_head *cu_headerp;
25084
25085   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25086
25087   if (cu_headerp->version == 2)
25088     return cu_headerp->addr_size;
25089   else
25090     return cu_headerp->offset_size;
25091 }
25092
25093 /* Return the text offset of the CU.  The returned offset comes from
25094    this CU's objfile.  If this objfile came from a separate debuginfo
25095    file, then the offset may be different from the corresponding
25096    offset in the parent objfile.  */
25097
25098 CORE_ADDR
25099 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25100 {
25101   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25102
25103   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25104 }
25105
25106 /* Return DWARF version number of PER_CU.  */
25107
25108 short
25109 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25110 {
25111   return per_cu->dwarf_version;
25112 }
25113
25114 /* Locate the .debug_info compilation unit from CU's objfile which contains
25115    the DIE at OFFSET.  Raises an error on failure.  */
25116
25117 static struct dwarf2_per_cu_data *
25118 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25119                                   unsigned int offset_in_dwz,
25120                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25121 {
25122   struct dwarf2_per_cu_data *this_cu;
25123   int low, high;
25124   const sect_offset *cu_off;
25125
25126   low = 0;
25127   high = dwarf2_per_objfile->n_comp_units - 1;
25128   while (high > low)
25129     {
25130       struct dwarf2_per_cu_data *mid_cu;
25131       int mid = low + (high - low) / 2;
25132
25133       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25134       cu_off = &mid_cu->sect_off;
25135       if (mid_cu->is_dwz > offset_in_dwz
25136           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25137         high = mid;
25138       else
25139         low = mid + 1;
25140     }
25141   gdb_assert (low == high);
25142   this_cu = dwarf2_per_objfile->all_comp_units[low];
25143   cu_off = &this_cu->sect_off;
25144   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25145     {
25146       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25147         error (_("Dwarf Error: could not find partial DIE containing "
25148                "offset 0x%x [in module %s]"),
25149                to_underlying (sect_off),
25150                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25151
25152       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25153                   <= sect_off);
25154       return dwarf2_per_objfile->all_comp_units[low-1];
25155     }
25156   else
25157     {
25158       this_cu = dwarf2_per_objfile->all_comp_units[low];
25159       if (low == dwarf2_per_objfile->n_comp_units - 1
25160           && sect_off >= this_cu->sect_off + this_cu->length)
25161         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
25162       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25163       return this_cu;
25164     }
25165 }
25166
25167 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25168
25169 static void
25170 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
25171 {
25172   memset (cu, 0, sizeof (*cu));
25173   per_cu->cu = cu;
25174   cu->per_cu = per_cu;
25175   cu->dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25176   obstack_init (&cu->comp_unit_obstack);
25177 }
25178
25179 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25180
25181 static void
25182 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25183                        enum language pretend_language)
25184 {
25185   struct attribute *attr;
25186
25187   /* Set the language we're debugging.  */
25188   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25189   if (attr)
25190     set_cu_language (DW_UNSND (attr), cu);
25191   else
25192     {
25193       cu->language = pretend_language;
25194       cu->language_defn = language_def (cu->language);
25195     }
25196
25197   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25198 }
25199
25200 /* Release one cached compilation unit, CU.  We unlink it from the tree
25201    of compilation units, but we don't remove it from the read_in_chain;
25202    the caller is responsible for that.
25203    NOTE: DATA is a void * because this function is also used as a
25204    cleanup routine.  */
25205
25206 static void
25207 free_heap_comp_unit (void *data)
25208 {
25209   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25210
25211   gdb_assert (cu->per_cu != NULL);
25212   cu->per_cu->cu = NULL;
25213   cu->per_cu = NULL;
25214
25215   obstack_free (&cu->comp_unit_obstack, NULL);
25216
25217   xfree (cu);
25218 }
25219
25220 /* This cleanup function is passed the address of a dwarf2_cu on the stack
25221    when we're finished with it.  We can't free the pointer itself, but be
25222    sure to unlink it from the cache.  Also release any associated storage.  */
25223
25224 static void
25225 free_stack_comp_unit (void *data)
25226 {
25227   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25228
25229   gdb_assert (cu->per_cu != NULL);
25230   cu->per_cu->cu = NULL;
25231   cu->per_cu = NULL;
25232
25233   obstack_free (&cu->comp_unit_obstack, NULL);
25234   cu->partial_dies = NULL;
25235 }
25236
25237 /* Free all cached compilation units.  */
25238
25239 static void
25240 free_cached_comp_units (void *data)
25241 {
25242   struct dwarf2_per_objfile *dwarf2_per_objfile
25243     = (struct dwarf2_per_objfile *) data;
25244
25245   dwarf2_per_objfile->free_cached_comp_units ();
25246 }
25247
25248 /* Increase the age counter on each cached compilation unit, and free
25249    any that are too old.  */
25250
25251 static void
25252 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25253 {
25254   struct dwarf2_per_cu_data *per_cu, **last_chain;
25255
25256   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25257   per_cu = dwarf2_per_objfile->read_in_chain;
25258   while (per_cu != NULL)
25259     {
25260       per_cu->cu->last_used ++;
25261       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25262         dwarf2_mark (per_cu->cu);
25263       per_cu = per_cu->cu->read_in_chain;
25264     }
25265
25266   per_cu = dwarf2_per_objfile->read_in_chain;
25267   last_chain = &dwarf2_per_objfile->read_in_chain;
25268   while (per_cu != NULL)
25269     {
25270       struct dwarf2_per_cu_data *next_cu;
25271
25272       next_cu = per_cu->cu->read_in_chain;
25273
25274       if (!per_cu->cu->mark)
25275         {
25276           free_heap_comp_unit (per_cu->cu);
25277           *last_chain = next_cu;
25278         }
25279       else
25280         last_chain = &per_cu->cu->read_in_chain;
25281
25282       per_cu = next_cu;
25283     }
25284 }
25285
25286 /* Remove a single compilation unit from the cache.  */
25287
25288 static void
25289 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25290 {
25291   struct dwarf2_per_cu_data *per_cu, **last_chain;
25292   struct dwarf2_per_objfile *dwarf2_per_objfile
25293     = target_per_cu->dwarf2_per_objfile;
25294
25295   per_cu = dwarf2_per_objfile->read_in_chain;
25296   last_chain = &dwarf2_per_objfile->read_in_chain;
25297   while (per_cu != NULL)
25298     {
25299       struct dwarf2_per_cu_data *next_cu;
25300
25301       next_cu = per_cu->cu->read_in_chain;
25302
25303       if (per_cu == target_per_cu)
25304         {
25305           free_heap_comp_unit (per_cu->cu);
25306           per_cu->cu = NULL;
25307           *last_chain = next_cu;
25308           break;
25309         }
25310       else
25311         last_chain = &per_cu->cu->read_in_chain;
25312
25313       per_cu = next_cu;
25314     }
25315 }
25316
25317 /* Release all extra memory associated with OBJFILE.  */
25318
25319 void
25320 dwarf2_free_objfile (struct objfile *objfile)
25321 {
25322   struct dwarf2_per_objfile *dwarf2_per_objfile
25323     = get_dwarf2_per_objfile (objfile);
25324
25325   if (dwarf2_per_objfile == NULL)
25326     return;
25327
25328   dwarf2_per_objfile->~dwarf2_per_objfile ();
25329 }
25330
25331 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25332    We store these in a hash table separate from the DIEs, and preserve them
25333    when the DIEs are flushed out of cache.
25334
25335    The CU "per_cu" pointer is needed because offset alone is not enough to
25336    uniquely identify the type.  A file may have multiple .debug_types sections,
25337    or the type may come from a DWO file.  Furthermore, while it's more logical
25338    to use per_cu->section+offset, with Fission the section with the data is in
25339    the DWO file but we don't know that section at the point we need it.
25340    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25341    because we can enter the lookup routine, get_die_type_at_offset, from
25342    outside this file, and thus won't necessarily have PER_CU->cu.
25343    Fortunately, PER_CU is stable for the life of the objfile.  */
25344
25345 struct dwarf2_per_cu_offset_and_type
25346 {
25347   const struct dwarf2_per_cu_data *per_cu;
25348   sect_offset sect_off;
25349   struct type *type;
25350 };
25351
25352 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25353
25354 static hashval_t
25355 per_cu_offset_and_type_hash (const void *item)
25356 {
25357   const struct dwarf2_per_cu_offset_and_type *ofs
25358     = (const struct dwarf2_per_cu_offset_and_type *) item;
25359
25360   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25361 }
25362
25363 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25364
25365 static int
25366 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25367 {
25368   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25369     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25370   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25371     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25372
25373   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25374           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25375 }
25376
25377 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25378    table if necessary.  For convenience, return TYPE.
25379
25380    The DIEs reading must have careful ordering to:
25381     * Not cause infite loops trying to read in DIEs as a prerequisite for
25382       reading current DIE.
25383     * Not trying to dereference contents of still incompletely read in types
25384       while reading in other DIEs.
25385     * Enable referencing still incompletely read in types just by a pointer to
25386       the type without accessing its fields.
25387
25388    Therefore caller should follow these rules:
25389      * Try to fetch any prerequisite types we may need to build this DIE type
25390        before building the type and calling set_die_type.
25391      * After building type call set_die_type for current DIE as soon as
25392        possible before fetching more types to complete the current type.
25393      * Make the type as complete as possible before fetching more types.  */
25394
25395 static struct type *
25396 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25397 {
25398   struct dwarf2_per_objfile *dwarf2_per_objfile = cu->dwarf2_per_objfile;
25399   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25400   struct objfile *objfile = dwarf2_per_objfile->objfile;
25401   struct attribute *attr;
25402   struct dynamic_prop prop;
25403
25404   /* For Ada types, make sure that the gnat-specific data is always
25405      initialized (if not already set).  There are a few types where
25406      we should not be doing so, because the type-specific area is
25407      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25408      where the type-specific area is used to store the floatformat).
25409      But this is not a problem, because the gnat-specific information
25410      is actually not needed for these types.  */
25411   if (need_gnat_info (cu)
25412       && TYPE_CODE (type) != TYPE_CODE_FUNC
25413       && TYPE_CODE (type) != TYPE_CODE_FLT
25414       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25415       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25416       && TYPE_CODE (type) != TYPE_CODE_METHOD
25417       && !HAVE_GNAT_AUX_INFO (type))
25418     INIT_GNAT_SPECIFIC (type);
25419
25420   /* Read DW_AT_allocated and set in type.  */
25421   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25422   if (attr_form_is_block (attr))
25423     {
25424       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25425         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25426     }
25427   else if (attr != NULL)
25428     {
25429       complaint (&symfile_complaints,
25430                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25431                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25432                  to_underlying (die->sect_off));
25433     }
25434
25435   /* Read DW_AT_associated and set in type.  */
25436   attr = dwarf2_attr (die, DW_AT_associated, cu);
25437   if (attr_form_is_block (attr))
25438     {
25439       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25440         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25441     }
25442   else if (attr != NULL)
25443     {
25444       complaint (&symfile_complaints,
25445                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25446                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25447                  to_underlying (die->sect_off));
25448     }
25449
25450   /* Read DW_AT_data_location and set in type.  */
25451   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25452   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25453     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25454
25455   if (dwarf2_per_objfile->die_type_hash == NULL)
25456     {
25457       dwarf2_per_objfile->die_type_hash =
25458         htab_create_alloc_ex (127,
25459                               per_cu_offset_and_type_hash,
25460                               per_cu_offset_and_type_eq,
25461                               NULL,
25462                               &objfile->objfile_obstack,
25463                               hashtab_obstack_allocate,
25464                               dummy_obstack_deallocate);
25465     }
25466
25467   ofs.per_cu = cu->per_cu;
25468   ofs.sect_off = die->sect_off;
25469   ofs.type = type;
25470   slot = (struct dwarf2_per_cu_offset_and_type **)
25471     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25472   if (*slot)
25473     complaint (&symfile_complaints,
25474                _("A problem internal to GDB: DIE 0x%x has type already set"),
25475                to_underlying (die->sect_off));
25476   *slot = XOBNEW (&objfile->objfile_obstack,
25477                   struct dwarf2_per_cu_offset_and_type);
25478   **slot = ofs;
25479   return type;
25480 }
25481
25482 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25483    or return NULL if the die does not have a saved type.  */
25484
25485 static struct type *
25486 get_die_type_at_offset (sect_offset sect_off,
25487                         struct dwarf2_per_cu_data *per_cu)
25488 {
25489   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25490   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25491
25492   if (dwarf2_per_objfile->die_type_hash == NULL)
25493     return NULL;
25494
25495   ofs.per_cu = per_cu;
25496   ofs.sect_off = sect_off;
25497   slot = ((struct dwarf2_per_cu_offset_and_type *)
25498           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25499   if (slot)
25500     return slot->type;
25501   else
25502     return NULL;
25503 }
25504
25505 /* Look up the type for DIE in CU in die_type_hash,
25506    or return NULL if DIE does not have a saved type.  */
25507
25508 static struct type *
25509 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25510 {
25511   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25512 }
25513
25514 /* Add a dependence relationship from CU to REF_PER_CU.  */
25515
25516 static void
25517 dwarf2_add_dependence (struct dwarf2_cu *cu,
25518                        struct dwarf2_per_cu_data *ref_per_cu)
25519 {
25520   void **slot;
25521
25522   if (cu->dependencies == NULL)
25523     cu->dependencies
25524       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25525                               NULL, &cu->comp_unit_obstack,
25526                               hashtab_obstack_allocate,
25527                               dummy_obstack_deallocate);
25528
25529   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25530   if (*slot == NULL)
25531     *slot = ref_per_cu;
25532 }
25533
25534 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25535    Set the mark field in every compilation unit in the
25536    cache that we must keep because we are keeping CU.  */
25537
25538 static int
25539 dwarf2_mark_helper (void **slot, void *data)
25540 {
25541   struct dwarf2_per_cu_data *per_cu;
25542
25543   per_cu = (struct dwarf2_per_cu_data *) *slot;
25544
25545   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25546      reading of the chain.  As such dependencies remain valid it is not much
25547      useful to track and undo them during QUIT cleanups.  */
25548   if (per_cu->cu == NULL)
25549     return 1;
25550
25551   if (per_cu->cu->mark)
25552     return 1;
25553   per_cu->cu->mark = 1;
25554
25555   if (per_cu->cu->dependencies != NULL)
25556     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25557
25558   return 1;
25559 }
25560
25561 /* Set the mark field in CU and in every other compilation unit in the
25562    cache that we must keep because we are keeping CU.  */
25563
25564 static void
25565 dwarf2_mark (struct dwarf2_cu *cu)
25566 {
25567   if (cu->mark)
25568     return;
25569   cu->mark = 1;
25570   if (cu->dependencies != NULL)
25571     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25572 }
25573
25574 static void
25575 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25576 {
25577   while (per_cu)
25578     {
25579       per_cu->cu->mark = 0;
25580       per_cu = per_cu->cu->read_in_chain;
25581     }
25582 }
25583
25584 /* Trivial hash function for partial_die_info: the hash value of a DIE
25585    is its offset in .debug_info for this objfile.  */
25586
25587 static hashval_t
25588 partial_die_hash (const void *item)
25589 {
25590   const struct partial_die_info *part_die
25591     = (const struct partial_die_info *) item;
25592
25593   return to_underlying (part_die->sect_off);
25594 }
25595
25596 /* Trivial comparison function for partial_die_info structures: two DIEs
25597    are equal if they have the same offset.  */
25598
25599 static int
25600 partial_die_eq (const void *item_lhs, const void *item_rhs)
25601 {
25602   const struct partial_die_info *part_die_lhs
25603     = (const struct partial_die_info *) item_lhs;
25604   const struct partial_die_info *part_die_rhs
25605     = (const struct partial_die_info *) item_rhs;
25606
25607   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25608 }
25609
25610 static struct cmd_list_element *set_dwarf_cmdlist;
25611 static struct cmd_list_element *show_dwarf_cmdlist;
25612
25613 static void
25614 set_dwarf_cmd (const char *args, int from_tty)
25615 {
25616   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25617              gdb_stdout);
25618 }
25619
25620 static void
25621 show_dwarf_cmd (const char *args, int from_tty)
25622 {
25623   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25624 }
25625
25626 /* Free data associated with OBJFILE, if necessary.  */
25627
25628 static void
25629 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25630 {
25631   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25632   int ix;
25633
25634   for (ix = 0; ix < data->n_comp_units; ++ix)
25635    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25636
25637   for (ix = 0; ix < data->n_type_units; ++ix)
25638     VEC_free (dwarf2_per_cu_ptr,
25639               data->all_type_units[ix]->per_cu.imported_symtabs);
25640   xfree (data->all_type_units);
25641
25642   VEC_free (dwarf2_section_info_def, data->types);
25643
25644   if (data->dwo_files)
25645     free_dwo_files (data->dwo_files, objfile);
25646   if (data->dwp_file)
25647     gdb_bfd_unref (data->dwp_file->dbfd);
25648
25649   if (data->dwz_file && data->dwz_file->dwz_bfd)
25650     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25651
25652   if (data->index_table != NULL)
25653     data->index_table->~mapped_index ();
25654 }
25655
25656 \f
25657 /* The "save gdb-index" command.  */
25658
25659 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25660    error checking.  */
25661
25662 static void
25663 file_write (FILE *file, const void *data, size_t size)
25664 {
25665   if (fwrite (data, 1, size, file) != size)
25666     error (_("couldn't data write to file"));
25667 }
25668
25669 /* Write the contents of VEC to FILE, with error checking.  */
25670
25671 template<typename Elem, typename Alloc>
25672 static void
25673 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25674 {
25675   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25676 }
25677
25678 /* In-memory buffer to prepare data to be written later to a file.  */
25679 class data_buf
25680 {
25681 public:
25682   /* Copy DATA to the end of the buffer.  */
25683   template<typename T>
25684   void append_data (const T &data)
25685   {
25686     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25687                reinterpret_cast<const gdb_byte *> (&data + 1),
25688                grow (sizeof (data)));
25689   }
25690
25691   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25692      terminating zero is appended too.  */
25693   void append_cstr0 (const char *cstr)
25694   {
25695     const size_t size = strlen (cstr) + 1;
25696     std::copy (cstr, cstr + size, grow (size));
25697   }
25698
25699   /* Store INPUT as ULEB128 to the end of buffer.  */
25700   void append_unsigned_leb128 (ULONGEST input)
25701   {
25702     for (;;)
25703       {
25704         gdb_byte output = input & 0x7f;
25705         input >>= 7;
25706         if (input)
25707           output |= 0x80;
25708         append_data (output);
25709         if (input == 0)
25710           break;
25711       }
25712   }
25713
25714   /* Accept a host-format integer in VAL and append it to the buffer
25715      as a target-format integer which is LEN bytes long.  */
25716   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25717   {
25718     ::store_unsigned_integer (grow (len), len, byte_order, val);
25719   }
25720
25721   /* Return the size of the buffer.  */
25722   size_t size () const
25723   {
25724     return m_vec.size ();
25725   }
25726
25727   /* Return true iff the buffer is empty.  */
25728   bool empty () const
25729   {
25730     return m_vec.empty ();
25731   }
25732
25733   /* Write the buffer to FILE.  */
25734   void file_write (FILE *file) const
25735   {
25736     ::file_write (file, m_vec);
25737   }
25738
25739 private:
25740   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25741      the start of the new block.  */
25742   gdb_byte *grow (size_t size)
25743   {
25744     m_vec.resize (m_vec.size () + size);
25745     return &*m_vec.end () - size;
25746   }
25747
25748   gdb::byte_vector m_vec;
25749 };
25750
25751 /* An entry in the symbol table.  */
25752 struct symtab_index_entry
25753 {
25754   /* The name of the symbol.  */
25755   const char *name;
25756   /* The offset of the name in the constant pool.  */
25757   offset_type index_offset;
25758   /* A sorted vector of the indices of all the CUs that hold an object
25759      of this name.  */
25760   std::vector<offset_type> cu_indices;
25761 };
25762
25763 /* The symbol table.  This is a power-of-2-sized hash table.  */
25764 struct mapped_symtab
25765 {
25766   mapped_symtab ()
25767   {
25768     data.resize (1024);
25769   }
25770
25771   offset_type n_elements = 0;
25772   std::vector<symtab_index_entry> data;
25773 };
25774
25775 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25776    the slot.
25777    
25778    Function is used only during write_hash_table so no index format backward
25779    compatibility is needed.  */
25780
25781 static symtab_index_entry &
25782 find_slot (struct mapped_symtab *symtab, const char *name)
25783 {
25784   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25785
25786   index = hash & (symtab->data.size () - 1);
25787   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25788
25789   for (;;)
25790     {
25791       if (symtab->data[index].name == NULL
25792           || strcmp (name, symtab->data[index].name) == 0)
25793         return symtab->data[index];
25794       index = (index + step) & (symtab->data.size () - 1);
25795     }
25796 }
25797
25798 /* Expand SYMTAB's hash table.  */
25799
25800 static void
25801 hash_expand (struct mapped_symtab *symtab)
25802 {
25803   auto old_entries = std::move (symtab->data);
25804
25805   symtab->data.clear ();
25806   symtab->data.resize (old_entries.size () * 2);
25807
25808   for (auto &it : old_entries)
25809     if (it.name != NULL)
25810       {
25811         auto &ref = find_slot (symtab, it.name);
25812         ref = std::move (it);
25813       }
25814 }
25815
25816 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25817    CU_INDEX is the index of the CU in which the symbol appears.
25818    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25819
25820 static void
25821 add_index_entry (struct mapped_symtab *symtab, const char *name,
25822                  int is_static, gdb_index_symbol_kind kind,
25823                  offset_type cu_index)
25824 {
25825   offset_type cu_index_and_attrs;
25826
25827   ++symtab->n_elements;
25828   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25829     hash_expand (symtab);
25830
25831   symtab_index_entry &slot = find_slot (symtab, name);
25832   if (slot.name == NULL)
25833     {
25834       slot.name = name;
25835       /* index_offset is set later.  */
25836     }
25837
25838   cu_index_and_attrs = 0;
25839   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25840   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25841   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25842
25843   /* We don't want to record an index value twice as we want to avoid the
25844      duplication.
25845      We process all global symbols and then all static symbols
25846      (which would allow us to avoid the duplication by only having to check
25847      the last entry pushed), but a symbol could have multiple kinds in one CU.
25848      To keep things simple we don't worry about the duplication here and
25849      sort and uniqufy the list after we've processed all symbols.  */
25850   slot.cu_indices.push_back (cu_index_and_attrs);
25851 }
25852
25853 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25854
25855 static void
25856 uniquify_cu_indices (struct mapped_symtab *symtab)
25857 {
25858   for (auto &entry : symtab->data)
25859     {
25860       if (entry.name != NULL && !entry.cu_indices.empty ())
25861         {
25862           auto &cu_indices = entry.cu_indices;
25863           std::sort (cu_indices.begin (), cu_indices.end ());
25864           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25865           cu_indices.erase (from, cu_indices.end ());
25866         }
25867     }
25868 }
25869
25870 /* A form of 'const char *' suitable for container keys.  Only the
25871    pointer is stored.  The strings themselves are compared, not the
25872    pointers.  */
25873 class c_str_view
25874 {
25875 public:
25876   c_str_view (const char *cstr)
25877     : m_cstr (cstr)
25878   {}
25879
25880   bool operator== (const c_str_view &other) const
25881   {
25882     return strcmp (m_cstr, other.m_cstr) == 0;
25883   }
25884
25885   /* Return the underlying C string.  Note, the returned string is
25886      only a reference with lifetime of this object.  */
25887   const char *c_str () const
25888   {
25889     return m_cstr;
25890   }
25891
25892 private:
25893   friend class c_str_view_hasher;
25894   const char *const m_cstr;
25895 };
25896
25897 /* A std::unordered_map::hasher for c_str_view that uses the right
25898    hash function for strings in a mapped index.  */
25899 class c_str_view_hasher
25900 {
25901 public:
25902   size_t operator () (const c_str_view &x) const
25903   {
25904     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25905   }
25906 };
25907
25908 /* A std::unordered_map::hasher for std::vector<>.  */
25909 template<typename T>
25910 class vector_hasher
25911 {
25912 public:
25913   size_t operator () (const std::vector<T> &key) const
25914   {
25915     return iterative_hash (key.data (),
25916                            sizeof (key.front ()) * key.size (), 0);
25917   }
25918 };
25919
25920 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25921    constant pool entries going into the data buffer CPOOL.  */
25922
25923 static void
25924 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25925 {
25926   {
25927     /* Elements are sorted vectors of the indices of all the CUs that
25928        hold an object of this name.  */
25929     std::unordered_map<std::vector<offset_type>, offset_type,
25930                        vector_hasher<offset_type>>
25931       symbol_hash_table;
25932
25933     /* We add all the index vectors to the constant pool first, to
25934        ensure alignment is ok.  */
25935     for (symtab_index_entry &entry : symtab->data)
25936       {
25937         if (entry.name == NULL)
25938           continue;
25939         gdb_assert (entry.index_offset == 0);
25940
25941         /* Finding before inserting is faster than always trying to
25942            insert, because inserting always allocates a node, does the
25943            lookup, and then destroys the new node if another node
25944            already had the same key.  C++17 try_emplace will avoid
25945            this.  */
25946         const auto found
25947           = symbol_hash_table.find (entry.cu_indices);
25948         if (found != symbol_hash_table.end ())
25949           {
25950             entry.index_offset = found->second;
25951             continue;
25952           }
25953
25954         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25955         entry.index_offset = cpool.size ();
25956         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25957         for (const auto index : entry.cu_indices)
25958           cpool.append_data (MAYBE_SWAP (index));
25959       }
25960   }
25961
25962   /* Now write out the hash table.  */
25963   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25964   for (const auto &entry : symtab->data)
25965     {
25966       offset_type str_off, vec_off;
25967
25968       if (entry.name != NULL)
25969         {
25970           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25971           if (insertpair.second)
25972             cpool.append_cstr0 (entry.name);
25973           str_off = insertpair.first->second;
25974           vec_off = entry.index_offset;
25975         }
25976       else
25977         {
25978           /* While 0 is a valid constant pool index, it is not valid
25979              to have 0 for both offsets.  */
25980           str_off = 0;
25981           vec_off = 0;
25982         }
25983
25984       output.append_data (MAYBE_SWAP (str_off));
25985       output.append_data (MAYBE_SWAP (vec_off));
25986     }
25987 }
25988
25989 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25990
25991 /* Helper struct for building the address table.  */
25992 struct addrmap_index_data
25993 {
25994   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25995     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25996   {}
25997
25998   struct objfile *objfile;
25999   data_buf &addr_vec;
26000   psym_index_map &cu_index_htab;
26001
26002   /* Non-zero if the previous_* fields are valid.
26003      We can't write an entry until we see the next entry (since it is only then
26004      that we know the end of the entry).  */
26005   int previous_valid;
26006   /* Index of the CU in the table of all CUs in the index file.  */
26007   unsigned int previous_cu_index;
26008   /* Start address of the CU.  */
26009   CORE_ADDR previous_cu_start;
26010 };
26011
26012 /* Write an address entry to ADDR_VEC.  */
26013
26014 static void
26015 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
26016                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
26017 {
26018   CORE_ADDR baseaddr;
26019
26020   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
26021
26022   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
26023   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
26024   addr_vec.append_data (MAYBE_SWAP (cu_index));
26025 }
26026
26027 /* Worker function for traversing an addrmap to build the address table.  */
26028
26029 static int
26030 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
26031 {
26032   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
26033   struct partial_symtab *pst = (struct partial_symtab *) obj;
26034
26035   if (data->previous_valid)
26036     add_address_entry (data->objfile, data->addr_vec,
26037                        data->previous_cu_start, start_addr,
26038                        data->previous_cu_index);
26039
26040   data->previous_cu_start = start_addr;
26041   if (pst != NULL)
26042     {
26043       const auto it = data->cu_index_htab.find (pst);
26044       gdb_assert (it != data->cu_index_htab.cend ());
26045       data->previous_cu_index = it->second;
26046       data->previous_valid = 1;
26047     }
26048   else
26049     data->previous_valid = 0;
26050
26051   return 0;
26052 }
26053
26054 /* Write OBJFILE's address map to ADDR_VEC.
26055    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
26056    in the index file.  */
26057
26058 static void
26059 write_address_map (struct objfile *objfile, data_buf &addr_vec,
26060                    psym_index_map &cu_index_htab)
26061 {
26062   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
26063
26064   /* When writing the address table, we have to cope with the fact that
26065      the addrmap iterator only provides the start of a region; we have to
26066      wait until the next invocation to get the start of the next region.  */
26067
26068   addrmap_index_data.objfile = objfile;
26069   addrmap_index_data.previous_valid = 0;
26070
26071   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
26072                    &addrmap_index_data);
26073
26074   /* It's highly unlikely the last entry (end address = 0xff...ff)
26075      is valid, but we should still handle it.
26076      The end address is recorded as the start of the next region, but that
26077      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
26078      anyway.  */
26079   if (addrmap_index_data.previous_valid)
26080     add_address_entry (objfile, addr_vec,
26081                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
26082                        addrmap_index_data.previous_cu_index);
26083 }
26084
26085 /* Return the symbol kind of PSYM.  */
26086
26087 static gdb_index_symbol_kind
26088 symbol_kind (struct partial_symbol *psym)
26089 {
26090   domain_enum domain = PSYMBOL_DOMAIN (psym);
26091   enum address_class aclass = PSYMBOL_CLASS (psym);
26092
26093   switch (domain)
26094     {
26095     case VAR_DOMAIN:
26096       switch (aclass)
26097         {
26098         case LOC_BLOCK:
26099           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
26100         case LOC_TYPEDEF:
26101           return GDB_INDEX_SYMBOL_KIND_TYPE;
26102         case LOC_COMPUTED:
26103         case LOC_CONST_BYTES:
26104         case LOC_OPTIMIZED_OUT:
26105         case LOC_STATIC:
26106           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26107         case LOC_CONST:
26108           /* Note: It's currently impossible to recognize psyms as enum values
26109              short of reading the type info.  For now punt.  */
26110           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26111         default:
26112           /* There are other LOC_FOO values that one might want to classify
26113              as variables, but dwarf2read.c doesn't currently use them.  */
26114           return GDB_INDEX_SYMBOL_KIND_OTHER;
26115         }
26116     case STRUCT_DOMAIN:
26117       return GDB_INDEX_SYMBOL_KIND_TYPE;
26118     default:
26119       return GDB_INDEX_SYMBOL_KIND_OTHER;
26120     }
26121 }
26122
26123 /* Add a list of partial symbols to SYMTAB.  */
26124
26125 static void
26126 write_psymbols (struct mapped_symtab *symtab,
26127                 std::unordered_set<partial_symbol *> &psyms_seen,
26128                 struct partial_symbol **psymp,
26129                 int count,
26130                 offset_type cu_index,
26131                 int is_static)
26132 {
26133   for (; count-- > 0; ++psymp)
26134     {
26135       struct partial_symbol *psym = *psymp;
26136
26137       if (SYMBOL_LANGUAGE (psym) == language_ada)
26138         error (_("Ada is not currently supported by the index"));
26139
26140       /* Only add a given psymbol once.  */
26141       if (psyms_seen.insert (psym).second)
26142         {
26143           gdb_index_symbol_kind kind = symbol_kind (psym);
26144
26145           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26146                            is_static, kind, cu_index);
26147         }
26148     }
26149 }
26150
26151 /* A helper struct used when iterating over debug_types.  */
26152 struct signatured_type_index_data
26153 {
26154   signatured_type_index_data (data_buf &types_list_,
26155                               std::unordered_set<partial_symbol *> &psyms_seen_)
26156     : types_list (types_list_), psyms_seen (psyms_seen_)
26157   {}
26158
26159   struct objfile *objfile;
26160   struct mapped_symtab *symtab;
26161   data_buf &types_list;
26162   std::unordered_set<partial_symbol *> &psyms_seen;
26163   int cu_index;
26164 };
26165
26166 /* A helper function that writes a single signatured_type to an
26167    obstack.  */
26168
26169 static int
26170 write_one_signatured_type (void **slot, void *d)
26171 {
26172   struct signatured_type_index_data *info
26173     = (struct signatured_type_index_data *) d;
26174   struct signatured_type *entry = (struct signatured_type *) *slot;
26175   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26176
26177   write_psymbols (info->symtab,
26178                   info->psyms_seen,
26179                   &info->objfile->global_psymbols[psymtab->globals_offset],
26180                   psymtab->n_global_syms, info->cu_index,
26181                   0);
26182   write_psymbols (info->symtab,
26183                   info->psyms_seen,
26184                   &info->objfile->static_psymbols[psymtab->statics_offset],
26185                   psymtab->n_static_syms, info->cu_index,
26186                   1);
26187
26188   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26189                                 to_underlying (entry->per_cu.sect_off));
26190   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26191                                 to_underlying (entry->type_offset_in_tu));
26192   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26193
26194   ++info->cu_index;
26195
26196   return 1;
26197 }
26198
26199 /* Recurse into all "included" dependencies and count their symbols as
26200    if they appeared in this psymtab.  */
26201
26202 static void
26203 recursively_count_psymbols (struct partial_symtab *psymtab,
26204                             size_t &psyms_seen)
26205 {
26206   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26207     if (psymtab->dependencies[i]->user != NULL)
26208       recursively_count_psymbols (psymtab->dependencies[i],
26209                                   psyms_seen);
26210
26211   psyms_seen += psymtab->n_global_syms;
26212   psyms_seen += psymtab->n_static_syms;
26213 }
26214
26215 /* Recurse into all "included" dependencies and write their symbols as
26216    if they appeared in this psymtab.  */
26217
26218 static void
26219 recursively_write_psymbols (struct objfile *objfile,
26220                             struct partial_symtab *psymtab,
26221                             struct mapped_symtab *symtab,
26222                             std::unordered_set<partial_symbol *> &psyms_seen,
26223                             offset_type cu_index)
26224 {
26225   int i;
26226
26227   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26228     if (psymtab->dependencies[i]->user != NULL)
26229       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26230                                   symtab, psyms_seen, cu_index);
26231
26232   write_psymbols (symtab,
26233                   psyms_seen,
26234                   &objfile->global_psymbols[psymtab->globals_offset],
26235                   psymtab->n_global_syms, cu_index,
26236                   0);
26237   write_psymbols (symtab,
26238                   psyms_seen,
26239                   &objfile->static_psymbols[psymtab->statics_offset],
26240                   psymtab->n_static_syms, cu_index,
26241                   1);
26242 }
26243
26244 /* DWARF-5 .debug_names builder.  */
26245 class debug_names
26246 {
26247 public:
26248   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26249                bfd_endian dwarf5_byte_order)
26250     : m_dwarf5_byte_order (dwarf5_byte_order),
26251       m_dwarf32 (dwarf5_byte_order),
26252       m_dwarf64 (dwarf5_byte_order),
26253       m_dwarf (is_dwarf64
26254                ? static_cast<dwarf &> (m_dwarf64)
26255                : static_cast<dwarf &> (m_dwarf32)),
26256       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26257       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26258       m_debugstrlookup (dwarf2_per_objfile)
26259   {}
26260
26261   int dwarf5_offset_size () const
26262   {
26263     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26264     return dwarf5_is_dwarf64 ? 8 : 4;
26265   }
26266
26267   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26268   enum class unit_kind { cu, tu };
26269
26270   /* Insert one symbol.  */
26271   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26272                unit_kind kind)
26273   {
26274     const int dwarf_tag = psymbol_tag (psym);
26275     if (dwarf_tag == 0)
26276       return;
26277     const char *const name = SYMBOL_SEARCH_NAME (psym);
26278     const auto insertpair
26279       = m_name_to_value_set.emplace (c_str_view (name),
26280                                      std::set<symbol_value> ());
26281     std::set<symbol_value> &value_set = insertpair.first->second;
26282     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26283   }
26284
26285   /* Build all the tables.  All symbols must be already inserted.
26286      This function does not call file_write, caller has to do it
26287      afterwards.  */
26288   void build ()
26289   {
26290     /* Verify the build method has not be called twice.  */
26291     gdb_assert (m_abbrev_table.empty ());
26292     const size_t name_count = m_name_to_value_set.size ();
26293     m_bucket_table.resize
26294       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26295     m_hash_table.reserve (name_count);
26296     m_name_table_string_offs.reserve (name_count);
26297     m_name_table_entry_offs.reserve (name_count);
26298
26299     /* Map each hash of symbol to its name and value.  */
26300     struct hash_it_pair
26301     {
26302       uint32_t hash;
26303       decltype (m_name_to_value_set)::const_iterator it;
26304     };
26305     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26306     bucket_hash.resize (m_bucket_table.size ());
26307     for (decltype (m_name_to_value_set)::const_iterator it
26308            = m_name_to_value_set.cbegin ();
26309          it != m_name_to_value_set.cend ();
26310          ++it)
26311       {
26312         const char *const name = it->first.c_str ();
26313         const uint32_t hash = dwarf5_djb_hash (name);
26314         hash_it_pair hashitpair;
26315         hashitpair.hash = hash;
26316         hashitpair.it = it;
26317         auto &slot = bucket_hash[hash % bucket_hash.size()];
26318         slot.push_front (std::move (hashitpair));
26319       }
26320     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26321       {
26322         const std::forward_list<hash_it_pair> &hashitlist
26323           = bucket_hash[bucket_ix];
26324         if (hashitlist.empty ())
26325           continue;
26326         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26327         /* The hashes array is indexed starting at 1.  */
26328         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26329                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26330                                 m_hash_table.size () + 1);
26331         for (const hash_it_pair &hashitpair : hashitlist)
26332           {
26333             m_hash_table.push_back (0);
26334             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26335                                                         (&m_hash_table.back ()),
26336                                     sizeof (m_hash_table.back ()),
26337                                     m_dwarf5_byte_order, hashitpair.hash);
26338             const c_str_view &name = hashitpair.it->first;
26339             const std::set<symbol_value> &value_set = hashitpair.it->second;
26340             m_name_table_string_offs.push_back_reorder
26341               (m_debugstrlookup.lookup (name.c_str ()));
26342             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26343             gdb_assert (!value_set.empty ());
26344             for (const symbol_value &value : value_set)
26345               {
26346                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26347                                                         value.is_static,
26348                                                         value.kind)];
26349                 if (idx == 0)
26350                   {
26351                     idx = m_idx_next++;
26352                     m_abbrev_table.append_unsigned_leb128 (idx);
26353                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26354                     m_abbrev_table.append_unsigned_leb128
26355                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26356                                                            : DW_IDX_type_unit);
26357                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26358                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26359                                                            ? DW_IDX_GNU_internal
26360                                                            : DW_IDX_GNU_external);
26361                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26362
26363                     /* Terminate attributes list.  */
26364                     m_abbrev_table.append_unsigned_leb128 (0);
26365                     m_abbrev_table.append_unsigned_leb128 (0);
26366                   }
26367
26368                 m_entry_pool.append_unsigned_leb128 (idx);
26369                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26370               }
26371
26372             /* Terminate the list of CUs.  */
26373             m_entry_pool.append_unsigned_leb128 (0);
26374           }
26375       }
26376     gdb_assert (m_hash_table.size () == name_count);
26377
26378     /* Terminate tags list.  */
26379     m_abbrev_table.append_unsigned_leb128 (0);
26380   }
26381
26382   /* Return .debug_names bucket count.  This must be called only after
26383      calling the build method.  */
26384   uint32_t bucket_count () const
26385   {
26386     /* Verify the build method has been already called.  */
26387     gdb_assert (!m_abbrev_table.empty ());
26388     const uint32_t retval = m_bucket_table.size ();
26389
26390     /* Check for overflow.  */
26391     gdb_assert (retval == m_bucket_table.size ());
26392     return retval;
26393   }
26394
26395   /* Return .debug_names names count.  This must be called only after
26396      calling the build method.  */
26397   uint32_t name_count () const
26398   {
26399     /* Verify the build method has been already called.  */
26400     gdb_assert (!m_abbrev_table.empty ());
26401     const uint32_t retval = m_hash_table.size ();
26402
26403     /* Check for overflow.  */
26404     gdb_assert (retval == m_hash_table.size ());
26405     return retval;
26406   }
26407
26408   /* Return number of bytes of .debug_names abbreviation table.  This
26409      must be called only after calling the build method.  */
26410   uint32_t abbrev_table_bytes () const
26411   {
26412     gdb_assert (!m_abbrev_table.empty ());
26413     return m_abbrev_table.size ();
26414   }
26415
26416   /* Recurse into all "included" dependencies and store their symbols
26417      as if they appeared in this psymtab.  */
26418   void recursively_write_psymbols
26419     (struct objfile *objfile,
26420      struct partial_symtab *psymtab,
26421      std::unordered_set<partial_symbol *> &psyms_seen,
26422      int cu_index)
26423   {
26424     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26425       if (psymtab->dependencies[i]->user != NULL)
26426         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26427                                     psyms_seen, cu_index);
26428
26429     write_psymbols (psyms_seen,
26430                     &objfile->global_psymbols[psymtab->globals_offset],
26431                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26432     write_psymbols (psyms_seen,
26433                     &objfile->static_psymbols[psymtab->statics_offset],
26434                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26435   }
26436
26437   /* Return number of bytes the .debug_names section will have.  This
26438      must be called only after calling the build method.  */
26439   size_t bytes () const
26440   {
26441     /* Verify the build method has been already called.  */
26442     gdb_assert (!m_abbrev_table.empty ());
26443     size_t expected_bytes = 0;
26444     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26445     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26446     expected_bytes += m_name_table_string_offs.bytes ();
26447     expected_bytes += m_name_table_entry_offs.bytes ();
26448     expected_bytes += m_abbrev_table.size ();
26449     expected_bytes += m_entry_pool.size ();
26450     return expected_bytes;
26451   }
26452
26453   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26454      FILE_STR.  This must be called only after calling the build
26455      method.  */
26456   void file_write (FILE *file_names, FILE *file_str) const
26457   {
26458     /* Verify the build method has been already called.  */
26459     gdb_assert (!m_abbrev_table.empty ());
26460     ::file_write (file_names, m_bucket_table);
26461     ::file_write (file_names, m_hash_table);
26462     m_name_table_string_offs.file_write (file_names);
26463     m_name_table_entry_offs.file_write (file_names);
26464     m_abbrev_table.file_write (file_names);
26465     m_entry_pool.file_write (file_names);
26466     m_debugstrlookup.file_write (file_str);
26467   }
26468
26469   /* A helper user data for write_one_signatured_type.  */
26470   class write_one_signatured_type_data
26471   {
26472   public:
26473     write_one_signatured_type_data (debug_names &nametable_,
26474                                     signatured_type_index_data &&info_)
26475     : nametable (nametable_), info (std::move (info_))
26476     {}
26477     debug_names &nametable;
26478     struct signatured_type_index_data info;
26479   };
26480
26481   /* A helper function to pass write_one_signatured_type to
26482      htab_traverse_noresize.  */
26483   static int
26484   write_one_signatured_type (void **slot, void *d)
26485   {
26486     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26487     struct signatured_type_index_data *info = &data->info;
26488     struct signatured_type *entry = (struct signatured_type *) *slot;
26489
26490     data->nametable.write_one_signatured_type (entry, info);
26491
26492     return 1;
26493   }
26494
26495 private:
26496
26497   /* Storage for symbol names mapping them to their .debug_str section
26498      offsets.  */
26499   class debug_str_lookup
26500   {
26501   public:
26502
26503     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26504        All .debug_str section strings are automatically stored.  */
26505     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26506       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26507         m_dwarf2_per_objfile (dwarf2_per_objfile)
26508     {
26509       dwarf2_read_section (dwarf2_per_objfile->objfile,
26510                            &dwarf2_per_objfile->str);
26511       if (dwarf2_per_objfile->str.buffer == NULL)
26512         return;
26513       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26514            data < (dwarf2_per_objfile->str.buffer
26515                    + dwarf2_per_objfile->str.size);)
26516         {
26517           const char *const s = reinterpret_cast<const char *> (data);
26518           const auto insertpair
26519             = m_str_table.emplace (c_str_view (s),
26520                                    data - dwarf2_per_objfile->str.buffer);
26521           if (!insertpair.second)
26522             complaint (&symfile_complaints,
26523                        _("Duplicate string \"%s\" in "
26524                          ".debug_str section [in module %s]"),
26525                        s, bfd_get_filename (m_abfd));
26526           data += strlen (s) + 1;
26527         }
26528     }
26529
26530     /* Return offset of symbol name S in the .debug_str section.  Add
26531        such symbol to the section's end if it does not exist there
26532        yet.  */
26533     size_t lookup (const char *s)
26534     {
26535       const auto it = m_str_table.find (c_str_view (s));
26536       if (it != m_str_table.end ())
26537         return it->second;
26538       const size_t offset = (m_dwarf2_per_objfile->str.size
26539                              + m_str_add_buf.size ());
26540       m_str_table.emplace (c_str_view (s), offset);
26541       m_str_add_buf.append_cstr0 (s);
26542       return offset;
26543     }
26544
26545     /* Append the end of the .debug_str section to FILE.  */
26546     void file_write (FILE *file) const
26547     {
26548       m_str_add_buf.file_write (file);
26549     }
26550
26551   private:
26552     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26553     bfd *const m_abfd;
26554     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26555
26556     /* Data to add at the end of .debug_str for new needed symbol names.  */
26557     data_buf m_str_add_buf;
26558   };
26559
26560   /* Container to map used DWARF tags to their .debug_names abbreviation
26561      tags.  */
26562   class index_key
26563   {
26564   public:
26565     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26566       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26567     {
26568     }
26569
26570     bool
26571     operator== (const index_key &other) const
26572     {
26573       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26574               && kind == other.kind);
26575     }
26576
26577     const int dwarf_tag;
26578     const bool is_static;
26579     const unit_kind kind;
26580   };
26581
26582   /* Provide std::unordered_map::hasher for index_key.  */
26583   class index_key_hasher
26584   {
26585   public:
26586     size_t
26587     operator () (const index_key &key) const
26588     {
26589       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26590     }
26591   };
26592
26593   /* Parameters of one symbol entry.  */
26594   class symbol_value
26595   {
26596   public:
26597     const int dwarf_tag, cu_index;
26598     const bool is_static;
26599     const unit_kind kind;
26600
26601     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26602                   unit_kind kind_)
26603       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26604         kind (kind_)
26605     {}
26606
26607     bool
26608     operator< (const symbol_value &other) const
26609     {
26610 #define X(n) \
26611   do \
26612     { \
26613       if (n < other.n) \
26614         return true; \
26615       if (n > other.n) \
26616         return false; \
26617     } \
26618   while (0)
26619       X (dwarf_tag);
26620       X (is_static);
26621       X (kind);
26622       X (cu_index);
26623 #undef X
26624       return false;
26625     }
26626   };
26627
26628   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26629      output.  */
26630   class offset_vec
26631   {
26632   protected:
26633     const bfd_endian dwarf5_byte_order;
26634   public:
26635     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26636       : dwarf5_byte_order (dwarf5_byte_order_)
26637     {}
26638
26639     /* Call std::vector::reserve for NELEM elements.  */
26640     virtual void reserve (size_t nelem) = 0;
26641
26642     /* Call std::vector::push_back with store_unsigned_integer byte
26643        reordering for ELEM.  */
26644     virtual void push_back_reorder (size_t elem) = 0;
26645
26646     /* Return expected output size in bytes.  */
26647     virtual size_t bytes () const = 0;
26648
26649     /* Write name table to FILE.  */
26650     virtual void file_write (FILE *file) const = 0;
26651   };
26652
26653   /* Template to unify DWARF-32 and DWARF-64 output.  */
26654   template<typename OffsetSize>
26655   class offset_vec_tmpl : public offset_vec
26656   {
26657   public:
26658     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26659       : offset_vec (dwarf5_byte_order_)
26660     {}
26661
26662     /* Implement offset_vec::reserve.  */
26663     void reserve (size_t nelem) override
26664     {
26665       m_vec.reserve (nelem);
26666     }
26667
26668     /* Implement offset_vec::push_back_reorder.  */
26669     void push_back_reorder (size_t elem) override
26670     {
26671       m_vec.push_back (elem);
26672       /* Check for overflow.  */
26673       gdb_assert (m_vec.back () == elem);
26674       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26675                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26676     }
26677
26678     /* Implement offset_vec::bytes.  */
26679     size_t bytes () const override
26680     {
26681       return m_vec.size () * sizeof (m_vec[0]);
26682     }
26683
26684     /* Implement offset_vec::file_write.  */
26685     void file_write (FILE *file) const override
26686     {
26687       ::file_write (file, m_vec);
26688     }
26689
26690   private:
26691     std::vector<OffsetSize> m_vec;
26692   };
26693
26694   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26695      respecting name table width.  */
26696   class dwarf
26697   {
26698   public:
26699     offset_vec &name_table_string_offs, &name_table_entry_offs;
26700
26701     dwarf (offset_vec &name_table_string_offs_,
26702            offset_vec &name_table_entry_offs_)
26703       : name_table_string_offs (name_table_string_offs_),
26704         name_table_entry_offs (name_table_entry_offs_)
26705     {
26706     }
26707   };
26708
26709   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26710      respecting name table width.  */
26711   template<typename OffsetSize>
26712   class dwarf_tmpl : public dwarf
26713   {
26714   public:
26715     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26716       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26717         m_name_table_string_offs (dwarf5_byte_order_),
26718         m_name_table_entry_offs (dwarf5_byte_order_)
26719     {}
26720
26721   private:
26722     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26723     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26724   };
26725
26726   /* Try to reconstruct original DWARF tag for given partial_symbol.
26727      This function is not DWARF-5 compliant but it is sufficient for
26728      GDB as a DWARF-5 index consumer.  */
26729   static int psymbol_tag (const struct partial_symbol *psym)
26730   {
26731     domain_enum domain = PSYMBOL_DOMAIN (psym);
26732     enum address_class aclass = PSYMBOL_CLASS (psym);
26733
26734     switch (domain)
26735       {
26736       case VAR_DOMAIN:
26737         switch (aclass)
26738           {
26739           case LOC_BLOCK:
26740             return DW_TAG_subprogram;
26741           case LOC_TYPEDEF:
26742             return DW_TAG_typedef;
26743           case LOC_COMPUTED:
26744           case LOC_CONST_BYTES:
26745           case LOC_OPTIMIZED_OUT:
26746           case LOC_STATIC:
26747             return DW_TAG_variable;
26748           case LOC_CONST:
26749             /* Note: It's currently impossible to recognize psyms as enum values
26750                short of reading the type info.  For now punt.  */
26751             return DW_TAG_variable;
26752           default:
26753             /* There are other LOC_FOO values that one might want to classify
26754                as variables, but dwarf2read.c doesn't currently use them.  */
26755             return DW_TAG_variable;
26756           }
26757       case STRUCT_DOMAIN:
26758         return DW_TAG_structure_type;
26759       default:
26760         return 0;
26761       }
26762   }
26763
26764   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26765   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26766                        struct partial_symbol **psymp, int count, int cu_index,
26767                        bool is_static, unit_kind kind)
26768   {
26769     for (; count-- > 0; ++psymp)
26770       {
26771         struct partial_symbol *psym = *psymp;
26772
26773         if (SYMBOL_LANGUAGE (psym) == language_ada)
26774           error (_("Ada is not currently supported by the index"));
26775
26776         /* Only add a given psymbol once.  */
26777         if (psyms_seen.insert (psym).second)
26778           insert (psym, cu_index, is_static, kind);
26779       }
26780   }
26781
26782   /* A helper function that writes a single signatured_type
26783      to a debug_names.  */
26784   void
26785   write_one_signatured_type (struct signatured_type *entry,
26786                              struct signatured_type_index_data *info)
26787   {
26788     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26789
26790     write_psymbols (info->psyms_seen,
26791                     &info->objfile->global_psymbols[psymtab->globals_offset],
26792                     psymtab->n_global_syms, info->cu_index, false,
26793                     unit_kind::tu);
26794     write_psymbols (info->psyms_seen,
26795                     &info->objfile->static_psymbols[psymtab->statics_offset],
26796                     psymtab->n_static_syms, info->cu_index, true,
26797                     unit_kind::tu);
26798
26799     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26800                                   to_underlying (entry->per_cu.sect_off));
26801
26802     ++info->cu_index;
26803   }
26804
26805   /* Store value of each symbol.  */
26806   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26807     m_name_to_value_set;
26808
26809   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26810      order.  */
26811   std::vector<uint32_t> m_bucket_table;
26812   std::vector<uint32_t> m_hash_table;
26813
26814   const bfd_endian m_dwarf5_byte_order;
26815   dwarf_tmpl<uint32_t> m_dwarf32;
26816   dwarf_tmpl<uint64_t> m_dwarf64;
26817   dwarf &m_dwarf;
26818   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26819   debug_str_lookup m_debugstrlookup;
26820
26821   /* Map each used .debug_names abbreviation tag parameter to its
26822      index value.  */
26823   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26824
26825   /* Next unused .debug_names abbreviation tag for
26826      m_indexkey_to_idx.  */
26827   int m_idx_next = 1;
26828
26829   /* .debug_names abbreviation table.  */
26830   data_buf m_abbrev_table;
26831
26832   /* .debug_names entry pool.  */
26833   data_buf m_entry_pool;
26834 };
26835
26836 /* Return iff any of the needed offsets does not fit into 32-bit
26837    .debug_names section.  */
26838
26839 static bool
26840 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26841 {
26842   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26843     {
26844       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26845
26846       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26847         return true;
26848     }
26849   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26850     {
26851       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26852       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26853
26854       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26855         return true;
26856     }
26857   return false;
26858 }
26859
26860 /* The psyms_seen set is potentially going to be largish (~40k
26861    elements when indexing a -g3 build of GDB itself).  Estimate the
26862    number of elements in order to avoid too many rehashes, which
26863    require rebuilding buckets and thus many trips to
26864    malloc/free.  */
26865
26866 static size_t
26867 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26868 {
26869   size_t psyms_count = 0;
26870   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26871     {
26872       struct dwarf2_per_cu_data *per_cu
26873         = dwarf2_per_objfile->all_comp_units[i];
26874       struct partial_symtab *psymtab = per_cu->v.psymtab;
26875
26876       if (psymtab != NULL && psymtab->user == NULL)
26877         recursively_count_psymbols (psymtab, psyms_count);
26878     }
26879   /* Generating an index for gdb itself shows a ratio of
26880      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26881   return psyms_count / 4;
26882 }
26883
26884 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26885    Return how many bytes were expected to be written into OUT_FILE.  */
26886
26887 static size_t
26888 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26889 {
26890   struct objfile *objfile = dwarf2_per_objfile->objfile;
26891   mapped_symtab symtab;
26892   data_buf cu_list;
26893
26894   /* While we're scanning CU's create a table that maps a psymtab pointer
26895      (which is what addrmap records) to its index (which is what is recorded
26896      in the index file).  This will later be needed to write the address
26897      table.  */
26898   psym_index_map cu_index_htab;
26899   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26900
26901   /* The CU list is already sorted, so we don't need to do additional
26902      work here.  Also, the debug_types entries do not appear in
26903      all_comp_units, but only in their own hash table.  */
26904
26905   std::unordered_set<partial_symbol *> psyms_seen
26906     (psyms_seen_size (dwarf2_per_objfile));
26907   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26908     {
26909       struct dwarf2_per_cu_data *per_cu
26910         = dwarf2_per_objfile->all_comp_units[i];
26911       struct partial_symtab *psymtab = per_cu->v.psymtab;
26912
26913       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26914          It may be referenced from a local scope but in such case it does not
26915          need to be present in .gdb_index.  */
26916       if (psymtab == NULL)
26917         continue;
26918
26919       if (psymtab->user == NULL)
26920         recursively_write_psymbols (objfile, psymtab, &symtab,
26921                                     psyms_seen, i);
26922
26923       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26924       gdb_assert (insertpair.second);
26925
26926       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26927                            to_underlying (per_cu->sect_off));
26928       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26929     }
26930
26931   /* Dump the address map.  */
26932   data_buf addr_vec;
26933   write_address_map (objfile, addr_vec, cu_index_htab);
26934
26935   /* Write out the .debug_type entries, if any.  */
26936   data_buf types_cu_list;
26937   if (dwarf2_per_objfile->signatured_types)
26938     {
26939       signatured_type_index_data sig_data (types_cu_list,
26940                                            psyms_seen);
26941
26942       sig_data.objfile = objfile;
26943       sig_data.symtab = &symtab;
26944       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26945       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26946                               write_one_signatured_type, &sig_data);
26947     }
26948
26949   /* Now that we've processed all symbols we can shrink their cu_indices
26950      lists.  */
26951   uniquify_cu_indices (&symtab);
26952
26953   data_buf symtab_vec, constant_pool;
26954   write_hash_table (&symtab, symtab_vec, constant_pool);
26955
26956   data_buf contents;
26957   const offset_type size_of_contents = 6 * sizeof (offset_type);
26958   offset_type total_len = size_of_contents;
26959
26960   /* The version number.  */
26961   contents.append_data (MAYBE_SWAP (8));
26962
26963   /* The offset of the CU list from the start of the file.  */
26964   contents.append_data (MAYBE_SWAP (total_len));
26965   total_len += cu_list.size ();
26966
26967   /* The offset of the types CU list from the start of the file.  */
26968   contents.append_data (MAYBE_SWAP (total_len));
26969   total_len += types_cu_list.size ();
26970
26971   /* The offset of the address table from the start of the file.  */
26972   contents.append_data (MAYBE_SWAP (total_len));
26973   total_len += addr_vec.size ();
26974
26975   /* The offset of the symbol table from the start of the file.  */
26976   contents.append_data (MAYBE_SWAP (total_len));
26977   total_len += symtab_vec.size ();
26978
26979   /* The offset of the constant pool from the start of the file.  */
26980   contents.append_data (MAYBE_SWAP (total_len));
26981   total_len += constant_pool.size ();
26982
26983   gdb_assert (contents.size () == size_of_contents);
26984
26985   contents.file_write (out_file);
26986   cu_list.file_write (out_file);
26987   types_cu_list.file_write (out_file);
26988   addr_vec.file_write (out_file);
26989   symtab_vec.file_write (out_file);
26990   constant_pool.file_write (out_file);
26991
26992   return total_len;
26993 }
26994
26995 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26996 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26997
26998 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26999    needed addition to .debug_str section to OUT_FILE_STR.  Return how
27000    many bytes were expected to be written into OUT_FILE.  */
27001
27002 static size_t
27003 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
27004                    FILE *out_file, FILE *out_file_str)
27005 {
27006   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
27007   struct objfile *objfile = dwarf2_per_objfile->objfile;
27008   const enum bfd_endian dwarf5_byte_order
27009     = gdbarch_byte_order (get_objfile_arch (objfile));
27010
27011   /* The CU list is already sorted, so we don't need to do additional
27012      work here.  Also, the debug_types entries do not appear in
27013      all_comp_units, but only in their own hash table.  */
27014   data_buf cu_list;
27015   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
27016                          dwarf5_byte_order);
27017   std::unordered_set<partial_symbol *>
27018     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
27019   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27020     {
27021       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
27022       partial_symtab *psymtab = per_cu->v.psymtab;
27023
27024       /* CU of a shared file from 'dwz -m' may be unused by this main
27025          file.  It may be referenced from a local scope but in such
27026          case it does not need to be present in .debug_names.  */
27027       if (psymtab == NULL)
27028         continue;
27029
27030       if (psymtab->user == NULL)
27031         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
27032
27033       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
27034                            to_underlying (per_cu->sect_off));
27035     }
27036
27037   /* Write out the .debug_type entries, if any.  */
27038   data_buf types_cu_list;
27039   if (dwarf2_per_objfile->signatured_types)
27040     {
27041       debug_names::write_one_signatured_type_data sig_data (nametable,
27042                         signatured_type_index_data (types_cu_list, psyms_seen));
27043
27044       sig_data.info.objfile = objfile;
27045       /* It is used only for gdb_index.  */
27046       sig_data.info.symtab = nullptr;
27047       sig_data.info.cu_index = 0;
27048       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27049                               debug_names::write_one_signatured_type,
27050                               &sig_data);
27051     }
27052
27053   nametable.build ();
27054
27055   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
27056
27057   const offset_type bytes_of_header
27058     = ((dwarf5_is_dwarf64 ? 12 : 4)
27059        + 2 + 2 + 7 * 4
27060        + sizeof (dwarf5_gdb_augmentation));
27061   size_t expected_bytes = 0;
27062   expected_bytes += bytes_of_header;
27063   expected_bytes += cu_list.size ();
27064   expected_bytes += types_cu_list.size ();
27065   expected_bytes += nametable.bytes ();
27066   data_buf header;
27067
27068   if (!dwarf5_is_dwarf64)
27069     {
27070       const uint64_t size64 = expected_bytes - 4;
27071       gdb_assert (size64 < 0xfffffff0);
27072       header.append_uint (4, dwarf5_byte_order, size64);
27073     }
27074   else
27075     {
27076       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
27077       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
27078     }
27079
27080   /* The version number.  */
27081   header.append_uint (2, dwarf5_byte_order, 5);
27082
27083   /* Padding.  */
27084   header.append_uint (2, dwarf5_byte_order, 0);
27085
27086   /* comp_unit_count - The number of CUs in the CU list.  */
27087   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
27088
27089   /* local_type_unit_count - The number of TUs in the local TU
27090      list.  */
27091   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
27092
27093   /* foreign_type_unit_count - The number of TUs in the foreign TU
27094      list.  */
27095   header.append_uint (4, dwarf5_byte_order, 0);
27096
27097   /* bucket_count - The number of hash buckets in the hash lookup
27098      table.  */
27099   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
27100
27101   /* name_count - The number of unique names in the index.  */
27102   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
27103
27104   /* abbrev_table_size - The size in bytes of the abbreviations
27105      table.  */
27106   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
27107
27108   /* augmentation_string_size - The size in bytes of the augmentation
27109      string.  This value is rounded up to a multiple of 4.  */
27110   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
27111   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
27112   header.append_data (dwarf5_gdb_augmentation);
27113
27114   gdb_assert (header.size () == bytes_of_header);
27115
27116   header.file_write (out_file);
27117   cu_list.file_write (out_file);
27118   types_cu_list.file_write (out_file);
27119   nametable.file_write (out_file, out_file_str);
27120
27121   return expected_bytes;
27122 }
27123
27124 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
27125    position is at the end of the file.  */
27126
27127 static void
27128 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27129 {
27130   const auto file_size = ftell (file);
27131   if (file_size == -1)
27132     error (_("Can't get `%s' size"), filename);
27133   gdb_assert (file_size == expected_size);
27134 }
27135
27136 /* Create an index file for OBJFILE in the directory DIR.  */
27137
27138 static void
27139 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27140                          const char *dir,
27141                          dw_index_kind index_kind)
27142 {
27143   struct objfile *objfile = dwarf2_per_objfile->objfile;
27144
27145   if (dwarf2_per_objfile->using_index)
27146     error (_("Cannot use an index to create the index"));
27147
27148   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27149     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27150
27151   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27152     return;
27153
27154   struct stat st;
27155   if (stat (objfile_name (objfile), &st) < 0)
27156     perror_with_name (objfile_name (objfile));
27157
27158   std::string filename (std::string (dir) + SLASH_STRING
27159                         + lbasename (objfile_name (objfile))
27160                         + (index_kind == dw_index_kind::DEBUG_NAMES
27161                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27162
27163   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27164   if (!out_file)
27165     error (_("Can't open `%s' for writing"), filename.c_str ());
27166
27167   /* Order matters here; we want FILE to be closed before FILENAME is
27168      unlinked, because on MS-Windows one cannot delete a file that is
27169      still open.  (Don't call anything here that might throw until
27170      file_closer is created.)  */
27171   gdb::unlinker unlink_file (filename.c_str ());
27172   gdb_file_up close_out_file (out_file);
27173
27174   if (index_kind == dw_index_kind::DEBUG_NAMES)
27175     {
27176       std::string filename_str (std::string (dir) + SLASH_STRING
27177                                 + lbasename (objfile_name (objfile))
27178                                 + DEBUG_STR_SUFFIX);
27179       FILE *out_file_str
27180         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27181       if (!out_file_str)
27182         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27183       gdb::unlinker unlink_file_str (filename_str.c_str ());
27184       gdb_file_up close_out_file_str (out_file_str);
27185
27186       const size_t total_len
27187         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27188       assert_file_size (out_file, filename.c_str (), total_len);
27189
27190       /* We want to keep the file .debug_str file too.  */
27191       unlink_file_str.keep ();
27192     }
27193   else
27194     {
27195       const size_t total_len
27196         = write_gdbindex (dwarf2_per_objfile, out_file);
27197       assert_file_size (out_file, filename.c_str (), total_len);
27198     }
27199
27200   /* We want to keep the file.  */
27201   unlink_file.keep ();
27202 }
27203
27204 /* Implementation of the `save gdb-index' command.
27205    
27206    Note that the .gdb_index file format used by this command is
27207    documented in the GDB manual.  Any changes here must be documented
27208    there.  */
27209
27210 static void
27211 save_gdb_index_command (const char *arg, int from_tty)
27212 {
27213   struct objfile *objfile;
27214   const char dwarf5space[] = "-dwarf-5 ";
27215   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27216
27217   if (!arg)
27218     arg = "";
27219
27220   arg = skip_spaces (arg);
27221   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27222     {
27223       index_kind = dw_index_kind::DEBUG_NAMES;
27224       arg += strlen (dwarf5space);
27225       arg = skip_spaces (arg);
27226     }
27227
27228   if (!*arg)
27229     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27230
27231   ALL_OBJFILES (objfile)
27232   {
27233     struct stat st;
27234
27235     /* If the objfile does not correspond to an actual file, skip it.  */
27236     if (stat (objfile_name (objfile), &st) < 0)
27237       continue;
27238
27239     struct dwarf2_per_objfile *dwarf2_per_objfile
27240       = get_dwarf2_per_objfile (objfile);
27241
27242     if (dwarf2_per_objfile != NULL)
27243       {
27244         TRY
27245           {
27246             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27247           }
27248         CATCH (except, RETURN_MASK_ERROR)
27249           {
27250             exception_fprintf (gdb_stderr, except,
27251                                _("Error while writing index for `%s': "),
27252                                objfile_name (objfile));
27253           }
27254         END_CATCH
27255       }
27256
27257   }
27258 }
27259
27260 \f
27261
27262 int dwarf_always_disassemble;
27263
27264 static void
27265 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27266                                struct cmd_list_element *c, const char *value)
27267 {
27268   fprintf_filtered (file,
27269                     _("Whether to always disassemble "
27270                       "DWARF expressions is %s.\n"),
27271                     value);
27272 }
27273
27274 static void
27275 show_check_physname (struct ui_file *file, int from_tty,
27276                      struct cmd_list_element *c, const char *value)
27277 {
27278   fprintf_filtered (file,
27279                     _("Whether to check \"physname\" is %s.\n"),
27280                     value);
27281 }
27282
27283 void
27284 _initialize_dwarf2_read (void)
27285 {
27286   struct cmd_list_element *c;
27287
27288   dwarf2_objfile_data_key
27289     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
27290
27291   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27292 Set DWARF specific variables.\n\
27293 Configure DWARF variables such as the cache size"),
27294                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27295                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27296
27297   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27298 Show DWARF specific variables\n\
27299 Show DWARF variables such as the cache size"),
27300                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27301                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27302
27303   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27304                             &dwarf_max_cache_age, _("\
27305 Set the upper bound on the age of cached DWARF compilation units."), _("\
27306 Show the upper bound on the age of cached DWARF compilation units."), _("\
27307 A higher limit means that cached compilation units will be stored\n\
27308 in memory longer, and more total memory will be used.  Zero disables\n\
27309 caching, which can slow down startup."),
27310                             NULL,
27311                             show_dwarf_max_cache_age,
27312                             &set_dwarf_cmdlist,
27313                             &show_dwarf_cmdlist);
27314
27315   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27316                            &dwarf_always_disassemble, _("\
27317 Set whether `info address' always disassembles DWARF expressions."), _("\
27318 Show whether `info address' always disassembles DWARF expressions."), _("\
27319 When enabled, DWARF expressions are always printed in an assembly-like\n\
27320 syntax.  When disabled, expressions will be printed in a more\n\
27321 conversational style, when possible."),
27322                            NULL,
27323                            show_dwarf_always_disassemble,
27324                            &set_dwarf_cmdlist,
27325                            &show_dwarf_cmdlist);
27326
27327   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27328 Set debugging of the DWARF reader."), _("\
27329 Show debugging of the DWARF reader."), _("\
27330 When enabled (non-zero), debugging messages are printed during DWARF\n\
27331 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27332 information.  A value greater than 1 provides more verbose information."),
27333                             NULL,
27334                             NULL,
27335                             &setdebuglist, &showdebuglist);
27336
27337   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27338 Set debugging of the DWARF DIE reader."), _("\
27339 Show debugging of the DWARF DIE reader."), _("\
27340 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27341 The value is the maximum depth to print."),
27342                              NULL,
27343                              NULL,
27344                              &setdebuglist, &showdebuglist);
27345
27346   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27347 Set debugging of the dwarf line reader."), _("\
27348 Show debugging of the dwarf line reader."), _("\
27349 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27350 A value of 1 (one) provides basic information.\n\
27351 A value greater than 1 provides more verbose information."),
27352                              NULL,
27353                              NULL,
27354                              &setdebuglist, &showdebuglist);
27355
27356   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27357 Set cross-checking of \"physname\" code against demangler."), _("\
27358 Show cross-checking of \"physname\" code against demangler."), _("\
27359 When enabled, GDB's internal \"physname\" code is checked against\n\
27360 the demangler."),
27361                            NULL, show_check_physname,
27362                            &setdebuglist, &showdebuglist);
27363
27364   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27365                            no_class, &use_deprecated_index_sections, _("\
27366 Set whether to use deprecated gdb_index sections."), _("\
27367 Show whether to use deprecated gdb_index sections."), _("\
27368 When enabled, deprecated .gdb_index sections are used anyway.\n\
27369 Normally they are ignored either because of a missing feature or\n\
27370 performance issue.\n\
27371 Warning: This option must be enabled before gdb reads the file."),
27372                            NULL,
27373                            NULL,
27374                            &setlist, &showlist);
27375
27376   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27377                _("\
27378 Save a gdb-index file.\n\
27379 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27380 \n\
27381 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27382 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27383 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27384                &save_cmdlist);
27385   set_cmd_completer (c, filename_completer);
27386
27387   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27388                                                         &dwarf2_locexpr_funcs);
27389   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27390                                                         &dwarf2_loclist_funcs);
27391
27392   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27393                                         &dwarf2_block_frame_base_locexpr_funcs);
27394   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27395                                         &dwarf2_block_frame_base_loclist_funcs);
27396
27397 #if GDB_SELF_TEST
27398   selftests::register_test ("dw2_expand_symtabs_matching",
27399                             selftests::dw2_expand_symtabs_matching::run_test);
27400 #endif
27401 }